@stacksjs/dnsx
Version:
A command-line & library DNS client. Like dig & dog, but for TypeScript.
9 lines • 147 kB
JavaScript
import{createRequire as q7}from"node:module";var J7=Object.create;var{getPrototypeOf:U7,defineProperty:c9,getOwnPropertyNames:Q7}=Object;var H7=Object.prototype.hasOwnProperty;function z7(Y){return this[Y]}var A7,W7,B7=(Y,$,G)=>{var X=Y!=null&&typeof Y==="object";if(X){var Z=$?A7??=new WeakMap:W7??=new WeakMap,_=Z.get(Y);if(_)return _}G=Y!=null?J7(U7(Y)):{};let J=$||!Y||!Y.__esModule?c9(G,"default",{value:Y,enumerable:!0}):G;for(let Q of Q7(Y))if(!H7.call(J,Q))c9(J,Q,{get:z7.bind(Y,Q),enumerable:!0});if(X)Z.set(Y,J);return J};var K7=(Y,$)=>()=>($||Y(($={exports:{}}).exports,$),$.exports);var e=q7(import.meta.url);var Z7=K7((DG,u9)=>{var e1=process||{},G7=e1.argv||[],t1=e1.env||{},E8=!(!!t1.NO_COLOR||G7.includes("--no-color"))&&(!!t1.FORCE_COLOR||G7.includes("--color")||e1.platform==="win32"||(e1.stdout||{}).isTTY&&t1.TERM!=="dumb"||!!t1.CI),O8=(Y,$,G=Y)=>(X)=>{let Z=""+X,_=Z.indexOf($,Y.length);return~_?Y+D8(Z,$,G,_)+$:Y+Z+$},D8=(Y,$,G,X)=>{let Z="",_=0;do Z+=Y.substring(_,X)+G,_=X+$.length,X=Y.indexOf($,_);while(~X);return Z+Y.substring(_)},X7=(Y=E8)=>{let $=Y?O8:()=>String;return{isColorSupported:Y,reset:$("\x1B[0m","\x1B[0m"),bold:$("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:$("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:$("\x1B[3m","\x1B[23m"),underline:$("\x1B[4m","\x1B[24m"),inverse:$("\x1B[7m","\x1B[27m"),hidden:$("\x1B[8m","\x1B[28m"),strikethrough:$("\x1B[9m","\x1B[29m"),black:$("\x1B[30m","\x1B[39m"),red:$("\x1B[31m","\x1B[39m"),green:$("\x1B[32m","\x1B[39m"),yellow:$("\x1B[33m","\x1B[39m"),blue:$("\x1B[34m","\x1B[39m"),magenta:$("\x1B[35m","\x1B[39m"),cyan:$("\x1B[36m","\x1B[39m"),white:$("\x1B[37m","\x1B[39m"),gray:$("\x1B[90m","\x1B[39m"),bgBlack:$("\x1B[40m","\x1B[49m"),bgRed:$("\x1B[41m","\x1B[49m"),bgGreen:$("\x1B[42m","\x1B[49m"),bgYellow:$("\x1B[43m","\x1B[49m"),bgBlue:$("\x1B[44m","\x1B[49m"),bgMagenta:$("\x1B[45m","\x1B[49m"),bgCyan:$("\x1B[46m","\x1B[49m"),bgWhite:$("\x1B[47m","\x1B[49m"),blackBright:$("\x1B[90m","\x1B[39m"),redBright:$("\x1B[91m","\x1B[39m"),greenBright:$("\x1B[92m","\x1B[39m"),yellowBright:$("\x1B[93m","\x1B[39m"),blueBright:$("\x1B[94m","\x1B[39m"),magentaBright:$("\x1B[95m","\x1B[39m"),cyanBright:$("\x1B[96m","\x1B[39m"),whiteBright:$("\x1B[97m","\x1B[39m"),bgBlackBright:$("\x1B[100m","\x1B[49m"),bgRedBright:$("\x1B[101m","\x1B[49m"),bgGreenBright:$("\x1B[102m","\x1B[49m"),bgYellowBright:$("\x1B[103m","\x1B[49m"),bgBlueBright:$("\x1B[104m","\x1B[49m"),bgMagentaBright:$("\x1B[105m","\x1B[49m"),bgCyanBright:$("\x1B[106m","\x1B[49m"),bgWhiteBright:$("\x1B[107m","\x1B[49m")}};u9.exports=X7();u9.exports.createColors=X7});var g;((K)=>{K[K.A=1]="A";K[K.NS=2]="NS";K[K.CNAME=5]="CNAME";K[K.SOA=6]="SOA";K[K.PTR=12]="PTR";K[K.MX=15]="MX";K[K.TXT=16]="TXT";K[K.AAAA=28]="AAAA";K[K.SRV=33]="SRV";K[K.NAPTR=35]="NAPTR";K[K.OPT=41]="OPT";K[K.SSHFP=44]="SSHFP";K[K.TLSA=52]="TLSA";K[K.DNSKEY=48]="DNSKEY";K[K.CAA=257]="CAA"})(g||={});var $9;((X)=>{X[X.IN=1]="IN";X[X.CH=3]="CH";X[X.HS=4]="HS"})($9||={});var L7;((X)=>{X.Disable="disable";X.Hide="hide";X.Show="show"})(L7||={});var F7;((A)=>{A[A.NoError=0]="NoError";A[A.FormErr=1]="FormErr";A[A.ServFail=2]="ServFail";A[A.NXDomain=3]="NXDomain";A[A.NotImp=4]="NotImp";A[A.Refused=5]="Refused";A[A.YXDomain=6]="YXDomain";A[A.YXRRSet=7]="YXRRSet";A[A.NXRRSet=8]="NXRRSet";A[A.NotAuth=9]="NotAuth";A[A.NotZone=10]="NotZone"})(F7||={});var j7;((H)=>{H.TruncatedPacket="TRUNCATED_PACKET";H.InvalidLength="INVALID_LENGTH";H.InvalidFormat="INVALID_FORMAT";H.InvalidName="INVALID_NAME";H.InvalidLabel="INVALID_LABEL";H.InvalidPointer="INVALID_POINTER";H.InvalidType="INVALID_TYPE";H.InvalidClass="INVALID_CLASS";H.NetworkError="NETWORK_ERROR"})(j7||={});import{existsSync as l9,statSync as i9}from"fs";import{existsSync as M9,mkdirSync as R7,readdirSync as E7,writeFileSync as O7}from"fs";import{homedir as $1}from"os";import{dirname as n9,resolve as y}from"path";import Y1 from"process";import{join as D7,relative as S7,resolve as o9}from"path";import v1 from"process";import{existsSync as C0,mkdirSync as c8,readdirSync as l8,writeFileSync as i8}from"fs";import{homedir as G9}from"os";import{dirname as s8,resolve as v}from"path";import K1 from"process";import{join as x7,relative as C7,resolve as s9}from"path";import y1 from"process";import{existsSync as k0,mkdirSync as Y$,readdirSync as $$,writeFileSync as G$}from"fs";import{dirname as Z$,resolve as h1}from"path";import V9 from"process";import{Buffer as a}from"buffer";import{createCipheriv as k7,createDecipheriv as P7,randomBytes as X9}from"crypto";import{closeSync as Z9,createReadStream as r9,createWriteStream as T7,existsSync as _9,fsyncSync as a9,openSync as t9,writeFileSync as b7}from"fs";import{access as v7,constants as e9,mkdir as y7,readdir as I1,rename as Y0,stat as G1,unlink as M1,writeFile as J9}from"fs/promises";import{join as X1}from"path";import C from"process";import{pipeline as h7}from"stream/promises";import{createGzip as $0}from"zlib";import Z1 from"process";import n from"process";import{Buffer as l}from"buffer";import{createCipheriv as f7,createDecipheriv as d7,randomBytes as U9}from"crypto";import{closeSync as Q9,createReadStream as G0,createWriteStream as m7,existsSync as V1,fsyncSync as X0,openSync as Z0,writeFileSync as u7}from"fs";import{access as p7,constants as _0,mkdir as g7,readdir as N1,rename as J0,stat as _1,unlink as w1,writeFile as H9}from"fs/promises";import{isAbsolute as c7,join as J1,resolve as l7}from"path";import q from"process";import{pipeline as i7}from"stream/promises";import{createGzip as U0}from"zlib";import U1 from"process";import o from"process";import R1 from"process";import{existsSync as E1}from"fs";import{resolve as z9}from"path";import{existsSync as n7}from"fs";import{existsSync as o7,readdirSync as s7}from"fs";import{extname as A9,resolve as Q0}from"path";import r7 from"process";import{join as aY,relative as tY,resolve as M0}from"path";import c1 from"process";import{Buffer as i}from"buffer";import{createCipheriv as $8,createDecipheriv as G8,randomBytes as L9}from"crypto";import{closeSync as F9,createReadStream as V0,createWriteStream as X8,existsSync as D1,fsyncSync as N0,openSync as w0,writeFileSync as Z8}from"fs";import{access as _8,constants as R0,mkdir as J8,readdir as S1,rename as E0,stat as Q1,unlink as x1,writeFile as j9}from"fs/promises";import{isAbsolute as U8,join as H1,resolve as Q8}from"path";import L from"process";import{pipeline as H8}from"stream/promises";import{createGzip as O0}from"zlib";import z1 from"process";import s from"process";var I7=Object.defineProperty;var M7=(Y)=>Y;function V7(Y,$){this[Y]=M7.bind(null,$)}var N7=(Y,$)=>{for(var G in $)I7(Y,G,{get:$[G],enumerable:!0,configurable:!0,set:V7.bind($,G)})},w7=(Y,$)=>()=>(Y&&($=Y(Y=0)),$);var x0={};N7(x0,{withErrorRecovery:()=>b0,tryLoadConfig:()=>IY,loadConfigWithResult:()=>FY,loadConfig:()=>d0,isRetryableError:()=>AY,isConfigNotFoundError:()=>zY,isBunfigError:()=>v0,globalPerformanceMonitor:()=>F1,globalCache:()=>A1,getEnvOrDefault:()=>WY,generateConfigTypes:()=>MY,defaultGeneratedDir:()=>n0,defaultConfigDir:()=>i0,deepMergeWithArrayStrategy:()=>v9,deepMerge:()=>y0,createLibraryConfig:()=>VY,config:()=>jY,bunfigPlugin:()=>NY,applyEnvVarsToConfig:()=>B1,TypeGenerationError:()=>S9,SchemaValidationError:()=>L1,PluginError:()=>C9,PerformanceMonitor:()=>P9,FileSystemError:()=>D9,ErrorFactory:()=>t,EnvVarError:()=>g1,EnvProcessor:()=>i1,ConfigValidator:()=>y9,ConfigValidationError:()=>E9,ConfigNotFoundError:()=>p1,ConfigMergeError:()=>O9,ConfigLoader:()=>h9,ConfigLoadError:()=>q1,ConfigFileLoader:()=>n1,ConfigCache:()=>k9,CacheUtils:()=>u0,BunfigError:()=>h,BrowserConfigError:()=>x9,ArrayMergeStrategies:()=>c0});class k9{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Y={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Y}}generateKey(Y,$){let G=$?`:${$}`:"";return`${this.options.keyPrefix}${Y}${G}`}isExpired(Y){return Date.now()-Y.timestamp.getTime()>Y.ttl}estimateSize(Y){try{return JSON.stringify(Y).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Y=Array.from(this.cache.entries()).sort(([,G],[,X])=>G.timestamp.getTime()-X.timestamp.getTime()),$=Y.length-this.options.maxSize+1;for(let G=0;G<$;G++)this.cache.delete(Y[G][0])}set(Y,$,G,X){if(!this.options.enabled)return;let Z=this.generateKey(Y,G),_=X??this.options.ttl,J=this.estimateSize($);this.cache.set(Z,{value:$,timestamp:new Date,ttl:_,hits:0,size:J}),this.evictIfNeeded()}get(Y,$){if(!this.options.enabled){this.totalMisses++;return}let G=this.generateKey(Y,$),X=this.cache.get(G);if(!X){this.totalMisses++;return}if(this.isExpired(X)){this.cache.delete(G),this.totalMisses++;return}return X.hits++,this.totalHits++,X.value}isFileModified(Y,$){try{if(!l9(Y))return!0;return i9(Y).mtime>$}catch{return!0}}getWithFileCheck(Y,$){let G=this.get(Y,$);if(!G)return;if(this.isFileModified($,G.fileTimestamp)){this.delete(Y,$);return}return G.value}setWithFileCheck(Y,$,G,X){try{let Z=l9(G)?i9(G):null,_=Z?Z.mtime:new Date;this.set(Y,{value:$,fileTimestamp:_},G,X)}catch{this.set(Y,$,G,X)}}delete(Y,$){let G=this.generateKey(Y,$);return this.cache.delete(G)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Y=0;for(let[$,G]of this.cache.entries())if(this.isExpired(G))this.cache.delete($),Y++;return Y}getStats(){let Y=Array.from(this.cache.values()),$=Y.reduce((X,Z)=>X+Z.size,0),G=Y.map((X)=>X.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:G[0],newestEntry:G[G.length-1]}}export(){let Y={};for(let[$,G]of this.cache.entries())Y[$]={value:G.value,timestamp:G.timestamp.toISOString(),ttl:G.ttl,hits:G.hits,size:G.size};return Y}import(Y){this.cache.clear();for(let[$,G]of Object.entries(Y))if(typeof G==="object"&&G!==null){let X=G;this.cache.set($,{value:X.value,timestamp:new Date(X.timestamp),ttl:X.ttl,hits:X.hits,size:X.size})}}}class P9{metrics=[];maxMetrics=1000;async track(Y,$,G={}){let X=performance.now(),Z=new Date;try{let _=await $(),J=performance.now()-X;return this.recordMetric({operation:Y,duration:J,timestamp:Z,...G}),_}catch(_){let J=performance.now()-X;throw this.recordMetric({operation:`${Y}:error`,duration:J,timestamp:Z,...G}),_}}recordMetric(Y){if(this.metrics.push(Y),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Y){let $=Y?this.metrics.filter((Z)=>Z.operation===Y):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let G=$.map((Z)=>Z.duration),X=G.reduce((Z,_)=>Z+_,0);return{count:$.length,averageDuration:X/$.length,minDuration:Math.min(...G),maxDuration:Math.max(...G),totalDuration:X,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Y){return this.metrics.filter(($)=>$.duration>Y)}}function a7(Y,$={}){let X=Object.keys($).sort().map((Z)=>`${Z}:${$[Z]}`).join("|");return X?`${Y}:${X}`:Y}function t7(Y,$){try{return JSON.stringify(Y)===JSON.stringify($)}catch{return Y===$}}function e7(Y){return Y.getStats().size*2}function T9(Y,$){if(Array.isArray($)&&Array.isArray(Y)&&$.length===2&&Y.length===2&&R($[0])&&"id"in $[0]&&$[0].id===3&&R($[1])&&"id"in $[1]&&$[1].id===4)return $;if(R($)&&R(Y)&&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 Y;if(Array.isArray($)&&!Array.isArray(Y))return $;if(Array.isArray($)&&Array.isArray(Y)){if(R(Y)&&"arr"in Y&&Array.isArray(Y.arr)&&R($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&Y.length>0&&R($[0])&&R(Y[0])){let X=[...$];for(let Z of Y)if(R(Z)&&"name"in Z){if(!X.find((J)=>R(J)&&("name"in J)&&J.name===Z.name))X.push(Z)}else if(R(Z)&&"path"in Z){if(!X.find((J)=>R(J)&&("path"in J)&&J.path===Z.path))X.push(Z)}else if(!X.some((_)=>f1(_,Z)))X.push(Z);return X}if($.every((X)=>typeof X==="string")&&Y.every((X)=>typeof X==="string")){let X=[...$];for(let Z of Y)if(!X.includes(Z))X.push(Z);return X}return $}if(!R($)||!R(Y))return $;let G={...Y};for(let X in $)if(Object.prototype.hasOwnProperty.call($,X)){let Z=$[X];if(Z===null||Z===void 0)continue;else if(R(Z)&&R(G[X]))G[X]=T9(G[X],Z);else if(Array.isArray(Z)&&Array.isArray(G[X]))if(Z.length>0&&G[X].length>0&&R(Z[0])&&R(G[X][0])){let _=[...Z];for(let J of G[X])if(R(J)&&"name"in J){if(!_.find((U)=>R(U)&&("name"in U)&&U.name===J.name))_.push(J)}else if(R(J)&&"path"in J){if(!_.find((U)=>R(U)&&("path"in U)&&U.path===J.path))_.push(J)}else if(!_.some((Q)=>f1(Q,J)))_.push(J);G[X]=_}else if(Z.every((_)=>typeof _==="string")&&G[X].every((_)=>typeof _==="string")){let _=[...Z];for(let J of G[X])if(!_.includes(J))_.push(J);G[X]=_}else G[X]=Z;else G[X]=Z}return G}function f1(Y,$){if(Y===$)return!0;if(Array.isArray(Y)&&Array.isArray($)){if(Y.length!==$.length)return!1;for(let G=0;G<Y.length;G++)if(!f1(Y[G],$[G]))return!1;return!0}if(R(Y)&&R($)){let G=Object.keys(Y),X=Object.keys($);if(G.length!==X.length)return!1;for(let Z of G){if(!Object.prototype.hasOwnProperty.call($,Z))return!1;if(!f1(Y[Z],$[Z]))return!1}return!0}return!1}function R(Y){return Boolean(Y&&typeof Y==="object"&&!Array.isArray(Y))}async function YY(Y,$){if(!k0(Y))return null;try{let G=await import(Y),X=G.default||G;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return T9($,X)}catch{return null}}catch{return null}}async function $Y({name:Y="",cwd:$,defaultConfig:G}){let X=$||V9.cwd(),Z=[".ts",".js",".mjs",".cjs",".json"],_=[`${Y}.config`,`.${Y}.config`,Y,`.${Y}`];for(let J of _)for(let Q of Z){let U=h1(X,`${J}${Q}`),H=await YY(U,G);if(H!==null)return H}try{let J=h1(X,"package.json");if(k0(J)){let U=(await import(J))[Y];if(U&&typeof U==="object"&&!Array.isArray(U))try{return T9(G,U)}catch{}}}catch{}return G}function GY(Y,$={}){let G=y1.cwd();while(G.includes("storage"))G=s9(G,"..");let X=s9(G,Y||"");if($?.relative)return C7(y1.cwd(),X);return X}async function XY(){try{let Y=await $Y({name:"clarity",defaultConfig:k1,cwd:y1.cwd(),endpoint:"",headers:{}});return{...k1,...Y}}catch{return k1}}function E(){if(n.env.NODE_ENV==="test"||n.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ZY(){if(n.env.NODE_ENV==="test"||n.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n<"u"){let Y=n.type;if(Y==="renderer"||Y==="worker")return!1;return!!(n.versions&&(n.versions.node||n.versions.bun))}return!1}class P0{async format(Y){let $=await ZY(),G=await this.getMetadata($);return JSON.stringify({timestamp:Y.timestamp.toISOString(),level:Y.level,name:Y.name,message:Y.message,metadata:G})}async getMetadata(Y){if(Y){let{hostname:$}=await import("os");return{pid:Z1.pid,hostname:$(),environment:Z1.env.NODE_ENV||"development",platform:Z1.platform,version:Z1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Z1.env.NODE_ENV||Z1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class d1{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(Y,$={}){this.name=Y,this.config={...w9},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new P0,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??C.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let G={...$},X=$.timestamp!==void 0;if(X)delete G.timestamp;if(this.config={...this.config,...G,timestamp:X||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Z=this.generateKeyId(),_=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,_),this.encryptionKeys.set(Z,{key:_,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Y){if(!Y.fingersCrossedEnabled&&Y.fingersCrossed)return{...P1,...Y.fingersCrossed};if(!Y.fingersCrossedEnabled)return null;if(!Y.fingersCrossed)return{...P1};return{...P1,...Y.fingersCrossed}}normalizeOptions(Y){let $={format:"json",level:"info",logDirectory:w9.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},G={...$,...Object.fromEntries(Object.entries(Y).filter(([,X])=>X!==void 0))};if(!G.level||!["debug","info","success","warning","error"].includes(G.level))G.level=$.level;return G}async writeToFile(Y){let G=(async()=>{let Z,_=0,J=3,Q=1000;while(_<J)try{try{try{await v7(this.config.logDirectory,e9.F_OK|e9.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await y7(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 U=this.validateEncryptionConfig()?(await this.encrypt(Y)).encrypted:a.from(Y);try{if(!_9(this.currentLogFile))await J9(this.currentLogFile,"",{mode:420});if(Z=t9(this.currentLogFile,"a",420),b7(Z,U,{flag:"a"}),a9(Z),Z!==void 0)Z9(Z),Z=void 0;if((await G1(this.currentLogFile)).size===0){if(await J9(this.currentLogFile,U,{flag:"w",mode:420}),(await G1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let z=H;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(_<J-1){let A=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${J}:`,A);let B=Q*2**_;await new Promise((W)=>setTimeout(W,B)),_++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(Z!==void 0)try{Z9(Z)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(U){if(_===J-1){let z=U,A=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),U}_++;let H=Q*2**(_-1);await new Promise((z)=>setTimeout(z,H))}})();this.pendingOperations.push(G);let X=this.pendingOperations.length-1;try{await G}catch(Z){throw console.error("Debug: [writeToFile] Error in operation:",Z),Z}finally{this.pendingOperations.splice(X,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 Y=new Date().toISOString().split("T")[0];return X1(this.config.logDirectory,`${this.name}-${Y}.log`)}setupRotation(){if(E())return;if(typeof this.config.rotation==="boolean")return;let Y=this.config.rotation,$;switch(Y.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 G=typeof $.interval==="number"?$.interval:60,X=Math.max(G,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Z)=>{console.error("Error rotating keys:",Z)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,G=this.generateKeyId(),X=this.generateKey();this.currentKeyId=G,this.keys.set(G,X),this.encryptionKeys.set(G,{key:X,createdAt:new Date});let Z=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,U])=>U.createdAt.getTime()-Q.createdAt.getTime()),_=typeof $.maxKeys==="number"?$.maxKeys:1,J=Math.max(1,_);if(Z.length>J)for(let[Q]of Z.slice(J))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return X9(16).toString("hex")}generateKey(){return X9(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Y=this.keys.get(this.currentKeyId);if(!Y)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Y,id:this.currentKeyId}}encrypt(Y){let{key:$}=this.getCurrentKey(),G=X9(16),X=k7("aes-256-gcm",$,G),Z=a.concat([X.update(Y,"utf8"),X.final()]),_=X.getAuthTag();return{encrypted:a.concat([G,Z,_]),iv:G}}async compressData(Y){return new Promise(($,G)=>{let X=$0(),Z=[];X.on("data",(_)=>Z.push(_)),X.on("end",()=>$(a.from(a.concat(Z)))),X.on("error",G),X.write(Y),X.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Y={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...Y,...$}}return Y}async rotateLog(){if(E())return;let Y=await G1(this.currentLogFile).catch(()=>null);if(!Y)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&Y.size>=$.maxSize){let G=this.currentLogFile,X=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Z=await I1(this.config.logDirectory),_=Z.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,H)=>{let z=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),J=_.length>0?Number.parseInt(_[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${G}.${J}`;if(await G1(G).catch(()=>null))try{if(await Y0(G,Q),$.compress)try{let U=`${Q}.gz`;await this.compressLogFile(Q,U),await M1(Q)}catch(U){console.error("Error compressing rotated file:",U)}if(_.length===0&&!Z.some((U)=>U.endsWith(".log.1")))try{let U=`${G}.1`;await J9(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Z=new Date().toISOString().replace(/[:.]/g,"-"),_=G.replace(/\.log$/,`-${Z}.log`);if(await G1(G).catch(()=>null))await Y0(G,_)}if(this.currentLogFile=X,$.maxFiles){let _=(await I1(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,Q)=>Q.localeCompare(J));for(let J of _.slice($.maxFiles))await M1(X1(this.config.logDirectory,J))}}}async compressLogFile(Y,$){let G=r9(Y),X=T7($),Z=$0();await h7(G,Z,X)}async handleFingersCrossedBuffer(Y,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Y)&&!this.isActivated){this.isActivated=!0;for(let G of this.logBuffer){let X=await this.formatter.format(G);await this.writeToFile(X),console.log(X)}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 G={timestamp:new Date,level:Y,message:$,name:this.name};this.logBuffer.push(G)}}shouldActivateFingersCrossed(Y){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Y)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Y){return{debug:0,info:1,success:2,warning:3,error:4}[Y]}shouldLog(Y){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[Y]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Y)=>{if(Y instanceof Promise)return Y.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),_9(this.currentLogFile))try{let Y=t9(this.currentLogFile,"r+");a9(Y),Z9(Y)}catch(Y){console.error(`Error flushing file: ${Y}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Y of this.pendingOperations)if(typeof Y.cancel==="function")Y.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Y){console.error("Error waiting for pending operations:",Y)}if(!E()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await I1(this.config.logDirectory)).filter((G)=>(G.includes("temp")||G.includes(".tmp"))&&G.includes(this.name));for(let G of $)try{await M1(X1(this.config.logDirectory,G))}catch(X){console.error(`Failed to delete temp file ${G}:`,X)}}catch(Y){console.error("Error cleaning up temporary files:",Y)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Y){if(!Y)return"";return`${this.tagFormat.prefix}${Y}${this.tagFormat.suffix}`}formatFileTimestamp(Y){return`[${Y.toISOString()}]`}formatConsoleTimestamp(Y){return this.fancy?w.gray(Y.toLocaleTimeString()):Y.toLocaleTimeString()}formatConsoleMessage(Y){let{timestamp:$,icon:G="",tag:X="",message:Z,level:_,showTimestamp:J=!0}=Y,Q=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(J)W.push($);if(_==="warning")W.push("WARN");else if(_==="error")W.push("ERROR");else if(G)W.push(G.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(X)W.push(X.replace(/[[\]]/g,""));return W.push(Z),W.join(" ")}let U=C.stdout.columns||120,H="";if(_==="warning"||_==="error")H=`${G} ${Z}`;else if(_==="info"||_==="success")H=`${G} ${X} ${Z}`;else H=`${G} ${X} ${w.cyan(Z)}`;if(!J)return H.trim();let z=Q(H).trim().length,A=Q($).length,B=Math.max(1,U-2-z-A);return`${H.trim()}${" ".repeat(B)}${$}`}formatMessage(Y,$){if($.length===1&&Array.isArray($[0]))return Y.replace(/\{(\d+)\}/g,(_,J)=>{let Q=Number.parseInt(J,10);return Q<$[0].length?String($[0][Q]):_});let G=/%([sdijfo%])/g,X=0,Z=Y.replace(G,(_,J)=>{if(J==="%")return"%";if(X>=$.length)return _;let Q=$[X++];switch(J){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return _}});if(X<$.length)Z+=` ${$.slice(X).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`;return Z}async log(Y,$,...G){let X=new Date,Z=this.formatConsoleTimestamp(X),_=this.formatFileTimestamp(X),J,Q;if($ instanceof Error)J=$.message,Q=$.stack;else J=this.formatMessage($,G);if(this.fancy&&!E()){let H=p0[Y],z=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",A;switch(Y){case"debug":A=this.formatConsoleMessage({timestamp:Z,icon:H,tag:z,message:w.gray(J),level:Y}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:Z,icon:H,tag:z,message:J,level:Y}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:Z,icon:H,tag:z,message:w.green(J),level:Y}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:Z,icon:H,tag:z,message:J,level:Y}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:Z,icon:H,tag:z,message:J,level:Y}),console.error(A),Q){let B=Q.split(`
`);for(let W of B)if(W.trim()&&!W.includes(J))console.error(this.formatConsoleMessage({timestamp:Z,message:w.gray(` ${W}`),level:Y,showTimestamp:!1}))}break}}else if(!E()){if(console.error(`${_} ${this.environment}.${Y.toUpperCase()}: ${J}`),Q)console.error(Q)}if(!this.shouldLog(Y))return;let U=`${_} ${this.environment}.${Y.toUpperCase()}: ${J}
`;if(Q)U+=`${Q}
`;U=U.replace(this.ANSI_PATTERN,""),await this.writeToFile(U)}time(Y){let $=performance.now();if(this.fancy&&!E()){let G=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",X=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:X,icon:w.blue("◐"),tag:G,message:`${w.cyan(Y)}...`}))}return async(G)=>{if(!this.enabled)return;let X=performance.now(),Z=Math.round(X-$),_=`${Y} completed in ${Z}ms`,J=new Date,Q=this.formatConsoleTimestamp(J),H=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${_}`;if(G)H+=` ${JSON.stringify(G)}`;if(H+=`
`,H=H.replace(this.ANSI_PATTERN,""),this.fancy&&!E()){let z=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:w.green("✓"),tag:z,message:`${_}${G?` ${JSON.stringify(G)}`:""}`}))}else if(!E())console.error(H.trim());await this.writeToFile(H)}}async debug(Y,...$){await this.log("debug",Y,...$)}async info(Y,...$){await this.log("info",Y,...$)}async success(Y,...$){await this.log("success",Y,...$)}async warn(Y,...$){await this.log("warning",Y,...$)}async error(Y,...$){await this.log("error",Y,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Y=this.config.rotation,{encrypt:$}=Y;return!!$}async only(Y){if(!this.enabled)return;return await Y()}isEnabled(){return this.enabled}setEnabled(Y){this.enabled=Y}extend(Y){let $=`${this.name}:${Y}`,G=new d1($,{...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(G),G}createReadStream(){if(E())throw Error("createReadStream is not supported in browser environments");if(!_9(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return r9(this.currentLogFile,{encoding:"utf8"})}async decrypt(Y){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 G=this.keys.get(this.currentKeyId);try{let X=a.isBuffer(Y)?Y:a.from(Y,"base64"),Z=X.slice(0,16),_=X.slice(-16),J=X.slice(16,-16),Q=P7("aes-256-gcm",G,Z);return Q.setAuthTag(_),a.concat([Q.update(J),Q.final()]).toString("utf8")}catch(X){throw Error(`Decryption failed: ${X instanceof Error?X.message:String(X)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return E()}isServerMode(){return!E()}setTestEncryptionKey(Y,$){this.currentKeyId=Y,this.keys.set(Y,$)}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(Y){if(!this.enabled)return;let $=new Date,G=this.formatConsoleTimestamp($),X=this.formatFileTimestamp($);if(this.fancy&&!E()){let _=Y.split(`
`),J=Math.max(..._.map((z)=>z.length))+2,Q=`┌${"─".repeat(J)}┐`,U=`└${"─".repeat(J)}┘`,H=_.map((z)=>{let A=" ".repeat(J-z.length-2);return`│ ${z}${A} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:G,message:w.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:G,message:w.cyan(Q)})),H.forEach((z)=>console.error(this.formatConsoleMessage({timestamp:G,message:w.cyan(z),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:G,message:w.cyan(U),showTimestamp:!1}))}else if(!E())console.error(`${X} ${this.environment}.INFO: [BOX] ${Y}`);let Z=`${X} ${this.environment}.INFO: [BOX] ${Y}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Z)}async prompt(Y){if(E())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${w.cyan("?")} ${Y} (y/n) `);let G=(X)=>{let Z=X.toString().trim().toLowerCase();C.stdin.removeListener("data",G);try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!1)}catch{}C.stdin.pause(),console.error(""),$(Z==="y"||Z==="yes")};try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!0)}catch{}C.stdin.resume(),C.stdin.once("data",G)})}setFancy(Y){this.fancy=Y}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Y,...$){if(!this.enabled)return;let G=Y;if($&&$.length>0){let J=/%([sdijfo%])/g,Q=0;if(G=Y.replace(J,(U,H)=>{if(H==="%")return"%";if(Q>=$.length)return U;let z=$[Q++];switch(H){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return U}}),Q<$.length)G+=` ${$.slice(Q).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!E()){let J=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",Q=w.blue("◐");console.error(`${Q} ${J} ${w.cyan(G)}`)}let _=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${G}
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(_)}progress(Y,$=""){if(!this.enabled||!this.fancy||E()||Y<=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 G=20;return this.activeProgressBar={total:Y,current:0,message:$,barLength:G,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,Q)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||E())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Y,J)),Q!==void 0)this.activeProgressBar.message=Q;let U=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,U)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||E())return;if(this.activeProgressBar.current=this.activeProgressBar.total,J!==void 0)this.activeProgressBar.message=J;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(J,Q="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||E())return;C.stdout.write(`${"\r".padEnd(C.stdout.columns||80)}\r`),this.log(Q,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Y,$=!1){if(!this.enabled||!this.fancy||E()||!C.stdout.isTTY)return;let G=Math.min(100,Math.max(0,Math.round(Y.current/Y.total*100))),X=Math.round(Y.barLength*G/100),Z=Y.barLength-X,_=w.green("━".repeat(X)),J=w.gray("━".repeat(Z)),Q=`[${_}${J}]`,U=`${G}%`.padStart(4),H=Y.message?` ${Y.message}`:"",z=$||G===100?w.green("✓"):w.blue("▶"),A=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",B=`\r${z}${A} ${Q} ${U}${H}`,W=C.stdout.columns||80,F=" ".repeat(Math.max(0,W-B.replace(this.ANSI_PATTERN,"").length));if(Y.lastRenderedLine=`${B}${F}`,C.stdout.write(Y.lastRenderedLine),$)C.stdout.write(`
`)}finishProgressBar(Y,$){if(!this.enabled||!this.fancy||E()||!C.stdout.isTTY){this.activeProgressBar=null;return}if(Y.current<Y.total)Y.current=Y.total;if($)Y.message=$;this.renderProgressBar(Y,!0),this.activeProgressBar=null}async clear(Y={}){if(E()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await I1(this.config.logDirectory),G=[];for(let X of $){if(!(Y.name?new RegExp(Y.name.replace("*",".*")).test(X):X.startsWith(this.name))||!X.endsWith(".log"))continue;let _=X1(this.config.logDirectory,X);if(Y.before)try{if((await G1(_)).mtime>=Y.before)continue}catch(J){console.error(`Failed to get stats for file ${_}:`,J);continue}G.push(_)}if(G.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${G.length} log file(s)...`);for(let X of G)try{await M1(X),console.warn(`Deleted log file: ${X}`)}catch(Z){console.error(`Failed to delete log file ${X}:`,Z)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function C1(Y,$){if(Array.isArray($)&&Array.isArray(Y)&&$.length===2&&Y.length===2&&N($[0])&&"id"in $[0]&&$[0].id===3&&N($[1])&&"id"in $[1]&&$[1].id===4)return $;if(N($)&&N(Y)&&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 Y;if(Array.isArray($)&&!Array.isArray(Y))return $;if(Array.isArray($)&&Array.isArray(Y)){if(N(Y)&&"arr"in Y&&Array.isArray(Y.arr)&&N($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&Y.length>0&&N($[0])&&N(Y[0])){let X=[...$];for(let Z of Y)if(N(Z)&&"name"in Z){if(!X.find((J)=>N(J)&&("name"in J)&&J.name===Z.name))X.push(Z)}else if(N(Z)&&"path"in Z){if(!X.find((J)=>N(J)&&("path"in J)&&J.path===Z.path))X.push(Z)}else if(!X.some((_)=>m1(_,Z)))X.push(Z);return X}if($.every((X)=>typeof X==="string")&&Y.every((X)=>typeof X==="string")){let X=[...$];for(let Z of Y)if(!X.includes(Z))X.push(Z);return X}return $}if(!N($)||!N(Y))return $;let G={...Y};for(let X in $)if(Object.prototype.hasOwnProperty.call($,X)){let Z=$[X];if(Z===null||Z===void 0)continue;else if(N(Z)&&N(G[X]))G[X]=C1(G[X],Z);else if(Array.isArray(Z)&&Array.isArray(G[X]))if(Z.length>0&&G[X].length>0&&N(Z[0])&&N(G[X][0])){let _=[...Z];for(let J of G[X])if(N(J)&&"name"in J){if(!_.find((U)=>N(U)&&("name"in U)&&U.name===J.name))_.push(J)}else if(N(J)&&"path"in J){if(!_.find((U)=>N(U)&&("path"in U)&&U.path===J.path))_.push(J)}else if(!_.some((Q)=>m1(Q,J)))_.push(J);G[X]=_}else if(Z.every((_)=>typeof _==="string")&&G[X].every((_)=>typeof _==="string")){let _=[...Z];for(let J of G[X])if(!_.includes(J))_.push(J);G[X]=_}else G[X]=Z;else G[X]=Z}return G}function b9(Y,$,G="replace"){if($===null||$===void 0)return Y;if(Array.isArray($))return G==="replace"?$:C1(Y,$);if(Array.isArray(Y))return G==="replace"?$:C1(Y,$);if(!N($)||!N(Y))return $;let X={...Y};for(let Z of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,Z))continue;let _=$[Z],J=X[Z];if(_===null||_===void 0)continue;if(Array.isArray(_)||Array.isArray(J))if(G==="replace")X[Z]=_;else X[Z]=C1(J,_);else if(N(_)&&N(J))X[Z]=b9(J,_,G);else X[Z]=_}return X}function m1(Y,$){if(Y===$)return!0;if(Array.isArray(Y)&&Array.isArray($)){if(Y.length!==$.length)return!1;for(let G=0;G<Y.length;G++)if(!m1(Y[G],$[G]))return!1;return!0}if(N(Y)&&N($)){let G=Object.keys(Y),X=Object.keys($);if(G.length!==X.length)return!1;for(let Z of G){if(!Object.prototype.hasOwnProperty.call($,Z))return!1;if(!m1(Y[Z],$[Z]))return!1}return!0}return!1}function N(Y){return Boolean(Y&&typeof Y==="object"&&!Array.isArray(Y))}async function O1(Y,$,G="replace"){if(!C0(Y))return null;try{let X=await import(Y),Z=X.default||X;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return b9($,Z,G)}catch{return null}}catch{return null}}function _Y(Y,$,G=!1){if(!Y)return $;let X=Y.toUpperCase().replace(/-/g,"_"),Z={...$};function _(J,Q=[]){let U={...J};for(let[H,z]of Object.entries(J)){let A=[...Q,H],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${X}_${A.map(B).join("_")}`,F=`${X}_${A.map((K)=>K.toUpperCase()).join("_")}`;if(G)P.info(`Checking environment variable ${W} for config ${Y}.${A.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))U[H]=_(z,A);else{let K=K1.env[W]||K1.env[F];if(K!==void 0){if(G)P.info(`Using environment variable ${K?W:F} for config ${Y}.${A.join(".")}`);if(typeof z==="number")U[H]=Number(K);else if(typeof z==="boolean")U[H]=K.toLowerCase()==="true";else if(Array.isArray(z))try{let V=JSON.parse(K);if(Array.isArray(V))U[H]=V;else U[H]=K.split(",").map((T)=>T.trim())}catch{U[H]=K.split(",").map((V)=>V.trim())}else U[H]=K}}}return U}return _(Z)}async function JY({name:Y="",alias:$,cwd:G,configDir:X,defaultConfig:Z,verbose:_=!1,checkEnv:J=!0,arrayStrategy:Q="replace"}){let U=J&&typeof Z==="object"&&Z!==null&&!Array.isArray(Z)?_Y(Y,Z,_):Z,H=G||K1.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(_)P.info(`Loading configuration for "${Y}"${$?` (alias: "${$}")`:""} from ${H}`);let A=[Y,`.${Y}`].filter(Boolean),B=[`${Y}.config`,`.${Y}.config`].filter(Boolean),W=$?[$,`.${$}`]:[],F=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([H,v(H,"config"),v(H,".config"),X?v(H,X):void 0].filter(Boolean)));for(let V of K){if(_)P.info(`Searching for configuration in: ${V}`);let b=[v(H,"config"),v(H,".config")].concat(X?[v(H,X)]:[]).includes(V)?[...A,...B,...W,...F]:[...B,...A,...F,...W];for(let c of b)for(let p of z){let m=v(V,`${c}${p}`),g9=await O1(m,U,Q);if(g9!==null){if(_)P.success(`Configuration loaded from: ${m}`);return g9}}}if(Y){let V=v(G9(),".config",Y),T=["config",`${Y}.config`];if($)T.push(`${$}.config`);if(_)P.info(`Checking user config directory: ${V}`);for(let b of T)for(let c of z){let p=v(V,`${b}${c}`),m=await O1(p,U,Q);if(m!==null){if(_)P.success(`Configuration loaded from user config directory: ${p}`);return m}}}if(Y){let V=v(G9(),".config"),T=[`.${Y}.config`];if($)T.push(`.${$}.config`);if(_)P.info(`Checking user config directory for dotfile configs: ${V}`);for(let b of T)for(let c of z){let p=v(V,`${b}${c}`),m=await O1(p,U,Q);if(m!==null){if(_)P.success(`Configuration loaded from user config directory dotfile: ${p}`);return m}}}if(Y){let V=G9(),T=[`.${Y}.config`,`.${Y}`];if($)T.push(`.${$}.config`),T.push(`.${$}`);if(_)P.info(`Checking user home directory for dotfile configs: ${V}`);for(let b of T)for(let c of z){let p=v(V,`${b}${c}`),m=await O1(p,U,Q);if(m!==null){if(_)P.success(`Configuration loaded from user home directory: ${p}`);return m}}}try{let V=v(H,"package.json");if(C0(V)){let T=await import(V),b=T[Y];if(!b&&$){if(b=T[$],b&&_)P.success(`Using alias "${$}" configuration from package.json`)}if(b&&typeof b==="object"&&!Array.isArray(b))try{if(_)P.success(`Configuration loaded from package.json: ${b===T[Y]?Y:$}`);return b9(U,b,Q)}catch(c){if(_)P.warn("Failed to merge package.json config:",c)}}}catch(V){if(_)P.warn("Failed to load package.json:",V)}if(_)P.info(`No configuration found for "${Y}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return U}function UY(Y,$={}){let G=v1.cwd();while(G.includes("storage"))G=o9(G,"..");let X=o9(G,Y||"");if($?.relative)return S7(v1.cwd(),X);return X}async function QY(){try{let Y=await JY({name:"clarity",alias:"logging",defaultConfig:T1,cwd:v1.cwd()});return{...T1,...Y||{}}}catch{return T1}}function O(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function HY(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Y=o.type;if(Y==="renderer"||Y==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class T0{async format(Y){let $=await HY(),G=await this.getMetadata($);return JSON.stringify({timestamp:Y.timestamp.toISOString(),level:Y.level,name:Y.name,message:Y.message,metadata:G})}async getMetadata(Y){if(Y){let{hostname:$}=await import("os");return{pid:U1.pid,hostname:$(),environment:U1.env.NODE_ENV||"development",platform:U1.platform,version:U1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:U1.env.NODE_ENV||U1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class u1{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(Y,$={}){this.name=Y,this.config={...R9},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new T0,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let G={...$},X=$.timestamp!==void 0;if(X)delete G.timestamp;if(this.config={...this.config,...G,timestamp:X||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Z=this.generateKeyId(),_=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,_),this.encryptionKeys.set(Z,{key:_,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Y){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},G=this.fingersCrossedConfig.activationLevel??"error";return $[Y]>=$[G]}initializeFingersCrossedConfig(Y){if(!Y.fingersCrossedEnabled&&Y.fingersCrossed)return{...b1,...Y.fingersCrossed};if(!Y.fingersCrossedEnabled)return null;if(!Y.fingersCrossed)return{...b1};return{...b1,...Y.fingersCrossed}}normalizeOptions(Y){let $={format:"json",level:"info",logDirectory:R9.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},G={...$,...Object.fromEntries(Object.entries(Y).filter(([,X])=>X!==void 0))};if(!G.level||!["debug","info","success","warning","error"].includes(G.level))G.level=$.level;return G}shouldWriteToFile(){return!O()&&this.config.writeToFile===!0}async writeToFile(Y){let G=(async()=>{let Z,_=0,J=3,Q=1000;while(_<J)try{try{try{await p7(this.config.logDirectory,_0.F_OK|_0.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await g7(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 U=this.validateEncryptionConfig()?(await this.encrypt(Y)).encrypted:l.from(Y);try{if(!V1(this.currentLogFile))await H9(this.currentLogFile,"",{mode:420});if(Z=Z0(this.currentLogFile,"a",420),u7(Z,U,{flag:"a"}),X0(Z),Z!==void 0)Q9(Z),Z=void 0;if((await _1(this.currentLogFile)).size===0){if(await H9(this.currentLogFile,U,{flag:"w",mode:420}),(await _1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let z=H;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(_<J-1){let A=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${_+1}/${J}:`,A);let B=Q*2**_;await new Promise((W)=>setTimeout(W,B)),_++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(Z!==void 0)try{Q9(Z)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(U){if(_===J-1){let z=U,A=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),U}_++;let H=Q*2**(_-1);await new Promise((z)=>setTimeout(z,H))}})();this.pendingOperations.push(G);let X=this.pendingOperations.length-1;try{await G}catch(Z){throw console.error("Debug: [writeToFile] Error in operation:",Z),Z}finally{this.pendingOperations.splice(X,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 J1(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 J1(this.config.logDirectory,`${this.name}.log`);let Y=new Date().toISOString().split("T")[0];return J1(this.config.logDirectory,`${this.name}-${Y}.log`)}setupRotation(){if(O())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Y=this.config.rotation,$;switch(Y.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 G=typeof $.interval==="number"?$.interval:60,X=Math.max(G,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Z)=>{console.error("Error rotating keys:",Z)})},X)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,G=this.generateKeyId(),X=this.generateKey();this.currentKeyId=G,this.keys.set(G,X),th