pickier 0.1.38 → 0.1.40
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 +3 -44355
- package/dist/chunk-34yzzbec.js +3 -0
- package/dist/chunk-5wzkpgv6.js +62 -0
- package/dist/chunk-88xjkex3.js +156 -0
- package/dist/chunk-cbqydxbp.js +33 -0
- package/dist/chunk-db1t9ezz.js +218 -0
- package/dist/chunk-h6ac3d60.js +3 -0
- package/dist/chunk-j2yn05ka.js +2 -0
- package/dist/chunk-nwytx79z.js +2 -0
- package/dist/chunk-p4y6z6j6.js +2 -0
- package/dist/chunk-vq1weh7a.js +2 -0
- package/dist/src/index.js +1 -40104
- package/package.json +1 -1
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{D as H,k as G}from"./chunk-cbqydxbp.js";import{L as K}from"./chunk-h6ac3d60.js";import{readFileSync as M,statSync as N,writeFileSync as Q}from"fs";import{isAbsolute as R,resolve as T}from"path";import U from"process";async function w(k,j){let B=j.mode||"auto";if(B==="format"&&k.length===1&&!/[*?[\]{}()!]/.test(k[0]))try{let q=k[0],z=R(q)?q:T(U.cwd(),q);if(N(z).isFile()){let J=await H(j.config),D=M(z,"utf8"),E=G(D,J,z);if(j.check&&E!==D)return 1;if(j.write&&E!==D)Q(z,E,"utf8");return 0}}catch{}let{runLint:x}=await import("./chunk-j2yn05ka.js");if(B==="lint")return x(k,j);if(B==="format"){let q={...j,fix:!0,dryRun:!!j.check,ext:j.ext,_formatOnly:!0};return x(k,q)}if(!(j.fix===!0||j.write===!0||j.check===!0))return x(k,j);let I={...j,fix:!0,dryRun:!!j.check,ext:j.ext};return x(k,I)}
|
|
3
|
+
export{w as h};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{L as l}from"./chunk-h6ac3d60.js";import{existsSync as iX,statSync as sX}from"fs";import{existsSync as LZ,mkdirSync as O8,readdirSync as N8,readFileSync as KZ,writeFileSync as C8}from"fs";import{homedir as YQ}from"os";import{dirname as P8,resolve as d}from"path";import eQ from"process";import{existsSync as oX,statSync as tX}from"fs";import{existsSync as DX,mkdirSync as jZ,readdirSync as IZ,writeFileSync as FZ}from"fs";import{homedir as ZQ}from"os";import{dirname as rX,resolve as y}from"path";import XQ from"process";import{join as MZ,relative as DZ,resolve as aX}from"path";import pQ from"process";import{existsSync as yY,mkdirSync as g8,readdirSync as c8,writeFileSync as l8}from"fs";import{homedir as ZX}from"os";import{dirname as s8,resolve as b}from"path";import wQ from"process";import{join as VZ,relative as SZ,resolve as eX}from"path";import mQ from"process";import{existsSync as vY,mkdirSync as e8,readdirSync as Q9,writeFileSync as X9}from"fs";import{dirname as Z9,resolve as uQ}from"path";import VX from"process";import{Buffer as e}from"buffer";import{createCipheriv as EZ,createDecipheriv as TZ,randomBytes as $X}from"crypto";import{closeSync as HX,createReadStream as QY,createWriteStream as OZ,existsSync as UX,fsyncSync as XY,openSync as YY,writeFileSync as NZ}from"fs";import{access as CZ,constants as ZY,mkdir as xZ,readdir as IQ,rename as $Y,stat as $Q,unlink as FQ,writeFile as JX}from"fs/promises";import{join as HQ}from"path";import N from"process";import{pipeline as kZ}from"stream/promises";import{createGzip as HY}from"zlib";import UQ from"process";import o from"process";import{Buffer as i}from"buffer";import{createCipheriv as PZ,createDecipheriv as bZ,randomBytes as GX}from"crypto";import{closeSync as _X,createReadStream as UY,createWriteStream as yZ,existsSync as MQ,fsyncSync as JY,openSync as GY,writeFileSync as vZ}from"fs";import{access as dZ,constants as _Y,mkdir as hZ,readdir as DQ,rename as qY,stat as JQ,unlink as VQ,writeFile as qX}from"fs/promises";import{isAbsolute as fZ,join as GQ,resolve as pZ}from"path";import R from"process";import{pipeline as mZ}from"stream/promises";import{createGzip as WY}from"zlib";import _Q from"process";import t from"process";import SQ from"process";import{existsSync as EQ}from"fs";import{resolve as WX}from"path";import{existsSync as uZ}from"fs";import{existsSync as gZ,readdirSync as cZ}from"fs";import{extname as AX,resolve as AY}from"path";import lZ from"process";import{join as nZ,relative as iZ,resolve as zY}from"path";import gQ from"process";import{Buffer as s}from"buffer";import{createCipheriv as sZ,createDecipheriv as oZ,randomBytes as zX}from"crypto";import{closeSync as BX,createReadStream as BY,createWriteStream as tZ,existsSync as TQ,fsyncSync as RY,openSync as wY,writeFileSync as rZ}from"fs";import{access as aZ,constants as LY,mkdir as eZ,readdir as OQ,rename as KY,stat as qQ,unlink as NQ,writeFile as RX}from"fs/promises";import{isAbsolute as Q0,join as WQ,resolve as X0}from"path";import w from"process";import{pipeline as Y0}from"stream/promises";import{createGzip as jY}from"zlib";import AQ from"process";import r from"process";import xQ from"process";import{existsSync as kQ}from"fs";import{resolve as FX}from"path";import{existsSync as M8}from"fs";class PY{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,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),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(!iX(Q))return!0;return sX(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 $=iX(Y)?sX(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 bY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,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 fQ=new PY,yX=new bY;var Z0=Object.defineProperty,$0=(Q)=>Q;function H0(Q,X){this[Q]=$0.bind(null,X)}var U0=(Q,X)=>{for(var Y in X)Z0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:H0.bind(X,Y)})},J0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),dY={};U0(dY,{withErrorRecovery:()=>pY,tryLoadConfig:()=>C0,loadConfigWithResult:()=>O0,loadConfig:()=>lY,isRetryableError:()=>M0,isConfigNotFoundError:()=>F0,isBunfigError:()=>mY,globalPerformanceMonitor:()=>jQ,globalCache:()=>zQ,getEnvOrDefault:()=>D0,generateConfigTypes:()=>x0,defaultGeneratedDir:()=>eY,defaultConfigDir:()=>aY,deepMergeWithArrayStrategy:()=>pX,deepMerge:()=>uY,createLibraryConfig:()=>k0,config:()=>N0,bunfigPlugin:()=>P0,applyEnvVarsToConfig:()=>RQ,TypeGenerationError:()=>xX,SchemaValidationError:()=>KQ,PluginError:()=>PX,PerformanceMonitor:()=>dX,FileSystemError:()=>CX,ErrorFactory:()=>QQ,EnvVarError:()=>oQ,EnvProcessor:()=>QX,ConfigValidator:()=>mX,ConfigValidationError:()=>OX,ConfigNotFoundError:()=>sQ,ConfigMergeError:()=>NX,ConfigLoader:()=>uX,ConfigLoadError:()=>LQ,ConfigFileLoader:()=>XX,ConfigCache:()=>vX,CacheUtils:()=>iY,BunfigError:()=>v,BrowserConfigError:()=>kX,ArrayMergeStrategies:()=>tY});class vX{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,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),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(!oX(Q))return!0;return tX(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 $=oX(Y)?tX(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 dX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,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 G0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function _0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function q0(Q){return Q.getStats().size*2}function hX(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((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>cQ(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]=hX(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 U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>cQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function cQ(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(!cQ(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(!cQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function W0(Q,X){if(!vY(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 hX(X,Z)}catch{return null}}catch{return null}}async function A0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||VX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=uQ(Z,`${U}${G}`),_=await W0(J,Y);if(_!==null)return _}try{let U=uQ(Z,"package.json");if(vY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return hX(Y,J)}catch{}}}catch{}return Y}function z0(Q,X={}){let Y=mQ.cwd();while(Y.includes("storage"))Y=eX(Y,"..");let Z=eX(Y,Q||"");if(X?.relative)return SZ(mQ.cwd(),Z);return Z}async function B0(){try{let Q=await A0({name:"clarity",defaultConfig:yQ,cwd:mQ.cwd(),endpoint:"",headers:{}});return{...yQ,...Q}}catch{return yQ}}function V(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function R0(){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 hY{async format(Q){let X=await R0(),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:UQ.pid,hostname:X(),environment:UQ.env.NODE_ENV||"development",platform:UQ.platform,version:UQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:UQ.env.NODE_ENV||UQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class lQ{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={...EX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new hY,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{...vQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...vQ};return{...vQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:EX.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,U=3,G=1000;while(H<U)try{try{try{await CZ(this.config.logDirectory,ZY.F_OK|ZY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await xZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!UX(this.currentLogFile))await JX(this.currentLogFile,"",{mode:420});if($=YY(this.currentLogFile,"a",420),NZ($,J,{flag:"a"}),XY($),$!==void 0)HX($),$=void 0;if((await $Q(this.currentLogFile)).size===0){if(await JX(this.currentLogFile,J,{flag:"w",mode:420}),(await $Q(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let W=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,W);let z=G*2**H;await new Promise((A)=>setTimeout(A,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{HX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,W=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),J}H++;let _=G*2**(H-1);await new Promise((q)=>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],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))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=EZ("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=HY(),$=[];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 IQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await $Q(Y).catch(()=>null))try{if(await $Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await FQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await JX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await $Q(Y).catch(()=>null))await $Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await IQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await FQ(HQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=QY(Q),Z=OZ(X),$=HY();await kZ(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()})),UX(this.currentLogFile))try{let Q=YY(this.currentLogFile,"r+");XY(Q),HX(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 IQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await FQ(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:U=!0}=Q,G=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(U)A.push(X);if(H==="warning")A.push("WARN");else if(H==="error")A.push("ERROR");else if(Y)A.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)A.push(Z.replace(/[[\]]/g,""));return A.push($),A.join(" ")}let J=N.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,W=G(X).length,z=Math.max(1,J-2-q-W);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){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),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!V()){let _=sY[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(W),G){let z=G.split(`
|
|
3
|
+
`);for(let A of z)if(A.trim()&&!A.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:M.gray(` ${A}`),level:Q,showTimestamp:!1}))}break}}else if(!V()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let J=`${H} ${this.environment}.${Q.toUpperCase()}: ${U}
|
|
4
|
+
`;if(G)J+=`${G}
|
|
5
|
+
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}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`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
|
|
6
|
+
`,_=_.replace(this.ANSI_PATTERN,""),this.fancy&&!V()){let q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:M.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!V())console.error(_.trim());await this.writeToFile(_)}}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 lQ(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(!UX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return QY(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),U=Z.slice(16,-16),G=TZ("aes-256-gcm",Y,$);return G.setAuthTag(H),e.concat([G.update(U),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
|
+
`),U=Math.max(...H.map((q)=>q.length))+2,G=`\u250C${"\u2500".repeat(U)}\u2510`,J=`\u2514${"\u2500".repeat(U)}\u2518`,_=H.map((q)=>{let W=" ".repeat(U-q.length-2);return`\u2502 ${q}${W} \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)})),_.forEach((q)=>console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(q),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(J),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 U=/%([sdijfo%])/g,G=0;if(Y=Q.replace(U,(J,_)=>{if(_==="%")return"%";if(G>=X.length)return J;let q=X[G++];switch(_){case"s":return String(q);case"d":case"i":return Number(q).toString();case"j":case"o":return JSON.stringify(q,null,2);default:return J}}),G<X.length)Y+=` ${X.slice(G).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!V()){let U=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",G=M.blue("\u25D0");console.error(`${G} ${U} ${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:(U,G)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,U)),G!==void 0)this.activeProgressBar.message=G;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,G="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||V())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(G,U),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)),U=M.gray("\u2501".repeat($)),G=`[${H}${U}]`,J=`${Y}%`.padStart(4),_=Q.message?` ${Q.message}`:"",q=X||Y===100?M.green("\u2713"):M.blue("\u25B6"),W=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",z=`\r${q}${W} ${G} ${J}${_}`,A=N.stdout.columns||80,I=" ".repeat(Math.max(0,A-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 IQ(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(U){console.error(`Failed to get stats for file ${H}:`,U);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 FQ(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 bQ(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((U)=>F(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(F($)&&"path"in $){if(!Z.find((U)=>F(U)&&("path"in U)&&U.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(!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]=bQ(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 U of Y[Z])if(F(U)&&"name"in U){if(!H.find((J)=>F(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(F(U)&&"path"in U){if(!H.find((J)=>F(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>nQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function fX(Q,X,Y="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return Y==="replace"?X:bQ(Q,X);if(Array.isArray(Q))return Y==="replace"?X:bQ(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[$],U=Z[$];if(H===null||H===void 0)continue;if(Array.isArray(H)||Array.isArray(U))if(Y==="replace")Z[$]=H;else Z[$]=bQ(U,H);else if(F(H)&&F(U))Z[$]=fX(U,H,Y);else Z[$]=H}return Z}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(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(!nQ(Q[$],X[$]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function CQ(Q,X,Y="replace"){if(!yY(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return fX(X,$,Y)}catch{return null}}catch{return null}}function w0(Q,X,Y=!1){if(!Q)return X;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...X};function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let W=[...G,_],z=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),A=`${Z}_${W.map(z).join("_")}`,I=`${Z}_${W.map((B)=>B.toUpperCase()).join("_")}`;if(Y)x.info(`Checking environment variable ${A} for config ${Q}.${W.join(".")}`);if(typeof q==="object"&&q!==null&&!Array.isArray(q))J[_]=H(q,W);else{let B=wQ.env[A]||wQ.env[I];if(B!==void 0){if(Y)x.info(`Using environment variable ${B?A:I} for config ${Q}.${W.join(".")}`);if(typeof q==="number")J[_]=Number(B);else if(typeof q==="boolean")J[_]=B.toLowerCase()==="true";else if(Array.isArray(q))try{let K=JSON.parse(B);if(Array.isArray(K))J[_]=K;else J[_]=B.split(",").map((k)=>k.trim())}catch{J[_]=B.split(",").map((K)=>K.trim())}else J[_]=B}}}return J}return H($)}async function L0({name:Q="",alias:X,cwd:Y,configDir:Z,defaultConfig:$,verbose:H=!1,checkEnv:U=!0,arrayStrategy:G="replace"}){let J=U&&typeof $==="object"&&$!==null&&!Array.isArray($)?w0(Q,$,H):$,_=Y||wQ.cwd(),q=[".ts",".js",".mjs",".cjs",".json"];if(H)x.info(`Loading configuration for "${Q}"${X?` (alias: "${X}")`:""} from ${_}`);let W=[Q,`.${Q}`].filter(Boolean),z=[`${Q}.config`,`.${Q}.config`].filter(Boolean),A=X?[X,`.${X}`]:[],I=X?[`${X}.config`,`.${X}.config`]:[],B=Array.from(new Set([_,b(_,"config"),b(_,".config"),Z?b(_,Z):void 0].filter(Boolean)));for(let K of B){if(H)x.info(`Searching for configuration in: ${K}`);let P=[b(_,"config"),b(_,".config")].concat(Z?[b(_,Z)]:[]).includes(K)?[...W,...z,...A,...I]:[...z,...W,...I,...A];for(let n of P)for(let g of q){let p=b(K,`${n}${g}`),nX=await CQ(p,J,G);if(nX!==null){if(H)x.success(`Configuration loaded from: ${p}`);return nX}}}if(Q){let K=b(ZX(),".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 q){let g=b(K,`${P}${n}`),p=await CQ(g,J,G);if(p!==null){if(H)x.success(`Configuration loaded from user config directory: ${g}`);return p}}}if(Q){let K=b(ZX(),".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 q){let g=b(K,`${P}${n}`),p=await CQ(g,J,G);if(p!==null){if(H)x.success(`Configuration loaded from user config directory dotfile: ${g}`);return p}}}if(Q){let K=ZX(),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 q){let g=b(K,`${P}${n}`),p=await CQ(g,J,G);if(p!==null){if(H)x.success(`Configuration loaded from user home directory: ${g}`);return p}}}try{let K=b(_,"package.json");if(yY(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 fX(J,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 J}function K0(Q,X={}){let Y=pQ.cwd();while(Y.includes("storage"))Y=aX(Y,"..");let Z=aX(Y,Q||"");if(X?.relative)return DZ(pQ.cwd(),Z);return Z}async function j0(){try{let Q=await L0({name:"clarity",alias:"logging",defaultConfig:dQ,cwd:pQ.cwd()});return{...dQ,...Q||{}}}catch{return dQ}}function S(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function I0(){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 fY{async format(Q){let X=await I0(),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:_Q.pid,hostname:X(),environment:_Q.env.NODE_ENV||"development",platform:_Q.platform,version:_Q.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_Q.env.NODE_ENV||_Q.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;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={...TX},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??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{...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:TX.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,U=3,G=1000;while(H<U)try{try{try{await dZ(this.config.logDirectory,_Y.F_OK|_Y.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await hZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:i.from(Q);try{if(!MQ(this.currentLogFile))await qX(this.currentLogFile,"",{mode:420});if($=GY(this.currentLogFile,"a",420),vZ($,J,{flag:"a"}),JY($),$!==void 0)_X($),$=void 0;if((await JQ(this.currentLogFile)).size===0){if(await qX(this.currentLogFile,J,{flag:"w",mode:420}),(await JQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let W=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,W);let z=G*2**H;await new Promise((A)=>setTimeout(A,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{_X($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,W=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),J}H++;let _=G*2**(H-1);await new Promise((q)=>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],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return GX(16).toString("hex")}generateKey(){return GX(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=GX(16),Z=PZ("aes-256-gcm",X,Y),$=i.isBuffer(Q)?Q:i.from(Q,"utf8"),H=Z.update($),U=Z.final(),G=H.length+U.length,J=Z.getAuthTag(),_=i.allocUnsafe(16+G+16);return Y.copy(_,0),H.copy(_,16),U.copy(_,16+H.length),J.copy(_,16+G),{encrypted:_,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 JQ(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 DQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await JQ(Y).catch(()=>null))try{if(await qY(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await VQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await qX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await JQ(Y).catch(()=>null))await qY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await DQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await VQ(GQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=UY(Q),Z=yZ(X),$=WY();await mZ(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()})),MQ(this.currentLogFile))try{let Q=GY(this.currentLogFile,"r+");JY(Q),_X(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 DQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await VQ(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()?L.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:U=!0}=Q,G=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(U)A.push(X);if(H==="warning")A.push("WARN");else if(H==="error")A.push("ERROR");else if(Y)A.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)A.push(Z.replace(/[[\]]/g,""));return A.push($),A.join(" ")}let J=R.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${L.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,W=G(X).length,z=Math.max(1,J-2-q-W);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){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=L.underline(L.blue(Z)),U=this.toAbsoluteFilePath($);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let G=`file://${encodeURI(U)}`,J="\x1B]8;;",_="\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)=>L.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>L.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>L.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(fZ(X)||X.startsWith("./")||X.startsWith("../"))X=pZ(X);else return null;return MQ(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),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);let{consoleText:J,fileText:_}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let W=this.options.showIcons===!1?"":oY[Q],z=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:W,tag:z,message:L.gray(J),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:W,tag:z,message:J,level:Q}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:W,tag:z,message:L.green(J),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:W,tag:z,message:J,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:W,tag:z,message:J,level:Q}),console.error(A),G){let I=G.split(`
|
|
11
|
+
`);for(let B of I)if(B.trim()&&!B.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:L.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let q=`${H} ${this.environment}.${Q.toUpperCase()}: ${_}
|
|
12
|
+
`;if(G)q+=`${G}
|
|
13
|
+
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,X=""){let Y={update:(G,J)=>{},finish:(G)=>{},interrupt:(G,J)=>{}};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,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,G),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!S()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(G)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,G)},interrupt:(G,J="info")=>{if(!S()&&R.stdout.isTTY)R.stdout.write(`
|
|
14
|
+
`);if(this[J==="warning"?"warn":J](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?L.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":L.blue("\u25D0"),tag:Y,message:`${L.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
|
|
15
|
+
`,_=_.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":L.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!S())console.error(_.trim());if(this.shouldWriteToFile())await this.writeToFile(_)}}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(S())throw Error("createReadStream is not supported in browser environments");if(!MQ(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),U=Z.subarray(16,Z.length-16),G=bZ("aes-256-gcm",Y,$);G.setAuthTag(H);let J=G.update(U),_=G.final(),q=J.length+_.length,W=i.allocUnsafe(q);return J.copy(W,0),_.copy(W,J.length),W.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
|
+
`),J=Math.max(...G.map((z)=>z.length))+2,_=`\u250C${"\u2500".repeat(J)}\u2510`,q=`\u2514${"\u2500".repeat(J)}\u2518`,W=G.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:L.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(_),showTimestamp:!1})),W.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(q),showTimestamp:!1}))}else if(!S())console.error(`${Z} ${this.environment}.INFO: [BOX] ${H}`);let U=`${Z} ${this.environment}.INFO: [BOX] ${H}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Q){if(S())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${L.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 J=/%([sdijfo%])/g,_=0;if(Y=Q.replace(J,(q,W)=>{if(W==="%")return"%";if(_>=X.length)return q;let z=X[_++];switch(W){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(_).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",_=this.options.showIcons===!1?"":`${L.blue("\u25D0")} `;console.error(`${_}${J} ${L.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=L.green("\u2501".repeat(Z)),U=L.gray("\u2501".repeat($)),G=`[${H}${U}]`,J=`${Y}%`.padStart(4),_=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":X||Y===100?L.green("\u2713"):L.blue("\u25B6"),W=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",z=`\r${q}${W} ${G} ${J}${_}`,A=R.stdout.columns||80,I=" ".repeat(Math.max(0,A-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 DQ(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 JQ(H)).mtime>=Q.before)continue}catch(U){console.error(`Failed to get stats for file ${H}:`,U);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 VQ(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 pY(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,U=Error("Unknown error occurred");for(let G=0;G<=Y;G++)try{return await Q()}catch(J){if(U=J instanceof Error?J:Error(String(J)),G===Y||!$(U))break;if(Z>0)await new Promise((_)=>setTimeout(_,Z))}if(H!==void 0)return H;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function mY(Q){return Q instanceof v}function F0(Q){return Q instanceof sQ}function M0(Q){if(mY(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 QX{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:U={},verbose:G=!1,trackPerformance:J=!0}=Y,_=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let q=Z||this.generateEnvPrefix(Q),W={...X};return this.processObject(W,[],q,{useCamelCase:$,useBackwardCompatibility:H,customParsers:U,verbose:G,configName:Q}),{config:W,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return jQ.track("applyEnvironmentVariables",_,{configName:Q});return _()}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 U=[...X,$],G=U.map((q)=>this.formatEnvKey(q,Z.useCamelCase)),J=`${Y}_${G.join("_")}`,_=Z.useBackwardCompatibility?`${Y}_${U.map((q)=>q.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,U,Y,Z);else{let q=SQ.env[J]||(_?SQ.env[_]:void 0);if(q!==void 0){if(Z.verbose){let W=SQ.env[J]?J:_}try{Q[$]=this.parseEnvironmentValue(q,typeof H,J,Z.customParsers,Z.configName)}catch(W){if(W instanceof oQ)throw W;throw QQ.envVar(J,q,typeof H,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[H,U]of Object.entries(Z))try{return U(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(SQ.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),U=[];switch(this.extractEnvVarInfo(X,[],H,U),$){case"markdown":return this.formatAsMarkdown(U,Q);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],G=`${Y}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,U,Y,Z);else Z.push({key:G,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${U.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 D0(Q,X){let Y=nY("process");if(typeof Y>"u"||!Y.env)return X;let Z=Y.env[Q];return Z!==void 0?Z:X}function uY(Q,X,Y={}){return gY(Q,X,Y,new WeakMap)}function gY(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:U}=Y;if(X===null||X===void 0)return H?Q:X;if(U){let G=U(Q,X);if(G!==void 0)return G}if(Array.isArray(X)||Array.isArray(Q))return cY(Q,X,$,Z);if(!h(X)||!h(Q))return X;return T0(Q,X,Y,Z)}function cY(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 V0(Q,X);case"smart":return S0(Q,X,Z);default:return X}return X}function V0(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>SX($,Z)))Y.push(Z);return Y}function S0(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(h(X[0])&&h(Q[0]))return E0(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 E0(Q,X,Y){let Z=[...X];for(let $ of Q){if(!h($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let G of H)if(G in $){if(Z.find((_)=>h(_)&&(G in _)&&_[G]===$[G])){U=!0;break}}if(!U)Z.push($)}return Z}function T0(Q,X,Y,Z){let $=X;if(h($)&&Z.has($))return Z.get($);let H={...Q};if(h($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let G=$[U],J=H[U];if(Y.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){H[U]=G;continue}if(h(G)&&h(J))H[U]=gY(J,G,Y,Z);else if(Array.isArray(G)||Array.isArray(J))H[U]=cY(J,G,Y.arrayMergeMode||"smart",Z);else H[U]=G}return H}function pX(Q,X,Y="replace"){return uY(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function SX(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(!SX(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(!SX(Q[$],X[$]))return!1}return!0}return!1}function h(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class XX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:U=!0,verbose:G=!1}=Y;if($){let _=zQ.getWithFileCheck("file",Q);if(_){if(G)console.log(`Configuration loaded from cache: ${Q}`);return _}}let J=async()=>{if(!EQ(Q))return null;try{let _=`?t=${Date.now()}`,q=await import(Q+_),W=q.default||q,z="default"in q,A=Object.keys(q).length>0;if(!z&&!A)throw new LQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof W!=="object"||W===null||Array.isArray(W))throw new LQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:pX(X,W,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)zQ.setWithFileCheck("file",K,Q,H);return K}catch(_){throw _ instanceof Error?QQ.configLoad(Q,_):QQ.configLoad(Q,Error(String(_)))}};if(U)return jQ.track("loadFromPath",J,{path:Q});return J()}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 U of this.extensions)$.push(WX(X,`${H}${U}`));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 pY(async()=>{return EQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!EQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let G=WX(Q,`${H}${U}`);if(await this.checkFileAccess(G))Z.push(G)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let G=WX(Q,U);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(!EQ(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 mX{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:G=!0,verbose:J=!1}=Y,_=async()=>{let q=[],W=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:G,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...U],z);else return this.validateWithJSONSchema(Q,X,z)}catch(A){return q.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:q,warnings:W}}};if(G)return await jQ.track("validateConfiguration",_);return _()}async validateWithSchemaFile(Q,X,Y){try{if(!uZ(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 U=Array.isArray(Q)?"array":typeof Q,G=Array.isArray(X.type)?X.type:[X.type];if(!G.includes(U)){if(Z.push({path:Y,message:`Expected type ${G.join(" or ")}, got ${U}`,expected:G.join(" or "),actual:U,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 U=0;U<Q.length;U++){let G=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let U=Q;if(H.validateRequired&&X.required){for(let G of X.required)if(!(G in U)){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,J]of Object.entries(X.properties))if(G in U){let _=Y?`${Y}.${G}`:G;if(this.validateObjectAgainstSchema(U[G],J,_,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let G=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!G.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let U=this.getValueByPath(Q,H.path),G=this.validateWithRule(U,H,H.path);if(Z.push(...G),Y.stopOnFirstError&&Z.length>0)break}catch(U){Z.push({path:H.path,message:`Rule validation failed: ${U}`,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,U]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(U)})}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:rY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class uX{fileLoader=new XX;envProcessor=new QX;validator=new mX;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...U}=Q;try{if(Y?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let G;try{G=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){let _=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(_)throw J;G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let q=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),W=!q&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),z=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(_&&(z||q))throw J;if(W&&(!_||!z))G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!_)G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||H)await this.validateConfiguration(G.config,$,H,U.name);if(Y?.enabled&&G)this.cacheResult(U.name||"",G,Y,U);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:U.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)m.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);G.metrics=J}return G}catch(G){let J=Date.now()-X;throw m.error(`Configuration loading failed after ${J}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:U,defaultConfig:G,checkEnv:J=!0,arrayStrategy:_="replace",verbose:q=!1}=Q,W=H||XQ.cwd(),z=[],A=await this.loadLocalConfiguration(Z,$,W,U,G,_,q,J,Y);if(A)return z.push(...this.getLocalSearchPaths(Z,$,W,U)),this.finalizeResult(A,z,J,Z,q);let I=await this.loadHomeConfiguration(Z,$,G,_,q,J);if(I)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(I,z,J,Z,q);let B=await this.loadPackageJsonConfiguration(Z,$,W,G,_,q,J);if(B)return z.push(y(W,"package.json")),this.finalizeResult(B,z,J,Z,q);if(z.push(...this.getAllSearchPaths(Z,$,W,U)),X)throw QQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,G,J,q),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,G,J){let _=G?RQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let W of q){if(U)m.info(`Searching for configuration in: ${W}`);let z=this.fileLoader.generateConfigPaths(Q,W,X),A=await this.fileLoader.tryLoadFromPaths(z,_,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(A){if(U)m.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let U=H?RQ(Q,Y,$):Y,G=[y(ZQ(),".config",Q),y(ZQ(),".config"),ZQ()];for(let J of G){if($)m.info(`Checking home directory: ${J}`);let _=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(_,U,{arrayStrategy:Z,verbose:$});if(q){if($)m.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let G=U?RQ(Q,Z,H):Z;try{let J=y(Y,"package.json");if(!DX(J))return null;let _=await import(J),q=_[Q],W=Q;if(!q&&X)q=_[X],W=X;if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)m.success(`Configuration loaded from package.json: ${W}`);return{config:pX(G,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)m.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}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((U)=>U.path?`${U.path}: ${U.message}`:U.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 U of $)H.push(...this.fileLoader.generateConfigPaths(Q,U,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 IY(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 O0(Q){return a.loadConfig({...Q,__strictErrorHandling:!0})}async function lY(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 N0(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"&&IY(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"&&IY(X)))return(await a.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw X}}async function C0(Q,X,Y="replace"){let Z=new XX;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 QX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let W=[...G,_],z=[`${$}_${W.join("_").toUpperCase()}`,`${$}_${W.map((B)=>B.toUpperCase()).join("")}`,`${$}_${W.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,I;for(let B of z)if(A=XQ.env[B],A!==void 0){I=B;break}if(A!==void 0&&I)if(typeof q==="boolean")J[_]=["true","1","yes"].includes(A.toLowerCase());else if(typeof q==="number"){let B=Number(A);if(!Number.isNaN(B))J[_]=B}else if(Array.isArray(q))try{J[_]=JSON.parse(A)}catch{J[_]=A.split(",").map((B)=>B.trim())}else J[_]=A;else if(q&&typeof q==="object"&&!Array.isArray(q))J[_]=H(q,W)}return J}return H(X)}function x0(Q){let X=y(XQ.cwd(),Q.configDir),Y=y(XQ.cwd(),Q.generatedDir),Z=y(Y,"config-types.ts");if(!DX(rX(Z)))jZ(rX(Z),{recursive:!0,mode:511});let $=DX(X)?IZ(X).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],H=`// Generated by bunfig v${U8}
|
|
32
|
+
export type ConfigNames = ${$.length?`'${$.join("' | '")}'`:"string"}
|
|
33
|
+
`;FZ(Z,H,{mode:438})}function k0(Q){let X=null,Y=null,Z=()=>{if(!Y)Y=lY(Q).then((H)=>{return X=H,H},(H)=>{let U="defaultConfig"in Q?Q.defaultConfig:{};if(X=U,"verbose"in Q&&Q.verbose)m.warn("Config loading failed, using defaults:",[H instanceof Error?H:Error(String(H))]);return U});return Y},$="defaultConfig"in Q?Q.defaultConfig:{};return X=$,Z(),new Proxy({},{get(H,U){if(X)return X[U];let G=$[U];return Z(),G},has(H,U){return U in(X||$)},ownKeys(){return Object.keys(X||$)},getOwnPropertyDescriptor(H,U){return Object.getOwnPropertyDescriptor(X||$,U)},set(H,U,G){if(!X)X={...$};return X[U]=G,!0}})}function P0(Q){let X=AY(lZ.cwd(),Q?.configDir||"./config");function Y(){if(!gZ(X))return[];let $=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),H=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=cZ(X).filter((J)=>$.has(AX(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),G=new Map;for(let{base:J,file:_}of U){let q=AX(_).toLowerCase(),W=G.get(J);if(!W){G.set(J,_);continue}let z=AX(W).toLowerCase();if(H.indexOf(q)<H.indexOf(z))G.set(J,_)}return Array.from(G.entries()).map(([J,_])=>({base:J,file:_})).sort((J,_)=>J.base.localeCompare(_.base))}function Z(){let $=Y(),H=$.map((_)=>_.base),U=H.length?H.map((_)=>`'${_}'`).join(" | "):"string",G=$.length?`{
|
|
34
|
+
${$.map((_)=>{let q=AY(X,_.file).replace(/\\/g,"/");return` '${_.base}': typeof import('${q}').default`}).join(`,
|
|
35
|
+
`)}
|
|
36
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
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 nY,zQ,jQ,iY,b0,y0,FY,yQ,EX,C,M,v0,MY,d0,DY,h0,f0,wX,p0,VY,SY,LX,m0,u0,g0,c0,vQ,sY,l0,x,n0,i0,EY,dQ,TX,E,L,s0,TY,o0,OY,t0,r0,KX,a0,NY,CY,e0,jX,Q8,X8,Y8,Z8,$8,hQ,oY,H8,U8="0.15.6",v,sQ,LQ,OX,NX,oQ,CX,xX,KQ,kX,PX,QQ,tY,rY,m,a,aY,eY,J8=J0(async()=>{nY=import.meta.require,zQ=new vX,jQ=new dX,iY={createKey:G0,isEquivalent:_0,estimateMemoryUsage:q0},b0=uQ(VX.cwd(),"config"),y0=uQ(VX.cwd(),"src/generated"),FY=mQ.env.CLARITY_LOG_DIR||VZ(z0(),"logs"),yQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:FY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},EX=await B0(),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,v0=C.red,MY=C.green,d0=C.yellow,DY=C.blue,h0=C.magenta,f0=C.cyan,wX=C.white,p0=C.gray,VY=C.bgRed,SY=C.bgYellow,LX=C.bold,m0=C.dim,u0=C.italic,g0=C.underline,c0=C.reset,vQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sY={debug:"\uD83D\uDD0D",info:DY("\u2139"),success:MY("\u2713"),warning:SY(wX(LX(" WARN "))),error:VY(wX(LX(" ERROR ")))},l0=new lQ("stacks"),x=new lQ("bunfig",{showTags:!0}),n0=b(wQ.cwd(),"config"),i0=b(wQ.cwd(),"src/generated"),EY=pQ.env.CLARITY_LOG_DIR||MZ(K0(),"logs"),dQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:EY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},TX=await j0(),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"},L=E,s0=E.red,TY=E.green,o0=E.yellow,OY=E.blue,t0=E.magenta,r0=E.cyan,KX=E.white,a0=E.gray,NY=E.bgRed,CY=E.bgYellow,e0=E.bgGray,jX=E.bold,Q8=E.dim,X8=E.italic,Y8=E.underline,Z8=E.strikethrough,$8=E.reset,hQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oY={debug:"\uD83D\uDD0D",info:OY("\u2139"),success:TY("\u2713"),warning:CY(KX(jX(" WARN "))),error:NY(KX(jX(" ERROR ")))},H8=new iQ("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}`}},sQ=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})}},LQ=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}},OX=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})}},NX=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}},oQ=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:$})}},CX=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}},xX=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})}},kX=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:$})}},PX=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 sQ(Q,X,Y)},configLoad(Q,X,Y){return new LQ(Q,X,Y)},configValidation(Q,X,Y){return new OX(Q,X,Y)},configMerge(Q,X,Y,Z){return new NX(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new oQ(Q,X,Y,Z)},fileSystem(Q,X,Y){return new CX(Q,X,Y)},typeGeneration(Q,X,Y){return new xX(Q,X,Y)},schemaValidation(Q,X,Y){return new KQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new kX(Q,X,Y,Z)},plugin(Q,X,Y){return new PX(Q,X,Y)}},tY={replace:"replace",concat:"concat",smart:"smart"},rY=/^https?:\/\//,m=new iQ("bunfig",{showTags:!0}),a=new uX,aY=y(XQ.cwd(),"config"),eY=y(XQ.cwd(),"src/generated")});function G8(Q,X={}){let Y=gQ.cwd();while(Y.includes("storage"))Y=zY(Y,"..");let Z=zY(Y,Q||"");if(X?.relative)return iZ(gQ.cwd(),Z);return Z}var _8=gQ.env.CLARITY_LOG_DIR||nZ(G8(),"logs"),QZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_8,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},tQ={...QZ},c9=(async()=>{try{let{loadConfig:Q}=await J8().then(()=>dY),X=await Q({name:"clarity",alias:"logging",defaultConfig:QZ,cwd:gQ.cwd()});if(X)Object.assign(tQ,X)}catch{}return tQ})();function T(){if(r.env.NODE_ENV==="test"||r.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function q8(){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 XZ{async format(Q){let X=await q8(),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:AQ.pid,hostname:X(),environment:AQ.env.NODE_ENV||"development",platform:AQ.platform,version:AQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:AQ.env.NODE_ENV||AQ.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,l9=O.red,W8=O.green,n9=O.yellow,A8=O.blue,i9=O.magenta,s9=O.cyan,xY=O.white,o9=O.gray,z8=O.bgRed,B8=O.bgYellow,t9=O.bgGray,kY=O.bold,r9=O.dim,a9=O.italic,e9=O.underline,Q$=O.strikethrough,X$=O.reset,IX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},R8={debug:"\uD83D\uDD0D",info:A8("\u2139"),success:W8("\u2713"),warning:B8(xY(kY(" WARN "))),error:z8(xY(kY(" ERROR ")))};class YX{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={...tQ},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new XZ,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??w.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{...IX,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...IX};return{...IX,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:tQ.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,U=3,G=1000;while(H<U)try{try{try{await aZ(this.config.logDirectory,LY.F_OK|LY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await eZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:s.from(Q);try{if(!TQ(this.currentLogFile))await RX(this.currentLogFile,"",{mode:420});if($=wY(this.currentLogFile,"a",420),rZ($,J,{flag:"a"}),RY($),$!==void 0)BX($),$=void 0;if((await qQ(this.currentLogFile)).size===0){if(await RX(this.currentLogFile,J,{flag:"w",mode:420}),(await qQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let W=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,W);let z=G*2**H;await new Promise((A)=>setTimeout(A,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{BX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,W=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),J}H++;let _=G*2**(H-1);await new Promise((q)=>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 WQ(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 WQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return WQ(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],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return zX(16).toString("hex")}generateKey(){return zX(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=zX(16),Z=sZ("aes-256-gcm",X,Y),$=s.isBuffer(Q)?Q:s.from(Q,"utf8"),H=Z.update($),U=Z.final(),G=H.length+U.length,J=Z.getAuthTag(),_=s.allocUnsafe(16+G+16);return Y.copy(_,0),H.copy(_,16),U.copy(_,16+H.length),J.copy(_,16+G),{encrypted:_,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=jY(),$=[];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 qQ(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 OQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await qQ(Y).catch(()=>null))try{if(await KY(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await NQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await RX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await qQ(Y).catch(()=>null))await KY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await OQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await NQ(WQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=BY(Q),Z=tZ(X),$=jY();await Y0(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()})),TQ(this.currentLogFile))try{let Q=wY(this.currentLogFile,"r+");RY(Q),BX(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 OQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await NQ(WQ(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 w.env.NO_COLOR<"u",X=w.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof w.stderr<"u"&&w.stderr.isTTY||typeof w.stdout<"u"&&w.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(U)A.push(X);if(H==="warning")A.push("WARN");else if(H==="error")A.push("ERROR");else if(Y)A.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)A.push(Z.replace(/[[\]]/g,""));return A.push($),A.join(" ")}let J=w.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${j.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,W=G(X).length,z=Math.max(1,J-2-q-W);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){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)),U=this.toAbsoluteFilePath($);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let G=`file://${encodeURI(U)}`,J="\x1B]8;;",_="\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=w.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=w.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(Q0(X)||X.startsWith("./")||X.startsWith("../"))X=X0(X);else return null;return TQ(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),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);let{consoleText:J,fileText:_}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let W=this.options.showIcons===!1?"":R8[Q],z=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:W,tag:z,message:j.gray(J),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:W,tag:z,message:J,level:Q}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:W,tag:z,message:j.green(J),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:W,tag:z,message:J,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:W,tag:z,message:J,level:Q}),console.error(A),G){let I=G.split(`
|
|
41
|
+
`);for(let B of I)if(B.trim()&&!B.includes(U))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()}: ${U}`),G)console.error(G)}let q=`${H} ${this.environment}.${Q.toUpperCase()}: ${_}
|
|
42
|
+
`;if(G)q+=`${G}
|
|
43
|
+
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,X=""){let Y={update:(G,J)=>{},finish:(G)=>{},interrupt:(G,J)=>{}};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()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(G,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,G),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(G)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,G)},interrupt:(G,J="info")=>{if(!T()&&w.stdout.isTTY)w.stdout.write(`
|
|
44
|
+
`);if(this[J==="warning"?"warn":J](G),this.activeProgressBar&&this.shouldStyleConsole()&&!T()&&w.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`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
|
|
45
|
+
`,_=_.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=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:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T())console.error(_.trim());if(this.shouldWriteToFile())await this.writeToFile(_)}}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 YX(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(!TQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return BY(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),U=Z.subarray(16,Z.length-16),G=oZ("aes-256-gcm",Y,$);G.setAuthTag(H);let J=G.update(U),_=G.final(),q=J.length+_.length,W=s.allocUnsafe(q);return J.copy(W,0),_.copy(W,J.length),W.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
|
+
`),J=Math.max(...G.map((z)=>z.length))+2,_=`\u250C${"\u2500".repeat(J)}\u2510`,q=`\u2514${"\u2500".repeat(J)}\u2518`,W=G.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:j.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(_),showTimestamp:!1})),W.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(q),showTimestamp:!1}))}else if(!T())console.error(`${Z} ${this.environment}.INFO: [BOX] ${H}`);let U=`${Z} ${this.environment}.INFO: [BOX] ${H}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}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();w.stdin.removeListener("data",Y);try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!1)}catch{}w.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!0)}catch{}w.stdin.resume(),w.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,_=0;if(Y=Q.replace(J,(q,W)=>{if(W==="%")return"%";if(_>=X.length)return q;let z=X[_++];switch(W){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(_).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",_=this.options.showIcons===!1?"":`${j.blue("\u25D0")} `;console.error(`${_}${J} ${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()||!w.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)),U=j.gray("\u2501".repeat($)),G=`[${H}${U}]`,J=`${Y}%`.padStart(4),_=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":X||Y===100?j.green("\u2713"):j.blue("\u25B6"),W=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",z=`\r${q}${W} ${G} ${J}${_}`,A=w.stdout.columns||80,I=" ".repeat(Math.max(0,A-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,w.stdout.write(Q.lastRenderedLine),X)w.stdout.write(`
|
|
49
|
+
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||T()||!w.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 OQ(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=WQ(this.config.logDirectory,Z);if(Q.before)try{if((await qQ(H)).mtime>=Q.before)continue}catch(U){console.error(`Failed to get stats for file ${H}:`,U);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 NQ(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 Y$=new YX("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 YZ 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 rQ 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 ZZ 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 $Z 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 gX 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 HZ 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 aQ 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 JZ 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 GZ 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 YZ(Q,X,Y)},configLoad(Q,X,Y){return new rQ(Q,X,Y)},configValidation(Q,X,Y){return new ZZ(Q,X,Y)},configMerge(Q,X,Y,Z){return new $Z(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new gX(Q,X,Y,Z)},fileSystem(Q,X,Y){return new HZ(Q,X,Y)},typeGeneration(Q,X,Y){return new UZ(Q,X,Y)},schemaValidation(Q,X,Y){return new aQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new JZ(Q,X,Y,Z)},plugin(Q,X,Y){return new GZ(Q,X,Y)}};async function w8(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,U=Error("Unknown error occurred");for(let G=0;G<=Y;G++)try{return await Q()}catch(J){if(U=J instanceof Error?J:Error(String(J)),G===Y||!$(U))break;if(Z>0)await new Promise((_)=>setTimeout(_,Z))}if(H!==void 0)return H;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class cX{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:U={},verbose:G=!1,trackPerformance:J=!0}=Y,_=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let q=Z||this.generateEnvPrefix(Q),W={...X};return this.processObject(W,[],q,{useCamelCase:$,useBackwardCompatibility:H,customParsers:U,verbose:G,configName:Q}),{config:W,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return yX.track("applyEnvironmentVariables",_,{configName:Q});return _()}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 U=[...X,$],G=U.map((q)=>this.formatEnvKey(q,Z.useCamelCase)),J=`${Y}_${G.join("_")}`,_=Z.useBackwardCompatibility?`${Y}_${U.map((q)=>q.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,U,Y,Z);else{let q=xQ.env[J]||(_?xQ.env[_]:void 0);if(q!==void 0){if(Z.verbose){let W=xQ.env[J]?J:_}try{Q[$]=this.parseEnvironmentValue(q,typeof H,J,Z.customParsers,Z.configName)}catch(W){if(W instanceof gX)throw W;throw BQ.envVar(J,q,typeof H,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[H,U]of Object.entries(Z))try{return U(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(xQ.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),U=[];switch(this.extractEnvVarInfo(X,[],H,U),$){case"markdown":return this.formatAsMarkdown(U,Q);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],G=`${Y}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,U,Y,Z);else Z.push({key:G,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${U.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 L8(Q,X,Y={}){return _Z(Q,X,Y,new WeakMap)}function _Z(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:U}=Y;if(X===null||X===void 0)return H?Q:X;if(U){let G=U(Q,X);if(G!==void 0)return G}if(Array.isArray(X)||Array.isArray(Q))return qZ(Q,X,$,Z);if(!f(X)||!f(Q))return X;return F8(Q,X,Y,Z)}function qZ(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 K8(Q,X);case"smart":return j8(Q,X,Z);default:return X}return X}function K8(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>bX($,Z)))Y.push(Z);return Y}function j8(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(f(X[0])&&f(Q[0]))return I8(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 I8(Q,X,Y){let Z=[...X];for(let $ of Q){if(!f($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let G of H)if(G in $){if(Z.find((_)=>f(_)&&(G in _)&&_[G]===$[G])){U=!0;break}}if(!U)Z.push($)}return Z}function F8(Q,X,Y,Z){let $=X;if(f($)&&Z.has($))return Z.get($);let H={...Q};if(f($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let G=$[U],J=H[U];if(Y.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){H[U]=G;continue}if(f(G)&&f(J))H[U]=_Z(J,G,Y,Z);else if(Array.isArray(G)||Array.isArray(J))H[U]=qZ(J,G,Y.arrayMergeMode||"smart",Z);else H[U]=G}return H}function WZ(Q,X,Y="replace"){return L8(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function bX(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(!bX(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(!bX(Q[$],X[$]))return!1}return!0}return!1}function f(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class AZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:U=!0,verbose:G=!1}=Y;if($){let _=fQ.getWithFileCheck("file",Q);if(_){if(G)console.log(`Configuration loaded from cache: ${Q}`);return _}}let J=async()=>{if(!kQ(Q))return null;try{let _=`?t=${Date.now()}`,q=await import(Q+_),W=q.default||q,z="default"in q,A=Object.keys(q).length>0;if(!z&&!A)throw new rQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof W!=="object"||W===null||Array.isArray(W))throw new rQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:WZ(X,W,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)fQ.setWithFileCheck("file",K,Q,H);return K}catch(_){throw _ instanceof Error?BQ.configLoad(Q,_):BQ.configLoad(Q,Error(String(_)))}};if(U)return yX.track("loadFromPath",J,{path:Q});return J()}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 U of this.extensions)$.push(FX(X,`${H}${U}`));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 w8(async()=>{return kQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!kQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let G=FX(Q,`${H}${U}`);if(await this.checkFileAccess(G))Z.push(G)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let G=FX(Q,U);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(!kQ(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 D8=/^https?:\/\//;class zZ{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:G=!0,verbose:J=!1}=Y,_=async()=>{let q=[],W=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:G,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...U],z);else return this.validateWithJSONSchema(Q,X,z)}catch(A){return q.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:q,warnings:W}}};if(G)return await yX.track("validateConfiguration",_);return _()}async validateWithSchemaFile(Q,X,Y){try{if(!M8(X))throw new aQ(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 aQ(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 U=Array.isArray(Q)?"array":typeof Q,G=Array.isArray(X.type)?X.type:[X.type];if(!G.includes(U)){if(Z.push({path:Y,message:`Expected type ${G.join(" or ")}, got ${U}`,expected:G.join(" or "),actual:U,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 U=0;U<Q.length;U++){let G=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let U=Q;if(H.validateRequired&&X.required){for(let G of X.required)if(!(G in U)){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,J]of Object.entries(X.properties))if(G in U){let _=Y?`${Y}.${G}`:G;if(this.validateObjectAgainstSchema(U[G],J,_,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let G=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!G.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let U=this.getValueByPath(Q,H.path),G=this.validateWithRule(U,H,H.path);if(Z.push(...G),Y.stopOnFirstError&&Z.length>0)break}catch(U){Z.push({path:H.path,message:`Rule validation failed: ${U}`,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,U]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(U)})}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:D8},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var c=new YX("bunfig",{showTags:!0});function V8(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 BZ{fileLoader=new AZ;envProcessor=new cX;validator=new zZ;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...U}=Q;try{if(Y?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let G;try{G=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){let _=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(_)throw J;G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let q=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),W=!q&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),z=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(_&&(z||q))throw J;if(W&&(!_||!z))G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!_)G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||H)await this.validateConfiguration(G.config,$,H,U.name);if(Y?.enabled&&G)this.cacheResult(U.name||"",G,Y,U);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:U.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)c.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);G.metrics=J}return G}catch(G){if(G instanceof Error&&G.name==="ConfigNotFoundError")throw G;let J=Date.now()-X;throw c.error(`Configuration loading failed after ${J}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:U,defaultConfig:G,checkEnv:J=!0,arrayStrategy:_="replace",verbose:q=!1}=Q,W=H||eQ.cwd(),z=[],A=await this.loadLocalConfiguration(Z,$,W,U,G,_,q,J,Y);if(A)return z.push(...this.getLocalSearchPaths(Z,$,W,U)),this.finalizeResult(A,z,J,Z,q);let I=await this.loadHomeConfiguration(Z,$,G,_,q,J);if(I)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(I,z,J,Z,q);let B=await this.loadPackageJsonConfiguration(Z,$,W,G,_,q,J);if(B)return z.push(d(W,"package.json")),this.finalizeResult(B,z,J,Z,q);if(z.push(...this.getAllSearchPaths(Z,$,W,U)),X)throw BQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,G,J,q),warnings:[`No configuration file found for "${Z}"${V8($)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,G,J){let _=G?PQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let W of q){if(U)c.info(`Searching for configuration in: ${W}`);let z=this.fileLoader.generateConfigPaths(Q,W,X),A=await this.fileLoader.tryLoadFromPaths(z,_,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(A){if(U)c.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let U=H?PQ(Q,Y,$):Y,G=[d(YQ(),".config",Q),d(YQ(),".config"),YQ()];for(let J of G){if($)c.info(`Checking home directory: ${J}`);let _=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(_,U,{arrayStrategy:Z,verbose:$});if(q){if($)c.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let G=U?PQ(Q,Z,H):Z;try{let J=d(Y,"package.json");if(!LZ(J))return null;let _={};try{_=JSON.parse(KZ(J,"utf8"))}catch(z){if(H)c.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let q=_[Q],W=Q;if(!q&&X){let z=Array.isArray(X)?X:[X];for(let A of z){if(!A)continue;if(_[A]){q=_[A],W=A;break}}}if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)c.success(`Configuration loaded from package.json: ${W}`);return{config:WZ(G,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)c.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}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:PQ(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((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if($.length>0)throw BQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return fQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);fQ.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 U of $)H.push(...this.fileLoader.generateConfigPaths(Q,U,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 MX=new BZ;async function RZ(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 MX.loadConfig(Q);else Z=await MX.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 MX.applyEnvironmentVariables(G.name||"",X,!0,G.verbose||!1))?.config??X;return X}}function PQ(Q,X,Y=!1){let Z=new cX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let W=[...G,_],z=[`${$}_${W.join("_").toUpperCase()}`,`${$}_${W.map((B)=>B.toUpperCase()).join("")}`,`${$}_${W.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,I;for(let B of z)if(A=eQ.env[B],A!==void 0){I=B;break}if(A!==void 0&&I)if(typeof q==="boolean")J[_]=["true","1","yes"].includes(A.toLowerCase());else if(typeof q==="number"){let B=Number(A);if(!Number.isNaN(B))J[_]=B}else if(Array.isArray(q))try{J[_]=JSON.parse(A)}catch{J[_]=A.split(",").map((B)=>B.trim())}else J[_]=A;else if(q&&typeof q==="object"&&!Array.isArray(q))J[_]=H(q,W)}return J}return H(X)}var J$=d(eQ.cwd(),"config"),G$=d(eQ.cwd(),"src/generated");var S8=["code-style","lint"],wZ={ignores:["**/node_modules/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/.output/**","**/.next/**","**/.nuxt/**","**/.vite/**","**/.turbo/**","**/.cache/**","**/coverage/**","**/vendor/**","**/pantry/**","**/tmp/**","**/.git/**","**/.idea/**","**/.vscode/**","**/.zed/**","**/.cursor/**","**/.claude/**","**/.github/**","**/*.test.ts","**/*.spec.ts","**/.bunpress/**","**/.vitepress/cache/**","**/*.lock","**/package-lock.json","**/pnpm-lock.yaml"],lint:{extensions:["ts","js","html","css","json","jsonc","md","yaml","yml","stx","sh","bash","zsh"],reporter:"stylish",cache:!1,maxWarnings:-1},format:{extensions:["ts","js","html","css","json","jsonc","md","yaml","yml","stx","sh","bash","zsh"],trimTrailingWhitespace:!0,maxConsecutiveBlankLines:1,finalNewline:"one",indent:2,indentStyle:"spaces",quotes:"single",semi:!1},rules:{noDebugger:"error",noConsole:"warn"},pluginRules:{"style/brace-style":"warn","style/curly":"off","style/if-newline":"off","style/max-statements-per-line":"warn","pickier/import-dedupe":"warn","pickier/no-import-node-modules-by-path":"error","pickier/no-import-dist":"error","pickier/prefer-const":"error","pickier/prefer-template":"warn","pickier/no-unused-vars":"error","pickier/sort-tailwind-classes":"warn","regexp/no-unused-capturing-group":"error","regexp/no-super-linear-backtracking":"error","regexp/no-useless-lazy":"error","ts/no-top-level-await":"error","ts/member-delimiter-style":"off","ts/type-annotation-spacing":"off","style/comma-dangle":"off","style/keyword-spacing":"off","style/arrow-spacing":"off","style/space-infix-ops":"off","style/object-curly-spacing":"off","style/spaced-comment":"off","style/block-spacing":"off","style/space-before-blocks":"off","style/comma-spacing":"off","style/semi-spacing":"off","style/rest-spread-spacing":"off","style/key-spacing":"off","style/computed-property-spacing":"off","style/array-bracket-spacing":"off","style/space-in-parens":"off","style/template-curly-spacing":"off","style/space-unary-ops":"off","style/switch-colon-spacing":"off","style/arrow-parens":"off","style/space-before-function-paren":"off","style/quote-props":"off","style/no-floating-decimal":"off","style/new-parens":"off","style/no-extra-parens":"off","style/wrap-iife":"off","style/comma-style":"off","style/dot-location":"off","style/operator-linebreak":"off","style/multiline-ternary":"off","style/padded-blocks":"off","style/lines-between-class-members":"off","style/no-tabs":"off","style/no-mixed-spaces-and-tabs":"off","style/generator-star-spacing":"off","style/yield-star-spacing":"off","style/function-call-spacing":"off","style/template-tag-spacing":"off","style/no-whitespace-before-property":"off","style/no-mixed-operators":"off","style/indent-binary-ops":"off","ts/type-generic-spacing":"off","ts/type-named-tuple-spacing":"off","markdown/heading-increment":"warn","markdown/heading-style":"warn","markdown/no-missing-space-atx":"error","markdown/no-multiple-space-atx":"error","markdown/no-missing-space-closed-atx":"error","markdown/no-multiple-space-closed-atx":"error","markdown/blanks-around-headings":"warn","markdown/heading-start-left":"warn","markdown/no-duplicate-heading":"warn","markdown/single-title":"warn","markdown/no-trailing-punctuation":"warn","markdown/ul-style":"warn","markdown/list-indent":"error","markdown/ul-indent":"warn","markdown/ol-prefix":"warn","markdown/list-marker-space":"error","markdown/blanks-around-lists":"warn","markdown/no-trailing-spaces":"error","markdown/no-hard-tabs":"error","markdown/no-multiple-blanks":"warn","markdown/no-multiple-space-blockquote":"error","markdown/no-blanks-blockquote":"warn","markdown/blanks-around-fences":"warn","markdown/single-trailing-newline":"error","markdown/blanks-around-tables":"warn","markdown/no-reversed-links":"error","markdown/no-bare-urls":"warn","markdown/no-space-in-links":"error","markdown/no-empty-links":"error","markdown/link-fragments":"warn","markdown/reference-links-images":"warn","markdown/link-image-reference-definitions":"warn","markdown/link-image-style":"warn","markdown/descriptive-link-text":"warn","markdown/line-length":"off","markdown/commands-show-output":"warn","markdown/fenced-code-language":"warn","markdown/code-block-style":"off","markdown/code-fence-style":"warn","markdown/no-emphasis-as-heading":"warn","markdown/no-space-in-emphasis":"warn","markdown/no-space-in-code":"warn","markdown/emphasis-style":"warn","markdown/strong-style":"warn","markdown/no-inline-html":"off","markdown/hr-style":"warn","markdown/first-line-heading":"off","markdown/required-headings":"off","markdown/proper-names":"off","markdown/no-alt-text":"warn","markdown/table-pipe-style":"warn","markdown/table-column-count":"warn","markdown/table-column-style":"warn","lockfile/validate-host":["warn",{allowedHosts:["npm","yarn"]}],"lockfile/validate-https":"error","lockfile/validate-integrity":["warn",{requiredAlgorithm:"sha512"}],"lockfile/validate-package-names":"error","lockfile/validate-scheme":["error",{allowedSchemes:["https:","git+https:","git+ssh:"]}],"publint/exports-types-should-be-first":"error","publint/exports-default-should-be-last":"error","publint/exports-module-should-precede-require":"error","publint/exports-value-invalid":"error","publint/imports-key-invalid":"error","publint/imports-value-invalid":"error","publint/imports-default-should-be-last":"error","publint/imports-module-should-precede-require":"error","publint/use-type":"warn","publint/deprecated-field-jsnext":"warn","publint/field-invalid-value-type":"error","publint/local-dependency":"error","publint/has-module-but-no-exports":"warn","publint/exports-missing-root-entrypoint":"warn","publint/exports-fallback-array-use":"warn","publint/file-does-not-exist":"warn","publint/file-invalid-format":"warn","publint/module-should-be-esm":"error","publint/bin-file-not-executable":"error","publint/exports-module-should-be-esm":"error","shell/command-substitution":"error","shell/quote-variables":"warn","shell/no-cd-without-check":"warn","shell/no-eval":"error","shell/no-useless-cat":"warn","shell/shebang":"warn","shell/indent":"warn","shell/function-style":"warn","shell/operator-spacing":"warn","shell/keyword-spacing":"warn","shell/no-trailing-semicolons":"warn","shell/no-trailing-whitespace":"error","shell/prefer-double-brackets":"warn","shell/set-options":"off","shell/prefer-printf":"warn","shell/consistent-case-terminators":"warn","shell/no-broken-redirect":"error","shell/heredoc-indent":"warn","shell/no-ls-parsing":"warn","shell/no-variable-in-single-quotes":"warn","shell/no-exit-in-subshell":"warn","spell/check":"off","spell/check-comments":"off","spell/check-markdown":"off"},verbose:!0},lX=null;async function W$(){if(!lX)lX=await RZ({name:"pickier",alias:[...S8],defaultConfig:wZ});return lX}var A$=wZ;
|
|
62
|
+
export{wZ as I,W$ as J,A$ as K};
|