@stacksjs/dtsx 0.9.18 → 0.9.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +5 -5
- package/dist/{chunk-zfrp784r.js → chunk-0cfb4831.js} +1 -1
- package/dist/{chunk-w71syh0b.js → chunk-0d5r9n78.js} +1 -1
- package/dist/chunk-1b1j60g0.js +2 -0
- package/dist/{chunk-fxh731yj.js → chunk-1hy2eypj.js} +1 -1
- package/dist/chunk-4mtbtmee.js +25 -0
- package/dist/{chunk-bb28rgpz.js → chunk-5zt12z1t.js} +1 -1
- package/dist/chunk-7hy98p24.js +62 -0
- package/dist/{chunk-w08v45h7.js → chunk-9e542zj7.js} +1 -1
- package/dist/{chunk-m5508xqy.js → chunk-a0gah6hn.js} +1 -1
- package/dist/{chunk-gc9n9za8.js → chunk-bymtns9a.js} +1 -1
- package/dist/chunk-c60qpa3j.js +2 -0
- package/dist/chunk-cdv5r51q.js +156 -0
- package/dist/chunk-dnbr0hke.js +2 -0
- package/dist/{chunk-fmhrt2ca.js → chunk-dymmh9x0.js} +1 -1
- package/dist/chunk-eqfegkc1.js +2 -0
- package/dist/{chunk-4hpfq116.js → chunk-fqym6cgw.js} +1 -1
- package/dist/chunk-ft0nf9jb.js +19 -0
- package/dist/{chunk-zs5mk604.js → chunk-fvgc14nk.js} +1 -1
- package/dist/{chunk-f7fatmz3.js → chunk-h0dndwyc.js} +1 -1
- package/dist/chunk-m94gn6yx.js +2 -0
- package/dist/chunk-nmmv0nrk.js +2 -0
- package/dist/{chunk-acf8x00j.js → chunk-nqwz71ak.js} +1 -1
- package/dist/{chunk-1zqrzfqx.js → chunk-r1yqh3qg.js} +1 -1
- package/dist/{chunk-72tqwhpx.js → chunk-rd7n0yj1.js} +1 -1
- package/dist/{chunk-7pwy4m0c.js → chunk-vx4a5crm.js} +1 -1
- package/dist/{chunk-zn70hw8f.js → chunk-wtqapt0n.js} +1 -1
- package/dist/chunk-xw9wfq8f.js +17 -0
- package/dist/{chunk-wcdd51hr.js → chunk-y2pe3jq3.js} +1 -1
- package/dist/{chunk-5qqybwef.js → chunk-y4g1csn2.js} +1 -1
- package/dist/extractor/builders.d.ts +1 -1
- package/dist/extractor/helpers.d.ts +9 -0
- package/dist/src/index.js +1 -1
- package/dist/src/plugins/bun.js +1 -1
- package/dist/src/plugins/esbuild.js +1 -1
- package/dist/src/plugins/index.js +1 -1
- package/dist/src/plugins/tsup.js +1 -1
- package/dist/src/plugins/vite.js +1 -1
- package/dist/src/plugins/webpack.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-1s045wj0.js +0 -2
- package/dist/chunk-4jw8qvts.js +0 -16
- package/dist/chunk-a3txc27m.js +0 -33
- package/dist/chunk-aafhn8pf.js +0 -2
- package/dist/chunk-asnnmvct.js +0 -19
- package/dist/chunk-e13937tc.js +0 -2
- package/dist/chunk-j0rnj1z0.js +0 -25
- package/dist/chunk-rv908n0q.js +0 -2
- package/dist/chunk-s8yqbjn4.js +0 -2
- package/dist/chunk-trm0gptj.js +0 -134
- package/dist/chunk-y515fe4f.js +0 -2
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Wc as wZ}from"./chunk-gssantc8.js";import{dd as l}from"./chunk-mcdb3q06.js";import{existsSync as T8}from"fs";import{resolve as O8}from"path";import KZ from"process";import{pathToFileURL as N8}from"url";import{existsSync as sX,statSync as oX}from"fs";import{existsSync as jZ,mkdirSync as b8,readdirSync as y8,readFileSync as IZ,writeFileSync as v8}from"fs";import{homedir as YQ}from"os";import{dirname as f8,resolve as d}from"path";import XX from"process";import{existsSync as tX,statSync as rX}from"fs";import{existsSync as SX,mkdirSync as FZ,readdirSync as MZ,writeFileSync as DZ}from"fs";import{homedir as ZQ}from"os";import{dirname as aX,resolve as y}from"path";import XQ from"process";import{join as VZ,relative as SZ,resolve as eX}from"path";import uQ from"process";import{existsSync as vY,mkdirSync as o8,readdirSync as t8,writeFileSync as r8}from"fs";import{homedir as HX}from"os";import{dirname as Q9,resolve as b}from"path";import LQ from"process";import{join as EZ,relative as TZ,resolve as QY}from"path";import gQ from"process";import{existsSync as dY,mkdirSync as H9,readdirSync as J9,writeFileSync as U9}from"fs";import{dirname as q9,resolve as cQ}from"path";import EX from"process";import{Buffer as e}from"buffer";import{createCipheriv as OZ,createDecipheriv as NZ,randomBytes as JX}from"crypto";import{closeSync as UX,createReadStream as XY,createWriteStream as CZ,existsSync as GX,fsyncSync as YY,openSync as ZY,writeFileSync as xZ}from"fs";import{access as kZ,constants as $Y,mkdir as PZ,readdir as MQ,rename as HY,stat as $Q,unlink as DQ,writeFile as qX}from"fs/promises";import{join as HQ}from"path";import N from"process";import{pipeline as bZ}from"stream/promises";import{createGzip as JY}from"zlib";import JQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as yZ,createDecipheriv as vZ,randomBytes as _X}from"crypto";import{closeSync as AX,createReadStream as UY,createWriteStream as dZ,existsSync as VQ,fsyncSync as GY,openSync as qY,writeFileSync as hZ}from"fs";import{access as fZ,constants as _Y,mkdir as pZ,readdir as SQ,rename as AY,stat as UQ,unlink as EQ,writeFile as WX}from"fs/promises";import{isAbsolute as mZ,join as GQ,resolve as uZ}from"path";import R from"process";import{pipeline as gZ}from"stream/promises";import{createGzip as WY}from"zlib";import qQ from"process";import t from"process";import TQ from"process";import{existsSync as OQ}from"fs";import{resolve as zX}from"path";import{existsSync as cZ}from"fs";import{existsSync as lZ,readdirSync as nZ}from"fs";import{extname as BX,resolve as zY}from"path";import iZ from"process";import{join as sZ,relative as oZ,resolve as BY}from"path";import lQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as tZ,createDecipheriv as rZ,randomBytes as RX}from"crypto";import{closeSync as LX,createReadStream as RY,createWriteStream as aZ,existsSync as NQ,fsyncSync as LY,openSync as wY,writeFileSync as eZ}from"fs";import{access as Q0,constants as KY,mkdir as X0,readdir as CQ,rename as jY,stat as _Q,unlink as xQ,writeFile as wX}from"fs/promises";import{isAbsolute as Y0,join as AQ,resolve as Z0}from"path";import L from"process";import{pipeline as $0}from"stream/promises";import{createGzip as IY}from"zlib";import WQ from"process";import r from"process";import PQ from"process";import{existsSync as bQ}from"fs";import{resolve as DX}from"path";import{existsSync as V8}from"fs";class bY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,J=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:J}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!sX(Q))return!0;return oX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=sX(Y)?oX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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 Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class yY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),J=performance.now()-Z;return this.recordMetric({operation:Q,duration:J,timestamp:$,...Y}),H}catch(H){let J=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:J,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var mQ=new bY,dX=new yY;var H0=Object.defineProperty,J0=(Q)=>Q;function U0(Q,X){this[Q]=J0.bind(null,X)}var G0=(Q,X)=>{for(var Y in X)H0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:U0.bind(X,Y)})},q0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),hY={};G0(hY,{withErrorRecovery:()=>mY,tryLoadConfig:()=>k0,loadConfigWithResult:()=>C0,loadConfig:()=>nY,isRetryableError:()=>V0,isConfigNotFoundError:()=>D0,isBunfigError:()=>uY,globalPerformanceMonitor:()=>jQ,globalCache:()=>zQ,getEnvOrDefault:()=>S0,generateConfigTypes:()=>P0,defaultGeneratedDir:()=>QZ,defaultConfigDir:()=>eY,deepMergeWithArrayStrategy:()=>uX,deepMerge:()=>gY,createLibraryConfig:()=>b0,config:()=>x0,bunfigPlugin:()=>y0,applyEnvVarsToConfig:()=>RQ,TypeGenerationError:()=>PX,SchemaValidationError:()=>KQ,PluginError:()=>yX,PerformanceMonitor:()=>fX,FileSystemError:()=>kX,ErrorFactory:()=>QQ,EnvVarError:()=>rQ,EnvProcessor:()=>YX,ConfigValidator:()=>gX,ConfigValidationError:()=>CX,ConfigNotFoundError:()=>tQ,ConfigMergeError:()=>xX,ConfigLoader:()=>cX,ConfigLoadError:()=>wQ,ConfigFileLoader:()=>ZX,ConfigCache:()=>hX,CacheUtils:()=>sY,BunfigError:()=>v,BrowserConfigError:()=>bX,ArrayMergeStrategies:()=>rY});class hX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,J=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:J}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!tX(Q))return!0;return rX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=tX(Y)?rX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,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 Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class fX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),J=performance.now()-Z;return this.recordMetric({operation:Q,duration:J,timestamp:$,...Y}),H}catch(H){let J=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:J,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function _0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function A0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function W0(Q){return Q.getStats().size*2}function pX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((J)=>D(J)&&("name"in J)&&J.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((J)=>D(J)&&("path"in J)&&J.path===$.path))Z.push($)}else if(!Z.some((H)=>nQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=pX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let J of Y[Z])if(D(J)&&"name"in J){if(!H.find((U)=>D(U)&&("name"in U)&&U.name===J.name))H.push(J)}else if(D(J)&&"path"in J){if(!H.find((U)=>D(U)&&("path"in U)&&U.path===J.path))H.push(J)}else if(!H.some((G)=>nQ(G,J)))H.push(J);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let J of Y[Z])if(!H.includes(J))H.push(J);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function nQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!nQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!nQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function z0(Q,X){if(!dY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return pX(X,Z)}catch{return null}}catch{return null}}async function B0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||EX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let J of H)for(let G of $){let U=cQ(Z,`${J}${G}`),q=await z0(U,Y);if(q!==null)return q}try{let J=cQ(Z,"package.json");if(dY(J)){let U=(await import(J))[Q];if(U&&typeof U==="object"&&!Array.isArray(U))try{return pX(Y,U)}catch{}}}catch{}return Y}function R0(Q,X={}){let Y=gQ.cwd();while(Y.includes("storage"))Y=QY(Y,"..");let Z=QY(Y,Q||"");if(X?.relative)return TZ(gQ.cwd(),Z);return Z}async function L0(){try{let Q=await B0({name:"clarity",defaultConfig:dQ,cwd:gQ.cwd(),endpoint:"",headers:{}});return{...dQ,...Q}}catch{return dQ}}function V(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function w0(){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 Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class fY{async format(Q){let X=await w0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:JQ.pid,hostname:X(),environment:JQ.env.NODE_ENV||"development",platform:JQ.platform,version:JQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:JQ.env.NODE_ENV||JQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class iQ{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(Q,X={}){this.name=Q,this.config={...OX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new fY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:OX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,J=3,G=1000;while(H<J)try{try{try{await kZ(this.config.logDirectory,$Y.F_OK|$Y.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await PZ(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let U=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!GX(this.currentLogFile))await qX(this.currentLogFile,"",{mode:420});if($=ZY(this.currentLogFile,"a",420),xZ($,U,{flag:"a"}),YY($),$!==void 0)UX($),$=void 0;if((await $Q(this.currentLogFile)).size===0){if(await qX(this.currentLogFile,U,{flag:"w",mode:420}),(await $Q(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(H<J-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${J}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{UX($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(U){if(H===J-1){let _=U,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),U}H++;let q=G*2**(H-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 HQ(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 HQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return HQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(V())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,U])=>U.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,J=Math.max(1,H);if($.length>J)for(let[G]of $.slice(J))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return JX(16).toString("hex")}generateKey(){return JX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=JX(16),Z=OZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=JY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(V())return;let Q=await $Q(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await MQ(this.config.logDirectory),H=$.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,q)=>{let _=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),J=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${J}`;if(await $Q(Y).catch(()=>null))try{if(await HY(Y,G),X.compress)try{let U=`${G}.gz`;await this.compressLogFile(G,U),await DQ(G)}catch(U){console.error("Error compressing rotated file:",U)}if(H.length===0&&!$.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await qX(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 $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await $Q(Y).catch(()=>null))await HY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await MQ(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,G)=>G.localeCompare(J));for(let J of H.slice(X.maxFiles))await DQ(HQ(this.config.logDirectory,J))}}}async compressLogFile(Q,X){let Y=XY(Q),Z=CZ(X),$=JY();await bZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),GX(this.currentLogFile))try{let Q=ZY(this.currentLogFile,"r+");YY(Q),UX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!V()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await MQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await DQ(HQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:J=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(J)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let U=N.stdout.columns||120,q="";if(H==="warning"||H==="error")q=`${Y} ${$}`;else if(H==="info"||H==="success")q=`${Y} ${Z} ${$}`;else q=`${Y} ${Z} ${M.cyan($)}`;if(!J)return q.trim();let _=G(q).trim().length,A=G(X).length,z=Math.max(1,U-2-_-A);return`${q.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,J)=>{let G=Number.parseInt(J,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,J)=>{if(J==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(J){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),J,G;if(X instanceof Error)J=X.message,G=X.stack;else J=this.formatMessage(X,Y);if(this.fancy&&!V()){let q=oY[Q],_=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:M.gray(J),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:J,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:M.green(J),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:J,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:q,tag:_,message:J,level:Q}),console.error(A),G){let z=G.split(`
|
|
3
|
+
`);for(let W of z)if(W.trim()&&!W.includes(J))console.error(this.formatConsoleMessage({timestamp:$,message:M.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!V()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${J}`),G)console.error(G)}if(!this.shouldLog(Q))return;let U=`${H} ${this.environment}.${Q.toUpperCase()}: ${J}
|
|
4
|
+
`;if(G)U+=`${G}
|
|
5
|
+
`;U=U.replace(this.ANSI_PATTERN,""),await this.writeToFile(U)}time(Q){let X=performance.now();if(this.fancy&&!V()){let Y=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:M.blue("\u25D0"),tag:Y,message:`${M.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,J=new Date,G=this.formatConsoleTimestamp(J),q=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${H}`;if(Y)q+=` ${JSON.stringify(Y)}`;if(q+=`
|
|
6
|
+
`,q=q.replace(this.ANSI_PATTERN,""),this.fancy&&!V()){let _=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:M.green("\u2713"),tag:_,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!V())console.error(q.trim());await this.writeToFile(q)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new iQ(X,{...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(V())throw Error("createReadStream is not supported in browser environments");if(!GX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return XY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.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 Z=e.isBuffer(Q)?Q:e.from(Q,"base64"),$=Z.slice(0,16),H=Z.slice(-16),J=Z.slice(16,-16),G=NZ("aes-256-gcm",Y,$);return G.setAuthTag(H),e.concat([G.update(J),G.final()]).toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return V()}isServerMode(){return!V()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}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(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X);if(this.fancy&&!V()){let H=Q.split(`
|
|
7
|
+
`),J=Math.max(...H.map((_)=>_.length))+2,G=`\u250C${"\u2500".repeat(J)}\u2510`,U=`\u2514${"\u2500".repeat(J)}\u2518`,q=H.map((_)=>{let A=" ".repeat(J-_.length-2);return`\u2502 ${_}${A} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:M.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(G)})),q.forEach((_)=>console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(_),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(U),showTimestamp:!1}))}else if(!V())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Q}`);let $=`${Z} ${this.environment}.INFO: [BOX] ${Q}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile($)}async prompt(Q){if(V())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${M.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();N.stdin.removeListener("data",Y);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let J=/%([sdijfo%])/g,G=0;if(Y=Q.replace(J,(U,q)=>{if(q==="%")return"%";if(G>=X.length)return U;let _=X[G++];switch(q){case"s":return String(_);case"d":case"i":return Number(_).toString();case"j":case"o":return JSON.stringify(_,null,2);default:return U}}),G<X.length)Y+=` ${X.slice(G).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!V()){let J=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",G=M.blue("\u25D0");console.error(`${G} ${J} ${M.cyan(Y)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
9
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(H)}progress(Q,X=""){if(!this.enabled||!this.fancy||V()||Q<=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:Q,current:0,message:X,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,G)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,J)),G!==void 0)this.activeProgressBar.message=G;let U=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,U)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())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,G="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(G,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,X=!1){if(!this.enabled||!this.fancy||V()||!N.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=M.green("\u2501".repeat(Z)),J=M.gray("\u2501".repeat($)),G=`[${H}${J}]`,U=`${Y}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=X||Y===100?M.green("\u2713"):M.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${G} ${U}${q}`,W=N.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,N.stdout.write(Q.lastRenderedLine),X)N.stdout.write(`
|
|
10
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||V()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(V()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await MQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=HQ(this.config.logDirectory,Z);if(Q.before)try{if((await $Q(H)).mtime>=Q.before)continue}catch(J){console.error(`Failed to get stats for file ${H}:`,J);continue}Y.push(H)}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 Z of Y)try{await DQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}function vQ(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&F(X[0])&&"id"in X[0]&&X[0].id===3&&F(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(F(X)&&F(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(F(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&F(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&F(X[0])&&F(Q[0])){let Z=[...X];for(let $ of Q)if(F($)&&"name"in $){if(!Z.find((J)=>F(J)&&("name"in J)&&J.name===$.name))Z.push($)}else if(F($)&&"path"in $){if(!Z.find((J)=>F(J)&&("path"in J)&&J.path===$.path))Z.push($)}else if(!Z.some((H)=>sQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!F(X)||!F(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(F($)&&F(Y[Z]))Y[Z]=vQ(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&F($[0])&&F(Y[Z][0])){let H=[...$];for(let J of Y[Z])if(F(J)&&"name"in J){if(!H.find((U)=>F(U)&&("name"in U)&&U.name===J.name))H.push(J)}else if(F(J)&&"path"in J){if(!H.find((U)=>F(U)&&("path"in U)&&U.path===J.path))H.push(J)}else if(!H.some((G)=>sQ(G,J)))H.push(J);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let J of Y[Z])if(!H.includes(J))H.push(J);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function mX(Q,X,Y="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return Y==="replace"?X:vQ(Q,X);if(Array.isArray(Q))return Y==="replace"?X:vQ(Q,X);if(!F(X)||!F(Q))return X;let Z={...Q};for(let $ of Object.keys(X)){if(!Object.prototype.hasOwnProperty.call(X,$))continue;let H=X[$],J=Z[$];if(H===null||H===void 0)continue;if(Array.isArray(H)||Array.isArray(J))if(Y==="replace")Z[$]=H;else Z[$]=vQ(J,H);else if(F(H)&&F(J))Z[$]=mX(J,H,Y);else Z[$]=H}return Z}function sQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!sQ(Q[Y],X[Y]))return!1;return!0}if(F(Q)&&F(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!sQ(Q[$],X[$]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function kQ(Q,X,Y="replace"){if(!vY(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return mX(X,$,Y)}catch{return null}}catch{return null}}function K0(Q,X,Y=!1){if(!Q)return X;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...X};function H(J,G=[]){let U={...J};for(let[q,_]of Object.entries(J)){let A=[...G,q],z=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${Z}_${A.map(z).join("_")}`,I=`${Z}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(Y)x.info(`Checking environment variable ${W} for config ${Q}.${A.join(".")}`);if(typeof _==="object"&&_!==null&&!Array.isArray(_))U[q]=H(_,A);else{let B=LQ.env[W]||LQ.env[I];if(B!==void 0){if(Y)x.info(`Using environment variable ${B?W:I} for config ${Q}.${A.join(".")}`);if(typeof _==="number")U[q]=Number(B);else if(typeof _==="boolean")U[q]=B.toLowerCase()==="true";else if(Array.isArray(_))try{let K=JSON.parse(B);if(Array.isArray(K))U[q]=K;else U[q]=B.split(",").map((k)=>k.trim())}catch{U[q]=B.split(",").map((K)=>K.trim())}else U[q]=B}}}return U}return H($)}async function j0({name:Q="",alias:X,cwd:Y,configDir:Z,defaultConfig:$,verbose:H=!1,checkEnv:J=!0,arrayStrategy:G="replace"}){let U=J&&typeof $==="object"&&$!==null&&!Array.isArray($)?K0(Q,$,H):$,q=Y||LQ.cwd(),_=[".ts",".js",".mjs",".cjs",".json"];if(H)x.info(`Loading configuration for "${Q}"${X?` (alias: "${X}")`:""} from ${q}`);let A=[Q,`.${Q}`].filter(Boolean),z=[`${Q}.config`,`.${Q}.config`].filter(Boolean),W=X?[X,`.${X}`]:[],I=X?[`${X}.config`,`.${X}.config`]:[],B=Array.from(new Set([q,b(q,"config"),b(q,".config"),Z?b(q,Z):void 0].filter(Boolean)));for(let K of B){if(H)x.info(`Searching for configuration in: ${K}`);let P=[b(q,"config"),b(q,".config")].concat(Z?[b(q,Z)]:[]).includes(K)?[...A,...z,...W,...I]:[...z,...A,...I,...W];for(let n of P)for(let g of _){let p=b(K,`${n}${g}`),iX=await kQ(p,U,G);if(iX!==null){if(H)x.success(`Configuration loaded from: ${p}`);return iX}}}if(Q){let K=b(HX(),".config",Q),k=["config",`${Q}.config`];if(X)k.push(`${X}.config`);if(H)x.info(`Checking user config directory: ${K}`);for(let P of k)for(let n of _){let g=b(K,`${P}${n}`),p=await kQ(g,U,G);if(p!==null){if(H)x.success(`Configuration loaded from user config directory: ${g}`);return p}}}if(Q){let K=b(HX(),".config"),k=[`.${Q}.config`];if(X)k.push(`.${X}.config`);if(H)x.info(`Checking user config directory for dotfile configs: ${K}`);for(let P of k)for(let n of _){let g=b(K,`${P}${n}`),p=await kQ(g,U,G);if(p!==null){if(H)x.success(`Configuration loaded from user config directory dotfile: ${g}`);return p}}}if(Q){let K=HX(),k=[`.${Q}.config`,`.${Q}`];if(X)k.push(`.${X}.config`),k.push(`.${X}`);if(H)x.info(`Checking user home directory for dotfile configs: ${K}`);for(let P of k)for(let n of _){let g=b(K,`${P}${n}`),p=await kQ(g,U,G);if(p!==null){if(H)x.success(`Configuration loaded from user home directory: ${g}`);return p}}}try{let K=b(q,"package.json");if(vY(K)){let k=await import(K),P=k[Q];if(!P&&X){if(P=k[X],P&&H)x.success(`Using alias "${X}" configuration from package.json`)}if(P&&typeof P==="object"&&!Array.isArray(P))try{if(H)x.success(`Configuration loaded from package.json: ${P===k[Q]?Q:X}`);return mX(U,P,G)}catch(n){if(H)x.warn("Failed to merge package.json config:",n)}}}catch(K){if(H)x.warn("Failed to load package.json:",K)}if(H)x.info(`No configuration found for "${Q}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return U}function I0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=eX(Y,"..");let Z=eX(Y,Q||"");if(X?.relative)return SZ(uQ.cwd(),Z);return Z}async function F0(){try{let Q=await j0({name:"clarity",alias:"logging",defaultConfig:fQ,cwd:uQ.cwd()});return{...fQ,...Q||{}}}catch{return fQ}}function S(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function M0(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t<"u"){let Q=t.type;if(Q==="renderer"||Q==="worker")return!1;return!!(t.versions&&(t.versions.node||t.versions.bun))}return!1}class pY{async format(Q){let X=await M0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:qQ.pid,hostname:X(),environment:qQ.env.NODE_ENV||"development",platform:qQ.platform,version:qQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qQ.env.NODE_ENV||qQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class oQ{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(Q,X={}){this.name=Q,this.config={...NX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new pY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return X[Q]>=X[Y]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...pQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...pQ};return{...pQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:NX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}shouldWriteToFile(){return!S()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,J=3,G=1000;while(H<J)try{try{try{await fZ(this.config.logDirectory,_Y.F_OK|_Y.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await pZ(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let U=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:i.from(Q);try{if(!VQ(this.currentLogFile))await WX(this.currentLogFile,"",{mode:420});if($=qY(this.currentLogFile,"a",420),hZ($,U,{flag:"a"}),GY($),$!==void 0)AX($),$=void 0;if((await UQ(this.currentLogFile)).size===0){if(await WX(this.currentLogFile,U,{flag:"w",mode:420}),(await UQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(H<J-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${J}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{AX($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(U){if(H===J-1){let _=U,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),U}H++;let q=G*2**(H-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 GQ(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 GQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return GQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,U])=>U.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,J=Math.max(1,H);if($.length>J)for(let[G]of $.slice(J))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return _X(16).toString("hex")}generateKey(){return _X(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=_X(16),Z=yZ("aes-256-gcm",X,Y),$=i.isBuffer(Q)?Q:i.from(Q,"utf8"),H=Z.update($),J=Z.final(),G=H.length+J.length,U=Z.getAuthTag(),q=i.allocUnsafe(16+G+16);return Y.copy(q,0),H.copy(q,16),J.copy(q,16+H.length),U.copy(q,16+G),{encrypted:q,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=WY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(i.from(i.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;if(!this.shouldWriteToFile())return;let Q=await UQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await SQ(this.config.logDirectory),H=$.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,q)=>{let _=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),J=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${J}`;if(await UQ(Y).catch(()=>null))try{if(await AY(Y,G),X.compress)try{let U=`${G}.gz`;await this.compressLogFile(G,U),await EQ(G)}catch(U){console.error("Error compressing rotated file:",U)}if(H.length===0&&!$.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await WX(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 $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await UQ(Y).catch(()=>null))await AY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await SQ(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,G)=>G.localeCompare(J));for(let J of H.slice(X.maxFiles))await EQ(GQ(this.config.logDirectory,J))}}}async compressLogFile(Q,X){let Y=UY(Q),Z=dZ(X),$=WY();await gZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),VQ(this.currentLogFile))try{let Q=qY(this.currentLogFile,"r+");GY(Q),AX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await SQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await EQ(GQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?w.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||S())return!1;let Q=typeof R.env.NO_COLOR<"u",X=R.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:J=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(J)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let U=R.stdout.columns||120,q="";if(H==="warning"||H==="error")q=`${Y} ${$}`;else if(H==="info"||H==="success")q=`${Y} ${Z} ${$}`;else q=`${Y} ${Z} ${w.cyan($)}`;if(!J)return q.trim();let _=G(q).trim().length,A=G(X).length,z=Math.max(1,U-2-_-A);return`${q.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,J)=>{let G=Number.parseInt(J,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,J)=>{if(J==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(J){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let X=Q;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,$)=>{let H=w.underline(w.blue(Z)),J=this.toAbsoluteFilePath($);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let G=`file://${encodeURI(J)}`,U="\x1B]8;;",q="\x1B\\";return`\x1B]8;;${G}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),X=X.replace(/`([^`]+)`/g,(Y,Z)=>w.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>w.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>w.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>w.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>w.strikethrough(Z)),X}supportsHyperlinks(){if(S())return!1;let Q=R.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let X=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let X=Q;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Y=R.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(mZ(X)||X.startsWith("./")||X.startsWith("../"))X=uZ(X);else return null;return VQ(X)?X:null}catch{return null}}buildOutputTexts(Q){let X=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Y=Q.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Y}}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),J,G;if(X instanceof Error)J=X.message,G=X.stack;else J=this.formatMessage(X,Y);let{consoleText:U,fileText:q}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":tY[Q],z=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:w.gray(U),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:U,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:w.green(U),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:U,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:U,level:Q}),console.error(W),G){let I=G.split(`
|
|
11
|
+
`);for(let B of I)if(B.trim()&&!B.includes(J))console.error(this.formatConsoleMessage({timestamp:$,message:w.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${J}`),G)console.error(G)}if(!this.shouldLog(Q))return;let _=`${H} ${this.environment}.${Q.toUpperCase()}: ${q}
|
|
12
|
+
`;if(G)_+=`${G}
|
|
13
|
+
`;if(_=_.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(_)}progress(Q,X=""){let Y={update:(G,U)=>{},finish:(G)=>{},interrupt:(G,U)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:X||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!S()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(G,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,G),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!S()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(G)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,G)},interrupt:(G,U="info")=>{if(!S()&&R.stdout.isTTY)R.stdout.write(`
|
|
14
|
+
`);if(this[U==="warning"?"warn":U](G),this.activeProgressBar&&this.shouldStyleConsole()&&!S()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":w.blue("\u25D0"),tag:Y,message:`${w.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,J=new Date,G=this.formatConsoleTimestamp(J),q=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${H}`;if(Y)q+=` ${JSON.stringify(Y)}`;if(q+=`
|
|
15
|
+
`,q=q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":w.green("\u2713"),tag:_,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!S())console.error(q.trim());if(this.shouldWriteToFile())await this.writeToFile(q)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new oQ(X,{...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(S())throw Error("createReadStream is not supported in browser environments");if(!VQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return UY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.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 Z=i.isBuffer(Q)?Q:i.from(Q,"base64"),$=Z.subarray(0,16),H=Z.subarray(Z.length-16),J=Z.subarray(16,Z.length-16),G=vZ("aes-256-gcm",Y,$);G.setAuthTag(H);let U=G.update(J),q=G.final(),_=U.length+q.length,A=i.allocUnsafe(_);return U.copy(A,0),q.copy(A,U.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S()}isServerMode(){return!S()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}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(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X),{consoleText:$,fileText:H}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let G=$.split(`
|
|
16
|
+
`),U=Math.max(...G.map((z)=>z.length))+2,q=`\u250C${"\u2500".repeat(U)}\u2510`,_=`\u2514${"\u2500".repeat(U)}\u2518`,A=G.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:w.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:w.cyan(q),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:w.cyan(_),showTimestamp:!1}))}else if(!S())console.error(`${Z} ${this.environment}.INFO: [BOX] ${H}`);let J=`${Z} ${this.environment}.INFO: [BOX] ${H}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt(Q){if(S())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${w.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();R.stdin.removeListener("data",Y);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let U=/%([sdijfo%])/g,q=0;if(Y=Q.replace(U,(_,A)=>{if(A==="%")return"%";if(q>=X.length)return _;let z=X[q++];switch(A){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 _}}),q<X.length)Y+=` ${X.slice(q).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",q=this.options.showIcons===!1?"":`${w.blue("\u25D0")} `;console.error(`${q}${U} ${w.cyan(Z)}`)}let G=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
18
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=w.green("\u2501".repeat(Z)),J=w.gray("\u2501".repeat($)),G=`[${H}${J}]`,U=`${Y}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=this.options.showIcons===!1?"":X||Y===100?w.green("\u2713"):w.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${G} ${U}${q}`,W=R.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,R.stdout.write(Q.lastRenderedLine),X)R.stdout.write(`
|
|
19
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||S()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await SQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=GQ(this.config.logDirectory,Z);if(Q.before)try{if((await UQ(H)).mtime>=Q.before)continue}catch(J){console.error(`Failed to get stats for file ${H}:`,J);continue}Y.push(H)}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 Z of Y)try{await EQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}async function mY(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,J=Error("Unknown error occurred");for(let G=0;G<=Y;G++)try{return await Q()}catch(U){if(J=U instanceof Error?U:Error(String(U)),G===Y||!$(J))break;if(Z>0)await new Promise((q)=>setTimeout(q,Z))}if(H!==void 0)return H;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}function uY(Q){return Q instanceof v}function D0(Q){return Q instanceof tQ}function V0(Q){if(uY(Q))return Q.code==="FILE_SYSTEM_ERROR"||Q.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>Q.message.toLowerCase().includes(Y.toLowerCase()))}class YX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,X)=>X==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let X=Q.toLowerCase();return["true","1","yes"].includes(X)}},{name:"number",canParse:(Q,X)=>X==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let X=Number(Q);if(Number.isNaN(X))throw TypeError(`Cannot parse "${Q}" as number`);return X}},{name:"array",canParse:(Q,X)=>X==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let X=JSON.parse(Q);if(Array.isArray(X))return X}catch{}return Q.split(",").map((X)=>X.trim())}},{name:"json",canParse:(Q,X)=>X==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(X){throw Error(`Cannot parse "${Q}" as JSON: ${X}`)}}}]}async applyEnvironmentVariables(Q,X,Y={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:H=!0,customParsers:J={},verbose:G=!1,trackPerformance:U=!0}=Y,q=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let _=Z||this.generateEnvPrefix(Q),A={...X};return this.processObject(A,[],_,{useCamelCase:$,useBackwardCompatibility:H,customParsers:J,verbose:G,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return jQ.track("applyEnvironmentVariables",q,{configName:Q});return q()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,X){if(!X)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let J=[...X,$],G=J.map((_)=>this.formatEnvKey(_,Z.useCamelCase)),U=`${Y}_${G.join("_")}`,q=Z.useBackwardCompatibility?`${Y}_${J.map((_)=>_.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,J,Y,Z);else{let _=TQ.env[U]||(q?TQ.env[q]:void 0);if(_!==void 0){if(Z.verbose){let A=TQ.env[U]?U:q}try{Q[$]=this.parseEnvironmentValue(_,typeof H,U,Z.customParsers,Z.configName)}catch(A){if(A instanceof rQ)throw A;throw QQ.envVar(U,_,typeof H,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[H,J]of Object.entries(Z))try{return J(Q)}catch{continue}for(let H of this.defaultParsers)if(H.canParse(Q,X))try{return H.parse(Q)}catch{throw QQ.envVar(Y,Q,`${X} (via ${H.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(TQ.env))if(Z.startsWith(Y)&&$!==void 0)X[Z]=$;return X}validateEnvironmentVariable(Q,X,Y){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Z.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Q,X,Y,{})}catch($){Z.push(`Cannot parse value "${X}" as ${Y}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,X,Y={}){let{prefix:Z,format:$="text"}=Y,H=Z||this.generateEnvPrefix(Q),J=[];switch(this.extractEnvVarInfo(X,[],H,J),$){case"markdown":return this.formatAsMarkdown(J,Q);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let J=[...X,$],G=`${Y}_${J.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,J,Y,Z);else Z.push({key:G,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${J.join(".")}`,example:this.generateExample(H)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,X){let Y=`Environment Variables for ${X}:
|
|
20
|
+
|
|
21
|
+
`;for(let Z of Q)Y+=`${Z.key}
|
|
22
|
+
`,Y+=` Type: ${Z.type}
|
|
23
|
+
`,Y+=` Description: ${Z.description}
|
|
24
|
+
`,Y+=` Example: ${Z.example}
|
|
25
|
+
|
|
26
|
+
`;return Y}formatAsMarkdown(Q,X){let Y=`# Environment Variables for ${X}
|
|
27
|
+
|
|
28
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
29
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
30
|
+
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
31
|
+
`;return Y}}function S0(Q,X){let Y=iY("process");if(typeof Y>"u"||!Y.env)return X;let Z=Y.env[Q];return Z!==void 0?Z:X}function gY(Q,X,Y={}){return cY(Q,X,Y,new WeakMap)}function cY(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:J}=Y;if(X===null||X===void 0)return H?Q:X;if(J){let G=J(Q,X);if(G!==void 0)return G}if(Array.isArray(X)||Array.isArray(Q))return lY(Q,X,$,Z);if(!h(X)||!h(Q))return X;return N0(Q,X,Y,Z)}function lY(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return E0(Q,X);case"smart":return T0(Q,X,Z);default:return X}return X}function E0(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>TX($,Z)))Y.push(Z);return Y}function T0(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(h(X[0])&&h(Q[0]))return O0(Q,X,Y);if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}function O0(Q,X,Y){let Z=[...X];for(let $ of Q){if(!h($)){Z.push($);continue}let H=["id","name","key","path","type"],J=!1;for(let G of H)if(G in $){if(Z.find((q)=>h(q)&&(G in q)&&q[G]===$[G])){J=!0;break}}if(!J)Z.push($)}return Z}function N0(Q,X,Y,Z){let $=X;if(h($)&&Z.has($))return Z.get($);let H={...Q};if(h($))Z.set($,H);for(let J in $){if(!Object.prototype.hasOwnProperty.call($,J))continue;let G=$[J],U=H[J];if(Y.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){H[J]=G;continue}if(h(G)&&h(U))H[J]=cY(U,G,Y,Z);else if(Array.isArray(G)||Array.isArray(U))H[J]=lY(U,G,Y.arrayMergeMode||"smart",Z);else H[J]=G}return H}function uX(Q,X,Y="replace"){return gY(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function TX(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!TX(Q[Y],X[Y]))return!1;return!0}if(h(Q)&&h(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!TX(Q[$],X[$]))return!1}return!0}return!1}function h(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class ZX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:J=!0,verbose:G=!1}=Y;if($){let q=zQ.getWithFileCheck("file",Q);if(q){if(G)console.log(`Configuration loaded from cache: ${Q}`);return q}}let U=async()=>{if(!OQ(Q))return null;try{let q=`?t=${Date.now()}`,_=await import(Q+q),A=_.default||_,z="default"in _,W=Object.keys(_).length>0;if(!z&&!W)throw new wQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new wQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:uX(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)zQ.setWithFileCheck("file",K,Q,H);return K}catch(q){throw q instanceof Error?QQ.configLoad(Q,q):QQ.configLoad(Q,Error(String(q)))}};if(J)return jQ.track("loadFromPath",U,{path:Q});return U()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){let Z=this.generateNamePatterns(Q,Y),$=[];for(let H of Z)for(let J of this.extensions)$.push(zX(X,`${H}${J}`));return $}generateNamePatterns(Q,X){let Y=[];if(Y.push("config",".config"),Q)Y.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(X){if(Y.push(X,`.${X}.config`,`${X}.config`,`.${X}`),Q)Y.push(`${Q}.${X}.config`,`.${Q}.${X}.config`)}return Y.filter(Boolean)}checkFileAccess(Q){return mY(async()=>{return OQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!OQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let J of this.extensions){let G=zX(Q,`${H}${J}`);if(await this.checkFileAccess(G))Z.push(G)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let J of H)if(this.looksLikeConfigFile(J)){let G=zX(Q,J);if(await this.checkFileAccess(G))Z.push(G)}}catch{return[]}return Z}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!OQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),H=$(Q,"utf8");JSON.parse(H)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}class gX{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:J=[],trackPerformance:G=!0,verbose:U=!1}=Y,q=async()=>{let _=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:J,trackPerformance:G,verbose:U};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...J],z);else return this.validateWithJSONSchema(Q,X,z)}catch(W){return _.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:_,warnings:A}}};if(G)return await jQ.track("validateConfiguration",q);return q()}async validateWithSchemaFile(Q,X,Y){try{if(!cZ(X))throw new KQ(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new KQ(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,H){if(H.validateTypes&&X.type){let J=Array.isArray(Q)?"array":typeof Q,G=Array.isArray(X.type)?X.type:[X.type];if(!G.includes(J)){if(Z.push({path:Y,message:`Expected type ${G.join(" or ")}, got ${J}`,expected:G.join(" or "),actual:J,rule:"type"}),H.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),H.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let J=0;J<Q.length;J++){let G=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema(Q[J],X.items,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q;if(H.validateRequired&&X.required){for(let G of X.required)if(!(G in J)){if(Z.push({path:Y?`${Y}.${G}`:G,message:`Missing required property '${G}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[G,U]of Object.entries(X.properties))if(G in J){let q=Y?`${Y}.${G}`:G;if(this.validateObjectAgainstSchema(J[G],U,q,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let G=new Set(Object.keys(X.properties||{}));for(let U of Object.keys(J))if(!G.has(U))$.push({path:Y?`${Y}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let J=this.getValueByPath(Q,H.path),G=this.validateWithRule(J,H,H.path);if(Z.push(...G),Y.stopOnFirstError&&Z.length>0)break}catch(J){Z.push({path:H.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,H,J]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(J)})}return X}mapTypeScriptType(Q){switch(Q.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:aY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class cX{fileLoader=new ZX;envProcessor=new YX;validator=new gX;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...J}=Q;try{if(Y?.enabled){let U=this.checkCache(J.name||"",J);if(U)return U}let G;try{G=await this.loadConfigurationStrategies(J,!0,Y)}catch(U){let q=J.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(q)throw U;G={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let _=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),A=!_&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),z=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(q&&(z||_))throw U;if(A&&(!q||!z))G={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!q)G={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else G={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if($||H)await this.validateConfiguration(G.config,$,H,J.name);if(Y?.enabled&&G)this.cacheResult(J.name||"",G,Y,J);if(Z?.enabled){let U={operation:"loadConfig",duration:Date.now()-X,configName:J.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(U);if(Z.slowThreshold&&U.duration>Z.slowThreshold)m.warn(`Slow configuration loading detected: ${U.duration}ms for ${J.name}`);G.metrics=U}return G}catch(G){let U=Date.now()-X;throw m.error(`Configuration loading failed after ${U}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:J,defaultConfig:G,checkEnv:U=!0,arrayStrategy:q="replace",verbose:_=!1}=Q,A=H||XQ.cwd(),z=[],W=await this.loadLocalConfiguration(Z,$,A,J,G,q,_,U,Y);if(W)return z.push(...this.getLocalSearchPaths(Z,$,A,J)),this.finalizeResult(W,z,U,Z,_);let I=await this.loadHomeConfiguration(Z,$,G,q,_,U);if(I)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(I,z,U,Z,_);let B=await this.loadPackageJsonConfiguration(Z,$,A,G,q,_,U);if(B)return z.push(y(A,"package.json")),this.finalizeResult(B,z,U,Z,_);if(z.push(...this.getAllSearchPaths(Z,$,A,J)),X)throw QQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,G,U,_),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,J,G,U){let q=G?RQ(Q,$,J):$,_=this.getLocalDirectories(Y,Z);for(let A of _){if(J)m.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,q,{arrayStrategy:H,verbose:J,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(W){if(J)m.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let J=H?RQ(Q,Y,$):Y,G=[y(ZQ(),".config",Q),y(ZQ(),".config"),ZQ()];for(let U of G){if($)m.info(`Checking home directory: ${U}`);let q=this.fileLoader.generateConfigPaths(Q,U,X),_=await this.fileLoader.tryLoadFromPaths(q,J,{arrayStrategy:Z,verbose:$});if(_){if($)m.success(`Configuration loaded from home directory: ${_.source.path}`);return _}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,J){let G=J?RQ(Q,Z,H):Z;try{let U=y(Y,"package.json");if(!SX(U))return null;let q=await import(U),_=q[Q],A=Q;if(!_&&X)_=q[X],A=X;if(_&&typeof _==="object"&&!Array.isArray(_)){if(H)m.success(`Configuration loaded from package.json: ${A}`);return{config:uX(G,_,$),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(H)m.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:RQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let H=Y(Q);if(H)$.push(...H)}if(X){let H=await this.validator.validateConfiguration(Q,X);if(!H.isValid)$.push(...H.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if($.length>0)throw QQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return zQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);zQ.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias)Y.push(`alias:${X.alias}`);if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return Array.from(new Set([Q,y(Q,"config"),y(Q,".config"),X?y(Q,X):void 0].filter(Boolean)))}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(y(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),H=[];for(let J of $)H.push(...this.fileLoader.generateConfigPaths(Q,J,X));return H}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[y(ZQ(),".config",Q),y(ZQ(),".config"),ZQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function FY(Q){let Y=!(Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"))&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")),Z=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");return Y||Z}async function C0(Q){return a.loadConfig({...Q,__strictErrorHandling:!0})}async function nY(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await a.loadConfig(Q);else Z=await a.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",H=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||H.includes("config"))&&Q.verbose)m.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let G=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await a.applyEnvironmentVariables(G.name||"",X,!0,G.verbose||!1))?.config??X;return X}}async function x0(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:X}=await import("process");try{return(await a.loadConfig({name:Q,cwd:X(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&FY(Y)))return(await a.applyEnvironmentVariables(Q,{},!0,!1)).config;throw Y}}try{return(await a.loadConfig({...Q,cwd:Q.cwd||XQ.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&FY(X)))return(await a.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw X}}async function k0(Q,X,Y="replace"){let Z=new ZX;try{let $=await Z.loadFromPath(Q,X,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return $?$.config:null}catch{return null}}function RQ(Q,X,Y=!1){let Z=new YX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(J,G=[]){let U={...J};for(let[q,_]of Object.entries(J)){let A=[...G,q],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,I;for(let B of z)if(W=XQ.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof _==="boolean")U[q]=["true","1","yes"].includes(W.toLowerCase());else if(typeof _==="number"){let B=Number(W);if(!Number.isNaN(B))U[q]=B}else if(Array.isArray(_))try{U[q]=JSON.parse(W)}catch{U[q]=W.split(",").map((B)=>B.trim())}else U[q]=W;else if(_&&typeof _==="object"&&!Array.isArray(_))U[q]=H(_,A)}return U}return H(X)}function P0(Q){let X=y(XQ.cwd(),Q.configDir),Y=y(XQ.cwd(),Q.generatedDir),Z=y(Y,"config-types.ts");if(!SX(aX(Z)))FZ(aX(Z),{recursive:!0,mode:511});let $=SX(X)?MZ(X).map((J)=>J.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],H=`// Generated by bunfig v${G8}
|
|
32
|
+
export type ConfigNames = ${$.length?`'${$.join("' | '")}'`:"string"}
|
|
33
|
+
`;DZ(Z,H,{mode:438})}function b0(Q){let X=null,Y=null,Z=()=>{if(!Y)Y=nY(Q).then((H)=>{return X=H,H},(H)=>{let J="defaultConfig"in Q?Q.defaultConfig:{};if(X=J,"verbose"in Q&&Q.verbose)m.warn("Config loading failed, using defaults:",[H instanceof Error?H:Error(String(H))]);return J});return Y},$="defaultConfig"in Q?Q.defaultConfig:{};return X=$,Z(),new Proxy({},{get(H,J){if(X)return X[J];let G=$[J];return Z(),G},has(H,J){return J in(X||$)},ownKeys(){return Object.keys(X||$)},getOwnPropertyDescriptor(H,J){return Object.getOwnPropertyDescriptor(X||$,J)},set(H,J,G){if(!X)X={...$};return X[J]=G,!0}})}function y0(Q){let X=zY(iZ.cwd(),Q?.configDir||"./config");function Y(){if(!lZ(X))return[];let $=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),H=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],J=nZ(X).filter((U)=>$.has(BX(U))).map((U)=>({base:U.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:U})),G=new Map;for(let{base:U,file:q}of J){let _=BX(q).toLowerCase(),A=G.get(U);if(!A){G.set(U,q);continue}let z=BX(A).toLowerCase();if(H.indexOf(_)<H.indexOf(z))G.set(U,q)}return Array.from(G.entries()).map(([U,q])=>({base:U,file:q})).sort((U,q)=>U.base.localeCompare(q.base))}function Z(){let $=Y(),H=$.map((q)=>q.base),J=H.length?H.map((q)=>`'${q}'`).join(" | "):"string",G=$.length?`{
|
|
34
|
+
${$.map((q)=>{let _=zY(X,q.file).replace(/\\/g,"/");return` '${q.base}': typeof import('${_}').default`}).join(`,
|
|
35
|
+
`)}
|
|
36
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${J}
|
|
37
|
+
export type ConfigByName = ${G}
|
|
38
|
+
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
|
+
export type ConfigOf = Config
|
|
40
|
+
`}return{name:"bunfig-plugin",setup($){$.onResolve({filter:/^virtual:bunfig-types$/},(H)=>{return{path:H.path,namespace:"bunfig-virtual"}}),$.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var iY,zQ,jQ,sY,v0,d0,MY,dQ,OX,C,M,h0,DY,f0,VY,p0,m0,KX,u0,SY,EY,jX,g0,c0,l0,n0,hQ,oY,i0,x,s0,o0,TY,fQ,NX,E,w,t0,OY,r0,NY,a0,e0,IX,Q8,CY,xY,X8,FX,Y8,Z8,$8,H8,J8,pQ,tY,U8,G8="0.15.6",v,tQ,wQ,CX,xX,rQ,kX,PX,KQ,bX,yX,QQ,rY,aY,m,a,eY,QZ,q8=q0(async()=>{iY=import.meta.require,zQ=new hX,jQ=new fX,sY={createKey:_0,isEquivalent:A0,estimateMemoryUsage:W0},v0=cQ(EX.cwd(),"config"),d0=cQ(EX.cwd(),"src/generated"),MY=gQ.env.CLARITY_LOG_DIR||EZ(R0(),"logs"),dQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:MY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},OX=await L0(),C={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},M=C,h0=C.red,DY=C.green,f0=C.yellow,VY=C.blue,p0=C.magenta,m0=C.cyan,KX=C.white,u0=C.gray,SY=C.bgRed,EY=C.bgYellow,jX=C.bold,g0=C.dim,c0=C.italic,l0=C.underline,n0=C.reset,hQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oY={debug:"\uD83D\uDD0D",info:VY("\u2139"),success:DY("\u2713"),warning:EY(KX(jX(" WARN "))),error:SY(KX(jX(" ERROR ")))},i0=new iQ("stacks"),x=new iQ("bunfig",{showTags:!0}),s0=b(LQ.cwd(),"config"),o0=b(LQ.cwd(),"src/generated"),TY=uQ.env.CLARITY_LOG_DIR||VZ(I0(),"logs"),fQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:TY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},NX=await F0(),E={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},w=E,t0=E.red,OY=E.green,r0=E.yellow,NY=E.blue,a0=E.magenta,e0=E.cyan,IX=E.white,Q8=E.gray,CY=E.bgRed,xY=E.bgYellow,X8=E.bgGray,FX=E.bold,Y8=E.dim,Z8=E.italic,$8=E.underline,H8=E.strikethrough,J8=E.reset,pQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},tY={debug:"\uD83D\uDD0D",info:NY("\u2139"),success:OY("\u2713"),warning:xY(IX(FX(" WARN "))),error:CY(IX(FX(" ERROR ")))},U8=new oQ("stacks"),v=class extends Error{timestamp;context;constructor(X,Y={}){super(X);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let X=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,Z])=>`${Y}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${X}`}},tQ=class extends v{code="CONFIG_NOT_FOUND";constructor(X,Y,Z){let $=Z?` or alias "${Z}"`:"";super(`Configuration "${X}"${$} not found`,{configName:X,alias:Z,searchPaths:Y,searchPathCount:Y.length})}},wQ=class extends v{code="CONFIG_LOAD_ERROR";constructor(X,Y,Z){super(`Failed to load configuration from "${X}": ${Y.message}`,{configPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},CX=class extends v{code="CONFIG_VALIDATION_ERROR";constructor(X,Y,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:Y,errorCount:Y.length})}},xX=class extends v{code="CONFIG_MERGE_ERROR";constructor(X,Y,Z,$){super(`Failed to merge configuration from "${X}" with "${Y}": ${Z.message}`,{sourcePath:X,targetPath:Y,configName:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},rQ=class extends v{code="ENV_VAR_ERROR";constructor(X,Y,Z,$){super(`Failed to parse environment variable "${X}" with value "${Y}" as ${Z}`,{envKey:X,envValue:Y,expectedType:Z,configName:$})}},kX=class extends v{code="FILE_SYSTEM_ERROR";constructor(X,Y,Z){super(`File system ${X} failed for "${Y}": ${Z.message}`,{operation:X,path:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},PX=class extends v{code="TYPE_GENERATION_ERROR";constructor(X,Y,Z){super(`Failed to generate types from "${X}" to "${Y}": ${Z.message}`,{configDir:X,outputPath:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},KQ=class extends v{code="SCHEMA_VALIDATION_ERROR";constructor(X,Y,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:X,configName:Z,validationErrors:Y,errorCount:Y.length})}},bX=class extends v{code="BROWSER_CONFIG_ERROR";constructor(X,Y,Z,$){super(`Failed to fetch configuration from "${X}": ${Y} ${Z}`,{endpoint:X,status:Y,statusText:Z,configName:$})}},yX=class extends v{code="PLUGIN_ERROR";constructor(X,Y,Z){super(`Plugin "${X}" failed during ${Y}: ${Z.message}`,{pluginName:X,operation:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},QQ={configNotFound(Q,X,Y){return new tQ(Q,X,Y)},configLoad(Q,X,Y){return new wQ(Q,X,Y)},configValidation(Q,X,Y){return new CX(Q,X,Y)},configMerge(Q,X,Y,Z){return new xX(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new rQ(Q,X,Y,Z)},fileSystem(Q,X,Y){return new kX(Q,X,Y)},typeGeneration(Q,X,Y){return new PX(Q,X,Y)},schemaValidation(Q,X,Y){return new KQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new bX(Q,X,Y,Z)},plugin(Q,X,Y){return new yX(Q,X,Y)}},rY={replace:"replace",concat:"concat",smart:"smart"},aY=/^https?:\/\//,m=new oQ("bunfig",{showTags:!0}),a=new cX,eY=y(XQ.cwd(),"config"),QZ=y(XQ.cwd(),"src/generated")});function _8(Q,X={}){let Y=lQ.cwd();while(Y.includes("storage"))Y=BY(Y,"..");let Z=BY(Y,Q||"");if(X?.relative)return oZ(lQ.cwd(),Z);return Z}var A8=lQ.env.CLARITY_LOG_DIR||sZ(_8(),"logs"),XZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:A8,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},aQ={...XZ},t9=(async()=>{try{let{loadConfig:Q}=await q8().then(()=>hY),X=await Q({name:"clarity",alias:"logging",defaultConfig:XZ,cwd:lQ.cwd()});if(X)Object.assign(aQ,X)}catch{}return aQ})();function T(){if(r.env.NODE_ENV==="test"||r.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function W8(){if(r.env.NODE_ENV==="test"||r.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof r<"u"){let Q=r.type;if(Q==="renderer"||Q==="worker")return!1;return!!(r.versions&&(r.versions.node||r.versions.bun))}return!1}class YZ{async format(Q){let X=await W8(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:WQ.pid,hostname:X(),environment:WQ.env.NODE_ENV||"development",platform:WQ.platform,version:WQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:WQ.env.NODE_ENV||WQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var O={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},j=O,r9=O.red,z8=O.green,a9=O.yellow,B8=O.blue,e9=O.magenta,Q$=O.cyan,kY=O.white,X$=O.gray,R8=O.bgRed,L8=O.bgYellow,Y$=O.bgGray,PY=O.bold,Z$=O.dim,$$=O.italic,H$=O.underline,J$=O.strikethrough,U$=O.reset,MX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},w8={debug:"\uD83D\uDD0D",info:B8("\u2139"),success:z8("\u2713"),warning:L8(kY(PY(" WARN "))),error:R8(kY(PY(" ERROR ")))};class $X{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(Q,X={}){this.name=Q,this.config={...aQ},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new YZ,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??L.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return X[Q]>=X[Y]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...MX,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...MX};return{...MX,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:aQ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}shouldWriteToFile(){return!T()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,J=3,G=1000;while(H<J)try{try{try{await Q0(this.config.logDirectory,KY.F_OK|KY.W_OK)}catch(q){if(q instanceof Error&&"code"in q)if(q.code==="ENOENT")await X0(this.config.logDirectory,{recursive:!0,mode:493});else if(q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw q;else throw q}}catch(q){throw console.error("Debug: [writeToFile] Failed to create log directory:",q),q}let U=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:s.from(Q);try{if(!NQ(this.currentLogFile))await wX(this.currentLogFile,"",{mode:420});if($=wY(this.currentLogFile,"a",420),eZ($,U,{flag:"a"}),LY($),$!==void 0)LX($),$=void 0;if((await _Q(this.currentLogFile)).size===0){if(await wX(this.currentLogFile,U,{flag:"w",mode:420}),(await _Q(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(q){let _=q;if(_.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(_.code)){if(H<J-1){let A=typeof _.message==="string"?_.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${J}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(_?.code&&["ENOSPC","EDQUOT"].includes(_.code))throw Error(`Disk quota exceeded or no space left on device: ${_.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",_),_}finally{if($!==void 0)try{LX($)}catch(q){console.error("Debug: [writeToFile] Error closing file descriptor:",q)}}}catch(U){if(H===J-1){let _=U,A=typeof _.message==="string"?_.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),U}H++;let q=G*2**(H-1);await new Promise((_)=>setTimeout(_,q))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 AQ(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 AQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return AQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(T())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,U])=>U.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,J=Math.max(1,H);if($.length>J)for(let[G]of $.slice(J))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return RX(16).toString("hex")}generateKey(){return RX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=RX(16),Z=tZ("aes-256-gcm",X,Y),$=s.isBuffer(Q)?Q:s.from(Q,"utf8"),H=Z.update($),J=Z.final(),G=H.length+J.length,U=Z.getAuthTag(),q=s.allocUnsafe(16+G+16);return Y.copy(q,0),H.copy(q,16),J.copy(q,16+H.length),U.copy(q,16+G),{encrypted:q,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=IY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(s.from(s.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(T())return;if(!this.shouldWriteToFile())return;let Q=await _Q(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await CQ(this.config.logDirectory),H=$.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,q)=>{let _=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(q.match(/\.log\.(\d+)$/)?.[1]||"0")-_}),J=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${J}`;if(await _Q(Y).catch(()=>null))try{if(await jY(Y,G),X.compress)try{let U=`${G}.gz`;await this.compressLogFile(G,U),await xQ(G)}catch(U){console.error("Error compressing rotated file:",U)}if(H.length===0&&!$.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await wX(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 $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await _Q(Y).catch(()=>null))await jY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await CQ(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,G)=>G.localeCompare(J));for(let J of H.slice(X.maxFiles))await xQ(AQ(this.config.logDirectory,J))}}}async compressLogFile(Q,X){let Y=RY(Q),Z=aZ(X),$=IY();await $0(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),NQ(this.currentLogFile))try{let Q=wY(this.currentLogFile,"r+");LY(Q),LX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!T()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await CQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await xQ(AQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?j.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T())return!1;let Q=typeof L.env.NO_COLOR<"u",X=L.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:J=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(J)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let U=L.stdout.columns||120,q="";if(H==="warning"||H==="error")q=`${Y} ${$}`;else if(H==="info"||H==="success")q=`${Y} ${Z} ${$}`;else q=`${Y} ${Z} ${j.cyan($)}`;if(!J)return q.trim();let _=G(q).trim().length,A=G(X).length,z=Math.max(1,U-2-_-A);return`${q.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,J)=>{let G=Number.parseInt(J,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,J)=>{if(J==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(J){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let X=Q;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,$)=>{let H=j.underline(j.blue(Z)),J=this.toAbsoluteFilePath($);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let G=`file://${encodeURI(J)}`,U="\x1B]8;;",q="\x1B\\";return`\x1B]8;;${G}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),X=X.replace(/`([^`]+)`/g,(Y,Z)=>j.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>j.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>j.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>j.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>j.strikethrough(Z)),X}supportsHyperlinks(){if(T())return!1;let Q=L.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let X=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let X=Q;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Y=L.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(Y0(X)||X.startsWith("./")||X.startsWith("../"))X=Z0(X);else return null;return NQ(X)?X:null}catch{return null}}buildOutputTexts(Q){let X=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Y=Q.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Y}}async log(Q,X,...Y){if(!this.shouldLog(Q))return;let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),J,G;if(X instanceof Error)J=X.message,G=X.stack;else J=this.formatMessage(X,Y);let{consoleText:U,fileText:q}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":w8[Q],z=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:j.gray(U),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:U,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:j.green(U),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:U,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:U,level:Q}),console.error(W),G){let I=G.split(`
|
|
41
|
+
`);for(let B of I)if(B.trim()&&!B.includes(J))console.error(this.formatConsoleMessage({timestamp:$,message:j.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!T()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${J}`),G)console.error(G)}let _=`${H} ${this.environment}.${Q.toUpperCase()}: ${q}
|
|
42
|
+
`;if(G)_+=`${G}
|
|
43
|
+
`;if(_=_.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(_)}progress(Q,X=""){let Y={update:(G,U)=>{},finish:(G)=>{},interrupt:(G,U)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:X||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!T()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(G,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,G),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!T()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(G)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,G)},interrupt:(G,U="info")=>{if(!T()&&L.stdout.isTTY)L.stdout.write(`
|
|
44
|
+
`);if(this[U==="warning"?"warn":U](G),this.activeProgressBar&&this.shouldStyleConsole()&&!T()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":j.blue("\u25D0"),tag:Y,message:`${j.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,J=new Date,G=this.formatConsoleTimestamp(J),q=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${H}`;if(Y)q+=` ${JSON.stringify(Y)}`;if(q+=`
|
|
45
|
+
`,q=q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let _=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":j.green("\u2713"),tag:_,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T())console.error(q.trim());if(this.shouldWriteToFile())await this.writeToFile(q)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new $X(X,{...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(T())throw Error("createReadStream is not supported in browser environments");if(!NQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return RY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.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 Z=s.isBuffer(Q)?Q:s.from(Q,"base64"),$=Z.subarray(0,16),H=Z.subarray(Z.length-16),J=Z.subarray(16,Z.length-16),G=rZ("aes-256-gcm",Y,$);G.setAuthTag(H);let U=G.update(J),q=G.final(),_=U.length+q.length,A=s.allocUnsafe(_);return U.copy(A,0),q.copy(A,U.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T()}isServerMode(){return!T()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}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(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X),{consoleText:$,fileText:H}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let G=$.split(`
|
|
46
|
+
`),U=Math.max(...G.map((z)=>z.length))+2,q=`\u250C${"\u2500".repeat(U)}\u2510`,_=`\u2514${"\u2500".repeat(U)}\u2518`,A=G.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:j.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(q),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(_),showTimestamp:!1}))}else if(!T())console.error(`${Z} ${this.environment}.INFO: [BOX] ${H}`);let J=`${Z} ${this.environment}.INFO: [BOX] ${H}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt(Q){if(T())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${j.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();L.stdin.removeListener("data",Y);try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!1)}catch{}L.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!0)}catch{}L.stdin.resume(),L.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let U=/%([sdijfo%])/g,q=0;if(Y=Q.replace(U,(_,A)=>{if(A==="%")return"%";if(q>=X.length)return _;let z=X[q++];switch(A){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 _}}),q<X.length)Y+=` ${X.slice(q).map((_)=>typeof _==="object"?JSON.stringify(_,null,2):String(_)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",q=this.options.showIcons===!1?"":`${j.blue("\u25D0")} `;console.error(`${q}${U} ${j.cyan(Z)}`)}let G=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
48
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!L.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=j.green("\u2501".repeat(Z)),J=j.gray("\u2501".repeat($)),G=`[${H}${J}]`,U=`${Y}%`.padStart(4),q=Q.message?` ${Q.message}`:"",_=this.options.showIcons===!1?"":X||Y===100?j.green("\u2713"):j.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",z=`\r${_}${A} ${G} ${U}${q}`,W=L.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,L.stdout.write(Q.lastRenderedLine),X)L.stdout.write(`
|
|
49
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||T()||!L.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(T()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await CQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=AQ(this.config.logDirectory,Z);if(Q.before)try{if((await _Q(H)).mtime>=Q.before)continue}catch(J){console.error(`Failed to get stats for file ${H}:`,J);continue}Y.push(H)}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 Z of Y)try{await xQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}var G$=new $X("stacks");class u extends Error{timestamp;context;constructor(Q,X={}){super(Q);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let Q=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,Y])=>`${X}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Q}`}}class ZZ extends u{code="CONFIG_NOT_FOUND";constructor(Q,X,Y){let Z=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],$="";if(Z.length===1)$=` or alias "${Z[0]}"`;else if(Z.length>1)$=` or aliases ${Z.map((H)=>`"${H}"`).join(", ")}`;super(`Configuration "${Q}"${$} not found`,{configName:Q,alias:Y,searchPaths:X,searchPathCount:X.length})}}class eQ extends u{code="CONFIG_LOAD_ERROR";constructor(Q,X,Y){super(`Failed to load configuration from "${Q}": ${X.message}`,{configPath:Q,configName:Y,originalError:X.name,originalMessage:X.message});this.cause=X}}class $Z extends u{code="CONFIG_VALIDATION_ERROR";constructor(Q,X,Y){super(`Configuration validation failed for "${Q}"`,{configPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class HZ extends u{code="CONFIG_MERGE_ERROR";constructor(Q,X,Y,Z){super(`Failed to merge configuration from "${Q}" with "${X}": ${Y.message}`,{sourcePath:Q,targetPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class lX extends u{code="ENV_VAR_ERROR";constructor(Q,X,Y,Z){super(`Failed to parse environment variable "${Q}" with value "${X}" as ${Y}`,{envKey:Q,envValue:X,expectedType:Y,configName:Z})}}class JZ extends u{code="FILE_SYSTEM_ERROR";constructor(Q,X,Y){super(`File system ${Q} failed for "${X}": ${Y.message}`,{operation:Q,path:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class UZ extends u{code="TYPE_GENERATION_ERROR";constructor(Q,X,Y){super(`Failed to generate types from "${Q}" to "${X}": ${Y.message}`,{configDir:Q,outputPath:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class QX extends u{code="SCHEMA_VALIDATION_ERROR";constructor(Q,X,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class GZ extends u{code="BROWSER_CONFIG_ERROR";constructor(Q,X,Y,Z){super(`Failed to fetch configuration from "${Q}": ${X} ${Y}`,{endpoint:Q,status:X,statusText:Y,configName:Z})}}class qZ extends u{code="PLUGIN_ERROR";constructor(Q,X,Y){super(`Plugin "${Q}" failed during ${X}: ${Y.message}`,{pluginName:Q,operation:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}var BQ={configNotFound(Q,X,Y){return new ZZ(Q,X,Y)},configLoad(Q,X,Y){return new eQ(Q,X,Y)},configValidation(Q,X,Y){return new $Z(Q,X,Y)},configMerge(Q,X,Y,Z){return new HZ(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new lX(Q,X,Y,Z)},fileSystem(Q,X,Y){return new JZ(Q,X,Y)},typeGeneration(Q,X,Y){return new UZ(Q,X,Y)},schemaValidation(Q,X,Y){return new QX(Q,X,Y)},browserConfig(Q,X,Y,Z){return new GZ(Q,X,Y,Z)},plugin(Q,X,Y){return new qZ(Q,X,Y)}};async function K8(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,J=Error("Unknown error occurred");for(let G=0;G<=Y;G++)try{return await Q()}catch(U){if(J=U instanceof Error?U:Error(String(U)),G===Y||!$(J))break;if(Z>0)await new Promise((q)=>setTimeout(q,Z))}if(H!==void 0)return H;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}class nX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,X)=>X==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let X=Q.toLowerCase();return["true","1","yes"].includes(X)}},{name:"number",canParse:(Q,X)=>X==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let X=Number(Q);if(Number.isNaN(X))throw TypeError(`Cannot parse "${Q}" as number`);return X}},{name:"array",canParse:(Q,X)=>X==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let X=JSON.parse(Q);if(Array.isArray(X))return X}catch{}return Q.split(",").map((X)=>X.trim())}},{name:"json",canParse:(Q,X)=>X==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(X){throw Error(`Cannot parse "${Q}" as JSON: ${X}`)}}}]}async applyEnvironmentVariables(Q,X,Y={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:H=!0,customParsers:J={},verbose:G=!1,trackPerformance:U=!0}=Y,q=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let _=Z||this.generateEnvPrefix(Q),A={...X};return this.processObject(A,[],_,{useCamelCase:$,useBackwardCompatibility:H,customParsers:J,verbose:G,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(U)return dX.track("applyEnvironmentVariables",q,{configName:Q});return q()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,X){if(!X)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let J=[...X,$],G=J.map((_)=>this.formatEnvKey(_,Z.useCamelCase)),U=`${Y}_${G.join("_")}`,q=Z.useBackwardCompatibility?`${Y}_${J.map((_)=>_.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,J,Y,Z);else{let _=PQ.env[U]||(q?PQ.env[q]:void 0);if(_!==void 0){if(Z.verbose){let A=PQ.env[U]?U:q}try{Q[$]=this.parseEnvironmentValue(_,typeof H,U,Z.customParsers,Z.configName)}catch(A){if(A instanceof lX)throw A;throw BQ.envVar(U,_,typeof H,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[H,J]of Object.entries(Z))try{return J(Q)}catch{continue}for(let H of this.defaultParsers)if(H.canParse(Q,X))try{return H.parse(Q)}catch{throw BQ.envVar(Y,Q,`${X} (via ${H.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(PQ.env))if(Z.startsWith(Y)&&$!==void 0)X[Z]=$;return X}validateEnvironmentVariable(Q,X,Y){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Z.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Q,X,Y,{})}catch($){Z.push(`Cannot parse value "${X}" as ${Y}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,X,Y={}){let{prefix:Z,format:$="text"}=Y,H=Z||this.generateEnvPrefix(Q),J=[];switch(this.extractEnvVarInfo(X,[],H,J),$){case"markdown":return this.formatAsMarkdown(J,Q);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let J=[...X,$],G=`${Y}_${J.map((U)=>this.formatEnvKey(U,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,J,Y,Z);else Z.push({key:G,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${J.join(".")}`,example:this.generateExample(H)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,X){let Y=`Environment Variables for ${X}:
|
|
50
|
+
|
|
51
|
+
`;for(let Z of Q)Y+=`${Z.key}
|
|
52
|
+
`,Y+=` Type: ${Z.type}
|
|
53
|
+
`,Y+=` Description: ${Z.description}
|
|
54
|
+
`,Y+=` Example: ${Z.example}
|
|
55
|
+
|
|
56
|
+
`;return Y}formatAsMarkdown(Q,X){let Y=`# Environment Variables for ${X}
|
|
57
|
+
|
|
58
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
59
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
60
|
+
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
61
|
+
`;return Y}}function j8(Q,X,Y={}){return _Z(Q,X,Y,new WeakMap)}function _Z(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:J}=Y;if(X===null||X===void 0)return H?Q:X;if(J){let G=J(Q,X);if(G!==void 0)return G}if(Array.isArray(X)||Array.isArray(Q))return AZ(Q,X,$,Z);if(!f(X)||!f(Q))return X;return D8(Q,X,Y,Z)}function AZ(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return I8(Q,X);case"smart":return F8(Q,X,Z);default:return X}return X}function I8(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>vX($,Z)))Y.push(Z);return Y}function F8(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(f(X[0])&&f(Q[0]))return M8(Q,X,Y);if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}function M8(Q,X,Y){let Z=[...X];for(let $ of Q){if(!f($)){Z.push($);continue}let H=["id","name","key","path","type"],J=!1;for(let G of H)if(G in $){if(Z.find((q)=>f(q)&&(G in q)&&q[G]===$[G])){J=!0;break}}if(!J)Z.push($)}return Z}function D8(Q,X,Y,Z){let $=X;if(f($)&&Z.has($))return Z.get($);let H={...Q};if(f($))Z.set($,H);for(let J in $){if(!Object.prototype.hasOwnProperty.call($,J))continue;let G=$[J],U=H[J];if(Y.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){H[J]=G;continue}if(f(G)&&f(U))H[J]=_Z(U,G,Y,Z);else if(Array.isArray(G)||Array.isArray(U))H[J]=AZ(U,G,Y.arrayMergeMode||"smart",Z);else H[J]=G}return H}function WZ(Q,X,Y="replace"){return j8(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function vX(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!vX(Q[Y],X[Y]))return!1;return!0}if(f(Q)&&f(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!vX(Q[$],X[$]))return!1}return!0}return!1}function f(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class zZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:J=!0,verbose:G=!1}=Y;if($){let q=mQ.getWithFileCheck("file",Q);if(q){if(G)console.log(`Configuration loaded from cache: ${Q}`);return q}}let U=async()=>{if(!bQ(Q))return null;try{let q=`?t=${Date.now()}`,_=await import(Q+q),A=_.default||_,z="default"in _,W=Object.keys(_).length>0;if(!z&&!W)throw new eQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new eQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:WZ(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)mQ.setWithFileCheck("file",K,Q,H);return K}catch(q){throw q instanceof Error?BQ.configLoad(Q,q):BQ.configLoad(Q,Error(String(q)))}};if(J)return dX.track("loadFromPath",U,{path:Q});return U()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){let Z=this.generateNamePatterns(Q,Y),$=[];for(let H of Z)for(let J of this.extensions)$.push(DX(X,`${H}${J}`));return $}generateNamePatterns(Q,X){let Y=[];if(Y.push("config",".config"),Q)Y.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);let Z=X===void 0?[]:Array.isArray(X)?X:[X];for(let H of Z){if(!H)continue;if(Y.push(H,`.${H}.config`,`${H}.config`,`.${H}`),Q)Y.push(`${Q}.${H}.config`,`.${Q}.${H}.config`)}let $=new Set;return Y.filter((H)=>{if(!H||$.has(H))return!1;return $.add(H),!0})}checkFileAccess(Q){return K8(async()=>{return bQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!bQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let J of this.extensions){let G=DX(Q,`${H}${J}`);if(await this.checkFileAccess(G))Z.push(G)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let J of H)if(this.looksLikeConfigFile(J)){let G=DX(Q,J);if(await this.checkFileAccess(G))Z.push(G)}}catch{return[]}return Z}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!bQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),H=$(Q,"utf8");JSON.parse(H)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}var S8=/^https?:\/\//;class BZ{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:J=[],trackPerformance:G=!0,verbose:U=!1}=Y,q=async()=>{let _=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:J,trackPerformance:G,verbose:U};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...J],z);else return this.validateWithJSONSchema(Q,X,z)}catch(W){return _.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:_,warnings:A}}};if(G)return await dX.track("validateConfiguration",q);return q()}async validateWithSchemaFile(Q,X,Y){try{if(!V8(X))throw new QX(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new QX(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,H){if(H.validateTypes&&X.type){let J=Array.isArray(Q)?"array":typeof Q,G=Array.isArray(X.type)?X.type:[X.type];if(!G.includes(J)){if(Z.push({path:Y,message:`Expected type ${G.join(" or ")}, got ${J}`,expected:G.join(" or "),actual:J,rule:"type"}),H.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),H.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let J=0;J<Q.length;J++){let G=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema(Q[J],X.items,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q;if(H.validateRequired&&X.required){for(let G of X.required)if(!(G in J)){if(Z.push({path:Y?`${Y}.${G}`:G,message:`Missing required property '${G}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[G,U]of Object.entries(X.properties))if(G in J){let q=Y?`${Y}.${G}`:G;if(this.validateObjectAgainstSchema(J[G],U,q,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let G=new Set(Object.keys(X.properties||{}));for(let U of Object.keys(J))if(!G.has(U))$.push({path:Y?`${Y}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let J=this.getValueByPath(Q,H.path),G=this.validateWithRule(J,H,H.path);if(Z.push(...G),Y.stopOnFirstError&&Z.length>0)break}catch(J){Z.push({path:H.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,H,J]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(J)})}return X}mapTypeScriptType(Q){switch(Q.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:S8},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var c=new $X("bunfig",{showTags:!0});function E8(Q){if(!Q)return"";let X=Array.isArray(Q)?Q.filter(Boolean):[Q];if(X.length===0)return"";if(X.length===1)return` or alias "${X[0]}"`;return` or aliases ${X.map((Y)=>`"${Y}"`).join(", ")}`}class RZ{fileLoader=new zZ;envProcessor=new nX;validator=new BZ;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...J}=Q;try{if(Y?.enabled){let U=this.checkCache(J.name||"",J);if(U)return U}let G;try{G=await this.loadConfigurationStrategies(J,!0,Y)}catch(U){let q=J.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(q)throw U;G={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let _=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),A=!_&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),z=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(q&&(z||_))throw U;if(A&&(!q||!z))G={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!q)G={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else G={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if($||H)await this.validateConfiguration(G.config,$,H,J.name);if(Y?.enabled&&G)this.cacheResult(J.name||"",G,Y,J);if(Z?.enabled){let U={operation:"loadConfig",duration:Date.now()-X,configName:J.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(U);if(Z.slowThreshold&&U.duration>Z.slowThreshold)c.warn(`Slow configuration loading detected: ${U.duration}ms for ${J.name}`);G.metrics=U}return G}catch(G){if(G instanceof Error&&G.name==="ConfigNotFoundError")throw G;let U=Date.now()-X;throw c.error(`Configuration loading failed after ${U}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:J,defaultConfig:G,checkEnv:U=!0,arrayStrategy:q="replace",verbose:_=!1}=Q,A=H||XX.cwd(),z=[],W=await this.loadLocalConfiguration(Z,$,A,J,G,q,_,U,Y);if(W)return z.push(...this.getLocalSearchPaths(Z,$,A,J)),this.finalizeResult(W,z,U,Z,_);let I=await this.loadHomeConfiguration(Z,$,G,q,_,U);if(I)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(I,z,U,Z,_);let B=await this.loadPackageJsonConfiguration(Z,$,A,G,q,_,U);if(B)return z.push(d(A,"package.json")),this.finalizeResult(B,z,U,Z,_);if(z.push(...this.getAllSearchPaths(Z,$,A,J)),X)throw BQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,G,U,_),warnings:[`No configuration file found for "${Z}"${E8($)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,J,G,U){let q=G?yQ(Q,$,J):$,_=this.getLocalDirectories(Y,Z);for(let A of _){if(J)c.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,q,{arrayStrategy:H,verbose:J,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(W){if(J)c.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let J=H?yQ(Q,Y,$):Y,G=[d(YQ(),".config",Q),d(YQ(),".config"),YQ()];for(let U of G){if($)c.info(`Checking home directory: ${U}`);let q=this.fileLoader.generateConfigPaths(Q,U,X),_=await this.fileLoader.tryLoadFromPaths(q,J,{arrayStrategy:Z,verbose:$});if(_){if($)c.success(`Configuration loaded from home directory: ${_.source.path}`);return _}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,J){let G=J?yQ(Q,Z,H):Z;try{let U=d(Y,"package.json");if(!jZ(U))return null;let q={};try{q=JSON.parse(IZ(U,"utf8"))}catch(z){if(H)c.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let _=q[Q],A=Q;if(!_&&X){let z=Array.isArray(X)?X:[X];for(let W of z){if(!W)continue;if(q[W]){_=q[W],A=W;break}}}if(_&&typeof _==="object"&&!Array.isArray(_)){if(H)c.success(`Configuration loaded from package.json: ${A}`);return{config:WZ(G,_,$),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(H)c.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:yQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let H=Y(Q);if(H)$.push(...H)}if(X){let H=await this.validator.validateConfiguration(Q,X);if(!H.isValid)$.push(...H.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if($.length>0)throw BQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return mQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);mQ.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias){let Z=Array.isArray(X.alias)?X.alias.join(","):X.alias;Y.push(`alias:${Z}`)}if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return Array.from(new Set([Q,d(Q,"config"),d(Q,".config"),X?d(Q,X):void 0].filter(Boolean)))}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(d(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),H=[];for(let J of $)H.push(...this.fileLoader.generateConfigPaths(Q,J,X));return H}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[d(YQ(),".config",Q),d(YQ(),".config"),YQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var VX=new RZ;async function LZ(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await VX.loadConfig(Q);else Z=await VX.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",H=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||H.includes("config"))&&Q.verbose)c.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let G=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await VX.applyEnvironmentVariables(G.name||"",X,!0,G.verbose||!1))?.config??X;return X}}function yQ(Q,X,Y=!1){let Z=new nX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(J,G=[]){let U={...J};for(let[q,_]of Object.entries(J)){let A=[...G,q],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,I;for(let B of z)if(W=XX.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof _==="boolean")U[q]=["true","1","yes"].includes(W.toLowerCase());else if(typeof _==="number"){let B=Number(W);if(!Number.isNaN(B))U[q]=B}else if(Array.isArray(_))try{U[q]=JSON.parse(W)}catch{U[q]=W.split(",").map((B)=>B.trim())}else U[q]=W;else if(_&&typeof _==="object"&&!Array.isArray(_))U[q]=H(_,A)}return U}return H(X)}var z$=d(XX.cwd(),"config"),B$=d(XX.cwd(),"src/generated");var FQ={cwd:KZ.cwd(),root:"./src",entrypoints:["**/*.ts"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",verbose:!1,importOrder:["bun"],declarationMap:!1},C8=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function x8(Q=KZ.cwd()){for(let X of C8){let Y=O8(Q,X);if(T8(Y))try{let $=await import(N8(Y).href),H=$.default||$.config||$,J=typeof H==="function"?await H():H;return{...FQ,...J,cwd:Q}}catch(Z){let $=Z instanceof Error?Z.message:String(Z);wZ.warn(`Failed to load config from ${X}: ${$}`)}}return null}var IQ=null;async function M$(Q){if(!IQ){let X=await x8(Q);if(X)IQ=X;else IQ=await LZ({name:"dts",defaultConfig:FQ})}return IQ}function D$(){IQ=null}function V$(Q){return{...FQ,...Q}}function S$(Q){return async()=>{let X=await Q();return{...FQ,...X}}}var E$=FQ;
|
|
62
|
+
export{FQ as Pc,M$ as Qc,D$ as Rc,V$ as Sc,S$ as Tc,E$ as Uc};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{tb as I}from"./chunk-
|
|
2
|
+
import{tb as I}from"./chunk-y4g1csn2.js";class H{options;generateOptions;constructor(j={}){let{onCompile:F=!1,afterEmit:w=!0,onWatchRun:q=!1,onGenerated:z,onError:B,...J}=j;this.options={onCompile:F,afterEmit:w,onWatchRun:q,onGenerated:z,onError:B},this.generateOptions=J}apply(j){if(!this.generateOptions.outdir&&j.options.output?.path)this.generateOptions.outdir=j.options.output.path;if(!this.generateOptions.cwd&&j.options.context)this.generateOptions.cwd=j.options.context;if(!this.generateOptions.entrypoints&&j.options.entry){let w=j.options.entry;if(typeof w==="string")this.generateOptions.entrypoints=[w];else if(Array.isArray(w))this.generateOptions.entrypoints=w;else if(typeof w==="object"&&w!==null){let q=[];for(let z of Object.values(w))if(typeof z==="string")q.push(z);else if(Array.isArray(z))q.push(...z.filter((B)=>typeof B==="string"));else if(typeof z==="object"&&z!==null&&"import"in z){let B=z.import;if(typeof B==="string")q.push(B);else if(Array.isArray(B))q.push(...B)}if(q.length>0)this.generateOptions.entrypoints=q}}if(this.options.onCompile)j.hooks.compile.tap("DtsxWebpackPlugin",()=>{this.runGenerate()});if(this.options.afterEmit)j.hooks.afterEmit.tapAsync("DtsxWebpackPlugin",async(w,q)=>{await this.runGenerate(),q()});if(this.options.onWatchRun)j.hooks.watchRun.tapAsync("DtsxWebpackPlugin",async(w,q)=>{await this.runGenerate(),q()})}async runGenerate(){try{let j=await I(this.generateOptions);this.options.onGenerated?.(j)}catch(j){let F=j instanceof Error?j:Error(String(j));if(this.options.onError?.(F),!this.options.onError)console.error("[dtsx] Generation failed:",F.message)}}}function K(j={}){return new H(j)}var M=K,Q=H;
|
|
3
3
|
export{H as qa,K as ra,M as sa,Q as ta};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h}from"./chunk-
|
|
2
|
+
import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h}from"./chunk-1hy2eypj.js";import"./chunk-ft0nf9jb.js";import"./chunk-2n1bbm2c.js";import"./chunk-y2pe3jq3.js";import"./chunk-4mtbtmee.js";import"./chunk-xw9wfq8f.js";import"./chunk-gssantc8.js";import"./chunk-mcdb3q06.js";export{a as parseJSDoc,f as generateTypeDocJSON,c as generateMarkdown,e as generateJSON,d as generateHTML,g as generateDocs,b as extractDocumentation,h as createDocsGenerator};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{lc as F,mc as L}from"./chunk-
|
|
2
|
+
import{lc as F,mc as L}from"./chunk-y2pe3jq3.js";import{oc as I}from"./chunk-4mtbtmee.js";import{Cc as g}from"./chunk-vx4a5crm.js";var R=100,w=0,z=new Map;function U(B,G="stdin.ts",J=!0,W=["bun"],P=!1){let N=F(B),Y=`${G}:${J?1:0}:${P?1:0}`,Q=z.get(Y);if(Q&&Q.contentHash===N)return Q.lastAccess=++w,Q.result;let j=L(B,G,J,P),v=g(j,{filePath:G,sourceCode:B,declarations:j},J,W);if(z.set(Y,{result:v,contentHash:N,lastAccess:++w}),z.size>R){let M=Math.max(1,Math.ceil(z.size*0.1)),V=[];for(let[q,$]of z)V.push([q,$.lastAccess]);V.sort((q,$)=>q[1]-$[1]);for(let q=0;q<M&&q<V.length;q++)z.delete(V[q][0])}return v}function b(){z.clear()}function H(B,G="stdin.ts",J=!0,W=["bun"],P=!1){let N=I(B,G,J,P);return g(N,{filePath:G,sourceCode:B,declarations:N},J,W)}
|
|
3
3
|
export{U as ic,b as jc,H as kc};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{l as a,m as b,n as c,o as d,p as e,q as f,r as g}from"./chunk-wtqapt0n.js";import"./chunk-y4g1csn2.js";import"./chunk-ft0nf9jb.js";import"./chunk-2n1bbm2c.js";import"./chunk-bymtns9a.js";import"./chunk-y2pe3jq3.js";import"./chunk-4mtbtmee.js";import"./chunk-vx4a5crm.js";import"./chunk-xw9wfq8f.js";import"./chunk-7hy98p24.js";import"./chunk-gssantc8.js";import"./chunk-mcdb3q06.js";export{b as sortProjectsByDependencies,f as resolveWorkspacePatterns,c as generateWorkspace,d as generateMonorepo,g as generateFromPackageWorkspaces,a as discoverWorkspaceProjects,e as discoverWorkspaceFromPackageJson};
|