@stacksjs/rpx 0.11.13 → 0.11.15
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 +178 -174
- package/dist/chunk-0zdj72ps.js +161 -0
- package/dist/{chunk-zs1tyy8z.js → chunk-hf6e07v4.js} +1 -1
- package/dist/{chunk-747af2w4.js → chunk-kv17r01q.js} +1 -1
- package/dist/chunk-pjwm8py7.js +1 -0
- package/dist/daemon-runner.d.ts +3 -2
- package/dist/daemon.d.ts +7 -1
- package/dist/host-match.d.ts +23 -0
- package/dist/index.d.ts +15 -2
- package/dist/index.js +6 -6
- package/dist/on-demand.d.ts +40 -0
- package/dist/proxy-handler.d.ts +18 -3
- package/dist/registry.d.ts +3 -2
- package/dist/sni.d.ts +20 -0
- package/dist/static-files.d.ts +46 -0
- package/dist/types.d.ts +64 -1
- package/package.json +2 -2
- package/src/daemon-runner.ts +12 -4
- package/src/daemon.ts +154 -21
- package/src/host-match.ts +52 -0
- package/src/index.ts +19 -2
- package/src/on-demand.ts +264 -0
- package/src/proxy-handler.ts +184 -21
- package/src/registry.ts +11 -3
- package/src/sni.ts +93 -0
- package/src/start.ts +66 -19
- package/src/static-files.ts +201 -0
- package/src/types.ts +138 -1
- package/dist/chunk-kbnzcycw.js +0 -1
- package/dist/chunk-pncxrxde.js +0 -157
package/dist/chunk-pncxrxde.js
DELETED
|
@@ -1,157 +0,0 @@
|
|
|
1
|
-
import{Aa as Sh,Ca as Fh,Da as Ch,pa as Y,ra as nr,sa as w,wa as gh,xa as Gf,za as zn}from"./chunk-zs1tyy8z.js";import ow from"node:dgram";import*as Hh from"node:fs/promises";import*as Lh from"node:path";import*as Qt from"node:process";import{spawn as _h}from"node:child_process";import*as Lt from"node:fs/promises";import{homedir as Pf}from"node:os";import*as Ot from"node:path";import*as U from"node:process";var Z={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 zi}from"node:child_process";import D from"node:fs/promises";import*as zf 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 Kh}from"node:module";import pn from"node:os";import Pn from"node:path";import{existsSync as ls,statSync as cs}from"fs";import{existsSync as xh,mkdirSync as _w,readdirSync as Ww,readFileSync as kh,writeFileSync as Yw}from"fs";import{homedir as ai}from"os";import{dirname as Hw,resolve as Tt}from"path";import Vr from"process";import{existsSync as hs,statSync as us}from"fs";import{existsSync as me,mkdirSync as Dh,readdirSync as bh,writeFileSync as Vh}from"fs";import{homedir as $i}from"os";import{dirname as os,resolve as ht}from"path";import ci from"process";import{join as ph,relative as Ph,resolve as as}from"path";import Wr from"process";import{existsSync as Qs,mkdirSync as Dw,readdirSync as bw,writeFileSync as Vw}from"fs";import{homedir as vn}from"os";import{dirname as vw,resolve as ct}from"path";import bi from"process";import{join as vh,relative as Xh,resolve as $s}from"path";import Yr from"process";import{existsSync as tl,mkdirSync as r0,readdirSync as n0,writeFileSync as e0}from"fs";import{dirname as s0,resolve as Ir}from"path";import Ae from"process";import{Buffer as ti}from"buffer";import{createCipheriv as Qh,createDecipheriv as tu,randomBytes as Xn}from"crypto";import{closeSync as Qn,createReadStream as ys,createWriteStream as iu,existsSync as te,fsyncSync as ws,openSync as ms,writeFileSync as ru}from"fs";import{access as nu,constants as As,mkdir as eu,readdir as $r,rename as ds,stat as yi,unlink as yr,writeFile as ie}from"fs/promises";import{join as wi}from"path";import rt from"process";import{pipeline as fu}from"stream/promises";import{createGzip as Es}from"zlib";import mi from"process";import Gt from"process";import{Buffer as Zt}from"buffer";import{createCipheriv as su,createDecipheriv as lu,randomBytes as re}from"crypto";import{closeSync as ne,createReadStream as Ts,createWriteStream as cu,existsSync as wr,fsyncSync as gs,openSync as Ss,writeFileSync as hu}from"fs";import{access as uu,constants as Cs,mkdir as ou,readdir as mr,rename as Rs,stat as Ai,unlink as Ar,writeFile as ee}from"fs/promises";import{isAbsolute as au,join as di,resolve as $u}from"path";import j from"process";import{pipeline as yu}from"stream/promises";import{createGzip as Bs}from"zlib";import Ei from"process";import qt from"process";import dr from"process";import{existsSync as Er}from"fs";import{resolve as fe}from"path";import{existsSync as wu}from"fs";import{existsSync as mu,readdirSync as Au}from"fs";import{extname as se,resolve as Us}from"path";import du from"process";import{join as Eu,relative as Tu,resolve as Fs}from"path";import Or from"process";import{Buffer as Mt}from"buffer";import{createCipheriv as gu,createDecipheriv as Su,randomBytes as le}from"crypto";import{closeSync as ce,createReadStream as Js,createWriteStream as Cu,existsSync as Tr,fsyncSync as Ns,openSync as js,writeFileSync as Ru}from"fs";import{access as Bu,constants as _s,mkdir as Uu,readdir as gr,rename as Ws,stat as Ti,unlink as Sr,writeFile as he}from"fs/promises";import{isAbsolute as Fu,join as gi,resolve as Ju}from"path";import _ from"process";import{pipeline as Nu}from"stream/promises";import{createGzip as Ys}from"zlib";import Si from"process";import Kt from"process";import Cr from"process";import{existsSync as Rr}from"fs";import{resolve as ue}from"path";import{existsSync as ju}from"fs";import{exec as Qo}from"node:child_process";import bs from"node:fs";import ta from"node:os";import Ut from"node:path";import Hl from"node:process";import{promisify as ia}from"node:util";import Ui from"node:crypto";import xt from"node:fs";import je from"node:path";import{execSync as Xs}from"node:child_process";import br from"node:os";var Uw=Kh(import.meta.url);class il{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(!ls(t))return!0;return cs(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=ls(r)?cs(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 rl{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 il,_e=new rl,_u=Object.defineProperty,Wu=(t)=>t;function Yu(t,i){this[t]=Wu.bind(null,i)}var Iu=(t,i)=>{for(var r in i)_u(t,r,{get:i[r],enumerable:!0,configurable:!0,set:Yu.bind(i,r)})},Ou=(t,i)=>()=>(t&&(i=t(t=0)),i),nl={};Iu(nl,{withErrorRecovery:()=>sl,tryLoadConfig:()=>eo,loadConfigWithResult:()=>ro,loadConfig:()=>ol,isRetryableError:()=>Pu,isConfigNotFoundError:()=>pu,isBunfigError:()=>ll,globalPerformanceMonitor:()=>vi,globalCache:()=>Ri,getEnvOrDefault:()=>vu,generateConfigTypes:()=>fo,defaultGeneratedDir:()=>El,defaultConfigDir:()=>dl,deepMergeWithArrayStrategy:()=>He,deepMerge:()=>cl,createLibraryConfig:()=>so,config:()=>no,bunfigPlugin:()=>lo,applyEnvVarsToConfig:()=>ki,TypeGenerationError:()=>Re,SchemaValidationError:()=>pi,PluginError:()=>Ue,PerformanceMonitor:()=>Ye,FileSystemError:()=>Ce,ErrorFactory:()=>ri,EnvVarError:()=>qr,EnvProcessor:()=>pr,ConfigValidator:()=>Le,ConfigValidationError:()=>ge,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>Se,ConfigLoader:()=>Ze,ConfigLoadError:()=>Vi,ConfigFileLoader:()=>Pr,ConfigCache:()=>We,CacheUtils:()=>$l,BunfigError:()=>mt,BrowserConfigError:()=>Be,ArrayMergeStrategies:()=>ml});class We{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(!hs(t))return!0;return us(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=hs(r)?us(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 Ye{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 Hu(t,i={}){let r=Object.keys(i).sort().map((n)=>`${n}:${i[n]}`).join("|");return r?`${t}:${r}`:t}function Lu(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Zu(t){return t.getStats().size*2}function Ie(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((f)=>G(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(G(e)&&"path"in e){if(!n.find((f)=>G(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(!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]=Ie(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((c)=>G(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(G(s)&&"path"in s){if(!f.find((c)=>G(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>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(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(!Lr(t[e],i[e]))return!1}return!0}return!1}function G(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Mu(t,i){if(!tl(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 Ie(i,n)}catch{return null}}catch{return null}}async function zu({name:t="",cwd:i,defaultConfig:r}){let n=i||Ae.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 Mu(l,r);if(h!==null)return h}try{let s=Ir(n,"package.json");if(tl(s)){let c=(await import(s))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Ie(r,c)}catch{}}}catch{}return r}function Gu(t,i={}){let r=Yr.cwd();while(r.includes("storage"))r=$s(r,"..");let n=$s(r,t||"");if(i?.relative)return Xh(Yr.cwd(),n);return n}async function qu(){try{let t=await zu({name:"clarity",defaultConfig:Jr,cwd:Yr.cwd(),endpoint:"",headers:{}});return{...Jr,...t}}catch{return Jr}}function K(){if(Gt.env.NODE_ENV==="test"||Gt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ku(){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 el{async format(t){let i=await Ku(),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:mi.pid,hostname:i(),environment:mi.env.NODE_ENV||"development",platform:mi.platform,version:mi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:mi.env.NODE_ENV||mi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}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={...Ee},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new el,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:Ee.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 nu(this.config.logDirectory,As.F_OK|As.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await eu(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(!te(this.currentLogFile))await ie(this.currentLogFile,"",{mode:420});if(n=ms(this.currentLogFile,"a",420),ru(n,c,{flag:"a"}),ws(n),n!==void 0)Qn(n),n=void 0;if((await yi(this.currentLogFile)).size===0){if(await ie(this.currentLogFile,c,{flag:"w",mode:420}),(await yi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let o=s*2**e;await new Promise(($)=>setTimeout($,o)),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{Qn(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let 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 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(K())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,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 Xn(16).toString("hex")}generateKey(){return Xn(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=Xn(16),n=Qh("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=Es(),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(K())return;let t=await yi(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 u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await yi(r).catch(()=>null))try{if(await ds(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 ie(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 yi(r).catch(()=>null))await ds(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(wi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=ys(t),n=iu(i),e=Es();await fu(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()})),te(this.currentLogFile))try{let t=ms(this.currentLogFile,"r+");ws(t),Qn(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!K()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await $r(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await yr(wi(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?M.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} ${M.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);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=yl[t],u=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:M.gray(s),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:M.green(s),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error(o),c){let $=c.split(`
|
|
2
|
-
`);for(let a of $)if(a.trim()&&!a.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:M.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}
|
|
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&&!K()){let r=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:M.blue("◐"),tag:r,message:`${M.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&&!K()){let h=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:M.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!K())console.error(l.trim());await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,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(K())throw Error("createReadStream is not supported in browser environments");if(!te(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ys(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=tu("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 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(`
|
|
6
|
-
`),s=Math.max(...f.map((u)=>u.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((u)=>{let o=" ".repeat(s-u.length-2);return`│ ${u}${o} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:M.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(c)})),h.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(l),showTimestamp:!1}))}else if(!K())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(K())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${M.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&&!K()){let e=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",f=M.blue("◐");console.error(`${f} ${e} ${M.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||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:(n,e)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||K())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||K())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||K())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||K()||!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=M.green("━".repeat(n)),s=M.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=i||r===100?M.green("✓"):M.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${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||K()||!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(K()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await $r(this.config.logDirectory),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=wi(this.config.logDirectory,n);if(t.before)try{if((await yi(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&&W(i[0])&&"id"in i[0]&&i[0].id===3&&W(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(W(i)&&W(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(W(t)&&"arr"in t&&Array.isArray(t.arr)&&W(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&W(i[0])&&W(t[0])){let n=[...i];for(let e of t)if(W(e)&&"name"in e){if(!n.find((f)=>W(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(W(e)&&"path"in e){if(!n.find((f)=>W(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(!W(i)||!W(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(W(e)&&W(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&&W(e[0])&&W(r[n][0])){let f=[...e];for(let s of r[n])if(W(s)&&"name"in s){if(!f.find((c)=>W(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(W(s)&&"path"in s){if(!f.find((c)=>W(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 Oe(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(!W(i)||!W(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(W(f)&&W(s))n[e]=Oe(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(W(t)&&W(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 W(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Br(t,i,r="replace"){if(!Qs(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 Oe(i,e,r)}catch{return null}}catch{return null}}function xu(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,u]of Object.entries(s)){let o=[...c,h],$=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),a=`${n}_${o.map($).join("_")}`,m=`${n}_${o.map((y)=>y.toUpperCase()).join("_")}`;if(r)et.info(`Checking environment variable ${a} for config ${t}.${o.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[h]=f(u,o);else{let y=bi.env[a]||bi.env[m];if(y!==void 0){if(r)et.info(`Using environment variable ${y?a:m} for config ${t}.${o.join(".")}`);if(typeof u==="number")l[h]=Number(y);else if(typeof u==="boolean")l[h]=y.toLowerCase()==="true";else if(Array.isArray(u))try{let A=JSON.parse(y);if(Array.isArray(A))l[h]=A;else l[h]=y.split(",").map((d)=>d.trim())}catch{l[h]=y.split(",").map((A)=>A.trim())}else l[h]=y}}}return l}return f(e)}async function ku({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)?xu(t,e,f):e,h=r||bi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(f)et.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let o=[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 A of y){if(f)et.info(`Searching for configuration in: ${A}`);let d=[ct(h,"config"),ct(h,".config")].concat(n?[ct(h,n)]:[]).includes(A)?[...o,...$,...a,...m]:[...$,...o,...m,...a];for(let g of d)for(let O of u){let L=ct(A,`${g}${O}`),H=await Br(L,l,c);if(H!==null){if(f)et.success(`Configuration loaded from: ${L}`);return H}}}if(t){let A=ct(vn(),".config",t),d=["config",`${t}.config`];if(i)d.push(`${i}.config`);if(f)et.info(`Checking user config directory: ${A}`);for(let g of d)for(let O of u){let L=ct(A,`${g}${O}`),H=await Br(L,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user config directory: ${L}`);return H}}}if(t){let A=ct(vn(),".config"),d=[`.${t}.config`];if(i)d.push(`.${i}.config`);if(f)et.info(`Checking user config directory for dotfile configs: ${A}`);for(let g of d)for(let O of u){let L=ct(A,`${g}${O}`),H=await Br(L,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user config directory dotfile: ${L}`);return H}}}if(t){let A=vn(),d=[`.${t}.config`,`.${t}`];if(i)d.push(`.${i}.config`),d.push(`.${i}`);if(f)et.info(`Checking user home directory for dotfile configs: ${A}`);for(let g of d)for(let O of u){let L=ct(A,`${g}${O}`),H=await Br(L,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user home directory: ${L}`);return H}}}try{let A=ct(h,"package.json");if(Qs(A)){let d=await import(A),g=d[t];if(!g&&i){if(g=d[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===d[t]?t:i}`);return Oe(l,g,c)}catch(O){if(f)et.warn("Failed to merge package.json config:",O)}}}catch(A){if(f)et.warn("Failed to load package.json:",A)}if(f)et.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function Du(t,i={}){let r=Wr.cwd();while(r.includes("storage"))r=as(r,"..");let n=as(r,t||"");if(i?.relative)return Ph(Wr.cwd(),n);return n}async function bu(){try{let t=await ku({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 Vu(){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 fl{async format(t){let i=await Vu(),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:Ei.pid,hostname:i(),environment:Ei.env.NODE_ENV||"development",platform:Ei.platform,version:Ei.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ei.env.NODE_ENV||Ei.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={...Te},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new fl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??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},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:Te.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 uu(this.config.logDirectory,Cs.F_OK|Cs.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await ou(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 ee(this.currentLogFile,"",{mode:420});if(n=Ss(this.currentLogFile,"a",420),hu(n,c,{flag:"a"}),gs(n),n!==void 0)ne(n),n=void 0;if((await Ai(this.currentLogFile)).size===0){if(await ee(this.currentLogFile,c,{flag:"w",mode:420}),(await Ai(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let o=s*2**e;await new Promise(($)=>setTimeout($,o)),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{ne(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let 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 re(16).toString("hex")}generateKey(){return re(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=re(16),n=su("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=Bs(),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 Ai(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let 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 u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ai(r).catch(()=>null))try{if(await Rs(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Ar(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 ee(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ai(r).catch(()=>null))await Rs(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 Ar(di(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Ts(t),n=cu(i),e=Bs();await yu(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=Ss(this.currentLogFile,"r+");gs(t),ne(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!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 Ar(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 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} ${R.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);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=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(au(i)||i.startsWith("./")||i.startsWith("../"))i=$u(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 o=this.options.showIcons===!1?"":wl[t],$=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:R.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:R.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:o,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 u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
11
|
-
`;if(c)u+=`${c}
|
|
12
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let 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()&&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()&&!b()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!b()&&j.stdout.isTTY)j.stdout.write(`
|
|
13
|
-
`);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!b()&&j.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 Ts(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let 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=lu("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,o=Zt.allocUnsafe(u);return l.copy(o,0),h.copy(o,l.length),o.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)}┐`,u=`└${"─".repeat(l)}┘`,o=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:R.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(h),showTimestamp:!1})),o.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(u),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();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 u=i[c++];switch(h){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),c<i.length)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()||!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=R.green("━".repeat(n)),s=R.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||r===100?R.green("✓"):R.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${R.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${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(`
|
|
18
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||b()||!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(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 Ai(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 Ar(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 sl(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 ll(t){return t instanceof mt}function pu(t){return t instanceof Gr}function Pu(t){if(ll(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 u=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return vi.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let u=dr.env[l]||(h?dr.env[h]:void 0);if(u!==void 0){if(n.verbose){let o=dr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof qr)throw o;throw ri.envVar(l,u,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(dr.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 vu(t,i){let r=al("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function cl(t,i,r={}){return hl(t,i,r,new WeakMap)}function hl(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 ul(t,i,e,n);if(!gt(i)||!gt(t))return i;return io(t,i,r,n)}function ul(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 Qu(t,i,n);default:return i}return i}function Xu(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>de(e,n)))r.push(n);return r}function Qu(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(gt(i[0])&>(t[0]))return to(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 to(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 io(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]=hl(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=ul(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function He(t,i,r="replace"){return cl(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=Ri.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()}`,u=await import(t+h),o=u.default||u,$="default"in u,a=Object.keys(u).length>0;if(!$&&!a)throw new Vi(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new Vi(t,Error("Configuration must export a valid object"),"unknown");let m={config:He(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Ri.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?ri.configLoad(t,h):ri.configLoad(t,Error(String(h)))}};if(s)return vi.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,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(fe(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 sl(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=fe(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=fe(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 Le{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 u=[],o=[],$={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 u.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:u,warnings:o}}};if(c)return await vi.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!wu(i))throw new pi(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 pi(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:Al},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ze{fileLoader=new Pr;envProcessor=new pr;validator=new Le;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 u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!u&&(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&&($||u))throw l;if(o&&(!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:u=!1}=t,o=f||ci.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,o,s,c,h,u,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(a,$,l,n,u);let m=await this.loadHomeConfiguration(n,e,c,h,u,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,u);let y=await this.loadPackageJsonConfiguration(n,e,o,c,h,u,l);if(y)return $.push(ht(o,"package.json")),this.finalizeResult(y,$,l,n,u);if($.push(...this.getAllSearchPaths(n,e,o,s)),i)throw ri.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,u),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?ki(t,e,s):e,u=this.getLocalDirectories(r,n);for(let o of u){if(s)Ft.info(`Searching for configuration in: ${o}`);let $=this.fileLoader.generateConfigPaths(t,o,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?ki(t,r,e):r,c=[ht($i(),".config",t),ht($i(),".config"),$i()];for(let l of c){if(e)Ft.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(u){if(e)Ft.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?ki(t,n,f):n;try{let l=ht(r,"package.json");if(!me(l))return null;let h=await import(l),u=h[t],o=t;if(!u&&i)u=h[i],o=i;if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)Ft.success(`Configuration loaded from package.json: ${o}`);return{config:He(c,u,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:ki(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 Ri.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Ri.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($i(),".config",t),ht($i(),".config"),$i()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function Is(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 ro(t){return kt.loadConfig({...t,__strictErrorHandling:!0})}async function ol(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 no(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"&&Is(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"&&Is(i)))return(await kt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function eo(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 ki(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,u]of Object.entries(s)){let o=[...c,h],$=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((y)=>y.toUpperCase()).join("")}`,`${e}_${o.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 u==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof u==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(u))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,o)}return l}return f(i)}function fo(t){let i=ht(ci.cwd(),t.configDir),r=ht(ci.cwd(),t.generatedDir),n=ht(r,"config-types.ts");if(!me(os(n)))Dh(os(n),{recursive:!0,mode:511});let e=me(i)?bh(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${Oo}
|
|
31
|
-
export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
|
|
32
|
-
`;Vh(n,f,{mode:438})}function so(t){let i=null,r=null,n=()=>{if(!r)r=ol(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 lo(t){let i=Us(du.cwd(),t?.configDir||"./config");function r(){if(!mu(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Au(i).filter((l)=>e.has(se(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let u=se(h).toLowerCase(),o=c.get(l);if(!o){c.set(l,h);continue}let $=se(o).toLowerCase();if(f.indexOf(u)<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=Us(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 al,Ri,vi,$l,co,ho,Os,Jr,Ee,nt,M,uo,Hs,oo,Ls,ao,$o,oe,yo,Zs,Ms,ae,wo,mo,Ao,Eo,Nr,yl,To,et,go,So,zs,jr,Te,V,R,Co,Gs,Ro,qs,Bo,Uo,$e,Fo,Ks,xs,Jo,ye,No,jo,_o,Wo,Yo,_r,wl,Io,Oo="0.15.6",mt,Gr,Vi,ge,Se,qr,Ce,Re,pi,Be,Ue,ri,ml,Al,Ft,kt,dl,El,Ho=Ou(async()=>{al=import.meta.require,Ri=new We,vi=new Ye,$l={createKey:Hu,isEquivalent:Lu,estimateMemoryUsage:Zu},co=Ir(Ae.cwd(),"config"),ho=Ir(Ae.cwd(),"src/generated"),Os=Yr.env.CLARITY_LOG_DIR||vh(Gu(),"logs"),Jr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Os,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ee=await qu(),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"},M=nt,uo=nt.red,Hs=nt.green,oo=nt.yellow,Ls=nt.blue,ao=nt.magenta,$o=nt.cyan,oe=nt.white,yo=nt.gray,Zs=nt.bgRed,Ms=nt.bgYellow,ae=nt.bold,wo=nt.dim,mo=nt.italic,Ao=nt.underline,Eo=nt.reset,Nr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},yl={debug:"\uD83D\uDD0D",info:Ls("ℹ"),success:Hs("✓"),warning:Ms(oe(ae(" WARN "))),error:Zs(oe(ae(" ERROR ")))},To=new Zr("stacks"),et=new Zr("bunfig",{showTags:!0}),go=ct(bi.cwd(),"config"),So=ct(bi.cwd(),"src/generated"),zs=Wr.env.CLARITY_LOG_DIR||ph(Du(),"logs"),jr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:zs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Te=await bu(),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,Co=V.red,Gs=V.green,Ro=V.yellow,qs=V.blue,Bo=V.magenta,Uo=V.cyan,$e=V.white,Fo=V.gray,Ks=V.bgRed,xs=V.bgYellow,Jo=V.bgGray,ye=V.bold,No=V.dim,jo=V.italic,_o=V.underline,Wo=V.strikethrough,Yo=V.reset,_r={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},wl={debug:"\uD83D\uDD0D",info:qs("ℹ"),success:Gs("✓"),warning:xs($e(ye(" WARN "))),error:Ks($e(ye(" ERROR ")))},Io=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})}},Vi=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}},ge=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})}},Se=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})}},Ce=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}},Re=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}},pi=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})}},Be=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})}},Ue=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 Vi(t,i,r)},configValidation(t,i,r){return new ge(t,i,r)},configMerge(t,i,r,n){return new Se(t,i,r,n)},envVar(t,i,r,n){return new qr(t,i,r,n)},fileSystem(t,i,r){return new Ce(t,i,r)},typeGeneration(t,i,r){return new Re(t,i,r)},schemaValidation(t,i,r){return new pi(t,i,r)},browserConfig(t,i,r,n){return new Be(t,i,r,n)},plugin(t,i,r){return new Ue(t,i,r)}},ml={replace:"replace",concat:"concat",smart:"smart"},Al=/^https?:\/\//,Ft=new zr("bunfig",{showTags:!0}),kt=new Ze,dl=ht(ci.cwd(),"config"),El=ht(ci.cwd(),"src/generated")});function Lo(t,i={}){let r=Or.cwd();while(r.includes("storage"))r=Fs(r,"..");let n=Fs(r,t||"");if(i?.relative)return Tu(Or.cwd(),n);return n}var Zo=Or.env.CLARITY_LOG_DIR||Eu(Lo(),"logs"),Tl={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Zo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Kr={...Tl},v0=(async()=>{try{let{loadConfig:t}=await Ho().then(()=>nl),i=await t({name:"clarity",alias:"logging",defaultConfig:Tl,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 Mo(){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 gl{async format(t){let i=await Mo(),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:Si.pid,hostname:i(),environment:Si.env.NODE_ENV||"development",platform:Si.platform,version:Si.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Si.env.NODE_ENV||Si.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"},F=tt,X0=tt.red,zo=tt.green,Q0=tt.yellow,Go=tt.blue,tm=tt.magenta,im=tt.cyan,ks=tt.white,rm=tt.gray,qo=tt.bgRed,Ko=tt.bgYellow,nm=tt.bgGray,Ds=tt.bold,em=tt.dim,fm=tt.italic,sm=tt.underline,lm=tt.strikethrough,cm=tt.reset,we={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xo={debug:"\uD83D\uDD0D",info:Go("ℹ"),success:zo("✓"),warning:Ko(ks(Ds(" WARN "))),error:qo(ks(Ds(" 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 gl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let 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{...we,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...we};return{...we,...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 Bu(this.config.logDirectory,_s.F_OK|_s.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Uu(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 he(this.currentLogFile,"",{mode:420});if(n=js(this.currentLogFile,"a",420),Ru(n,c,{flag:"a"}),Ns(n),n!==void 0)ce(n),n=void 0;if((await Ti(this.currentLogFile)).size===0){if(await he(this.currentLogFile,c,{flag:"w",mode:420}),(await Ti(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let o=s*2**e;await new Promise(($)=>setTimeout($,o)),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{ce(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let 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 gi(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 gi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return gi(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 le(16).toString("hex")}generateKey(){return le(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=le(16),n=gu("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=Ys(),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 Ti(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 u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ti(r).catch(()=>null))try{if(await Ws(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 he(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 Ti(r).catch(()=>null))await Ws(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(gi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Js(t),n=Cu(i),e=Ys();await Nu(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=js(this.currentLogFile,"r+");Ns(t),ce(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await gr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Sr(gi(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()?F.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof _.env.NO_COLOR<"u",i=_.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon: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=_.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 u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);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(p())return!1;let t=_.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=_.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Fu(i)||i.startsWith("./")||i.startsWith("../"))i=Ju(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 o=this.options.showIcons===!1?"":xo[t],$=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:F.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:F.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:o,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:F.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
41
|
-
`;if(c)u+=`${c}
|
|
42
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let 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()&&_.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()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!p()&&_.stdout.isTTY)_.stdout.write(`
|
|
43
|
-
`);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&_.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),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?F.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":F.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 Js(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=Su("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,o=Mt.allocUnsafe(u);return l.copy(o,0),h.copy(o,l.length),o.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)}┐`,u=`└${"─".repeat(l)}┘`,o=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:F.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(h),showTimestamp:!1})),o.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(u),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(`${F.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.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 u=i[c++];switch(h){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),c<i.length)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?F.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${F.blue("◐")} `;console.error(`${c}${s} ${F.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()||!_.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}`:"",u=this.options.showIcons===!1?"":i||r===100?F.green("✓"):F.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${F.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${c} ${l}${h}`,a=_.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,_.stdout.write(t.lastRenderedLine),i)_.stdout.write(`
|
|
48
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!_.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=gi(this.config.logDirectory,n);if(t.before)try{if((await Ti(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 hm=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 Sl 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 Cl 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 Rl 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 Me 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 Bl 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 Ul 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 Fl 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 Jl 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 Bi={configNotFound(t,i,r){return new Sl(t,i,r)},configLoad(t,i,r){return new xr(t,i,r)},configValidation(t,i,r){return new Cl(t,i,r)},configMerge(t,i,r,n){return new Rl(t,i,r,n)},envVar(t,i,r,n){return new Me(t,i,r,n)},fileSystem(t,i,r){return new Bl(t,i,r)},typeGeneration(t,i,r){return new Ul(t,i,r)},schemaValidation(t,i,r){return new kr(t,i,r)},browserConfig(t,i,r,n){return new Fl(t,i,r,n)},plugin(t,i,r){return new Jl(t,i,r)}};async function ko(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 ze{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 u=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return _e.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((u)=>this.formatEnvKey(u,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let u=Cr.env[l]||(h?Cr.env[h]:void 0);if(u!==void 0){if(n.verbose){let o=Cr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof Me)throw o;throw Bi.envVar(l,u,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 Bi.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 Do(t,i,r={}){return Nl(t,i,r,new WeakMap)}function Nl(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 jl(t,i,e,n);if(!St(i)||!St(t))return i;return Po(t,i,r,n)}function jl(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 bo(t,i);case"smart":return Vo(t,i,n);default:return i}return i}function bo(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Fe(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(St(i[0])&&St(t[0]))return po(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 po(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 Po(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]=Nl(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=jl(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function _l(t,i,r="replace"){return Do(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Fe(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Fe(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(!Fe(t[e],i[e]))return!1}return!0}return!1}function St(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Wl{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()}`,u=await import(t+h),o=u.default||u,$="default"in u,a=Object.keys(u).length>0;if(!$&&!a)throw new xr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new xr(t,Error("Configuration must export a valid object"),"unknown");let m={config:_l(i,o,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?Bi.configLoad(t,h):Bi.configLoad(t,Error(String(h)))}};if(s)return _e.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(ue(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 ko(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=ue(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=ue(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 vo=/^https?:\/\//;class Yl{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 u=[],o=[],$={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 u.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:u,warnings:o}}};if(c)return await _e.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!ju(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:vo},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var zt=new vr("bunfig",{showTags:!0});function Xo(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 Il{fileLoader=new Wl;envProcessor=new ze;validator=new Yl;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 u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!u&&(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&&($||u))throw l;if(o&&(!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:u=!1}=t,o=f||Vr.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,o,s,c,h,u,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(a,$,l,n,u);let m=await this.loadHomeConfiguration(n,e,c,h,u,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,u);let y=await this.loadPackageJsonConfiguration(n,e,o,c,h,u,l);if(y)return $.push(Tt(o,"package.json")),this.finalizeResult(y,$,l,n,u);if($.push(...this.getAllSearchPaths(n,e,o,s)),i)throw Bi.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,u),warnings:[`No configuration file found for "${n}"${Xo(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,u=this.getLocalDirectories(r,n);for(let o of u){if(s)zt.info(`Searching for configuration in: ${o}`);let $=this.fileLoader.generateConfigPaths(t,o,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(ai(),".config",t),Tt(ai(),".config"),ai()];for(let l of c){if(e)zt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(u){if(e)zt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}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(!xh(l))return null;let h={};try{h=JSON.parse(kh(l,"utf8"))}catch($){if(f)zt.warn("Failed to parse package.json:",[$ instanceof Error?$:Error(String($))]);return null}let u=h[t],o=t;if(!u&&i){let $=Array.isArray(i)?i:[i];for(let a of $){if(!a)continue;if(h[a]){u=h[a],o=a;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)zt.success(`Configuration loaded from package.json: ${o}`);return{config:_l(c,u,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 Bi.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(ai(),".config",t),Tt(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)}}var um=new Il;function Ur(t,i,r=!1){let n=new ze,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let o=[...c,h],$=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((y)=>y.toUpperCase()).join("")}`,`${e}_${o.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 u==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof u==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(u))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,o)}return l}return f(i)}var om=Tt(Vr.cwd(),"config"),am=Tt(Vr.cwd(),"src/generated"),Ol={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(pn.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:Pn.join(pn.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:Pn.join(pn.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},k=Ol,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"},Ci={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function Je(t,i){let r=[];function n(e){let f;try{f=bs.readdirSync(e)}catch{return}for(let s of f){let c=Ut.join(e,s);try{if(bs.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||k.verbose)console.debug(`[tlsx:${t}] ${i}`)}var ra=ia(Qo);function Ll(){return Hl.env.SUDO_PASSWORD}var Vs="[redacted]",na=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),ea=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function fa(t){let i=t.toLowerCase();return na.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 ea.test(t)?Vs:t;if(!t||typeof t!=="object")return t;let i={};for(let[r,n]of Object.entries(t)){if(fa(r)){i[r]=Vs;continue}i[r]=Dr(n)}return i}function Xr(t){return JSON.stringify(Dr(t))}function sa(t){let i=Ll();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=sa(t);try{let{stdout:n,stderr:e}=await ra(r,{cwd:i.cwd||Hl.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 Zl(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 Ge(t){let i=Ut.join(ta.homedir(),".stacks","ssl"),r=t.basePath&&t.basePath.trim()!==""?t.basePath:k.basePath&&k.basePath.trim()!==""?k.basePath:i,n=t.certPath?Ut.isAbsolute(t.certPath)?t.certPath:Ut.join(r,t.certPath):Ut.join(r,k.certPath),e=t.keyPath?Ut.isAbsolute(t.keyPath)?t.keyPath:Ut.join(r,t.keyPath):Ut.join(r,k.keyPath),f=t.caCertPath?Ut.isAbsolute(t.caCertPath)?t.caCertPath:Ut.join(r,t.caCertPath):Ut.join(r,k.caCertPath);return{certPath:n,keyPath:e,caCertPath:f,basePath:r}}function Ml(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 qe(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},ut={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};function Di(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 dt(t,i){let r=Di(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 dt(Nt.OID,Buffer.from(r))}function Ne(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 dt(Nt.INTEGER,i)}function zl(t,i=0){return dt(Nt.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function Gl(t){return dt(Nt.OCTET_STRING,t)}function At(...t){return dt(Nt.SEQUENCE,Buffer.concat(t))}function la(...t){return dt(Nt.SET,Buffer.concat(t))}function ca(t){return dt(Nt.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function ha(t){return dt(Nt.UTF8_STRING,Buffer.from(t,"utf8"))}function ua(){return Buffer.from([Nt.NULL,0])}function ps(t,i,r=!0){let n=160|t|(r?0:0),e=Di(i.length);return Buffer.concat([Buffer.from([n]),e,i])}function Ps(t){let i=t.getUTCFullYear();if(i>=2050){let r=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return dt(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 dt(Nt.UTC_TIME,Buffer.from(l,"ascii"))}}function oa(t,i){return At(Ps(t),Ps(i))}function vs(t){let i=[];for(let r of t){let n;switch(r.shortName){case"CN":n=ut.COMMON_NAME;break;case"C":n=ut.COUNTRY;break;case"L":n=ut.LOCALITY;break;case"ST":n=ut.STATE;break;case"O":n=ut.ORGANIZATION;break;case"OU":n=ut.ORGANIZATIONAL_UNIT;break;default:continue}let e=r.shortName==="C"?ca(r.value):ha(r.value),f=At(Pi(n),e);i.push(la(f))}return At(...i)}function ql(t){return At(Pi(t),ua())}function aa(t){return t.export({type:"spki",format:"der"})}function $a(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 ya(t){let i=[];for(let r of t)if(r.type===2&&r.value){let n=Di(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=$a(r.ip),e=Di(n.length);i.push(Buffer.concat([Buffer.from([135]),e,n]))}else if(r.type===6&&r.value){let n=Di(r.value.length);i.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return At(...i)}function wa(t,i){if(t){if(i!==void 0)return At(dt(1,Buffer.from([255])),Ne(i));return At(dt(1,Buffer.from([255])))}return At()}function ma(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 zl(Buffer.from([i]),r)}function Aa(t){let i=[];if(t.serverAuth)i.push(Pi(ut.SERVER_AUTH));if(t.clientAuth)i.push(Pi(ut.CLIENT_AUTH));return At(...i)}function xi(t,i,r){let n=[Pi(t)];if(i)n.push(dt(1,Buffer.from([255])));return n.push(Gl(r)),At(...n)}function da(t){let i=[];if(i.push(ps(0,Ne(2))),i.push(Ne(t.serialNumber)),i.push(ql(ut.SHA256_WITH_RSA)),i.push(vs(t.issuer)),i.push(oa(t.notBefore,t.notAfter)),i.push(vs(t.subject)),i.push(aa(t.publicKey)),t.extensions){let r=[];if(t.extensions.basicConstraints)r.push(xi(ut.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,wa(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)r.push(xi(ut.KEY_USAGE,t.extensions.keyUsage.critical??!0,ma(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)r.push(xi(ut.EXTENDED_KEY_USAGE,!1,Aa(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)r.push(xi(ut.SUBJECT_ALT_NAME,!1,ya(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)r.push(xi(ut.SUBJECT_KEY_IDENTIFIER,!1,Gl(t.extensions.subjectKeyIdentifier)));if(r.length>0)i.push(ps(3,At(...r)))}return At(...i)}function Ea(t,i){let r=Ui.createSign("SHA256");r.update(t);let n=r.sign(i);return At(t,ql(ut.SHA256_WITH_RSA),zl(n))}function Ta(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 Ke(){return Ui.randomBytes(20)}function Kl(t=2048){let{privateKey:i,publicKey:r}=Ui.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:r}}function ga(t){let i=t.export({type:"spki",format:"der"});return Ui.createHash("sha1").update(i).digest()}function xl(t){let i={serialNumber:t.serialNumber||Ke(),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:ga(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=da(i),n=Ea(r,t.signingKey);return{certificate:Ta(n,"CERTIFICATE"),certificateDer:n}}function kl(t){return t.export({type:"pkcs8",format:"pem"})}function Sa(t){return Ui.createPrivateKey(t)}function Ca(t){let i=new Ui.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 xe(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}=Kl(i),e=[{shortName:"C",value:t.countryName||k.countryName},{shortName:"ST",value:t.stateName||k.stateName},{shortName:"L",value:t.localityName||k.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:f,notAfter:s}=qe({validityYears:t.validityYears||Jt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:c}=xl({serialNumber:Ke(),notBefore:f,notAfter:s,subject:e,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:kl(r),notBefore:f,notAfter:s}}async function ke(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}=Ca(t.rootCA.certificate),r=Sa(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}=Kl(n),s=t.commonName||Zl(t),c=t.certificateAttributes||[{shortName:"C",value:t.countryName||k.countryName},{shortName:"ST",value:t.stateName||k.stateName},{shortName:"L",value:t.localityName||k.localityName},{shortName:"O",value:t.organizationName||k.organizationName},{shortName:"CN",value:s}],{notBefore:l,notAfter:h}=qe({validityDays:t.validityDays||Jt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),u=Ml(t),o=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},$=t.extKeyUsage||{serverAuth:!0},{certificate:a}=xl({serialNumber:Ke(),notBefore:l,notAfter:h,subject:c,issuer:i,publicKey:f,signingKey:r,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:o,extendedKeyUsage:$,subjectAltName:u});return{certificate:a,privateKey:kl(e),notBefore:l,notAfter:h}}function Dl(t,i){E(T.STORAGE,`Storing certificate and private key with options: ${Xr(i)}`,i?.verbose);let{certPath:r,keyPath:n}=Ge({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=je.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=je.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 bl(t,i){E(T.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:r}=Ge({basePath:i?.basePath,caCertPath:i?.caCertPath});E(T.STORAGE,`CA certificate path: ${r}`,i?.verbose);let n=je.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 Ra(t,i){if(br.platform()!=="darwin")return!1;try{let r=Xs(`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(Xs("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 Ba={platform:"darwin",async addCertificate(t,i){if(await Ra(t,i?.verbose)){E(T.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),Ci.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||k.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}}},Ua={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||k.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}}},Fa={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=Je(r,n);if(f.length===0){Ci.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let s of f){E(T.TRUST,`Processing certificate database in ${s}`,i?.verbose);try{E(T.TRUST,`Attempting to delete existing cert for ${k.commonName}`,i?.verbose),await ii(`certutil -d sql:${s} -D -n ${k.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 ${k.commonName} -i ${t}`),Ci.info(`Cert added to ${s}`)}},async removeCertificate(t,i,r){let n=r||k.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=Je(e,f);if(s.length===0){Ci.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}"`),Ci.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}`)}}}},Ja={darwin:Ba,win32:Ua,linux:Fa};async function De(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=Dl(t,r);E(T.TRUST,"Storing CA certificate",r?.verbose);let e=bl(i,r),f=br.platform();E(T.TRUST,`Detected platform: ${f}`,r?.verbose);let s=Ja[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 Of}from"node:os";import{join as Hf,resolve as Gd}from"node:path";import{existsSync as Vl,statSync as pl}from"fs";import{existsSync as Na,mkdirSync as iA,readdirSync as rA,readFileSync as ja,writeFileSync as nA}from"fs";import{homedir as Fi}from"os";import{dirname as sA,resolve as Ct}from"path";import Yn from"process";import{existsSync as Pl,statSync as vl}from"fs";import{existsSync as $f,mkdirSync as _a,readdirSync as Wa,writeFileSync as Ya}from"fs";import{homedir as Ji}from"os";import{dirname as Xl,resolve as at}from"path";import hi from"process";import{join as Ia,relative as Oa,resolve as Ql}from"path";import Tn from"process";import{existsSync as Hc,mkdirSync as mA,readdirSync as AA,writeFileSync as dA}from"fs";import{homedir as be}from"os";import{dirname as gA,resolve as ot}from"path";import Qi from"process";import{join as Ha,relative as La,resolve as tc}from"path";import gn from"process";import{existsSync as Lc,mkdirSync as UA,readdirSync as FA,writeFileSync as JA}from"fs";import{dirname as jA,resolve as Sn}from"path";import yf from"process";import{Buffer as ni}from"buffer";import{createCipheriv as Za,createDecipheriv as Ma,randomBytes as Ve}from"crypto";import{closeSync as pe,createReadStream as ic,createWriteStream as za,existsSync as Pe,fsyncSync as rc,openSync as nc,writeFileSync as Ga}from"fs";import{access as qa,constants as ec,mkdir as Ka,readdir as Qr,rename as fc,stat as Ni,unlink as tn,writeFile as ve}from"fs/promises";import{join as ji}from"path";import ft from"process";import{pipeline as xa}from"stream/promises";import{createGzip as sc}from"zlib";import _i from"process";import pt from"process";import{Buffer as Dt}from"buffer";import{createCipheriv as ka,createDecipheriv as Da,randomBytes as Xe}from"crypto";import{closeSync as Qe,createReadStream as lc,createWriteStream as ba,existsSync as rn,fsyncSync as cc,openSync as hc,writeFileSync as Va}from"fs";import{access as pa,constants as uc,mkdir as Pa,readdir as nn,rename as oc,stat as Wi,unlink as en,writeFile as tf}from"fs/promises";import{isAbsolute as va,join as Yi,resolve as Xa}from"path";import S from"process";import{pipeline as Qa}from"stream/promises";import{createGzip as ac}from"zlib";import Ii from"process";import Pt from"process";import fn from"process";import{existsSync as sn}from"fs";import{resolve as rf}from"path";import{existsSync as t$}from"fs";import{existsSync as i$,readdirSync as r$}from"fs";import{extname as nf,resolve as $c}from"path";import n$ from"process";import{join as e$,relative as f$,resolve as yc}from"path";import Cn from"process";import{Buffer as bt}from"buffer";import{createCipheriv as s$,createDecipheriv as l$,randomBytes as ef}from"crypto";import{closeSync as ff,createReadStream as wc,createWriteStream as c$,existsSync as ln,fsyncSync as mc,openSync as Ac,writeFileSync as h$}from"fs";import{access as u$,constants as dc,mkdir as o$,readdir as cn,rename as Ec,stat as Oi,unlink as hn,writeFile as sf}from"fs/promises";import{isAbsolute as a$,join as Hi,resolve as $$}from"path";import C from"process";import{pipeline as y$}from"stream/promises";import{createGzip as Tc}from"zlib";import Li from"process";import vt from"process";import on from"process";import{existsSync as an}from"fs";import{resolve as af}from"path";import{existsSync as Iy}from"fs";class Ic{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(!Vl(t))return!0;return pl(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=Vl(r)?pl(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 Oc{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 Ic,Bf=new Oc;var w$=Object.defineProperty,m$=(t)=>t;function A$(t,i){this[t]=m$.bind(null,i)}var d$=(t,i)=>{for(var r in i)w$(t,r,{get:i[r],enumerable:!0,configurable:!0,set:A$.bind(i,r)})},E$=(t,i)=>()=>(t&&(i=t(t=0)),i),Zc={};d$(Zc,{withErrorRecovery:()=>Gc,tryLoadConfig:()=>q$,loadConfigWithResult:()=>z$,loadConfig:()=>Dc,isRetryableError:()=>I$,isConfigNotFoundError:()=>Y$,isBunfigError:()=>qc,globalPerformanceMonitor:()=>rr,globalCache:()=>Zi,getEnvOrDefault:()=>O$,generateConfigTypes:()=>K$,defaultGeneratedDir:()=>th,defaultConfigDir:()=>Qc,deepMergeWithArrayStrategy:()=>jf,deepMerge:()=>Kc,createLibraryConfig:()=>x$,config:()=>G$,bunfigPlugin:()=>k$,applyEnvVarsToConfig:()=>Xi,TypeGenerationError:()=>gf,SchemaValidationError:()=>ir,PluginError:()=>Cf,PerformanceMonitor:()=>Ff,FileSystemError:()=>Tf,ErrorFactory:()=>ei,EnvVarError:()=>Nn,EnvProcessor:()=>In,ConfigValidator:()=>_f,ConfigValidationError:()=>df,ConfigNotFoundError:()=>Jn,ConfigMergeError:()=>Ef,ConfigLoader:()=>Wf,ConfigLoadError:()=>tr,ConfigFileLoader:()=>On,ConfigCache:()=>Uf,CacheUtils:()=>Vc,BunfigError:()=>Et,BrowserConfigError:()=>Sf,ArrayMergeStrategies:()=>vc});class Uf{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(!Pl(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=Pl(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 Ff{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 T$(t,i={}){let n=Object.keys(i).sort().map((e)=>`${e}:${i[e]}`).join("|");return n?`${t}:${n}`:t}function g$(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function S$(t){return t.getStats().size*2}function Jf(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&q(i[0])&&"id"in i[0]&&i[0].id===3&&q(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(q(i)&&q(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(q(t)&&"arr"in t&&Array.isArray(t.arr)&&q(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&q(i[0])&&q(t[0])){let n=[...i];for(let e of t)if(q(e)&&"name"in e){if(!n.find((s)=>q(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(q(e)&&"path"in e){if(!n.find((s)=>q(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(!q(i)||!q(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(q(e)&&q(r[n]))r[n]=Jf(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&q(e[0])&&q(r[n][0])){let f=[...e];for(let s of r[n])if(q(s)&&"name"in s){if(!f.find((l)=>q(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(q(s)&&"path"in s){if(!f.find((l)=>q(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(q(t)&&q(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 q(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function C$(t,i){if(!Lc(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 Jf(i,n)}catch{return null}}catch{return null}}async function R$({name:t="",cwd:i,defaultConfig:r}){let n=i||yf.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 C$(l,r);if(h!==null)return h}try{let s=Sn(n,"package.json");if(Lc(s)){let l=(await import(s))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return Jf(r,l)}catch{}}}catch{}return r}function B$(t,i={}){let r=gn.cwd();while(r.includes("storage"))r=tc(r,"..");let n=tc(r,t||"");if(i?.relative)return La(gn.cwd(),n);return n}async function U$(){try{let t=await R$({name:"clarity",defaultConfig:wn,cwd:gn.cwd(),endpoint:"",headers:{}});return{...wn,...t}}catch{return wn}}function x(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function F$(){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 Mc{async format(t){let i=await F$(),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:_i.pid,hostname:i(),environment:_i.env.NODE_ENV||"development",platform:_i.platform,version:_i.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_i.env.NODE_ENV||_i.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class 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={...mf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Mc,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:mf.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 qa(this.config.logDirectory,ec.F_OK|ec.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Ka(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 ve(this.currentLogFile,"",{mode:420});if(e=nc(this.currentLogFile,"a",420),Ga(e,l,{flag:"a"}),rc(e),e!==void 0)pe(e),e=void 0;if((await Ni(this.currentLogFile)).size===0){if(await ve(this.currentLogFile,l,{flag:"w",mode:420}),(await Ni(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<s-1){let o=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(e!==void 0)try{pe(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let u=l,o=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,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 ji(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ji(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return ji(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(x())return;if(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=Za("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=sc(),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(x())return;let t=await Ni(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let 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 u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ni(r).catch(()=>null))try{if(await fc(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 ve(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 Ni(r).catch(()=>null))await fc(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(ji(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=ic(t),n=za(i),e=sc();await xa(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=nc(this.currentLogFile,"r+");rc(t),pe(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 Qr(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await tn(ji(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 u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);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&&!x()){let h=pc[t],u=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:z.gray(s),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:z.green(s),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error(o),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(!x()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
|
|
68
|
-
`;if(c)l+=`${c}
|
|
69
|
-
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!x()){let 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&&!x()){let u=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:z.green("✓"),tag:u,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!x())console.error(h.trim());await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,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(x())throw Error("createReadStream is not supported in browser environments");if(!Pe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ic(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let 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=Ma("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 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);if(this.fancy&&!x()){let f=t.split(`
|
|
71
|
-
`),s=Math.max(...f.map((u)=>u.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((u)=>{let o=" ".repeat(s-u.length-2);return`│ ${u}${o} │`});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((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(l),showTimestamp:!1}))}else if(!x())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(x())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 u=i[c++];switch(h){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!x()){let s=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",c=z.blue("◐");console.error(`${c} ${s} ${z.cyan(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||x()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let 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||x())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,s)),c!==void 0)this.activeProgressBar.message=c;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=this.activeProgressBar.total,s!==void 0)this.activeProgressBar.message=s;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(s,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;ft.stdout.write(`${"\r".padEnd(ft.stdout.columns||80)}\r`),this.log(c,s),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||x()||!ft.stdout.isTTY)return;let 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}`:"",u=i||r===100?z.green("✓"):z.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${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||x()||!ft.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(x()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await 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=ji(this.config.logDirectory,n);if(t.before)try{if((await Ni(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}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&&I(i[0])&&"id"in i[0]&&i[0].id===3&&I(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(I(i)&&I(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(I(t)&&"arr"in t&&Array.isArray(t.arr)&&I(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&I(i[0])&&I(t[0])){let n=[...i];for(let e of t)if(I(e)&&"name"in e){if(!n.find((s)=>I(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(I(e)&&"path"in e){if(!n.find((s)=>I(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(!I(i)||!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(I(e)&&I(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&&I(e[0])&&I(r[n][0])){let f=[...e];for(let s of r[n])if(I(s)&&"name"in s){if(!f.find((l)=>I(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(I(s)&&"path"in s){if(!f.find((l)=>I(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 Nf(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(!I(i)||!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]=yn(s,f);else if(I(f)&&I(s))n[e]=Nf(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(I(t)&&I(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 I(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function un(t,i,r="replace"){if(!Hc(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 Nf(i,e,r)}catch{return null}}catch{return null}}function J$(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,u]of Object.entries(s)){let o=[...c,h],$=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),a=`${n}_${o.map($).join("_")}`,m=`${n}_${o.map((y)=>y.toUpperCase()).join("_")}`;if(r)lt.info(`Checking environment variable ${a} for config ${t}.${o.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[h]=f(u,o);else{let y=Qi.env[a]||Qi.env[m];if(y!==void 0){if(r)lt.info(`Using environment variable ${y?a:m} for config ${t}.${o.join(".")}`);if(typeof u==="number")l[h]=Number(y);else if(typeof u==="boolean")l[h]=y.toLowerCase()==="true";else if(Array.isArray(u))try{let A=JSON.parse(y);if(Array.isArray(A))l[h]=A;else l[h]=y.split(",").map((d)=>d.trim())}catch{l[h]=y.split(",").map((A)=>A.trim())}else l[h]=y}}}return l}return f(e)}async function N$({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)?J$(t,e,f):e,h=r||Qi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(f)lt.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let o=[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,ot(h,"config"),ot(h,".config"),n?ot(h,n):void 0].filter(Boolean)));for(let A of y){if(f)lt.info(`Searching for configuration in: ${A}`);let g=[ot(h,"config"),ot(h,".config")].concat(n?[ot(h,n)]:[]).includes(A)?[...o,...$,...a,...m]:[...$,...o,...m,...a];for(let O of g)for(let L of u){let H=ot(A,`${O}${L}`),oi=await un(H,l,c);if(oi!==null){if(f)lt.success(`Configuration loaded from: ${H}`);return oi}}}if(t){let A=ot(be(),".config",t),d=["config",`${t}.config`];if(i)d.push(`${i}.config`);if(f)lt.info(`Checking user config directory: ${A}`);for(let g of d)for(let O of u){let L=ot(A,`${g}${O}`),H=await un(L,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user config directory: ${L}`);return H}}}if(t){let A=ot(be(),".config"),d=[`.${t}.config`];if(i)d.push(`.${i}.config`);if(f)lt.info(`Checking user config directory for dotfile configs: ${A}`);for(let g of d)for(let O of u){let L=ot(A,`${g}${O}`),H=await un(L,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user config directory dotfile: ${L}`);return H}}}if(t){let A=be(),d=[`.${t}.config`,`.${t}`];if(i)d.push(`.${i}.config`),d.push(`.${i}`);if(f)lt.info(`Checking user home directory for dotfile configs: ${A}`);for(let g of d)for(let O of u){let L=ot(A,`${g}${O}`),H=await un(L,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user home directory: ${L}`);return H}}}try{let A=ot(h,"package.json");if(Hc(A)){let d=await import(A),g=d[t];if(!g&&i){if(g=d[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===d[t]?t:i}`);return Nf(l,g,c)}catch(O){if(f)lt.warn("Failed to merge package.json config:",O)}}}catch(A){if(f)lt.warn("Failed to load package.json:",A)}if(f)lt.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function j$(t,i={}){let r=Tn.cwd();while(r.includes("storage"))r=Ql(r,"..");let n=Ql(r,t||"");if(i?.relative)return Oa(Tn.cwd(),n);return n}async function _$(){try{let t=await N$({name:"clarity",alias:"logging",defaultConfig:An,cwd:Tn.cwd()});return{...An,...t||{}}}catch{return An}}function P(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function W$(){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 zc{async format(t){let i=await W$(),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:Ii.pid,hostname:i(),environment:Ii.env.NODE_ENV||"development",platform:Ii.platform,version:Ii.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ii.env.NODE_ENV||Ii.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}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={...Af},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new zc,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{...dn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...dn};return{...dn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Af.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 pa(this.config.logDirectory,uc.F_OK|uc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Pa(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 tf(this.currentLogFile,"",{mode:420});if(e=hc(this.currentLogFile,"a",420),Va(e,l,{flag:"a"}),cc(e),e!==void 0)Qe(e),e=void 0;if((await Wi(this.currentLogFile)).size===0){if(await tf(this.currentLogFile,l,{flag:"w",mode:420}),(await Wi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<s-1){let o=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(e!==void 0)try{Qe(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let u=l,o=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,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 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(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 Xe(16).toString("hex")}generateKey(){return Xe(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Xe(16),n=ka("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=ac(),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 Wi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let 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 u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Wi(r).catch(()=>null))try{if(await oc(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 tf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Wi(r).catch(()=>null))await oc(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(Yi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=lc(t),n=ba(i),e=ac();await Qa(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=hc(this.currentLogFile,"r+");cc(t),Qe(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(Yi(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 u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);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=Xa(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 o=this.options.showIcons===!1?"":Pc[t],$=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:B.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:B.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:o,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 u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
76
|
-
`;if(c)u+=`${c}
|
|
77
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let 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 u=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:u,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 lc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let 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=Da("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,o=Dt.allocUnsafe(u);return l.copy(o,0),h.copy(o,l.length),o.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)}┐`,u=`└${"─".repeat(l)}┘`,o=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:B.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(h),showTimestamp:!1})),o.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(u),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,(u,o)=>{if(o==="%")return"%";if(h>=i.length)return u;let $=i[h++];switch(o){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return u}}),h<i.length)r+=` ${i.slice(h).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).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}`:"",u=this.options.showIcons===!1?"":i||r===100?B.green("✓"):B.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${B.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${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=Yi(this.config.logDirectory,n);if(t.before)try{if((await Wi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}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 Gc(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 qc(t){return t instanceof Et}function Y$(t){return t instanceof Jn}function I$(t){if(qc(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 u=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return rr.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((u)=>this.formatEnvKey(u,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let u=fn.env[l]||(h?fn.env[h]:void 0);if(u!==void 0){if(n.verbose){let o=fn.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof Nn)throw o;throw ei.envVar(l,u,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 O$(t,i){let r=bc("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function Kc(t,i,r={}){return xc(t,i,r,new WeakMap)}function xc(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 kc(t,i,e,n);if(!Rt(i)||!Rt(t))return i;return M$(t,i,r,n)}function kc(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 H$(t,i);case"smart":return L$(t,i,n);default:return i}return i}function H$(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>wf(e,n)))r.push(n);return r}function L$(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Rt(i[0])&&Rt(t[0]))return Z$(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 Z$(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 M$(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]=xc(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=kc(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function jf(t,i,r="replace"){return Kc(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function wf(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(!wf(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(!wf(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=Zi.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()}`,u=await import(t+h),o=u.default||u,$="default"in u,a=Object.keys(u).length>0;if(!$&&!a)throw new tr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new tr(t,Error("Configuration must export a valid object"),"unknown");let A={config:jf(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Zi.setWithFileCheck("file",A,t,f);return A}catch(h){throw h instanceof Error?ei.configLoad(t,h):ei.configLoad(t,Error(String(h)))}};if(s)return rr.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(rf(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 Gc(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=rf(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=rf(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 _f{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 u=[],o=[],$={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 u.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:u,warnings:o}}};if(c)return await rr.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!t$(i))throw new ir(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 ir(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:Xc},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Wf{fileLoader=new On;envProcessor=new In;validator=new _f;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 u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!u&&(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&&($||u))throw l;if(o&&(!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:u=!1}=t,o=f||hi.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,o,s,c,h,u,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(a,$,l,n,u);let m=await this.loadHomeConfiguration(n,e,c,h,u,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,u);let y=await this.loadPackageJsonConfiguration(n,e,o,c,h,u,l);if(y)return $.push(at(o,"package.json")),this.finalizeResult(y,$,l,n,u);if($.push(...this.getAllSearchPaths(n,e,o,s)),i)throw ei.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,u),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,u=this.getLocalDirectories(r,n);for(let o of u){if(s)_t.info(`Searching for configuration in: ${o}`);let $=this.fileLoader.generateConfigPaths(t,o,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?Xi(t,r,e):r,c=[at(Ji(),".config",t),at(Ji(),".config"),Ji()];for(let l of c){if(e)_t.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(u){if(e)_t.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Xi(t,n,f):n;try{let l=at(r,"package.json");if(!$f(l))return null;let h=await import(l),u=h[t],o=t;if(!u&&i)u=h[i],o=i;if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)_t.success(`Configuration loaded from package.json: ${o}`);return{config:jf(c,u,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: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 ei.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Zi.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Zi.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(Ji(),".config",t),at(Ji(),".config"),Ji()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function gc(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 z$(t){return Xt.loadConfig({...t,__strictErrorHandling:!0})}async function Dc(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 G$(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"&&gc(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"&&gc(i)))return(await Xt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function q$(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 Xi(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,u]of Object.entries(s)){let o=[...c,h],$=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((y)=>y.toUpperCase()).join("")}`,`${e}_${o.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 u==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof u==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(u))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,o)}return l}return f(i)}function K$(t){let i=at(hi.cwd(),t.configDir),r=at(hi.cwd(),t.generatedDir),n=at(r,"config-types.ts");if(!$f(Xl(n)))_a(Xl(n),{recursive:!0,mode:511});let e=$f(i)?Wa(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${dy}
|
|
96
|
-
export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
|
|
97
|
-
`;Ya(n,f,{mode:438})}function x$(t){let i=null,r=null,n=()=>{if(!r)r=Dc(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 k$(t){let i=$c(n$.cwd(),t?.configDir||"./config");function r(){if(!i$(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=r$(i).filter((l)=>e.has(nf(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let u=nf(h).toLowerCase(),o=c.get(l);if(!o){c.set(l,h);continue}let $=nf(o).toLowerCase();if(f.indexOf(u)<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 u=$c(i,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${u}').default`}).join(`,
|
|
99
|
-
`)}
|
|
100
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
101
|
-
export type ConfigByName = ${c}
|
|
102
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
103
|
-
export type ConfigOf = Config
|
|
104
|
-
`}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var bc,Zi,rr,Vc,D$,b$,Sc,wn,mf,st,z,V$,Cc,p$,Rc,P$,v$,lf,X$,Bc,Uc,cf,Q$,ty,iy,ry,mn,pc,ny,lt,ey,fy,Fc,An,Af,v,B,sy,Jc,ly,Nc,cy,hy,hf,uy,jc,_c,oy,uf,ay,$y,yy,wy,my,dn,Pc,Ay,dy="0.15.6",Et,Jn,tr,df,Ef,Nn,Tf,gf,ir,Sf,Cf,ei,vc,Xc,_t,Xt,Qc,th,Ey=E$(async()=>{bc=import.meta.require,Zi=new Uf,rr=new Ff,Vc={createKey:T$,isEquivalent:g$,estimateMemoryUsage:S$},D$=Sn(yf.cwd(),"config"),b$=Sn(yf.cwd(),"src/generated"),Sc=gn.env.CLARITY_LOG_DIR||Ha(B$(),"logs"),wn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Sc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},mf=await U$(),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,V$=st.red,Cc=st.green,p$=st.yellow,Rc=st.blue,P$=st.magenta,v$=st.cyan,lf=st.white,X$=st.gray,Bc=st.bgRed,Uc=st.bgYellow,cf=st.bold,Q$=st.dim,ty=st.italic,iy=st.underline,ry=st.reset,mn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},pc={debug:"\uD83D\uDD0D",info:Rc("ℹ"),success:Cc("✓"),warning:Uc(lf(cf(" WARN "))),error:Bc(lf(cf(" ERROR ")))},ny=new Bn("stacks"),lt=new Bn("bunfig",{showTags:!0}),ey=ot(Qi.cwd(),"config"),fy=ot(Qi.cwd(),"src/generated"),Fc=Tn.env.CLARITY_LOG_DIR||Ia(j$(),"logs"),An={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Af=await _$(),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,sy=v.red,Jc=v.green,ly=v.yellow,Nc=v.blue,cy=v.magenta,hy=v.cyan,hf=v.white,uy=v.gray,jc=v.bgRed,_c=v.bgYellow,oy=v.bgGray,uf=v.bold,ay=v.dim,$y=v.italic,yy=v.underline,wy=v.strikethrough,my=v.reset,dn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Pc={debug:"\uD83D\uDD0D",info:Nc("ℹ"),success:Jc("✓"),warning:_c(hf(uf(" WARN "))),error:jc(hf(uf(" ERROR ")))},Ay=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})}},tr=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})}},Ef=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})}},Tf=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}},gf=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}},ir=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})}},Sf=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})}},Cf=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 tr(t,i,r)},configValidation(t,i,r){return new df(t,i,r)},configMerge(t,i,r,n){return new Ef(t,i,r,n)},envVar(t,i,r,n){return new Nn(t,i,r,n)},fileSystem(t,i,r){return new Tf(t,i,r)},typeGeneration(t,i,r){return new gf(t,i,r)},schemaValidation(t,i,r){return new ir(t,i,r)},browserConfig(t,i,r,n){return new Sf(t,i,r,n)},plugin(t,i,r){return new Cf(t,i,r)}},vc={replace:"replace",concat:"concat",smart:"smart"},Xc=/^https?:\/\//,_t=new Fn("bunfig",{showTags:!0}),Xt=new Wf,Qc=at(hi.cwd(),"config"),th=at(hi.cwd(),"src/generated")});function Ty(t,i={}){let r=Cn.cwd();while(r.includes("storage"))r=yc(r,"..");let n=yc(r,t||"");if(i?.relative)return f$(Cn.cwd(),n);return n}var gy=Cn.env.CLARITY_LOG_DIR||e$(Ty(),"logs"),ih={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},jn={...ih},Ad=(async()=>{try{let{loadConfig:t}=await Ey().then(()=>Zc),i=await t({name:"clarity",alias:"logging",defaultConfig:ih,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 Sy(){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 rh{async format(t){let i=await Sy(),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:Li.pid,hostname:i(),environment:Li.env.NODE_ENV||"development",platform:Li.platform,version:Li.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Li.env.NODE_ENV||Li.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var it={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},J=it,dd=it.red,Cy=it.green,Ed=it.yellow,Ry=it.blue,Td=it.magenta,gd=it.cyan,Wc=it.white,Sd=it.gray,By=it.bgRed,Uy=it.bgYellow,Cd=it.bgGray,Yc=it.bold,Rd=it.dim,Bd=it.italic,Ud=it.underline,Fd=it.strikethrough,Jd=it.reset,of={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Fy={debug:"\uD83D\uDD0D",info:Ry("ℹ"),success:Cy("✓"),warning:Uy(Wc(Yc(" WARN "))),error:By(Wc(Yc(" 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 rh,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 u$(this.config.logDirectory,dc.F_OK|dc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await o$(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 sf(this.currentLogFile,"",{mode:420});if(e=Ac(this.currentLogFile,"a",420),h$(e,l,{flag:"a"}),mc(e),e!==void 0)ff(e),e=void 0;if((await Oi(this.currentLogFile)).size===0){if(await sf(this.currentLogFile,l,{flag:"w",mode:420}),(await Oi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<s-1){let o=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(e!==void 0)try{ff(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let u=l,o=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,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 Hi(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 Hi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Hi(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 ef(16).toString("hex")}generateKey(){return ef(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=ef(16),n=s$("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=Tc(),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 Oi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let 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 u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Oi(r).catch(()=>null))try{if(await Ec(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 sf(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 Oi(r).catch(()=>null))await Ec(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(Hi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=wc(t),n=c$(i),e=Tc();await y$(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=Ac(this.currentLogFile,"r+");mc(t),ff(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(Hi(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()?J.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} ${J.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);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=J.underline(J.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)=>J.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>J.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>J.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>J.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>J.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(a$(i)||i.startsWith("./")||i.startsWith("../"))i=$$(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 o=this.options.showIcons===!1?"":Fy[t],$=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:J.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:J.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:o,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:J.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!X()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
106
|
-
`;if(c)u+=`${c}
|
|
107
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let 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?J.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":J.blue("◐"),tag:r,message:`${J.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 u=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":J.green("✓"),tag:u,message:`${f}${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 wc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let 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=l$("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,o=bt.allocUnsafe(u);return l.copy(o,0),h.copy(o,l.length),o.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)}┐`,u=`└${"─".repeat(l)}┘`,o=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:J.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:J.cyan(h),showTimestamp:!1})),o.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:J.cyan(u),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(`${J.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,(u,o)=>{if(o==="%")return"%";if(h>=i.length)return u;let $=i[h++];switch(o){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return u}}),h<i.length)r+=` ${i.slice(h).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${J.blue("◐")} `;console.error(`${h}${l} ${J.cyan(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=J.green("━".repeat(n)),s=J.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||r===100?J.green("✓"):J.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${J.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${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=Hi(this.config.logDirectory,n);if(t.before)try{if((await Oi(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 Nd=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 nh 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 eh 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 fh 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 Yf 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 sh 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 lh 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 ch 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 hh 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 Mi={configNotFound(t,i,r){return new nh(t,i,r)},configLoad(t,i,r){return new _n(t,i,r)},configValidation(t,i,r){return new eh(t,i,r)},configMerge(t,i,r,n){return new fh(t,i,r,n)},envVar(t,i,r,n){return new Yf(t,i,r,n)},fileSystem(t,i,r){return new sh(t,i,r)},typeGeneration(t,i,r){return new lh(t,i,r)},schemaValidation(t,i,r){return new Wn(t,i,r)},browserConfig(t,i,r,n){return new ch(t,i,r,n)},plugin(t,i,r){return new hh(t,i,r)}};async function Jy(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 If{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 u=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Bf.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((u)=>this.formatEnvKey(u,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let u=on.env[l]||(h?on.env[h]:void 0);if(u!==void 0){if(n.verbose){let o=on.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof Yf)throw o;throw Mi.envVar(l,u,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 Mi.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(on.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 Ny(t,i,r={}){return uh(t,i,r,new WeakMap)}function uh(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 oh(t,i,e,n);if(!Bt(i)||!Bt(t))return i;return Yy(t,i,r,n)}function oh(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 jy(t,i);case"smart":return _y(t,i,n);default:return i}return i}function jy(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Rf(e,n)))r.push(n);return r}function _y(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Bt(i[0])&&Bt(t[0]))return Wy(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 Wy(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 Yy(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]=uh(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=oh(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function ah(t,i,r="replace"){return Ny(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Rf(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(!Rf(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(!Rf(t[e],i[e]))return!1}return!0}return!1}function Bt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class $h{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()}`,u=await import(t+h),o=u.default||u,$="default"in u,a=Object.keys(u).length>0;if(!$&&!a)throw new _n(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new _n(t,Error("Configuration must export a valid object"),"unknown");let A={config:ah(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)En.setWithFileCheck("file",A,t,f);return A}catch(h){throw h instanceof Error?Mi.configLoad(t,h):Mi.configLoad(t,Error(String(h)))}};if(s)return Bf.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(af(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 Jy(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=af(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=af(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 Oy=/^https?:\/\//;class yh{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 u=[],o=[],$={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 u.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:u,warnings:o}}};if(c)return await Bf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!Iy(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:Oy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Vt=new Hn("bunfig",{showTags:!0});function Hy(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class wh{fileLoader=new $h;envProcessor=new If;validator=new yh;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 u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!u&&(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&&($||u))throw l;if(o&&(!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:u=!1}=t,o=f||Yn.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,o,s,c,h,u,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(a,$,l,n,u);let m=await this.loadHomeConfiguration(n,e,c,h,u,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,u);let y=await this.loadPackageJsonConfiguration(n,e,o,c,h,u,l);if(y)return $.push(Ct(o,"package.json")),this.finalizeResult(y,$,l,n,u);if($.push(...this.getAllSearchPaths(n,e,o,s)),i)throw Mi.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,u),warnings:[`No configuration file found for "${n}"${Hy(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,u=this.getLocalDirectories(r,n);for(let o of u){if(s)Vt.info(`Searching for configuration in: ${o}`);let $=this.fileLoader.generateConfigPaths(t,o,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(Fi(),".config",t),Ct(Fi(),".config"),Fi()];for(let l of c){if(e)Vt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(u){if(e)Vt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}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(!Na(l))return null;let h={};try{h=JSON.parse(ja(l,"utf8"))}catch($){if(f)Vt.warn("Failed to parse package.json:",[$ instanceof Error?$:Error(String($))]);return null}let u=h[t],o=t;if(!u&&i){let $=Array.isArray(i)?i:[i];for(let a of $){if(!a)continue;if(h[a]){u=h[a],o=a;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)Vt.success(`Configuration loaded from package.json: ${o}`);return{config:ah(c,u,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 Mi.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(Fi(),".config",t),Ct(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)}}var Id=new wh;function $n(t,i,r=!1){let n=new If,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let o=[...c,h],$=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((y)=>y.toUpperCase()).join("")}`,`${e}_${o.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 u==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof u==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(u))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,o)}return l}return f(i)}var Od=Ct(Yn.cwd(),"config"),Hd=Ct(Yn.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Ly={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Hf(Of(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Hf(Of(),".stacks","ssl","stacks.localhost.crt"),keyPath:Hf(Of(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var mh=Ly;import{execSync as er}from"node:child_process";import{homedir as qy}from"node:os";import{join as Ky}from"node:path";import{execSync as Ln}from"node:child_process";function Ah(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 Ah(i)}catch{return null}}function Zy(t){try{return Ln(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function My(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 zy(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 Gy(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",ui="/Library/Keychains/System.keychain",Lf="rpx.localhost";function fr(){return Ky(qy(),"Library/Keychains/login.keychain-db")}function Zf(){return[ui,fr()]}function dh(t,i=Lf){let r=er(`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??Lf,n=t.keychains??Zf();for(let e of n)for(let f of dh(e,r)){if(f===i)continue;try{if(e.startsWith("/Library"))nr(`security delete-certificate -Z ${f} "${e}"`);else er(`security delete-certificate -Z ${f} "${e}"`,{stdio:"ignore"});w("ssl",`Removed stale Root CA ${f} from ${e}`,t.verbose)}catch{}}}function sr(t,i,r){if(process.platform!=="darwin")return lr(t,r);try{let e=er(`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 lr(t,i){let r=Zn(t);if(!r)return!1;for(let n of Zf())try{let e=er(`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 Mf(t,i){if(process.platform!=="darwin")return!1;let r=i.serverName;Mn({caPath:t,commonName:i.commonName,verbose:i.verbose});let n=fr();try{er(`security add-trusted-cert ${fi} -k "${n}" "${t}"`,{stdio:"ignore"})}catch{}try{nr(`security add-trusted-cert ${fi} -k ${ui} "${t}"`)}catch{return!1}return sr(t,r,{verbose:i.verbose})||lr(t,{verbose:i.verbose})}var si=null,xy="rpx-root-ca.crt",ky="rpx-root-ca.key";function qf(t){return{caCertPath:Q(t,xy),caKeyPath:Q(t,ky)}}function c1(t){return{certPath:Q(t,"rpx.localhost.crt"),keyPath:Q(t,"rpx.localhost.key"),caCertPath:Q(t,"rpx.localhost.ca.crt"),rootCA:qf(t)}}async function Dy(t,i){try{let[r,n]=await Promise.all([D.readFile(t.caCertPath,"utf8"),D.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 Eh(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 Rh(t){let r=Gf(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 Th(t){let i=new Set;if(zn(t))t.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";Eh(n).forEach((e)=>i.add(e))});else if(Sh(t)){let r=t.to||"rpx.localhost";Eh(r).forEach((n)=>i.add(n))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function h1(t){w("ssl","Loading SSL configuration",t.verbose);let i={...mh,...t};if(t.https=xf(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 D.readFile(t.https?.keyPath,"utf8"),n=await D.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 u1(t,i){if(Yt.platform==="darwin")return by(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 by(t,i){if(Yt.platform!=="darwin")return!1;let r=i?.serverName??"rpx.localhost",n=i?.verbose??!1;try{if(sr(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),Mf(t,{serverName:r,verbose:n})}catch{return!1}}async function Bh(t){if(si&&!t.forceRegenerate){w("ssl","Using cached SSL configuration",t.verbose);return}Vy();let i=zn(t)?t.proxies.map((u)=>u.to):[t.to];w("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let r=xf(t,t.verbose),n=r.basePath||Q(Gn(),".stacks","ssl");await D.mkdir(n,{recursive:!0});let e=qf(n),f=await Dy(e,t.verbose),s=!1;if(!f){if(t.verbose)Z.info("Generating Root CA certificate (one-time)...");f=await xe(r);try{await Promise.all([D.writeFile(e.caCertPath,f.certificate),D.writeFile(e.caKeyPath,f.privateKey,{mode:384})]),s=!0,w("ssl",`Persisted Root CA at ${e.caCertPath}`,t.verbose)}catch(u){throw w("ssl",`Error saving Root CA files: ${u}`,t.verbose),Error(`Failed to save Root CA files: ${u}`)}}else w("ssl",`Reusing existing Root CA from ${e.caCertPath}`,t.verbose);if(t.verbose)Z.info(`Generating host certificate for: ${i.join(", ")}`);let c=await ke({...r,rootCA:{certificate:f.certificate,privateKey:f.privateKey}});try{await Promise.all([D.writeFile(r.certPath,c.certificate),D.writeFile(r.keyPath,c.privateKey),D.writeFile(r.caCertPath,f.certificate)]),w("ssl","Certificate files saved successfully",t.verbose)}catch(u){throw w("ssl",`Error saving certificate files: ${u}`,t.verbose),Error(`Failed to save certificate files: ${u}`)}if(s?!1:await Uh(e.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(w("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)Z.success("Root CA is already trusted in system trust store");if(si={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)Z.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)Z.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 u=fr();try{zi(`security add-trusted-cert ${fi} -k "${u}" "${e.caCertPath}"`,{stdio:"ignore"})}catch{}if(nr(`security add-trusted-cert ${fi} -k ${ui} "${e.caCertPath}"`),t.verbose)Z.success("Successfully added Root CA to system trust store");h=!0;let o=Q(n,"trust-rpx-cert.sh"),$=`#!/bin/bash
|
|
129
|
-
echo "Trusting RPX Root CA"
|
|
130
|
-
sudo security add-trusted-cert ${fi} -k ${ui} "${e.caCertPath}"
|
|
131
|
-
echo "Root CA trusted! Please restart your browser."
|
|
132
|
-
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
133
|
-
`;await D.writeFile(o,$,{mode:493})}catch(u){if(t.verbose)Z.warn(`Could not add Root CA to trust store automatically: ${u}`);let o=Q(n,"trust-rpx-cert.sh"),$=`#!/bin/bash
|
|
134
|
-
echo "Trusting RPX Root CA"
|
|
135
|
-
sudo security add-trusted-cert ${fi} -k ${ui} "${e.caCertPath}"
|
|
136
|
-
echo "Root CA trusted! Please restart your browser."
|
|
137
|
-
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
138
|
-
`;if(await D.writeFile(o,$,{mode:493}),t.verbose)Z.info(`Created a trust helper script at: ${o}`),Z.info(`If you're still having certificate issues, run: sh ${o}`)}else if(Yt.platform==="linux")try{let{exec:u}=await import("node:child_process"),o="/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(zf.tmpdir(),`rpx-trust-${Date.now()}.sh`);await D.writeFile(a,$,{mode:493}),await new Promise((m)=>{u(`sudo bash "${a}"`,(y)=>{if(y){if(t.verbose)Z.warn(`Could not trust certificates: ${y}`);m(!1)}else{if(t.verbose)Z.success("Successfully added certificates to system trust store");m(!0)}})}),await D.unlink(a).catch(()=>{}),h=!0}catch(u){if(t.verbose)Z.warn(`Failed to trust certificates: ${u}`)}else if(Yt.platform==="win32")try{let u=`
|
|
144
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${e.caCertPath.replace(/\//g,"\\")}")
|
|
145
|
-
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
146
|
-
$store.Open("ReadWrite")
|
|
147
|
-
$store.Add($cert)
|
|
148
|
-
$store.Close()
|
|
149
|
-
Write-Host "Root CA trusted successfully!"
|
|
150
|
-
`,o=Q(zf.tmpdir(),"rpx-trust.ps1");if(await D.writeFile(o,u),zi(`powershell -ExecutionPolicy Bypass -File "${o}"`),t.verbose)Z.success("Successfully added certificate to Windows trust store");h=!0}catch(u){if(t.verbose)Z.warn(`Could not trust certificate: ${u}`)}else try{await De(c,f.certificate,r),h=!0}catch(u){if(t.verbose)Z.warn(`Could not add certificate to trust store: ${u}`)}if(si={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)Z.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!h&&t.verbose)Z.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),Z.warn("This will bypass the warning and you should only need to do it once")}function Vy(){si=null}async function Kf(t){if(!t)return null;if(si)return si;let i=xf(t);try{let[r,n,e]=await Promise.all([D.access(i.keyPath).then(()=>!0).catch(()=>!1),D.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?D.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!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=qf(l);if(!(c?await Uh(h.caCertPath,t):!0))return w("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[o,$,a]=await Promise.all([D.readFile(i.keyPath,"utf8"),D.readFile(i.certPath,"utf8"),e&&i.caCertPath?D.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(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"),A=new m($).subjectAltName||"",g=t.proxies.map((O)=>O.to).filter((O)=>!A.includes(`DNS:${O}`));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:o,cert:$,ca:a},si}catch(r){return w("ssl",`Error checking existing certificates: ${r}`,t.verbose),null}}function xf(t,i){let r=Gf(t);w("ssl",`Primary domain: ${r}`,i);let n=Rh(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(Th(t)).map((c)=>({type:2,value:c}))};if(gh(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(Th(t)).map((f)=>({type:2,value:f}))}}async function o1(t,i){let r=Rh({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)=>Ch(e,i)))}async function Uh(t,i){try{if(w("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),Yt.platform==="darwin"){if(i?.serverName)return sr(t,i.serverName,{verbose:i.verbose});return lr(t,{verbose:i.verbose})}else if(Yt.platform==="win32")try{let n=zi(`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(zi(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=zi(`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(zi(`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 Jh(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=Fh(n.pathname,s.pathRewrites);if(h)c=h.targetHost,l=h.targetPath,w("request",`Path rewrite: ${n.pathname} → ${c}${l}`,i);let u=`http://${c}${l}${n.search}`;try{let o=new Headers(r.headers);if(o.set("host",c),s.changeOrigin)o.set("origin",`http://${s.sourceHost}`);o.set("x-forwarded-for","127.0.0.1"),o.set("x-forwarded-proto","https"),o.set("x-forwarded-host",f);let $=await fetch(u,{method:r.method,headers:o,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(o){return w("request",`Proxy error for ${f}: ${o}`,i),new Response(`Proxy Error: ${o}`,{status:502})}}}import*as qn from"node:fs";import*as $t from"node:fs/promises";import{homedir as py}from"node:os";import*as kf from"node:path";import*as Kn from"node:process";var Py=/^[a-zA-Z0-9._-]+$/;function qi(){return kf.join(py(),".stacks","rpx","registry.d")}function Df(t){return typeof t==="string"&&t.length>0&&t.length<=128&&Py.test(t)}function bf(t,i){if(!Df(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return kf.join(t,`${i}.json`)}function It(t){if(!Number.isInteger(t)||t<=0)return!1;try{return Kn.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function Nh(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"&&Df(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 T1(t,i=qi(),r){if(!Nh(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await vy(i);let n=bf(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 Xy(t,i=qi(),r){let n=bf(i,t);try{await $t.unlink(n),w("registry",`removed entry ${t}`,r)}catch(e){if(e.code!=="ENOENT")throw e}}async function Qy(t,i=qi(),r){let n=bf(i,t);try{let e=await $t.readFile(n,"utf8"),f=JSON.parse(e);if(!Nh(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 Gi(t=qi(),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(!Df(f))continue;let s=await Qy(f,t,i);if(s)n.push(s)}return n}async function Vf(t=qi(),i){let r=await Gi(t,i),n=0;for(let e of r){if(e.pid===void 0)continue;if(!It(e.pid))w("registry",`GC: pid ${e.pid} for ${e.id} is dead, removing`,i),await Xy(e.id,t,i).catch(()=>{}),n++}return n}function jh(t,i={}){let r=i.dir??qi(),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,u=(A)=>{return JSON.stringify(A.map((d)=>({id:d.id,from:d.from,to:d.to,pid:d.pid,pathRewrites:d.pathRewrites,cleanUrls:d.cleanUrls,changeOrigin:d.changeOrigin})).sort((d,g)=>d.id.localeCompare(g.id)))},o=()=>{if(s=null,c)return;Gi(r,f).then((A)=>{return l=u(A),t(A)}).catch((A)=>{w("registry",`watcher onChange failed: ${A}`,f)})},$=()=>{if(c)return;if(s)clearTimeout(s);s=setTimeout(o,n)},m=setInterval(()=>{if(c||h)return;h=!0,Gi(r,f).then((A)=>{if(u(A)!==l)$()}).catch((A)=>{w("registry",`watcher poll failed: ${A}`,f)}).finally(()=>{h=!1})},e),y=qn.watch(r,{persistent:!0},(A,d)=>{if(d&&/\.tmp\.\d+\.\d+$/.test(d))return;$()});return y.on("error",(A)=>{w("registry",`watcher error: ${A}`,f)}),$(),{close:()=>{if(c=!0,s)clearTimeout(s);clearInterval(m),y.close()}}}var tw=5000;function yt(){return Ot.join(Pf(),".stacks","rpx")}function xn(t=yt()){return Ot.join(t,"daemon.pid")}async function Ki(t=yt()){try{let i=await Lt.readFile(xn(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 iw(t=yt()){let i=await Ki(t);return i!==null&&It(i)}async function rw(t=yt()){await Lt.mkdir(t,{recursive:!0});let i=xn(t);while(!0){try{let n=await Lt.open(i,"wx");try{await n.write(`${U.pid}
|
|
151
|
-
`)}finally{await n.close()}return i}catch(n){if(n.code!=="EEXIST")throw n}let r=await Ki(t);if(r!==null&&It(r))throw Error(`rpx daemon already running (pid=${r})`);await Lt.unlink(i).catch(()=>{})}}async function cr(t=yt()){await Lt.unlink(xn(t)).catch(()=>{})}function nw(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 ew(t){return t.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??t[0]??"rpx.localhost"}async function fw(t,i){let r=await Gi(i,t.verbose),n=[...new Set(r.map((u)=>u.to))],e=ew(n),f=[...new Set([e,...n,"rpx.localhost"])],s=Ot.join(Pf(),".stacks","ssl"),c=Ot.join(s,"rpx.localhost.crt"),l={https:typeof t.https==="object"?{...t.https,certPath:c,keyPath:Ot.join(s,"rpx.localhost.key"),commonName:e}:{certPath:c,keyPath:Ot.join(s,"rpx.localhost.key"),caCertPath:Ot.join(s,"rpx.localhost.ca.crt"),commonName:e},verbose:t.verbose,regenerateUntrustedCerts:!0,...f.length>1?{proxies:f.map((u)=>({from:"localhost:1",to:u}))}:{to:e,from:"localhost:1"}},h=await Kf(l);if(!h)w("daemon","no usable cert on disk, generating one",t.verbose),await Bh(l),h=await Kf(l);if(!h)throw Error("failed to bootstrap TLS for rpx daemon");return h}async function sw(t,i,r,n){let e=U.env.SUDO_PASSWORD,f=U.env.HOME??Pf(),s=[U.execPath,...U.argv.slice(1)],c=[`HOME=${f}`,`PATH=${U.env.PATH??""}`];if(n)c.push("RPX_VERBOSE=1");let l=e?["-S","-p","","env",...c,...s]:["-n","env",...c,...s];w("daemon",`elevating daemon via sudo for privileged ports ${i}/${r}`,n);let h=_h("sudo",l,{detached:!0,stdio:["pipe","ignore","ignore"]}),u=null,o=null;if(h.once("error",(m)=>{u=m}),h.once("exit",(m)=>{o=m??0}),e&&h.stdin)h.stdin.write(`${e}
|
|
152
|
-
`),h.stdin.end();h.unref();let $=xn(t),a=Date.now()+15000;while(Date.now()<a){if(u)throw u;let m=await Ki(t);if(m!==null&&It(m)){if(n)Z.success(`rpx daemon elevated to root (pid=${m}, https on :${i})`);return{httpsPort:i,httpPort:r,pidPath:$,done:Promise.resolve(),stop:async()=>{try{U.kill(m,"SIGTERM")}catch{}}}}if(o!==null&&o!==0)throw Error(`rpx daemon could not elevate to bind :${i} (sudo exited ${o}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((y)=>setTimeout(y,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${t})`)}async function _1(t={}){let i=t.verbose??!1,r=t.rpxDir??yt(),n=t.registryDir??Ot.join(r,"registry.d"),e=t.httpsPort??443,f=t.httpPort??80,s=t.hostname??"0.0.0.0",c=t.gcIntervalMs??tw,l=e>0&&e<1024||f>0&&f<1024,h=typeof U.getuid==="function"&&U.getuid()===0;if(U.platform!=="win32"&&l&&!h)return sw(r,e,f,i);let u=await rw(r),o=new Map,$=(N)=>o.get(N);function a(N){let Ht=new Map;for(let ar of N)Ht.set(ar.to,nw(ar));o=Ht,w("daemon",`routing table now covers ${Ht.size} host(s): ${Array.from(Ht.keys()).join(", ")||"<empty>"}`,i)}await Vf(n,i).catch((N)=>{w("daemon",`initial gc failed: ${N}`,i)});let m=await Gi(n,i);a(m),await ur({rpxDir:r,verbose:i}).catch((N)=>{w("daemon",`DNS reconcile on start failed: ${N}`,i)}),await pf(m,{rpxDir:r,verbose:i,ownerPid:U.pid}).catch((N)=>{w("daemon",`DNS setup on start failed: ${N}`,i)});let y=await fw(t,n),A=Bun.serve({port:e,hostname:s,tls:{key:y.key,cert:y.cert,ca:y.ca,requestCert:!1,rejectUnauthorized:!1},fetch:Jh($,i),error(N){return w("daemon",`https server error: ${N}`,i),new Response(`Server Error: ${N.message}`,{status:500})}}),d=null;if(f>0)d=Bun.serve({port:f,hostname:s,fetch(N){let Ht=new URL(N.url),ar=(N.headers.get("host")??Ht.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${ar}${Ht.pathname}${Ht.search}`}})}});if(i)Z.success(`rpx daemon listening on https://${s}:${e}${d?` (http→https on :${f})`:""}`),Z.info(`pid file: ${u}`),Z.info(`registry: ${n}`);let g=jh((N)=>{a(N),pf(N,{rpxDir:r,verbose:i,ownerPid:U.pid}).catch((Ht)=>{w("daemon",`DNS sync on registry change failed: ${Ht}`,i)})},{dir:n,verbose:i}),O=setInterval(()=>{Vf(n,i).then((N)=>{if(N>0)w("daemon",`gc reaped ${N} stale entries`,i)}).catch((N)=>{w("daemon",`periodic gc failed: ${N}`,i)})},c);if(typeof O.unref==="function")O.unref();let L=!1,H,oi=new Promise((N)=>{H=N});async function fs(){if(L)return oi;if(L=!0,clearInterval(O),g.close(),A.stop(!1),d?.stop(!1),await hr({rpxDir:r,verbose:i}).catch((N)=>{w("daemon",`DNS teardown failed: ${N}`,i)}),await cr(r),i)Z.info("rpx daemon stopped");return H(),oi}let ss=(N)=>{w("daemon",`received ${N}, shutting down`,i),fs().catch(()=>{})};return U.once("SIGINT",ss),U.once("SIGTERM",ss),{stop:fs,done:oi,httpsPort:typeof A.port==="number"?A.port:e,httpPort:d&&typeof d.port==="number"?d.port:f,pidPath:u}}function lw(){let t=U.execPath,i=Ot.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&U.argv[1])return[t,U.argv[1],"daemon:start"];return[t,"daemon:start"]}async function W1(t={}){let i=t.rpxDir??yt(),r=t.verbose??!1;await ur({rpxDir:i,verbose:r}).catch((u)=>{w("daemon",`DNS reconcile before ensureDaemonRunning: ${u}`,r)});let n=await Ki(i);if(n!==null&&It(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 cr(i);await Lt.mkdir(i,{recursive:!0});let e=t.spawnCommand??lw();if(e.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");w("daemon",`spawning daemon: ${e.join(" ")}`,r);let f=_h(e[0],e.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??U.cwd(),env:t.spawnEnv?{...U.env,...t.spawnEnv}:U.env});f.unref();let s=null;f.once("error",(u)=>{s=u});let c=t.startupTimeoutMs??5000,l=t.pollIntervalMs??50,h=Date.now()+c;while(Date.now()<h){if(s)throw s;let u=await Ki(i);if(u!==null&&It(u))return w("daemon",`daemon registered with pid=${u}`,r),{pid:u,spawned:!0};await new Promise((o)=>setTimeout(o,l))}if(s)throw s;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${i})`)}async function Y1(t={}){let i=t.rpxDir??yt(),r=t.verbose??!1,n=t.timeoutMs??5000,e=t.pollIntervalMs??50,f=t.forceAfterTimeout??!0,s=await Ki(i);if(s===null||!It(s)){if(s!==null)await cr(i);return await ur({rpxDir:i,verbose:r}).catch(()=>{}),{stopped:!1,pid:s,forced:!1}}try{U.kill(s,"SIGTERM")}catch(l){if(l.code==="ESRCH")return await cr(i),{stopped:!1,pid:s,forced:!1};throw l}let c=Date.now()+n;while(Date.now()<c){if(!It(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{U.kill(s,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}return await cr(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 I1(t={}){let i=t.rpxDir??yt();if(await iw(i))return;await ur({rpxDir:i,verbose:t.verbose})}import*as li from"node:fs/promises";import{homedir as cw}from"node:os";import*as vf from"node:path";var kn=1,hw="dns-state.json",Wh=["com","test","dev","app","page","local","localhost","example","invalid"];function Yh(){return vf.join(cw(),".stacks","rpx")}function Xf(t=Yh()){return vf.join(t,hw)}async function Dn(t=Yh()){try{let i=await li.readFile(Xf(t),"utf8"),r=JSON.parse(i);if(r.version!==kn||!Array.isArray(r.resolvers))return null;return{version:kn,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 Ih(t,i){await li.mkdir(t,{recursive:!0}),await li.writeFile(Xf(t),`${JSON.stringify(i,null,2)}
|
|
153
|
-
`,"utf8")}async function Qf(t){await li.rm(Xf(t),{force:!0})}function Oh(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 uw(t){let i=Oh(t);if(!i)return null;let r=i.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function ts(t){let i=new Set;for(let r of t){let n=uw(r);if(n)i.add(n)}return Array.from(i).sort()}function is(t){let i=new Set;for(let r of t){let n=Oh(r);if(n)i.add(n)}return Array.from(i).sort()}var rs=15353,aw="# managed-by: rpx",Zh="/etc/resolver",wt=null,bn=new Set;function $w(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 Mh(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}=Mh(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 yw(t,i){let{name:r,newOffset:n}=Mh(t,i),e=t.readUInt16BE(n),f=t.readUInt16BE(n+2);return{question:{name:r,type:e,class:f},newOffset:n+4}}function Vn(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 ww(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(Vn(i.name));let f=Buffer.alloc(4);f.writeUInt16BE(i.type,0),f.writeUInt16BE(i.class,2),n.push(f),n.push(Vn(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,Vn(i.name),f]);return Buffer.concat(n)}function mw(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(Vn(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 Aw(t,i){if(Qt.platform!=="darwin")return!1;let r=is(t);if(r.length===0)return!1;if(wt){for(let n of r)bn.add(n);return w("dns","DNS server already running — merged domains",i),!0}return bn=new Set(r),new Promise((n)=>{wt=ow.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=$w(e),{question:c}=yw(e,12);w("dns",`Query for ${c.name} type ${c.type} from ${f.address}`,i);let l=c.name.toLowerCase(),h=!1;for(let o of bn)if(l===o||l.endsWith(`.${o}`)){h=!0;break}let u;if(h&&(c.type===1||c.type===28))u=ww(s.id,c,"127.0.0.1"),w("dns",`Responding with localhost for ${c.name}`,i);else u=mw(s.id,c),w("dns",`NXDOMAIN for ${c.name}`,i);wt?.send(u,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(rs,"127.0.0.1")}catch(e){w("dns",`Failed to bind DNS server: ${e}`,i),n(!1)}})}function zh(t){if(wt)w("dns","Stopping DNS server",t),wt.close(),wt=null,bn=new Set}function K1(){return wt!==null}function dw(){return`${aw}
|
|
154
|
-
nameserver 127.0.0.1
|
|
155
|
-
port ${rs}
|
|
156
|
-
`}function or(t){return Lh.join(Zh,t)}function Ew(t){return t.includes("127.0.0.1")&&t.includes(String(rs))}async function Tw(t){try{return await Hh.readFile(or(t),"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ns(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 gw(t,i){let{execSudoSync:r}=await import("./chunk-747af2w4.js"),n=dw().replace(/\n/g,"\\n"),e=`bash -c 'mkdir -p ${Zh} && printf "%b" "${n}" > ${or(t)}'`;r(e),w("dns",`Created ${or(t)}`,i)}async function Sw(t,i){let{execSudoSync:r}=await import("./chunk-747af2w4.js");r(`rm -f ${or(t)}`),w("dns",`Removed ${or(t)}`,i)}async function x1(t,i){return qh({domains:i??[],verbose:t})}async function Cw(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 gw(n,i);return await ns(i),!0}catch(n){return w("dns",`Failed to create resolver file: ${n}`,i),!1}}async function es(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 Sw(n,i);await ns(i)}catch(n){w("dns",`Failed to remove resolver files: ${n}`,i)}}async function Gh(t){if(Qt.platform!=="darwin")return[];let i=[];for(let r of Wh){let n=await Tw(r);if(n&&Ew(n))await es([r],t),i.push(r)}return i}async function qh(t){let i=t.rpxDir??yt(),r=is(t.domains);if(r.length===0)return!1;let n=ts(r);if(!await Aw(r,t.verbose))return!1;if(!await Cw(n,t.verbose))return!1;let s={version:kn,resolvers:n,domains:r,ownerPid:t.ownerPid??Qt.pid,updatedAt:new Date().toISOString()};return await Ih(i,s),!0}async function pf(t,i={}){let r=t.map((l)=>l.to).filter(Boolean),n=i.rpxDir??yt(),e=ts(r),c=((await Dn(n))?.resolvers??[]).filter((l)=>!e.includes(l));if(c.length>0)await es(c,i.verbose);if(e.length===0){zh(i.verbose),await Qf(n);return}await qh({domains:r,rpxDir:n,verbose:i.verbose,ownerPid:i.ownerPid??Qt.pid})}async function hr(t={}){let i=t.rpxDir??yt();zh(t.verbose);let n=(await Dn(i))?.resolvers??[];await es(n,t.verbose),await Gh(t.verbose),await Qf(i)}async function k1(t){await hr({verbose:t})}async function ur(t={}){let i=t.rpxDir??yt(),r=await Dn(i),n=r?.ownerPid!=null&&It(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 Gh(t.verbose);if(e.length>0)w("dns",`reconcile: removed legacy TLD resolvers: ${e.join(", ")}`,t.verbose);await ns(t.verbose)}
|
|
157
|
-
export{Z as a,mh as b,Ah as c,Zn as d,Zy as e,My as f,zy as g,Gy as h,fi as i,ui as j,Lf as k,fr as l,Zf as m,dh as n,Mn as o,sr as p,lr as q,Mf as r,qf as s,c1 as t,h1 as u,u1 as v,Bh as w,Vy as x,Kf as y,xf as z,o1 as A,Uh as B,Jh as C,qi as D,Df as E,It as F,T1 as G,Xy as H,Qy as I,Gi as J,Vf as K,jh as L,kn as M,Wh as N,Oh as O,uw as P,ts as Q,is as R,rs as S,aw as T,Aw as U,zh as V,K1 as W,or as X,Ew as Y,x1 as Z,Gh as _,qh as $,pf as aa,hr as ba,k1 as ca,ur as da,yt as ea,xn as fa,Ki as ga,iw as ha,rw as ia,cr as ja,_1 as ka,lw as la,W1 as ma,Y1 as na,I1 as oa};
|