@stacksjs/rpx
Version:
A modern and smart reverse proxy.
12 lines • 650 kB
JavaScript
#!/usr/bin/env bun
// @bun
#!/usr/bin/env bun
import{createRequire as q6}from"node:module";var G6=Object.defineProperty;var K6=(w)=>w;function F6(w,$){this[w]=K6.bind(null,$)}var fB=(w,$)=>{for(var Y in $)G6(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:F6.bind($,Y)})};var t=(w,$)=>()=>(w&&($=w(w=0)),$);var b=q6(import.meta.url);import{existsSync as DB,statSync as xB}from"fs";import{existsSync as HK,mkdirSync as L4,readdirSync as _4,readFileSync as RK,writeFileSync as S4}from"fs";import{homedir as $1}from"os";import{dirname as h4,resolve as Xw}from"path";import gA from"process";import{existsSync as PB,statSync as bB}from"fs";import{existsSync as pJ,mkdirSync as MK,readdirSync as IK,writeFileSync as VK}from"fs";import{homedir as Y1}from"os";import{dirname as uB,resolve as m0}from"path";import u$ from"process";import{join as CK,relative as yK,resolve as cB}from"path";import SA from"process";import{existsSync as Mj,mkdirSync as g4,readdirSync as d4,writeFileSync as l4}from"fs";import{homedir as OJ}from"os";import{dirname as r4,resolve as i0}from"path";import qY from"process";import{join as OK,relative as LK,resolve as vB}from"path";import ZA from"process";import{existsSync as Ij,mkdirSync as e4,readdirSync as wI,writeFileSync as $I}from"fs";import{dirname as AI,resolve as kA}from"path";import rJ from"process";import{Buffer as N$}from"buffer";import{createCipheriv as _K,createDecipheriv as SK,randomBytes as LJ}from"crypto";import{closeSync as _J,createReadStream as iB,createWriteStream as ZK,existsSync as SJ,fsyncSync as mB,openSync as gB,writeFileSync as kK}from"fs";import{access as hK,constants as dB,mkdir as DK,readdir as jA,rename as lB,stat as A1,unlink as zA,writeFile as ZJ}from"fs/promises";import{join as X1}from"path";import O0 from"process";import{pipeline as xK}from"stream/promises";import{createGzip as nB}from"zlib";import J1 from"process";import mw from"process";import{Buffer as vw}from"buffer";import{createCipheriv as PK,createDecipheriv as bK,randomBytes as kJ}from"crypto";import{closeSync as hJ,createReadStream as pB,createWriteStream as uK,existsSync as GA,fsyncSync as rB,openSync as tB,writeFileSync as cK}from"fs";import{access as vK,constants as aB,mkdir as iK,readdir as KA,rename as sB,stat as U1,unlink as FA,writeFile as DJ}from"fs/promises";import{isAbsolute as mK,join as Q1,resolve as gK}from"path";import h from"process";import{pipeline as dK}from"stream/promises";import{createGzip as oB}from"zlib";import W1 from"process";import gw from"process";import qA from"process";import{existsSync as NA}from"fs";import{resolve as xJ}from"path";import{existsSync as lK}from"fs";import{existsSync as nK,readdirSync as pK}from"fs";import{extname as PJ,resolve as eB}from"path";import rK from"process";import{join as tK,relative as aK,resolve as wj}from"path";import hA from"process";import{Buffer as iw}from"buffer";import{createCipheriv as sK,createDecipheriv as oK,randomBytes as bJ}from"crypto";import{closeSync as uJ,createReadStream as $j,createWriteStream as eK,existsSync as EA,fsyncSync as Yj,openSync as Aj,writeFileSync as w7}from"fs";import{access as $7,constants as Xj,mkdir as Y7,readdir as fA,rename as Jj,stat as B1,unlink as TA,writeFile as cJ}from"fs/promises";import{isAbsolute as A7,join as j1,resolve as X7}from"path";import D from"process";import{pipeline as J7}from"stream/promises";import{createGzip as Uj}from"zlib";import z1 from"process";import dw from"process";import RA from"process";import{existsSync as MA}from"fs";import{resolve as lJ}from"path";import{existsSync as CF}from"fs";class Hj{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!DB(w))return!0;return xB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=DB(Y)?xB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Rj{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function W7(w,$){this[w]=Q7.bind(null,$)}class UU{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!PB(w))return!0;return bB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=PB(Y)?bB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class QU{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function z7(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function G7(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function K7(w){return w.getStats().size*2}function WU(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&w0($[0])&&"id"in $[0]&&$[0].id===3&&w0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(w0($)&&w0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(w0(w)&&"arr"in w&&Array.isArray(w.arr)&&w0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&w0($[0])&&w0(w[0])){let A=[...$];for(let X of w)if(w0(X)&&"name"in X){if(!A.find((U)=>w0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(w0(X)&&"path"in X){if(!A.find((U)=>w0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>DA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!w0($)||!w0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(w0(X)&&w0(Y[A]))Y[A]=WU(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&w0(X[0])&&w0(Y[A][0])){let J=[...X];for(let U of Y[A])if(w0(U)&&"name"in U){if(!J.find((Q)=>w0(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(w0(U)&&"path"in U){if(!J.find((Q)=>w0(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((W)=>DA(W,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function DA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!DA(w[Y],$[Y]))return!1;return!0}if(w0(w)&&w0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!DA(w[X],$[X]))return!1}return!0}return!1}function w0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function F7(w,$){if(!Ij(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return WU($,A)}catch{return null}}catch{return null}}async function q7({name:w="",cwd:$,defaultConfig:Y}){let A=$||rJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let W of X){let Q=kA(A,`${U}${W}`),B=await F7(Q,Y);if(B!==null)return B}try{let U=kA(A,"package.json");if(Ij(U)){let Q=(await import(U))[w];if(Q&&typeof Q==="object"&&!Array.isArray(Q))try{return WU(Y,Q)}catch{}}}catch{}return Y}function N7(w,$={}){let Y=ZA.cwd();while(Y.includes("storage"))Y=vB(Y,"..");let A=vB(Y,w||"");if($?.relative)return LK(ZA.cwd(),A);return A}async function E7(){try{let w=await q7({name:"clarity",defaultConfig:CA,cwd:ZA.cwd(),endpoint:"",headers:{}});return{...CA,...w}}catch{return CA}}function Q0(){if(mw.env.NODE_ENV==="test"||mw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function f7(){if(mw.env.NODE_ENV==="test"||mw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof mw<"u"){let w=mw.type;if(w==="renderer"||w==="worker")return!1;return!!(mw.versions&&(mw.versions.node||mw.versions.bun))}return!1}class Cj{async format(w){let $=await f7(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:J1.pid,hostname:$(),environment:J1.env.NODE_ENV||"development",platform:J1.platform,version:J1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:J1.env.NODE_ENV||J1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xA{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(w,$={}){this.name=w,this.config={...aJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Cj,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??O0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...yA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...yA};return{...yA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:aJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await hK(this.config.logDirectory,dB.F_OK|dB.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await DK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:N$.from(w);try{if(!SJ(this.currentLogFile))await ZJ(this.currentLogFile,"",{mode:420});if(X=gB(this.currentLogFile,"a",420),kK(X,Q,{flag:"a"}),mB(X),X!==void 0)_J(X),X=void 0;if((await A1(this.currentLogFile)).size===0){if(await ZJ(this.currentLogFile,Q,{flag:"w",mode:420}),(await A1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{_J(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,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 X1(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 X1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return X1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(Q0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return LJ(16).toString("hex")}generateKey(){return LJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=LJ(16),A=_K("aes-256-gcm",$,Y),X=N$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:N$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=nB(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(N$.from(N$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(Q0())return;let w=await A1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await jA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await A1(Y).catch(()=>null))try{if(await lB(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await zA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await ZJ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await A1(Y).catch(()=>null))await lB(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await jA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await zA(X1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=iB(w),A=ZK($),X=nB();await xK(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),SJ(this.currentLogFile))try{let w=gB(this.currentLogFile,"r+");mB(w),_J(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!Q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await jA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await zA(X1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?a.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=O0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${a.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!Q0()){let B=xj[w],j=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:a.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:a.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z),W){let G=W.split(`
`);for(let K of G)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:a.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!Q0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let Q=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
`;if(W)Q+=`${W}
`;Q=Q.replace(this.ANSI_PATTERN,""),await this.writeToFile(Q)}time(w){let $=performance.now();if(this.fancy&&!Q0()){let Y=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:a.blue("◐"),tag:Y,message:`${a.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!Q0()){let j=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:a.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!Q0())console.error(B.trim());await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new xA($,{...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(Y),Y}createReadStream(){if(Q0())throw Error("createReadStream is not supported in browser environments");if(!SJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return iB(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=N$.isBuffer(w)?w:N$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),W=SK("aes-256-gcm",Y,X);return W.setAuthTag(J),N$.concat([W.update(U),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Q0()}isServerMode(){return!Q0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!Q0()){let J=w.split(`
`),U=Math.max(...J.map((j)=>j.length))+2,W=`┌${"─".repeat(U)}┐`,Q=`└${"─".repeat(U)}┘`,B=J.map((j)=>{let z=" ".repeat(U-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:a.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(Q),showTimestamp:!1}))}else if(!Q0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(Q0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${a.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();O0.stdin.removeListener("data",Y);try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!1)}catch{}O0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!0)}catch{}O0.stdin.resume(),O0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,W=0;if(Y=w.replace(U,(Q,B)=>{if(B==="%")return"%";if(W>=$.length)return Q;let j=$[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return Q}}),W<$.length)Y+=` ${$.slice(W).map((Q)=>typeof Q==="object"?JSON.stringify(Q,null,2):String(Q)).join(" ")}`}if(this.fancy&&!Q0()){let U=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",W=a.blue("◐");console.error(`${W} ${U} ${a.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||Q0()||w<=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 Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),W!==void 0)this.activeProgressBar.message=W;let Q=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Q)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())return;O0.stdout.write(`${"\r".padEnd(O0.stdout.columns||80)}\r`),this.log(W,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||Q0()||!O0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=a.green("━".repeat(A)),U=a.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=$||Y===100?a.green("✓"):a.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${a.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=O0.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,O0.stdout.write(w.lastRenderedLine),$)O0.stdout.write(`
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||Q0()||!O0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(Q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await jA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=X1(this.config.logDirectory,A);if(w.before)try{if((await A1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await zA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function VA(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&d($[0])&&"id"in $[0]&&$[0].id===3&&d($[1])&&"id"in $[1]&&$[1].id===4)return $;if(d($)&&d(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(d(w)&&"arr"in w&&Array.isArray(w.arr)&&d($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&d($[0])&&d(w[0])){let A=[...$];for(let X of w)if(d(X)&&"name"in X){if(!A.find((U)=>d(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(d(X)&&"path"in X){if(!A.find((U)=>d(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>PA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!d($)||!d(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(d(X)&&d(Y[A]))Y[A]=VA(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&d(X[0])&&d(Y[A][0])){let J=[...X];for(let U of Y[A])if(d(U)&&"name"in U){if(!J.find((Q)=>d(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(d(U)&&"path"in U){if(!J.find((Q)=>d(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((W)=>PA(W,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function BU(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:VA(w,$);if(Array.isArray(w))return Y==="replace"?$:VA(w,$);if(!d($)||!d(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=VA(U,J);else if(d(J)&&d(U))A[X]=BU(U,J,Y);else A[X]=J}return A}function PA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!PA(w[Y],$[Y]))return!1;return!0}if(d(w)&&d($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!PA(w[X],$[X]))return!1}return!0}return!1}function d(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function HA(w,$,Y="replace"){if(!Mj(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return BU($,X,Y)}catch{return null}}catch{return null}}function T7(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),K=`${A}_${z.map(G).join("_")}`,E=`${A}_${z.map((q)=>q.toUpperCase()).join("_")}`;if(Y)_0.info(`Checking environment variable ${K} for config ${w}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))Q[B]=J(j,z);else{let q=qY.env[K]||qY.env[E];if(q!==void 0){if(Y)_0.info(`Using environment variable ${q?K:E} for config ${w}.${z.join(".")}`);if(typeof j==="number")Q[B]=Number(q);else if(typeof j==="boolean")Q[B]=q.toLowerCase()==="true";else if(Array.isArray(j))try{let N=JSON.parse(q);if(Array.isArray(N))Q[B]=N;else Q[B]=q.split(",").map((f)=>f.trim())}catch{Q[B]=q.split(",").map((N)=>N.trim())}else Q[B]=q}}}return Q}return J(X)}async function H7({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let Q=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?T7(w,X,J):X,B=Y||qY.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)_0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${B}`);let z=[w,`.${w}`].filter(Boolean),G=[`${w}.config`,`.${w}.config`].filter(Boolean),K=$?[$,`.${$}`]:[],E=$?[`${$}.config`,`.${$}.config`]:[],q=Array.from(new Set([B,i0(B,"config"),i0(B,".config"),A?i0(B,A):void 0].filter(Boolean)));for(let N of q){if(J)_0.info(`Searching for configuration in: ${N}`);let R=[i0(B,"config"),i0(B,".config")].concat(A?[i0(B,A)]:[]).includes(N)?[...z,...G,...K,...E]:[...G,...z,...E,...K];for(let O of R)for(let y of j){let T=i0(N,`${O}${y}`),M=await HA(T,Q,W);if(M!==null){if(J)_0.success(`Configuration loaded from: ${T}`);return M}}}if(w){let N=i0(OJ(),".config",w),f=["config",`${w}.config`];if($)f.push(`${$}.config`);if(J)_0.info(`Checking user config directory: ${N}`);for(let R of f)for(let O of j){let y=i0(N,`${R}${O}`),T=await HA(y,Q,W);if(T!==null){if(J)_0.success(`Configuration loaded from user config directory: ${y}`);return T}}}if(w){let N=i0(OJ(),".config"),f=[`.${w}.config`];if($)f.push(`.${$}.config`);if(J)_0.info(`Checking user config directory for dotfile configs: ${N}`);for(let R of f)for(let O of j){let y=i0(N,`${R}${O}`),T=await HA(y,Q,W);if(T!==null){if(J)_0.success(`Configuration loaded from user config directory dotfile: ${y}`);return T}}}if(w){let N=OJ(),f=[`.${w}.config`,`.${w}`];if($)f.push(`.${$}.config`),f.push(`.${$}`);if(J)_0.info(`Checking user home directory for dotfile configs: ${N}`);for(let R of f)for(let O of j){let y=i0(N,`${R}${O}`),T=await HA(y,Q,W);if(T!==null){if(J)_0.success(`Configuration loaded from user home directory: ${y}`);return T}}}try{let N=i0(B,"package.json");if(Mj(N)){let f=await import(N),R=f[w];if(!R&&$){if(R=f[$],R&&J)_0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)_0.success(`Configuration loaded from package.json: ${R===f[w]?w:$}`);return BU(Q,R,W)}catch(O){if(J)_0.warn("Failed to merge package.json config:",O)}}}catch(N){if(J)_0.warn("Failed to load package.json:",N)}if(J)_0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return Q}function R7(w,$={}){let Y=SA.cwd();while(Y.includes("storage"))Y=cB(Y,"..");let A=cB(Y,w||"");if($?.relative)return yK(SA.cwd(),A);return A}async function M7(){try{let w=await H7({name:"clarity",alias:"logging",defaultConfig:OA,cwd:SA.cwd()});return{...OA,...w||{}}}catch{return OA}}function F0(){if(gw.env.NODE_ENV==="test"||gw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function I7(){if(gw.env.NODE_ENV==="test"||gw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof gw<"u"){let w=gw.type;if(w==="renderer"||w==="worker")return!1;return!!(gw.versions&&(gw.versions.node||gw.versions.bun))}return!1}class yj{async format(w){let $=await I7(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:W1.pid,hostname:$(),environment:W1.env.NODE_ENV||"development",platform:W1.platform,version:W1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:W1.env.NODE_ENV||W1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class bA{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(w,$={}){this.name=w,this.config={...sJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new yj,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??h.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...LA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...LA};return{...LA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:sJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await vK(this.config.logDirectory,aB.F_OK|aB.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await iK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:vw.from(w);try{if(!GA(this.currentLogFile))await DJ(this.currentLogFile,"",{mode:420});if(X=tB(this.currentLogFile,"a",420),cK(X,Q,{flag:"a"}),rB(X),X!==void 0)hJ(X),X=void 0;if((await U1(this.currentLogFile)).size===0){if(await DJ(this.currentLogFile,Q,{flag:"w",mode:420}),(await U1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{hJ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,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 Q1(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 Q1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return Q1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(F0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return kJ(16).toString("hex")}generateKey(){return kJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw