@stacksjs/rpx 0.11.8 → 0.11.9
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 +137 -136
- package/dist/cert-inspect.d.ts +15 -0
- package/dist/https.d.ts +30 -2
- package/dist/index.d.ts +22 -0
- package/dist/index.js +81 -79
- package/dist/macos-trust.d.ts +40 -0
- package/package.json +1 -1
- package/src/cert-inspect.ts +69 -0
- package/src/https.ts +78 -67
- package/src/index.ts +24 -0
- package/src/macos-trust.ts +175 -0
package/dist/bin/cli.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
3
|
#!/usr/bin/env bun
|
|
4
|
-
import{createRequire as uF}from"node:module";var bF=Object.defineProperty;var iF=($)=>$;function cF($,w){this[$]=iF.bind(null,w)}var G8=($,w)=>{for(var A in w)bF($,A,{get:w[A],enumerable:!0,configurable:!0,set:cF.bind(w,A)})};var FU=($,w)=>()=>($&&(w=$($=0)),w);var b=uF(import.meta.url);import{existsSync as mE,statSync as dE}from"fs";import{existsSync as Oh,mkdirSync as lT,readdirSync as tT,writeFileSync as pT}from"fs";import{homedir as gw}from"os";import{dirname as gE,resolve as x$}from"path";import ww from"process";import{join as rT,relative as aT,resolve as lE}from"path";import _J from"process";import{existsSync as VW,mkdirSync as fK,readdirSync as ZK,writeFileSync as EK}from"fs";import{homedir as Bh}from"os";import{dirname as BK,resolve as Q$}from"path";import M1 from"process";import{join as sT,relative as oT,resolve as tE}from"path";import XJ from"process";import{existsSync as DW,mkdirSync as GK,readdirSync as qK,writeFileSync as RK}from"fs";import{dirname as KK,resolve as kJ}from"path";import _h from"process";import{Buffer as t0}from"buffer";import{createCipheriv as eT,createDecipheriv as $G,randomBytes as jh}from"crypto";import{closeSync as zh,createReadStream as pE,createWriteStream as wG,existsSync as Hh,fsyncSync as rE,openSync as aE,writeFileSync as AG}from"fs";import{access as JG,constants as sE,mkdir as UG,readdir as HJ,rename as oE,stat as lw,unlink as TJ,writeFile as Th}from"fs/promises";import{join as tw}from"path";import y$ from"process";import{pipeline as YG}from"stream/promises";import{createGzip as eE}from"zlib";import pw from"process";import x0 from"process";import{Buffer as k0}from"buffer";import{createCipheriv as hG,createDecipheriv as fG,randomBytes as Gh}from"crypto";import{closeSync as qh,createReadStream as $W,createWriteStream as ZG,existsSync as GJ,fsyncSync as wW,openSync as AW,writeFileSync as EG}from"fs";import{access as WG,constants as JW,mkdir as FG,readdir as qJ,rename as UW,stat as rw,unlink as RJ,writeFile as Rh}from"fs/promises";import{isAbsolute as BG,join as aw,resolve as jG}from"path";import D from"process";import{pipeline as zG}from"stream/promises";import{createGzip as YW}from"zlib";import sw from"process";import P0 from"process";import NJ from"process";import{existsSync as KJ}from"fs";import{resolve as Nh}from"path";import{existsSync as HG}from"fs";import{existsSync as TG,readdirSync as GG}from"fs";import{extname as Kh,resolve as hW}from"path";import qG from"process";import{join as R2,relative as N2,resolve as qW}from"path";import uJ from"process";import{Buffer as Q0}from"buffer";import{createCipheriv as I2,createDecipheriv as y2,randomBytes as Ch}from"crypto";import{closeSync as Sh,createReadStream as RW,createWriteStream as L2,existsSync as IJ,fsyncSync as NW,openSync as KW,writeFileSync as C2}from"fs";import{access as S2,constants as MW,mkdir as V2,readdir as yJ,rename as IW,stat as ow,unlink as LJ,writeFile as Vh}from"fs/promises";import{isAbsolute as D2,join as ew,resolve as O2}from"path";import O from"process";import{pipeline as _2}from"stream/promises";import{createGzip as yW}from"zlib";import $1 from"process";import b0 from"process";function mT($,w){this[$]=vT.bind(null,w)}class nh{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,h=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:h}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!mE($))return!0;return dE($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=mE(A)?dE(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class vh{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),h=performance.now()-J;return this.recordMetric({operation:$,duration:h,timestamp:U,...A}),Y}catch(Y){let h=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:h,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function RG($,w={}){let J=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return J?`${$}:${J}`:$}function NG($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function KG($){return $.getStats().size*2}function mh($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&r(w[0])&&"id"in w[0]&&w[0].id===3&&r(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(r(w)&&r($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(r($)&&"arr"in $&&Array.isArray($.arr)&&r(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&r(w[0])&&r($[0])){let J=[...w];for(let U of $)if(r(U)&&"name"in U){if(!J.find((h)=>r(h)&&("name"in h)&&h.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((h)=>r(h)&&("path"in h)&&h.path===U.path))J.push(U)}else if(!J.some((Y)=>QJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!r(w)||!r($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(r(U)&&r(A[J]))A[J]=mh(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&r(U[0])&&r(A[J][0])){let Y=[...U];for(let h of A[J])if(r(h)&&"name"in h){if(!Y.find((f)=>r(f)&&("name"in f)&&f.name===h.name))Y.push(h)}else if(r(h)&&"path"in h){if(!Y.find((f)=>r(f)&&("path"in f)&&f.path===h.path))Y.push(h)}else if(!Y.some((Z)=>QJ(Z,h)))Y.push(h);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let h of A[J])if(!Y.includes(h))Y.push(h);A[J]=Y}else A[J]=U;else A[J]=U}return A}function QJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!QJ($[A],w[A]))return!1;return!0}if(r($)&&r(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!QJ($[U],w[U]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function MG($,w){if(!DW($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return mh(w,J)}catch{return null}}catch{return null}}async function IG({name:$="",cwd:w,defaultConfig:A}){let J=w||_h.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let h of Y)for(let Z of U){let f=kJ(J,`${h}${Z}`),E=await MG(f,A);if(E!==null)return E}try{let h=kJ(J,"package.json");if(DW(h)){let f=(await import(h))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return mh(A,f)}catch{}}}catch{}return A}function yG($,w={}){let A=XJ.cwd();while(A.includes("storage"))A=tE(A,"..");let J=tE(A,$||"");if(w?.relative)return oT(XJ.cwd(),J);return J}async function LG(){try{let $=await IG({name:"clarity",defaultConfig:SJ,cwd:XJ.cwd(),endpoint:"",headers:{}});return{...SJ,...$}}catch{return SJ}}function $$(){if(x0.env.NODE_ENV==="test"||x0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CG(){if(x0.env.NODE_ENV==="test"||x0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof x0<"u"){let $=x0.type;if($==="renderer"||$==="worker")return!1;return!!(x0.versions&&(x0.versions.node||x0.versions.bun))}return!1}class OW{async format($){let w=await CG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:pw.pid,hostname:w(),environment:pw.env.NODE_ENV||"development",platform:pw.platform,version:pw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pw.env.NODE_ENV||pw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...kh},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new OW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??y$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...VJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...VJ};return{...VJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:kh.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let U,Y=0,h=3,Z=1000;while(Y<h)try{try{try{await JG(this.config.logDirectory,sE.F_OK|sE.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await UG(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:t0.from($);try{if(!Hh(this.currentLogFile))await Th(this.currentLogFile,"",{mode:420});if(U=aE(this.currentLogFile,"a",420),AG(U,f,{flag:"a"}),rE(U),U!==void 0)zh(U),U=void 0;if((await lw(this.currentLogFile)).size===0){if(await Th(this.currentLogFile,f,{flag:"w",mode:420}),(await lw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(Y<h-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${h}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(U!==void 0)try{zh(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(Y===h-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}Y++;let E=Z*2**(Y-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 tw(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 tw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return tw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if($$())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,h=Math.max(1,Y);if(U.length>h)for(let[Z]of U.slice(h))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return jh(16).toString("hex")}generateKey(){return jh(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=jh(16),J=eT("aes-256-gcm",w,A),U=t0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:t0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=eE(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(t0.from(t0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if($$())return;let $=await lw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await HJ(this.config.logDirectory),Y=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),h=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${h}`;if(await lw(A).catch(()=>null))try{if(await oE(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await TJ(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(Y.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await Th(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await lw(A).catch(()=>null))await oE(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await HJ(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,Z)=>Z.localeCompare(h));for(let h of Y.slice(w.maxFiles))await TJ(tw(this.config.logDirectory,h))}}}async compressLogFile($,w){let A=pE($),J=wG(w),U=eE();await YG(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),Hh(this.currentLogFile))try{let $=aE(this.currentLogFile,"r+");rE($),zh($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!$$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await HJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await TJ(tw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:h=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(h)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let f=y$.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${g.cyan(U)}`;if(!h)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,h)=>{let Z=Number.parseInt(h,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,h)=>{if(h==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(h){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),h,Z;if(w instanceof Error)h=w.message,Z=w.stack;else h=this.formatMessage(w,A);if(this.fancy&&!$$()){let E=uW[$],W=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:g.gray(h),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:h,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:g.green(h),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:h,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:h,level:$}),console.error(F),Z){let j=Z.split(`
|
|
5
|
-
`);for(let B of j)if(B.trim()&&!B.includes(
|
|
6
|
-
`;if(Z)
|
|
7
|
-
`;
|
|
8
|
-
`,
|
|
9
|
-
`),
|
|
10
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if($$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${g.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress($,w=""){if(!this.enabled||!this.fancy||$$()||$<=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 A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(
|
|
12
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||$$()||!y$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if($$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await HJ(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=tw(this.config.logDirectory,J);if($.before)try{if((await lw(Y)).mtime>=$.before)continue}catch(h){console.error(`Failed to get stats for file ${Y}:`,h);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await TJ(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function CJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&v(w[0])&&"id"in w[0]&&w[0].id===3&&v(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(v(w)&&v($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(v($)&&"arr"in $&&Array.isArray($.arr)&&v(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&v(w[0])&&v($[0])){let J=[...w];for(let U of $)if(v(U)&&"name"in U){if(!J.find((h)=>v(h)&&("name"in h)&&h.name===U.name))J.push(U)}else if(v(U)&&"path"in U){if(!J.find((h)=>v(h)&&("path"in h)&&h.path===U.path))J.push(U)}else if(!J.some((Y)=>PJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!v(w)||!v($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(v(U)&&v(A[J]))A[J]=CJ(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&v(U[0])&&v(A[J][0])){let Y=[...U];for(let h of A[J])if(v(h)&&"name"in h){if(!Y.find((f)=>v(f)&&("name"in f)&&f.name===h.name))Y.push(h)}else if(v(h)&&"path"in h){if(!Y.find((f)=>v(f)&&("path"in f)&&f.path===h.path))Y.push(h)}else if(!Y.some((Z)=>PJ(Z,h)))Y.push(h);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let h of A[J])if(!Y.includes(h))Y.push(h);A[J]=Y}else A[J]=U;else A[J]=U}return A}function dh($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:CJ($,w);if(Array.isArray($))return A==="replace"?w:CJ($,w);if(!v(w)||!v($))return w;let J={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let Y=w[U],h=J[U];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(h))if(A==="replace")J[U]=Y;else J[U]=CJ(h,Y);else if(v(Y)&&v(h))J[U]=dh(h,Y,A);else J[U]=Y}return J}function PJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!PJ($[A],w[A]))return!1;return!0}if(v($)&&v(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!PJ($[U],w[U]))return!1}return!0}return!1}function v($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function MJ($,w,A="replace"){if(!VW($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return dh(w,U,A)}catch{return null}}catch{return null}}function SG($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(h,Z=[]){let f={...h};for(let[E,W]of Object.entries(h)){let F=[...Z,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),B=`${J}_${F.map(j).join("_")}`,T=`${J}_${F.map((H)=>H.toUpperCase()).join("_")}`;if(A)C$.info(`Checking environment variable ${B} for config ${$}.${F.join(".")}`);if(typeof W==="object"&&W!==null&&!Array.isArray(W))f[E]=Y(W,F);else{let H=M1.env[B]||M1.env[T];if(H!==void 0){if(A)C$.info(`Using environment variable ${H?B:T} for config ${$}.${F.join(".")}`);if(typeof W==="number")f[E]=Number(H);else if(typeof W==="boolean")f[E]=H.toLowerCase()==="true";else if(Array.isArray(W))try{let q=JSON.parse(H);if(Array.isArray(q))f[E]=q;else f[E]=H.split(",").map((G)=>G.trim())}catch{f[E]=H.split(",").map((q)=>q.trim())}else f[E]=H}}}return f}return Y(U)}async function VG({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:U,verbose:Y=!1,checkEnv:h=!0,arrayStrategy:Z="replace"}){let f=h&&typeof U==="object"&&U!==null&&!Array.isArray(U)?SG($,U,Y):U,E=A||M1.cwd(),W=[".ts",".js",".mjs",".cjs",".json"];if(Y)C$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let F=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),B=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,Q$(E,"config"),Q$(E,".config"),J?Q$(E,J):void 0].filter(Boolean)));for(let q of H){if(Y)C$.info(`Searching for configuration in: ${q}`);let R=[Q$(E,"config"),Q$(E,".config")].concat(J?[Q$(E,J)]:[]).includes(q)?[...F,...j,...B,...T]:[...j,...F,...T,...B];for(let K of R)for(let L of W){let C=Q$(q,`${K}${L}`),M=await MJ(C,f,Z);if(M!==null){if(Y)C$.success(`Configuration loaded from: ${C}`);return M}}}if($){let q=Q$(Bh(),".config",$),G=["config",`${$}.config`];if(w)G.push(`${w}.config`);if(Y)C$.info(`Checking user config directory: ${q}`);for(let R of G)for(let K of W){let L=Q$(q,`${R}${K}`),C=await MJ(L,f,Z);if(C!==null){if(Y)C$.success(`Configuration loaded from user config directory: ${L}`);return C}}}if($){let q=Q$(Bh(),".config"),G=[`.${$}.config`];if(w)G.push(`.${w}.config`);if(Y)C$.info(`Checking user config directory for dotfile configs: ${q}`);for(let R of G)for(let K of W){let L=Q$(q,`${R}${K}`),C=await MJ(L,f,Z);if(C!==null){if(Y)C$.success(`Configuration loaded from user config directory dotfile: ${L}`);return C}}}if($){let q=Bh(),G=[`.${$}.config`,`.${$}`];if(w)G.push(`.${w}.config`),G.push(`.${w}`);if(Y)C$.info(`Checking user home directory for dotfile configs: ${q}`);for(let R of G)for(let K of W){let L=Q$(q,`${R}${K}`),C=await MJ(L,f,Z);if(C!==null){if(Y)C$.success(`Configuration loaded from user home directory: ${L}`);return C}}}try{let q=Q$(E,"package.json");if(VW(q)){let G=await import(q),R=G[$];if(!R&&w){if(R=G[w],R&&Y)C$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(Y)C$.success(`Configuration loaded from package.json: ${R===G[$]?$:w}`);return dh(f,R,Z)}catch(K){if(Y)C$.warn("Failed to merge package.json config:",K)}}}catch(q){if(Y)C$.warn("Failed to load package.json:",q)}if(Y)C$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function DG($,w={}){let A=_J.cwd();while(A.includes("storage"))A=lE(A,"..");let J=lE(A,$||"");if(w?.relative)return aT(_J.cwd(),J);return J}async function OG(){try{let $=await VG({name:"clarity",alias:"logging",defaultConfig:DJ,cwd:_J.cwd()});return{...DJ,...$||{}}}catch{return DJ}}function E$(){if(P0.env.NODE_ENV==="test"||P0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _G(){if(P0.env.NODE_ENV==="test"||P0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof P0<"u"){let $=P0.type;if($==="renderer"||$==="worker")return!1;return!!(P0.versions&&(P0.versions.node||P0.versions.bun))}return!1}class _W{async format($){let w=await _G(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:sw.pid,hostname:w(),environment:sw.env.NODE_ENV||"development",platform:sw.platform,version:sw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:sw.env.NODE_ENV||sw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class bJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...Qh},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new _W,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...OJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...OJ};return{...OJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Qh.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!E$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,h=3,Z=1000;while(Y<h)try{try{try{await WG(this.config.logDirectory,JW.F_OK|JW.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await FG(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:k0.from($);try{if(!GJ(this.currentLogFile))await Rh(this.currentLogFile,"",{mode:420});if(U=AW(this.currentLogFile,"a",420),EG(U,f,{flag:"a"}),wW(U),U!==void 0)qh(U),U=void 0;if((await rw(this.currentLogFile)).size===0){if(await Rh(this.currentLogFile,f,{flag:"w",mode:420}),(await rw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(Y<h-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${h}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(U!==void 0)try{qh(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(Y===h-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}Y++;let E=Z*2**(Y-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 aw(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 aw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return aw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(E$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,h=Math.max(1,Y);if(U.length>h)for(let[Z]of U.slice(h))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return Gh(16).toString("hex")}generateKey(){return Gh(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=Gh(16),J=hG("aes-256-gcm",w,A),U=k0.isBuffer($)?$:k0.from($,"utf8"),Y=J.update(U),h=J.final(),Z=Y.length+h.length,f=J.getAuthTag(),E=k0.allocUnsafe(16+Z+16);return A.copy(E,0),Y.copy(E,16),h.copy(E,16+Y.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=YW(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(k0.from(k0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(E$())return;if(!this.shouldWriteToFile())return;let $=await rw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await qJ(this.config.logDirectory),Y=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),h=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${h}`;if(await rw(A).catch(()=>null))try{if(await UW(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await RJ(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(Y.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await Rh(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await rw(A).catch(()=>null))await UW(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await qJ(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,Z)=>Z.localeCompare(h));for(let h of Y.slice(w.maxFiles))await RJ(aw(this.config.logDirectory,h))}}}async compressLogFile($,w){let A=$W($),J=ZG(w),U=YW();await zG(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),GJ(this.currentLogFile))try{let $=AW(this.currentLogFile,"r+");wW($),qh($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!E$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await qJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await RJ(aw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?k.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E$())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:h=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(h)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let f=D.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${k.cyan(U)}`;if(!h)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,h)=>{let Z=Number.parseInt(h,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,h)=>{if(h==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(h){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=k.underline(k.blue(J)),h=this.toAbsoluteFilePath(U);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(h)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>k.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>k.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>k.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>k.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>k.strikethrough(J)),w}supportsHyperlinks(){if(E$())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=D.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(BG(w)||w.startsWith("./")||w.startsWith("../"))w=jG(w);else return null;return GJ(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),h,Z;if(w instanceof Error)h=w.message,Z=w.stack;else h=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":nW[$],j=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:k.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:k.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
|
|
13
|
-
`);for(let
|
|
14
|
-
`;if(Z)
|
|
15
|
-
`;if(
|
|
16
|
-
`);if(this[
|
|
17
|
-
`,
|
|
18
|
-
`),
|
|
19
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
21
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
4
|
+
import{createRequire as oF}from"node:module";var rF=Object.defineProperty;var aF=($)=>$;function sF($,w){this[$]=aF.bind(null,w)}var V8=($,w)=>{for(var A in w)rF($,A,{get:w[A],enumerable:!0,configurable:!0,set:sF.bind(w,A)})};var qU=($,w)=>()=>($&&(w=$($=0)),w);var b=oF(import.meta.url);import{existsSync as $h,statSync as wh}from"fs";import{existsSync as bf,mkdirSync as YG,readdirSync as fG,writeFileSync as EG}from"fs";import{homedir as dw}from"os";import{dirname as Ah,resolve as x$}from"path";import ww from"process";import{join as ZG,relative as WG,resolve as Jh}from"path";import QJ from"process";import{existsSync as ch,mkdirSync as yK,readdirSync as CK,writeFileSync as SK}from"fs";import{homedir as Rf}from"os";import{dirname as DK,resolve as Q$}from"path";import L1 from"process";import{join as hG,relative as FG,resolve as Uh}from"path";import xJ from"process";import{existsSync as uh,mkdirSync as xK,readdirSync as PK,writeFileSync as bK}from"fs";import{dirname as cK,resolve as PJ}from"path";import cf from"process";import{Buffer as t0}from"buffer";import{createCipheriv as BG,createDecipheriv as jG,randomBytes as Nf}from"crypto";import{closeSync as Kf,createReadStream as Yh,createWriteStream as zG,existsSync as Mf,fsyncSync as fh,openSync as Eh,writeFileSync as TG}from"fs";import{access as HG,constants as Zh,mkdir as GG,readdir as qJ,rename as Wh,stat as gw,unlink as RJ,writeFile as If}from"fs/promises";import{join as lw}from"path";import L$ from"process";import{pipeline as qG}from"stream/promises";import{createGzip as hh}from"zlib";import tw from"process";import x0 from"process";import{Buffer as k0}from"buffer";import{createCipheriv as RG,createDecipheriv as NG,randomBytes as Lf}from"crypto";import{closeSync as yf,createReadStream as Fh,createWriteStream as KG,existsSync as NJ,fsyncSync as Bh,openSync as jh,writeFileSync as MG}from"fs";import{access as IG,constants as zh,mkdir as LG,readdir as KJ,rename as Th,stat as pw,unlink as MJ,writeFile as Cf}from"fs/promises";import{isAbsolute as yG,join as rw,resolve as CG}from"path";import O from"process";import{pipeline as SG}from"stream/promises";import{createGzip as Hh}from"zlib";import aw from"process";import P0 from"process";import IJ from"process";import{existsSync as LJ}from"fs";import{resolve as Sf}from"path";import{existsSync as VG}from"fs";import{existsSync as OG,readdirSync as DG}from"fs";import{extname as Vf,resolve as Gh}from"path";import _G from"process";import{join as X2,relative as k2,resolve as Oh}from"path";import mJ from"process";import{Buffer as Q0}from"buffer";import{createCipheriv as P2,createDecipheriv as b2,randomBytes as kf}from"crypto";import{closeSync as Qf,createReadStream as Dh,createWriteStream as i2,existsSync as CJ,fsyncSync as _h,openSync as Xh,writeFileSync as c2}from"fs";import{access as u2,constants as kh,mkdir as n2,readdir as SJ,rename as Qh,stat as sw,unlink as VJ,writeFile as xf}from"fs/promises";import{isAbsolute as v2,join as ow,resolve as m2}from"path";import D from"process";import{pipeline as d2}from"stream/promises";import{createGzip as xh}from"zlib";import ew from"process";import b0 from"process";function AG($,w){this[$]=wG.bind(null,w)}class rf{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,f=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:f}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!$h($))return!0;return wh($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=$h(A)?wh(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class af{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),f=performance.now()-J;return this.recordMetric({operation:$,duration:f,timestamp:U,...A}),Y}catch(Y){let f=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:f,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function XG($,w={}){let J=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return J?`${$}:${J}`:$}function kG($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function QG($){return $.getStats().size*2}function sf($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&r(w[0])&&"id"in w[0]&&w[0].id===3&&r(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(r(w)&&r($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(r($)&&"arr"in $&&Array.isArray($.arr)&&r(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&r(w[0])&&r($[0])){let J=[...w];for(let U of $)if(r(U)&&"name"in U){if(!J.find((f)=>r(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((f)=>r(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>bJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!r(w)||!r($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(r(U)&&r(A[J]))A[J]=sf(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&r(U[0])&&r(A[J][0])){let Y=[...U];for(let f of A[J])if(r(f)&&"name"in f){if(!Y.find((E)=>r(E)&&("name"in E)&&E.name===f.name))Y.push(f)}else if(r(f)&&"path"in f){if(!Y.find((E)=>r(E)&&("path"in E)&&E.path===f.path))Y.push(f)}else if(!Y.some((Z)=>bJ(Z,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function bJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!bJ($[A],w[A]))return!1;return!0}if(r($)&&r(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!bJ($[U],w[U]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function xG($,w){if(!uh($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return sf(w,J)}catch{return null}}catch{return null}}async function PG({name:$="",cwd:w,defaultConfig:A}){let J=w||cf.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let f of Y)for(let Z of U){let E=PJ(J,`${f}${Z}`),W=await xG(E,A);if(W!==null)return W}try{let f=PJ(J,"package.json");if(uh(f)){let E=(await import(f))[$];if(E&&typeof E==="object"&&!Array.isArray(E))try{return sf(A,E)}catch{}}}catch{}return A}function bG($,w={}){let A=xJ.cwd();while(A.includes("storage"))A=Uh(A,"..");let J=Uh(A,$||"");if(w?.relative)return FG(xJ.cwd(),J);return J}async function iG(){try{let $=await PG({name:"clarity",defaultConfig:DJ,cwd:xJ.cwd(),endpoint:"",headers:{}});return{...DJ,...$}}catch{return DJ}}function $$(){if(x0.env.NODE_ENV==="test"||x0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cG(){if(x0.env.NODE_ENV==="test"||x0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof x0<"u"){let $=x0.type;if($==="renderer"||$==="worker")return!1;return!!(x0.versions&&(x0.versions.node||x0.versions.bun))}return!1}class nh{async format($){let w=await cG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:tw.pid,hostname:w(),environment:tw.env.NODE_ENV||"development",platform:tw.platform,version:tw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tw.env.NODE_ENV||tw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class iJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...nf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new nh,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??L$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{..._J,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{..._J};return{..._J,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:nf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,Z=1000;while(Y<f)try{try{try{await HG(this.config.logDirectory,Zh.F_OK|Zh.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await GG(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let E=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:t0.from($);try{if(!Mf(this.currentLogFile))await If(this.currentLogFile,"",{mode:420});if(U=Eh(this.currentLogFile,"a",420),TG(U,E,{flag:"a"}),fh(U),U!==void 0)Kf(U),U=void 0;if((await gw(this.currentLogFile)).size===0){if(await If(this.currentLogFile,E,{flag:"w",mode:420}),(await gw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let h=W;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(Y<f-1){let F=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(U!==void 0)try{Kf(U)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(E){if(Y===f-1){let h=E,F=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),E}Y++;let W=Z*2**(Y-1);await new Promise((h)=>setTimeout(h,W))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 lw(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 lw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return lw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if($$())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,E])=>E.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[Z]of U.slice(f))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return Nf(16).toString("hex")}generateKey(){return Nf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=Nf(16),J=BG("aes-256-gcm",w,A),U=t0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:t0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=hh(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(t0.from(t0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if($$())return;let $=await gw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await qJ(this.config.logDirectory),Y=U.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,W)=>{let h=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${f}`;if(await gw(A).catch(()=>null))try{if(await Wh(A,Z),w.compress)try{let E=`${Z}.gz`;await this.compressLogFile(Z,E),await RJ(Z)}catch(E){console.error("Error compressing rotated file:",E)}if(Y.length===0&&!U.some((E)=>E.endsWith(".log.1")))try{let E=`${A}.1`;await If(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await gw(A).catch(()=>null))await Wh(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await qJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,Z)=>Z.localeCompare(f));for(let f of Y.slice(w.maxFiles))await RJ(lw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=Yh($),J=zG(w),U=hh();await qG(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),Mf(this.currentLogFile))try{let $=Eh(this.currentLogFile,"r+");fh($),Kf($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!$$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await qJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await RJ(lw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(f)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let E=L$.stdout.columns||120,W="";if(Y==="warning"||Y==="error")W=`${A} ${U}`;else if(Y==="info"||Y==="success")W=`${A} ${J} ${U}`;else W=`${A} ${J} ${g.cyan(U)}`;if(!f)return W.trim();let h=Z(W).trim().length,F=Z(w).length,j=Math.max(1,E-2-h-F);return`${W.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let Z=Number.parseInt(f,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(f){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 Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,Z;if(w instanceof Error)f=w.message,Z=w.stack;else f=this.formatMessage(w,A);if(this.fancy&&!$$()){let W=sh[$],h=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:g.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:f,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:g.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:f,level:$}),console.error(F),Z){let j=Z.split(`
|
|
5
|
+
`);for(let B of j)if(B.trim()&&!B.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:g.gray(` ${B}`),level:$,showTimestamp:!1}))}break}}else if(!$$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),Z)console.error(Z)}if(!this.shouldLog($))return;let E=`${Y} ${this.environment}.${$.toUpperCase()}: ${f}
|
|
6
|
+
`;if(Z)E+=`${Z}
|
|
7
|
+
`;E=E.replace(this.ANSI_PATTERN,""),await this.writeToFile(E)}time($){let w=performance.now();if(this.fancy&&!$$()){let A=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:g.blue("◐"),tag:A,message:`${g.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,Z=this.formatConsoleTimestamp(f),W=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)W+=` ${JSON.stringify(A)}`;if(W+=`
|
|
8
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.fancy&&!$$()){let h=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:g.green("✓"),tag:h,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!$$())console.error(W.trim());await this.writeToFile(W)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new iJ(w,{...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(A),A}createReadStream(){if($$())throw Error("createReadStream is not supported in browser environments");if(!Mf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Yh(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=t0.isBuffer($)?$:t0.from($,"base64"),U=J.slice(0,16),Y=J.slice(-16),f=J.slice(16,-16),Z=jG("aes-256-gcm",A,U);return Z.setAuthTag(Y),t0.concat([Z.update(f),Z.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return $$()}isServerMode(){return!$$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w);if(this.fancy&&!$$()){let Y=$.split(`
|
|
9
|
+
`),f=Math.max(...Y.map((h)=>h.length))+2,Z=`┌${"─".repeat(f)}┐`,E=`└${"─".repeat(f)}┘`,W=Y.map((h)=>{let F=" ".repeat(f-h.length-2);return`│ ${h}${F} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:g.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(Z)})),W.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(E),showTimestamp:!1}))}else if(!$$())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let U=`${J} ${this.environment}.INFO: [BOX] ${$}
|
|
10
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if($$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${g.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();L$.stdin.removeListener("data",A);try{if(typeof L$.stdin.setRawMode==="function")L$.stdin.setRawMode(!1)}catch{}L$.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof L$.stdin.setRawMode==="function")L$.stdin.setRawMode(!0)}catch{}L$.stdin.resume(),L$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,Z=0;if(A=$.replace(f,(E,W)=>{if(W==="%")return"%";if(Z>=w.length)return E;let h=w[Z++];switch(W){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return E}}),Z<w.length)A+=` ${w.slice(Z).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}if(this.fancy&&!$$()){let f=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",Z=g.blue("◐");console.error(`${Z} ${f} ${g.cyan(A)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
11
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress($,w=""){if(!this.enabled||!this.fancy||$$()||$<=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 A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(f,Z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,f)),Z!==void 0)this.activeProgressBar.message=Z;let E=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,E)},finish:(f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;if(this.activeProgressBar.current=this.activeProgressBar.total,f!==void 0)this.activeProgressBar.message=f;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(f,Z="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;L$.stdout.write(`${"\r".padEnd(L$.stdout.columns||80)}\r`),this.log(Z,f),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||$$()||!L$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=g.green("━".repeat(J)),f=g.gray("━".repeat(U)),Z=`[${Y}${f}]`,E=`${A}%`.padStart(4),W=$.message?` ${$.message}`:"",h=w||A===100?g.green("✓"):g.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",j=`\r${h}${F} ${Z} ${E}${W}`,B=L$.stdout.columns||80,H=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${H}`,L$.stdout.write($.lastRenderedLine),w)L$.stdout.write(`
|
|
12
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||$$()||!L$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if($$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await qJ(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=lw(this.config.logDirectory,J);if($.before)try{if((await gw(Y)).mtime>=$.before)continue}catch(f){console.error(`Failed to get stats for file ${Y}:`,f);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await RJ(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function OJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&v(w[0])&&"id"in w[0]&&w[0].id===3&&v(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(v(w)&&v($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(v($)&&"arr"in $&&Array.isArray($.arr)&&v(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&v(w[0])&&v($[0])){let J=[...w];for(let U of $)if(v(U)&&"name"in U){if(!J.find((f)=>v(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(v(U)&&"path"in U){if(!J.find((f)=>v(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>cJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!v(w)||!v($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(v(U)&&v(A[J]))A[J]=OJ(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&v(U[0])&&v(A[J][0])){let Y=[...U];for(let f of A[J])if(v(f)&&"name"in f){if(!Y.find((E)=>v(E)&&("name"in E)&&E.name===f.name))Y.push(f)}else if(v(f)&&"path"in f){if(!Y.find((E)=>v(E)&&("path"in E)&&E.path===f.path))Y.push(f)}else if(!Y.some((Z)=>cJ(Z,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function of($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:OJ($,w);if(Array.isArray($))return A==="replace"?w:OJ($,w);if(!v(w)||!v($))return w;let J={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let Y=w[U],f=J[U];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(f))if(A==="replace")J[U]=Y;else J[U]=OJ(f,Y);else if(v(Y)&&v(f))J[U]=of(f,Y,A);else J[U]=Y}return J}function cJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!cJ($[A],w[A]))return!1;return!0}if(v($)&&v(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!cJ($[U],w[U]))return!1}return!0}return!1}function v($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function yJ($,w,A="replace"){if(!ch($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return of(w,U,A)}catch{return null}}catch{return null}}function uG($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,Z=[]){let E={...f};for(let[W,h]of Object.entries(f)){let F=[...Z,W],j=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),B=`${J}_${F.map(j).join("_")}`,H=`${J}_${F.map((T)=>T.toUpperCase()).join("_")}`;if(A)C$.info(`Checking environment variable ${B} for config ${$}.${F.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))E[W]=Y(h,F);else{let T=L1.env[B]||L1.env[H];if(T!==void 0){if(A)C$.info(`Using environment variable ${T?B:H} for config ${$}.${F.join(".")}`);if(typeof h==="number")E[W]=Number(T);else if(typeof h==="boolean")E[W]=T.toLowerCase()==="true";else if(Array.isArray(h))try{let q=JSON.parse(T);if(Array.isArray(q))E[W]=q;else E[W]=T.split(",").map((G)=>G.trim())}catch{E[W]=T.split(",").map((q)=>q.trim())}else E[W]=T}}}return E}return Y(U)}async function nG({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:U,verbose:Y=!1,checkEnv:f=!0,arrayStrategy:Z="replace"}){let E=f&&typeof U==="object"&&U!==null&&!Array.isArray(U)?uG($,U,Y):U,W=A||L1.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(Y)C$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${W}`);let F=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),B=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],T=Array.from(new Set([W,Q$(W,"config"),Q$(W,".config"),J?Q$(W,J):void 0].filter(Boolean)));for(let q of T){if(Y)C$.info(`Searching for configuration in: ${q}`);let R=[Q$(W,"config"),Q$(W,".config")].concat(J?[Q$(W,J)]:[]).includes(q)?[...F,...j,...B,...H]:[...j,...F,...H,...B];for(let K of R)for(let y of h){let C=Q$(q,`${K}${y}`),M=await yJ(C,E,Z);if(M!==null){if(Y)C$.success(`Configuration loaded from: ${C}`);return M}}}if($){let q=Q$(Rf(),".config",$),G=["config",`${$}.config`];if(w)G.push(`${w}.config`);if(Y)C$.info(`Checking user config directory: ${q}`);for(let R of G)for(let K of h){let y=Q$(q,`${R}${K}`),C=await yJ(y,E,Z);if(C!==null){if(Y)C$.success(`Configuration loaded from user config directory: ${y}`);return C}}}if($){let q=Q$(Rf(),".config"),G=[`.${$}.config`];if(w)G.push(`.${w}.config`);if(Y)C$.info(`Checking user config directory for dotfile configs: ${q}`);for(let R of G)for(let K of h){let y=Q$(q,`${R}${K}`),C=await yJ(y,E,Z);if(C!==null){if(Y)C$.success(`Configuration loaded from user config directory dotfile: ${y}`);return C}}}if($){let q=Rf(),G=[`.${$}.config`,`.${$}`];if(w)G.push(`.${w}.config`),G.push(`.${w}`);if(Y)C$.info(`Checking user home directory for dotfile configs: ${q}`);for(let R of G)for(let K of h){let y=Q$(q,`${R}${K}`),C=await yJ(y,E,Z);if(C!==null){if(Y)C$.success(`Configuration loaded from user home directory: ${y}`);return C}}}try{let q=Q$(W,"package.json");if(ch(q)){let G=await import(q),R=G[$];if(!R&&w){if(R=G[w],R&&Y)C$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(Y)C$.success(`Configuration loaded from package.json: ${R===G[$]?$:w}`);return of(E,R,Z)}catch(K){if(Y)C$.warn("Failed to merge package.json config:",K)}}}catch(q){if(Y)C$.warn("Failed to load package.json:",q)}if(Y)C$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return E}function vG($,w={}){let A=QJ.cwd();while(A.includes("storage"))A=Jh(A,"..");let J=Jh(A,$||"");if(w?.relative)return WG(QJ.cwd(),J);return J}async function mG(){try{let $=await nG({name:"clarity",alias:"logging",defaultConfig:XJ,cwd:QJ.cwd()});return{...XJ,...$||{}}}catch{return XJ}}function W$(){if(P0.env.NODE_ENV==="test"||P0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function dG(){if(P0.env.NODE_ENV==="test"||P0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof P0<"u"){let $=P0.type;if($==="renderer"||$==="worker")return!1;return!!(P0.versions&&(P0.versions.node||P0.versions.bun))}return!1}class vh{async format($){let w=await dG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:aw.pid,hostname:w(),environment:aw.env.NODE_ENV||"development",platform:aw.platform,version:aw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:aw.env.NODE_ENV||aw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class uJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...vf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new vh,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...kJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...kJ};return{...kJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:vf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!W$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,Z=1000;while(Y<f)try{try{try{await IG(this.config.logDirectory,zh.F_OK|zh.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await LG(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let E=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:k0.from($);try{if(!NJ(this.currentLogFile))await Cf(this.currentLogFile,"",{mode:420});if(U=jh(this.currentLogFile,"a",420),MG(U,E,{flag:"a"}),Bh(U),U!==void 0)yf(U),U=void 0;if((await pw(this.currentLogFile)).size===0){if(await Cf(this.currentLogFile,E,{flag:"w",mode:420}),(await pw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let h=W;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(Y<f-1){let F=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(U!==void 0)try{yf(U)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(E){if(Y===f-1){let h=E,F=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),E}Y++;let W=Z*2**(Y-1);await new Promise((h)=>setTimeout(h,W))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 rw(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 rw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return rw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(W$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,E])=>E.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[Z]of U.slice(f))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return Lf(16).toString("hex")}generateKey(){return Lf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=Lf(16),J=RG("aes-256-gcm",w,A),U=k0.isBuffer($)?$:k0.from($,"utf8"),Y=J.update(U),f=J.final(),Z=Y.length+f.length,E=J.getAuthTag(),W=k0.allocUnsafe(16+Z+16);return A.copy(W,0),Y.copy(W,16),f.copy(W,16+Y.length),E.copy(W,16+Z),{encrypted:W,iv:A}}async compressData($){return new Promise((w,A)=>{let J=Hh(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(k0.from(k0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(W$())return;if(!this.shouldWriteToFile())return;let $=await pw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await KJ(this.config.logDirectory),Y=U.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,W)=>{let h=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${f}`;if(await pw(A).catch(()=>null))try{if(await Th(A,Z),w.compress)try{let E=`${Z}.gz`;await this.compressLogFile(Z,E),await MJ(Z)}catch(E){console.error("Error compressing rotated file:",E)}if(Y.length===0&&!U.some((E)=>E.endsWith(".log.1")))try{let E=`${A}.1`;await Cf(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await pw(A).catch(()=>null))await Th(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await KJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,Z)=>Z.localeCompare(f));for(let f of Y.slice(w.maxFiles))await MJ(rw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=Fh($),J=KG(w),U=Hh();await SG(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),NJ(this.currentLogFile))try{let $=jh(this.currentLogFile,"r+");Bh($),yf($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!W$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await KJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await MJ(rw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?k.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||W$())return!1;let $=typeof O.env.NO_COLOR<"u",w=O.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof O.stderr<"u"&&O.stderr.isTTY||typeof O.stdout<"u"&&O.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(f)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let E=O.stdout.columns||120,W="";if(Y==="warning"||Y==="error")W=`${A} ${U}`;else if(Y==="info"||Y==="success")W=`${A} ${J} ${U}`;else W=`${A} ${J} ${k.cyan(U)}`;if(!f)return W.trim();let h=Z(W).trim().length,F=Z(w).length,j=Math.max(1,E-2-h-F);return`${W.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let Z=Number.parseInt(f,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(f){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 Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=k.underline(k.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(f)}`,E="\x1B]8;;",W="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>k.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>k.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>k.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>k.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>k.strikethrough(J)),w}supportsHyperlinks(){if(W$())return!1;let $=O.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=O.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(yG(w)||w.startsWith("./")||w.startsWith("../"))w=CG(w);else return null;return NJ(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,Z;if(w instanceof Error)f=w.message,Z=w.stack;else f=this.formatMessage(w,A);let{consoleText:E,fileText:W}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":oh[$],j=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:k.gray(E),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:k.green(E),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.error(B),Z){let H=Z.split(`
|
|
13
|
+
`);for(let T of H)if(T.trim()&&!T.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:k.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!W$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),Z)console.error(Z)}if(!this.shouldLog($))return;let h=`${Y} ${this.environment}.${$.toUpperCase()}: ${W}
|
|
14
|
+
`;if(Z)h+=`${Z}
|
|
15
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress($,w=""){let A={update:(Z,E)=>{},finish:(Z)=>{},interrupt:(Z,E)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!W$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Z,E)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Z),this.activeProgressBar.total),E!==void 0)this.activeProgressBar.message=E;if(this.shouldStyleConsole()&&!W$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Z)},interrupt:(Z,E="info")=>{if(!W$()&&O.stdout.isTTY)O.stdout.write(`
|
|
16
|
+
`);if(this[E==="warning"?"warn":E](Z),this.activeProgressBar&&this.shouldStyleConsole()&&!W$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":k.blue("◐"),tag:A,message:`${k.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,Z=this.formatConsoleTimestamp(f),W=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)W+=` ${JSON.stringify(A)}`;if(W+=`
|
|
17
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":k.green("✓"),tag:h,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!W$())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new uJ(w,{...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(A),A}createReadStream(){if(W$())throw Error("createReadStream is not supported in browser environments");if(!NJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Fh(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=k0.isBuffer($)?$:k0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),Z=NG("aes-256-gcm",A,U);Z.setAuthTag(Y);let E=Z.update(f),W=Z.final(),h=E.length+W.length,F=k0.allocUnsafe(h);return E.copy(F,0),W.copy(F,E.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return W$()}isServerMode(){return!W$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=U.split(`
|
|
18
|
+
`),E=Math.max(...Z.map((j)=>j.length))+2,W=`┌${"─".repeat(E)}┐`,h=`└${"─".repeat(E)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:k.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:k.cyan(W),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:k.cyan(h),showTimestamp:!1}))}else if(!W$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
19
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(W$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${k.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();O.stdin.removeListener("data",A);try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!1)}catch{}O.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!0)}catch{}O.stdin.resume(),O.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let E=/%([sdijfo%])/g,W=0;if(A=$.replace(E,(h,F)=>{if(F==="%")return"%";if(W>=w.length)return h;let j=w[W++];switch(F){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return h}}),W<w.length)A+=` ${w.slice(W).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${k.blue("◐")} `;console.error(`${W}${E} ${k.cyan(J)}`)}let Z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
20
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!O.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=k.green("━".repeat(J)),f=k.gray("━".repeat(U)),Z=`[${Y}${f}]`,E=`${A}%`.padStart(4),W=$.message?` ${$.message}`:"",h=this.options.showIcons===!1?"":w||A===100?k.green("✓"):k.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",j=`\r${h}${F} ${Z} ${E}${W}`,B=O.stdout.columns||80,H=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${H}`,O.stdout.write($.lastRenderedLine),w)O.stdout.write(`
|
|
21
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||W$()||!O.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(W$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await KJ(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=rw(this.config.logDirectory,J);if($.before)try{if((await pw(Y)).mtime>=$.before)continue}catch(f){console.error(`Failed to get stats for file ${Y}:`,f);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await MJ(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function mh($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let Z=0;Z<=A;Z++)try{return await $()}catch(E){if(f=E instanceof Error?E:Error(String(E)),Z===A||!U(f))break;if(J>0)await new Promise((W)=>setTimeout(W,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}function dh($){return $ instanceof d$}function gG($){return $ instanceof nJ}function lG($){if(dh($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((A)=>$.message.toLowerCase().includes(A.toLowerCase()))}class gJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:J,useCamelCase:U=!0,useBackwardCompatibility:Y=!0,customParsers:f={},verbose:Z=!1,trackPerformance:E=!0}=A,W=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let h=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],h,{useCamelCase:U,useBackwardCompatibility:Y,customParsers:f,verbose:Z,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(E)return S1.track("applyEnvironmentVariables",W,{configName:$});return W()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],Z=f.map((h)=>this.formatEnvKey(h,J.useCamelCase)),E=`${A}_${Z.join("_")}`,W=J.useBackwardCompatibility?`${A}_${f.map((h)=>h.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,f,A,J);else{let h=IJ.env[E]||(W?IJ.env[W]:void 0);if(h!==void 0){if(J.verbose){let F=IJ.env[E]?E:W}try{$[U]=this.parseEnvironmentValue(h,typeof Y,E,J.customParsers,J.configName)}catch(F){if(F instanceof vJ)throw F;throw p0.envVar(E,h,typeof Y,J.configName)}}}}}parseEnvironmentValue($,w,A,J,U){for(let[Y,f]of Object.entries(J))try{return f($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,w))try{return Y.parse($)}catch{throw p0.envVar(A,$,`${w} (via ${Y.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,U]of Object.entries(IJ.env))if(J.startsWith(A)&&U!==void 0)w[J]=U;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(U){J.push(`Cannot parse value "${w}" as ${A}: ${U}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:U="text"}=A,Y=J||this.generateEnvPrefix($),f=[];switch(this.extractEnvVarInfo(w,[],Y,f),U){case"markdown":return this.formatAsMarkdown(f,$);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,$)}}extractEnvVarInfo($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],Z=`${A}_${f.map((E)=>this.formatEnvKey(E,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,f,A,J);else J.push({key:Z,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${f.join(".")}`,example:this.generateExample(Y)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
22
22
|
|
|
23
23
|
`;for(let J of $)A+=`${J.key}
|
|
24
24
|
`,A+=` Type: ${J.type}
|
|
@@ -30,80 +30,80 @@ import{createRequire as uF}from"node:module";var bF=Object.defineProperty;var iF
|
|
|
30
30
|
`;A+=`| Variable | Type | Description | Example |
|
|
31
31
|
`,A+=`|----------|------|-------------|----------|
|
|
32
32
|
`;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
|
|
33
|
-
`;return A}}function QG($,w){let A=iW("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function QW($,w,A={}){return xW($,w,A,new WeakMap)}function xW($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:h}=A;if(w===null||w===void 0)return Y?$:w;if(h){let Z=h($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return PW($,w,U,J);if(!$0(w)||!$0($))return w;return iG($,w,A,J)}function PW($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return xG($,w);case"smart":return PG($,w,J);default:return w}return w}function xG($,w){let A=[...w];for(let J of $)if(!A.some((U)=>Xh(U,J)))A.push(J);return A}function PG($,w,A){if(w.length===0)return $;if($.length===0)return w;if($0(w[0])&&$0($[0]))return bG($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function bG($,w,A){let J=[...w];for(let U of $){if(!$0(U)){J.push(U);continue}let Y=["id","name","key","path","type"],h=!1;for(let Z of Y)if(Z in U){if(J.find((E)=>$0(E)&&(Z in E)&&E[Z]===U[Z])){h=!0;break}}if(!h)J.push(U)}return J}function iG($,w,A,J){let U=w;if($0(U)&&J.has(U))return J.get(U);let Y={...$};if($0(U))J.set(U,Y);for(let h in U){if(!Object.prototype.hasOwnProperty.call(U,h))continue;let Z=U[h],f=Y[h];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){Y[h]=Z;continue}if($0(Z)&&$0(f))Y[h]=xW(f,Z,A,J);else if(Array.isArray(Z)||Array.isArray(f))Y[h]=PW(f,Z,A.arrayMergeMode||"smart",J);else Y[h]=Z}return Y}function gh($,w,A="replace"){return QW($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function Xh($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!Xh($[A],w[A]))return!1;return!0}if($0($)&&$0(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!Xh($[U],w[U]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class mJ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:h=!0,verbose:Z=!1}=A;if(U){let E=w1.getWithFileCheck("file",$);if(E){if(Z)console.log(`Configuration loaded from cache: ${$}`);return E}}let f=async()=>{if(!KJ($))return null;try{let E=`?t=${Date.now()}`,W=await import($+E),F=W.default||W,j="default"in W,B=Object.keys(W).length>0;if(!j&&!B)throw new I1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new I1($,Error("Configuration must export a valid object"),"unknown");let q={config:gh(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)w1.setWithFileCheck("file",q,$,Y);return q}catch(E){throw E instanceof Error?p0.configLoad($,E):p0.configLoad($,Error(String(E)))}};if(h)return L1.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let h of this.extensions)U.push(Nh(w,`${Y}${h}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return XW(async()=>{return KJ($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!KJ($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let h of this.extensions){let Z=Nh($,`${Y}${h}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let h of Y)if(this.looksLikeConfigFile(h)){let Z=Nh($,h);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){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((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!KJ($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class lh{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:h=[],trackPerformance:Z=!0,verbose:f=!1}=A,E=async()=>{let W=[],F=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:h,trackPerformance:Z,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...h],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return W.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:W,warnings:F}}};if(Z)return await L1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!HG(w))throw new y1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new y1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let h=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(h)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${h}`,expected:Z.join(" or "),actual:h,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let h=0;h<$.length;h++){let Z=A?`${A}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema($[h],w.items,Z,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let h=$;if(Y.validateRequired&&w.required){for(let Z of w.required)if(!(Z in h)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[Z,f]of Object.entries(w.properties))if(Z in h){let E=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(h[Z],f,E,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(h))if(!Z.has(f))U.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let h=this.getValueByPath($,Y.path),Z=this.validateWithRule(h,Y,Y.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(h){J.push({path:Y.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,h]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(h)})}return w}mapTypeScriptType($){switch($.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:mW},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class th{fileLoader=new mJ;envProcessor=new vJ;validator=new lh;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...h}=$;try{if(A?.enabled){let f=this.checkCache(h.name||"",h);if(f)return f}let Z;try{Z=await this.loadConfigurationStrategies(h,!0,A)}catch(f){let E=h.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(E)throw f;Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let W=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),F=!W&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),j=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(E&&(j||W))throw f;if(F&&(!E||!j))Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||Y)await this.validateConfiguration(Z.config,U,Y,h.name);if(A?.enabled&&Z)this.cacheResult(h.name||"",Z,A,h);if(J?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:h.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(f);if(J.slowThreshold&&f.duration>J.slowThreshold)W0.warn(`Slow configuration loading detected: ${f.duration}ms for ${h.name}`);Z.metrics=f}return Z}catch(Z){let f=Date.now()-w;throw W0.error(`Configuration loading failed after ${f}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:h,defaultConfig:Z,checkEnv:f=!0,arrayStrategy:E="replace",verbose:W=!1}=$,F=Y||ww.cwd(),j=[],B=await this.loadLocalConfiguration(J,U,F,h,Z,E,W,f,A);if(B)return j.push(...this.getLocalSearchPaths(J,U,F,h)),this.finalizeResult(B,j,f,J,W);let T=await this.loadHomeConfiguration(J,U,Z,E,W,f);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,f,J,W);let H=await this.loadPackageJsonConfiguration(J,U,F,Z,E,W,f);if(H)return j.push(x$(F,"package.json")),this.finalizeResult(H,j,f,J,W);if(j.push(...this.getAllSearchPaths(J,U,F,h)),w)throw p0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,Z,f,W),warnings:[`No configuration file found for "${J}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,h,Z,f){let E=Z?K1($,U,h):U,W=this.getLocalDirectories(A,J);for(let F of W){if(h)W0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:h,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(B){if(h)W0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let h=Y?K1($,A,U):A,Z=[x$(gw(),".config",$),x$(gw(),".config"),gw()];for(let f of Z){if(U)W0.info(`Checking home directory: ${f}`);let E=this.fileLoader.generateConfigPaths($,f,w),W=await this.fileLoader.tryLoadFromPaths(E,h,{arrayStrategy:J,verbose:U});if(W){if(U)W0.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,h){let Z=h?K1($,J,Y):J;try{let f=x$(A,"package.json");if(!Oh(f))return null;let E=await import(f),W=E[$],F=$;if(!W&&w)W=E[w],F=w;if(W&&typeof W==="object"&&!Array.isArray(W)){if(Y)W0.success(`Configuration loaded from package.json: ${F}`);return{config:gh(Z,W,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(Y)W0.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:K1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(U.length>0)throw p0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return w1.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);w1.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,x$($,"config"),x$($,".config"),w?x$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(x$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let h of U)Y.push(...this.fileLoader.generateConfigPaths($,h,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[x$(gw(),".config",$),x$(gw(),".config"),gw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function fW($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),J=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||J}async function cG($){return i0.loadConfig({...$,__strictErrorHandling:!0})}async function bW($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await i0.loadConfig($);else J=await i0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let U=J instanceof Error?J.name:"UnknownError",Y=J instanceof Error?J.message:String(J);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||Y.includes("config"))&&$.verbose)W0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let Z=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await i0.applyEnvironmentVariables(Z.name||"",w,!0,Z.verbose||!1))?.config??w;return w}}async function uG($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await i0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&fW(A)))return(await i0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await i0.loadConfig({...$,cwd:$.cwd||ww.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&fW(w)))return(await i0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function nG($,w,A="replace"){let J=new mJ;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function K1($,w,A=!1){let J=new vJ,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(h,Z=[]){let f={...h};for(let[E,W]of Object.entries(h)){let F=[...Z,E],j=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((H)=>H.toUpperCase()).join("")}`,`${U}_${F.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,T;for(let H of j)if(B=ww.env[H],B!==void 0){T=H;break}if(B!==void 0&&T)if(typeof W==="boolean")f[E]=["true","1","yes"].includes(B.toLowerCase());else if(typeof W==="number"){let H=Number(B);if(!Number.isNaN(H))f[E]=H}else if(Array.isArray(W))try{f[E]=JSON.parse(B)}catch{f[E]=B.split(",").map((H)=>H.trim())}else f[E]=B;else if(W&&typeof W==="object"&&!Array.isArray(W))f[E]=Y(W,F)}return f}return Y(w)}function vG($){let w=x$(ww.cwd(),$.configDir),A=x$(ww.cwd(),$.generatedDir),J=x$(A,"config-types.ts");if(!Oh(gE(J)))lT(gE(J),{recursive:!0,mode:511});let U=Oh(w)?tT(w).map((h)=>h.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${G2}
|
|
33
|
+
`;return A}}function tG($,w){let A=rh("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function gh($,w,A={}){return lh($,w,A,new WeakMap)}function lh($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:f}=A;if(w===null||w===void 0)return Y?$:w;if(f){let Z=f($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return th($,w,U,J);if(!$0(w)||!$0($))return w;return sG($,w,A,J)}function th($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return pG($,w);case"smart":return rG($,w,J);default:return w}return w}function pG($,w){let A=[...w];for(let J of $)if(!A.some((U)=>uf(U,J)))A.push(J);return A}function rG($,w,A){if(w.length===0)return $;if($.length===0)return w;if($0(w[0])&&$0($[0]))return aG($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function aG($,w,A){let J=[...w];for(let U of $){if(!$0(U)){J.push(U);continue}let Y=["id","name","key","path","type"],f=!1;for(let Z of Y)if(Z in U){if(J.find((W)=>$0(W)&&(Z in W)&&W[Z]===U[Z])){f=!0;break}}if(!f)J.push(U)}return J}function sG($,w,A,J){let U=w;if($0(U)&&J.has(U))return J.get(U);let Y={...$};if($0(U))J.set(U,Y);for(let f in U){if(!Object.prototype.hasOwnProperty.call(U,f))continue;let Z=U[f],E=Y[f];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){Y[f]=Z;continue}if($0(Z)&&$0(E))Y[f]=lh(E,Z,A,J);else if(Array.isArray(Z)||Array.isArray(E))Y[f]=th(E,Z,A.arrayMergeMode||"smart",J);else Y[f]=Z}return Y}function ef($,w,A="replace"){return gh($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function uf($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!uf($[A],w[A]))return!1;return!0}if($0($)&&$0(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!uf($[U],w[U]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class lJ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:f=!0,verbose:Z=!1}=A;if(U){let W=$1.getWithFileCheck("file",$);if(W){if(Z)console.log(`Configuration loaded from cache: ${$}`);return W}}let E=async()=>{if(!LJ($))return null;try{let W=`?t=${Date.now()}`,h=await import($+W),F=h.default||h,j="default"in h,B=Object.keys(h).length>0;if(!j&&!B)throw new y1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new y1($,Error("Configuration must export a valid object"),"unknown");let q={config:ef(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)$1.setWithFileCheck("file",q,$,Y);return q}catch(W){throw W instanceof Error?p0.configLoad($,W):p0.configLoad($,Error(String(W)))}};if(f)return S1.track("loadFromPath",E,{path:$});return E()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let f of this.extensions)U.push(Sf(w,`${Y}${f}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return mh(async()=>{return LJ($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!LJ($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let Z=Sf($,`${Y}${f}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let f of Y)if(this.looksLikeConfigFile(f)){let Z=Sf($,f);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){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((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!LJ($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class $8{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:Z=!0,verbose:E=!1}=A,W=async()=>{let h=[],F=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:Z,verbose:E};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return h.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:h,warnings:F}}};if(Z)return await S1.track("validateConfiguration",W);return W()}async validateWithSchemaFile($,w,A){try{if(!VG(w))throw new C1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new C1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let f=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(f)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${f}`,expected:Z.join(" or "),actual:f,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let f=0;f<$.length;f++){let Z=A?`${A}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema($[f],w.items,Z,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let f=$;if(Y.validateRequired&&w.required){for(let Z of w.required)if(!(Z in f)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[Z,E]of Object.entries(w.properties))if(Z in f){let W=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(f[Z],E,W,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let E of Object.keys(f))if(!Z.has(E))U.push({path:A?`${A}.${E}`:E,message:`Additional property '${E}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let f=this.getValueByPath($,Y.path),Z=this.validateWithRule(f,Y,Y.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(f){J.push({path:Y.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,f]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(f)})}return w}mapTypeScriptType($){switch($.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:$F},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class w8{fileLoader=new lJ;envProcessor=new gJ;validator=new $8;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...f}=$;try{if(A?.enabled){let E=this.checkCache(f.name||"",f);if(E)return E}let Z;try{Z=await this.loadConfigurationStrategies(f,!0,A)}catch(E){let W=f.__strictErrorHandling;if(E instanceof Error&&E.name==="ConfigNotFoundError"){if(W)throw E;Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(E instanceof Error&&E.name==="ConfigLoadError"){let h=E.message.includes("EACCES")||E.message.includes("EPERM")||E.message.includes("permission denied"),F=!h&&(E.message.includes("syntax")||E.message.includes("Expected")||E.message.includes("Unexpected")||E.message.includes("BuildMessage")||E.message.includes("errors building")),j=E.message.includes("Configuration must export a valid object")||E.message.includes("Configuration file is empty and exports nothing");if(W&&(j||h))throw E;if(F&&(!W||!j))Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!W)Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${E.message}`]};else throw E}else Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${E instanceof Error?E.message:String(E)}`]}}if(U||Y)await this.validateConfiguration(Z.config,U,Y,f.name);if(A?.enabled&&Z)this.cacheResult(f.name||"",Z,A,f);if(J?.enabled){let E={operation:"loadConfig",duration:Date.now()-w,configName:f.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(E);if(J.slowThreshold&&E.duration>J.slowThreshold)h0.warn(`Slow configuration loading detected: ${E.duration}ms for ${f.name}`);Z.metrics=E}return Z}catch(Z){let E=Date.now()-w;throw h0.error(`Configuration loading failed after ${E}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:f,defaultConfig:Z,checkEnv:E=!0,arrayStrategy:W="replace",verbose:h=!1}=$,F=Y||ww.cwd(),j=[],B=await this.loadLocalConfiguration(J,U,F,f,Z,W,h,E,A);if(B)return j.push(...this.getLocalSearchPaths(J,U,F,f)),this.finalizeResult(B,j,E,J,h);let H=await this.loadHomeConfiguration(J,U,Z,W,h,E);if(H)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(H,j,E,J,h);let T=await this.loadPackageJsonConfiguration(J,U,F,Z,W,h,E);if(T)return j.push(x$(F,"package.json")),this.finalizeResult(T,j,E,J,h);if(j.push(...this.getAllSearchPaths(J,U,F,f)),w)throw p0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,Z,E,h),warnings:[`No configuration file found for "${J}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,Z,E){let W=Z?I1($,U,f):U,h=this.getLocalDirectories(A,J);for(let F of h){if(f)h0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,W,{arrayStrategy:Y,verbose:f,cacheTtl:E?.ttl,useCache:!E?.ttl||E.ttl>100});if(B){if(f)h0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?I1($,A,U):A,Z=[x$(dw(),".config",$),x$(dw(),".config"),dw()];for(let E of Z){if(U)h0.info(`Checking home directory: ${E}`);let W=this.fileLoader.generateConfigPaths($,E,w),h=await this.fileLoader.tryLoadFromPaths(W,f,{arrayStrategy:J,verbose:U});if(h){if(U)h0.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let Z=f?I1($,J,Y):J;try{let E=x$(A,"package.json");if(!bf(E))return null;let W=await import(E),h=W[$],F=$;if(!h&&w)h=W[w],F=w;if(h&&typeof h==="object"&&!Array.isArray(h)){if(Y)h0.success(`Configuration loaded from package.json: ${F}`);return{config:ef(Z,h,U),source:{type:"package.json",path:E,priority:30,timestamp:new Date}}}}catch(E){if(Y)h0.warn("Failed to load package.json:",[E instanceof Error?E:Error(String(E))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:I1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(U.length>0)throw p0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return $1.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);$1.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,x$($,"config"),x$($,".config"),w?x$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(x$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let f of U)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[x$(dw(),".config",$),x$(dw(),".config"),dw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function qh($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),J=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||J}async function oG($){return i0.loadConfig({...$,__strictErrorHandling:!0})}async function ph($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await i0.loadConfig($);else J=await i0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let U=J instanceof Error?J.name:"UnknownError",Y=J instanceof Error?J.message:String(J);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||Y.includes("config"))&&$.verbose)h0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let Z=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await i0.applyEnvironmentVariables(Z.name||"",w,!0,Z.verbose||!1))?.config??w;return w}}async function eG($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await i0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&qh(A)))return(await i0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await i0.loadConfig({...$,cwd:$.cwd||ww.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&qh(w)))return(await i0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function $2($,w,A="replace"){let J=new lJ;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function I1($,w,A=!1){let J=new gJ,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,Z=[]){let E={...f};for(let[W,h]of Object.entries(f)){let F=[...Z,W],j=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((T)=>T.toUpperCase()).join("")}`,`${U}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,H;for(let T of j)if(B=ww.env[T],B!==void 0){H=T;break}if(B!==void 0&&H)if(typeof h==="boolean")E[W]=["true","1","yes"].includes(B.toLowerCase());else if(typeof h==="number"){let T=Number(B);if(!Number.isNaN(T))E[W]=T}else if(Array.isArray(h))try{E[W]=JSON.parse(B)}catch{E[W]=B.split(",").map((T)=>T.trim())}else E[W]=B;else if(h&&typeof h==="object"&&!Array.isArray(h))E[W]=Y(h,F)}return E}return Y(w)}function w2($){let w=x$(ww.cwd(),$.configDir),A=x$(ww.cwd(),$.generatedDir),J=x$(A,"config-types.ts");if(!bf(Ah(J)))YG(Ah(J),{recursive:!0,mode:511});let U=bf(w)?fG(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${D2}
|
|
34
34
|
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
35
|
-
`;
|
|
36
|
-
${U.map((
|
|
35
|
+
`;EG(J,Y,{mode:438})}function A2($){let w=null,A=null,J=()=>{if(!A)A=ph($).then((Y)=>{return w=Y,Y},(Y)=>{let f="defaultConfig"in $?$.defaultConfig:{};if(w=f,"verbose"in $&&$.verbose)h0.warn("Config loading failed, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);return f});return A},U="defaultConfig"in $?$.defaultConfig:{};return w=U,J(),new Proxy({},{get(Y,f){if(w)return w[f];let Z=U[f];return J(),Z},has(Y,f){return f in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(Y,f){return Object.getOwnPropertyDescriptor(w||U,f)},set(Y,f,Z){if(!w)w={...U};return w[f]=Z,!0}})}function J2($){let w=Gh(_G.cwd(),$?.configDir||"./config");function A(){if(!OG(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),Y=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],f=DG(w).filter((E)=>U.has(Vf(E))).map((E)=>({base:E.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:E})),Z=new Map;for(let{base:E,file:W}of f){let h=Vf(W).toLowerCase(),F=Z.get(E);if(!F){Z.set(E,W);continue}let j=Vf(F).toLowerCase();if(Y.indexOf(h)<Y.indexOf(j))Z.set(E,W)}return Array.from(Z.entries()).map(([E,W])=>({base:E,file:W})).sort((E,W)=>E.base.localeCompare(W.base))}function J(){let U=A(),Y=U.map((W)=>W.base),f=Y.length?Y.map((W)=>`'${W}'`).join(" | "):"string",Z=U.length?`{
|
|
36
|
+
${U.map((W)=>{let h=Gh(w,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${h}').default`}).join(`,
|
|
37
37
|
`)}
|
|
38
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
38
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${f}
|
|
39
39
|
export type ConfigByName = ${Z}
|
|
40
40
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
41
41
|
export type ConfigOf = Config
|
|
42
|
-
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}function K2($,w={}){let A=uJ.cwd();while(A.includes("storage"))A=qW(A,"..");let J=qW(A,$||"");if(w?.relative)return N2(uJ.cwd(),J);return J}function F$(){if(b0.env.NODE_ENV==="test"||b0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function X2(){if(b0.env.NODE_ENV==="test"||b0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof b0<"u"){let $=b0.type;if($==="renderer"||$==="worker")return!1;return!!(b0.versions&&(b0.versions.node||b0.versions.bun))}return!1}class tW{async format($){let w=await X2(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:$1.pid,hostname:w(),environment:$1.env.NODE_ENV||"development",platform:$1.platform,version:$1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$1.env.NODE_ENV||$1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Aw{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...nJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new tW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...Dh,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Dh};return{...Dh,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:nJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!F$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,h=3,Z=1000;while(Y<h)try{try{try{await S2(this.config.logDirectory,MW.F_OK|MW.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await V2(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Q0.from($);try{if(!IJ(this.currentLogFile))await Vh(this.currentLogFile,"",{mode:420});if(U=KW(this.currentLogFile,"a",420),C2(U,f,{flag:"a"}),NW(U),U!==void 0)Sh(U),U=void 0;if((await ow(this.currentLogFile)).size===0){if(await Vh(this.currentLogFile,f,{flag:"w",mode:420}),(await ow(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(Y<h-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${h}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(U!==void 0)try{Sh(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(Y===h-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}Y++;let E=Z*2**(Y-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 ew(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 ew(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return ew(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(F$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,h=Math.max(1,Y);if(U.length>h)for(let[Z]of U.slice(h))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return Ch(16).toString("hex")}generateKey(){return Ch(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=Ch(16),J=I2("aes-256-gcm",w,A),U=Q0.isBuffer($)?$:Q0.from($,"utf8"),Y=J.update(U),h=J.final(),Z=Y.length+h.length,f=J.getAuthTag(),E=Q0.allocUnsafe(16+Z+16);return A.copy(E,0),Y.copy(E,16),h.copy(E,16+Y.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=yW(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(Q0.from(Q0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(F$())return;if(!this.shouldWriteToFile())return;let $=await ow(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await yJ(this.config.logDirectory),Y=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),h=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${h}`;if(await ow(A).catch(()=>null))try{if(await IW(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await LJ(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(Y.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await Vh(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await ow(A).catch(()=>null))await IW(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await yJ(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,Z)=>Z.localeCompare(h));for(let h of Y.slice(w.maxFiles))await LJ(ew(this.config.logDirectory,h))}}}async compressLogFile($,w){let A=RW($),J=L2(w),U=yW();await _2(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),IJ(this.currentLogFile))try{let $=KW(this.currentLogFile,"r+");NW($),Sh($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!F$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await yJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await LJ(ew(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?P.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F$())return!1;let $=typeof O.env.NO_COLOR<"u",w=O.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof O.stderr<"u"&&O.stderr.isTTY||typeof O.stdout<"u"&&O.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:h=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(h)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let f=O.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${P.cyan(U)}`;if(!h)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,h)=>{let Z=Number.parseInt(h,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,h)=>{if(h==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(h){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=P.underline(P.blue(J)),h=this.toAbsoluteFilePath(U);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(h)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>P.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>P.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>P.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>P.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>P.strikethrough(J)),w}supportsHyperlinks(){if(F$())return!1;let $=O.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=O.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(D2(w)||w.startsWith("./")||w.startsWith("../"))w=O2(w);else return null;return IJ(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),h,Z;if(w instanceof Error)h=w.message,Z=w.stack;else h=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":b2[$],j=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:P.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:P.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
|
|
43
|
-
`);for(let
|
|
44
|
-
`;if(Z)
|
|
45
|
-
`;if(
|
|
46
|
-
`);if(this[
|
|
47
|
-
`,
|
|
48
|
-
`),
|
|
49
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
51
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F$()||!O.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(F$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await yJ(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=ew(this.config.logDirectory,J);if($.before)try{if((await ow(Y)).mtime>=$.before)continue}catch(h){console.error(`Failed to get stats for file ${Y}:`,h);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await LJ(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var nT,vT=($)=>$,dT=($,w)=>{for(var A in w)nT($,A,{get:w[A],enumerable:!0,configurable:!0,set:mT.bind(w,A)})},gT=($,w)=>()=>($&&(w=$($=0)),w),SW,iW,w1,L1,cW,gG,lG,ZW,SJ,kh,L$,g,tG,EW,pG,WW,rG,aG,Mh,sG,FW,BW,Ih,oG,eG,$2,w2,VJ,uW,A2,C$,J2,U2,jW,DJ,Qh,W$,k,Y2,zW,h2,HW,f2,Z2,yh,E2,TW,GW,W2,Lh,F2,B2,j2,z2,H2,OJ,nW,T2,G2="0.15.6",d$,iJ,I1,xh,Ph,cJ,bh,ih,y1,ch,uh,p0,vW,mW,W0,i0,dW,gW,q2,M2,lW,nJ,oK,H$,P,EM,k2,WM,Q2,FM,BM,LW,jM,x2,P2,zM,CW,HM,TM,GM,qM,RM,Dh,b2,NM;var ph=FU(()=>{nT=Object.defineProperty;SW={};dT(SW,{withErrorRecovery:()=>XW,tryLoadConfig:()=>nG,loadConfigWithResult:()=>cG,loadConfig:()=>bW,isRetryableError:()=>kG,isConfigNotFoundError:()=>XG,isBunfigError:()=>kW,globalPerformanceMonitor:()=>L1,globalCache:()=>w1,getEnvOrDefault:()=>QG,generateConfigTypes:()=>vG,defaultGeneratedDir:()=>gW,defaultConfigDir:()=>dW,deepMergeWithArrayStrategy:()=>gh,deepMerge:()=>QW,createLibraryConfig:()=>mG,config:()=>uG,bunfigPlugin:()=>dG,applyEnvVarsToConfig:()=>K1,TypeGenerationError:()=>ih,SchemaValidationError:()=>y1,PluginError:()=>uh,PerformanceMonitor:()=>vh,FileSystemError:()=>bh,ErrorFactory:()=>p0,EnvVarError:()=>cJ,EnvProcessor:()=>vJ,ConfigValidator:()=>lh,ConfigValidationError:()=>xh,ConfigNotFoundError:()=>iJ,ConfigMergeError:()=>Ph,ConfigLoader:()=>th,ConfigLoadError:()=>I1,ConfigFileLoader:()=>mJ,ConfigCache:()=>nh,CacheUtils:()=>cW,BunfigError:()=>d$,BrowserConfigError:()=>ch,ArrayMergeStrategies:()=>vW});q2=gT(async()=>{iW=import.meta.require,w1=new nh,L1=new vh,cW={createKey:RG,isEquivalent:NG,estimateMemoryUsage:KG},gG=kJ(_h.cwd(),"config"),lG=kJ(_h.cwd(),"src/generated"),ZW=XJ.env.CLARITY_LOG_DIR||sT(yG(),"logs"),SJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ZW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},kh=await LG(),L$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},g=L$,tG=L$.red,EW=L$.green,pG=L$.yellow,WW=L$.blue,rG=L$.magenta,aG=L$.cyan,Mh=L$.white,sG=L$.gray,FW=L$.bgRed,BW=L$.bgYellow,Ih=L$.bold,oG=L$.dim,eG=L$.italic,$2=L$.underline,w2=L$.reset,VJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},uW={debug:"\uD83D\uDD0D",info:WW("ℹ"),success:EW("✓"),warning:BW(Mh(Ih(" WARN "))),error:FW(Mh(Ih(" ERROR ")))},A2=new xJ("stacks"),C$=new xJ("bunfig",{showTags:!0}),J2=Q$(M1.cwd(),"config"),U2=Q$(M1.cwd(),"src/generated"),jW=_J.env.CLARITY_LOG_DIR||rT(DG(),"logs"),DJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:jW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Qh=await OG(),W$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},k=W$,Y2=W$.red,zW=W$.green,h2=W$.yellow,HW=W$.blue,f2=W$.magenta,Z2=W$.cyan,yh=W$.white,E2=W$.gray,TW=W$.bgRed,GW=W$.bgYellow,W2=W$.bgGray,Lh=W$.bold,F2=W$.dim,B2=W$.italic,j2=W$.underline,z2=W$.strikethrough,H2=W$.reset,OJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nW={debug:"\uD83D\uDD0D",info:HW("ℹ"),success:zW("✓"),warning:GW(yh(Lh(" WARN "))),error:TW(yh(Lh(" ERROR ")))},T2=new bJ("stacks"),d$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,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 w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,J])=>`${A}: ${J}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},iJ=class extends d${code="CONFIG_NOT_FOUND";constructor(w,A,J){let U=J?` or alias "${J}"`:"";super(`Configuration "${w}"${U} not found`,{configName:w,alias:J,searchPaths:A,searchPathCount:A.length})}},I1=class extends d${code="CONFIG_LOAD_ERROR";constructor(w,A,J){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},xh=class extends d${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},Ph=class extends d${code="CONFIG_MERGE_ERROR";constructor(w,A,J,U){super(`Failed to merge configuration from "${w}" with "${A}": ${J.message}`,{sourcePath:w,targetPath:A,configName:U,originalError:J.name,originalMessage:J.message});this.cause=J}},cJ=class extends d${code="ENV_VAR_ERROR";constructor(w,A,J,U){super(`Failed to parse environment variable "${w}" with value "${A}" as ${J}`,{envKey:w,envValue:A,expectedType:J,configName:U})}},bh=class extends d${code="FILE_SYSTEM_ERROR";constructor(w,A,J){super(`File system ${w} failed for "${A}": ${J.message}`,{operation:w,path:A,originalError:J.name,originalMessage:J.message});this.cause=J}},ih=class extends d${code="TYPE_GENERATION_ERROR";constructor(w,A,J){super(`Failed to generate types from "${w}" to "${A}": ${J.message}`,{configDir:w,outputPath:A,originalError:J.name,originalMessage:J.message});this.cause=J}},y1=class extends d${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,J){super(`Schema validation failed${J?` for config "${J}"`:""}`,{schemaPath:w,configName:J,validationErrors:A,errorCount:A.length})}},ch=class extends d${code="BROWSER_CONFIG_ERROR";constructor(w,A,J,U){super(`Failed to fetch configuration from "${w}": ${A} ${J}`,{endpoint:w,status:A,statusText:J,configName:U})}},uh=class extends d${code="PLUGIN_ERROR";constructor(w,A,J){super(`Plugin "${w}" failed during ${A}: ${J.message}`,{pluginName:w,operation:A,originalError:J.name,originalMessage:J.message});this.cause=J}},p0={configNotFound($,w,A){return new iJ($,w,A)},configLoad($,w,A){return new I1($,w,A)},configValidation($,w,A){return new xh($,w,A)},configMerge($,w,A,J){return new Ph($,w,A,J)},envVar($,w,A,J){return new cJ($,w,A,J)},fileSystem($,w,A){return new bh($,w,A)},typeGeneration($,w,A){return new ih($,w,A)},schemaValidation($,w,A){return new y1($,w,A)},browserConfig($,w,A,J){return new ch($,w,A,J)},plugin($,w,A){return new uh($,w,A)}},vW={replace:"replace",concat:"concat",smart:"smart"},mW=/^https?:\/\//,W0=new bJ("bunfig",{showTags:!0}),i0=new th,dW=x$(ww.cwd(),"config"),gW=x$(ww.cwd(),"src/generated")});M2=uJ.env.CLARITY_LOG_DIR||R2(K2(),"logs"),lW={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:M2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},nJ={...lW},oK=(async()=>{try{let{loadConfig:$}=await q2().then(()=>SW),w=await $({name:"clarity",alias:"logging",defaultConfig:lW,cwd:uJ.cwd()});if(w)Object.assign(nJ,w)}catch{}return nJ})();H$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P=H$,EM=H$.red,k2=H$.green,WM=H$.yellow,Q2=H$.blue,FM=H$.magenta,BM=H$.cyan,LW=H$.white,jM=H$.gray,x2=H$.bgRed,P2=H$.bgYellow,zM=H$.bgGray,CW=H$.bold,HM=H$.dim,TM=H$.italic,GM=H$.underline,qM=H$.strikethrough,RM=H$.reset,Dh={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},b2={debug:"\uD83D\uDD0D",info:Q2("ℹ"),success:k2("✓"),warning:P2(LW(CW(" WARN "))),error:x2(LW(CW(" ERROR ")))};NM=new Aw("stacks")});var lJ={};G8(lJ,{safeStringify:()=>w0,safeDeleteFile:()=>oh,resolvePathRewrite:()=>sh,redactSensitive:()=>dJ,isValidRootCA:()=>ah,isSingleProxyOptions:()=>C1,isSingleProxyConfig:()=>m2,isMultiProxyOptions:()=>Uw,isMultiProxyConfig:()=>sW,getSudoPassword:()=>Jw,getPrimaryDomain:()=>gJ,extractHostname:()=>v2,execSudoSync:()=>rh,debugLog:()=>z});import{execSync as pW}from"node:child_process";import*as aW from"node:fs/promises";function Jw(){return process.env.SUDO_PASSWORD}function rh($){let w=Jw(),A=$.replace(/'/g,"'\\''");if(w)return pW(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return pW(`sudo sh -c '${A}'`,{encoding:"utf-8"})}function z($,w,A){if(A)i2.debug(`[rpx:${$}] ${w}`)}function n2($){let w=$.toLowerCase();return c2.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function dJ($){if(Array.isArray($))return $.map((A)=>dJ(A));if(typeof $==="string")return u2.test($)?rW:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(n2(A)){w[A]=rW;continue}w[A]=dJ(J)}return w}function w0($,w){return JSON.stringify(dJ($),null,w)}function v2($){if(Uw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if(C1($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function ah($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function gJ($){if(!$)return"stacks.localhost";if(Uw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(C1($))return $.to||"stacks.localhost";return"stacks.localhost"}function sW($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function Uw($){return"proxies"in $&&Array.isArray($.proxies)}function C1($){return"to"in $&&typeof $.to==="string"}function m2($){return!!($&&("to"in $)&&!("proxies"in $))}function sh($,w){if(!w||w.length===0)return null;for(let A of w)if($===A.from||$.startsWith(`${A.from}/`)){let J=A.to.startsWith("http")?new URL(A.to).host:A.to,U=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:J,targetPath:U}}return null}async function oh($,w){try{await aW.unlink($),z("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")z("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var i2,rW="[redacted]",c2,u2;var T$=FU(()=>{ph();i2=new Aw("rpx",{showTags:!1});c2=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),u2=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});var hU={};G8(hU,{stopDnsServer:()=>y7,startDnsServer:()=>I7,setupResolver:()=>V7,removeResolver:()=>D7,isDnsServerRunning:()=>L7});import q7 from"node:dgram";function R7($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function CF($,w){let A=[],J=w;while(!0){let U=$[J];if(U===0){J++;break}if((U&192)===192){let Y=$.readUInt16BE(J)&16383,{name:h}=CF($,Y);A.push(h),J+=2;break}J++,A.push($.subarray(J,J+U).toString("ascii")),J+=U}return{name:A.join("."),newOffset:J}}function N7($,w){let{name:A,newOffset:J}=CF($,w),U=$.readUInt16BE(J),Y=$.readUInt16BE(J+2);return{question:{name:A,type:U,class:Y},newOffset:J+4}}function UU($){let w=$.split("."),A=[];for(let J of w)A.push(Buffer.from([J.length])),A.push(Buffer.from(J,"ascii"));return A.push(Buffer.from([0])),Buffer.concat(A)}function K7($,w,A){let J=[],U=Buffer.alloc(12);U.writeUInt16BE($,0),U.writeUInt16BE(33152,2),U.writeUInt16BE(1,4),U.writeUInt16BE(1,6),U.writeUInt16BE(0,8),U.writeUInt16BE(0,10),J.push(U),J.push(UU(w.name));let Y=Buffer.alloc(4);Y.writeUInt16BE(w.type,0),Y.writeUInt16BE(w.class,2),J.push(Y),J.push(UU(w.name));let h=Buffer.alloc(10);if(h.writeUInt16BE(w.type,0),h.writeUInt16BE(1,2),h.writeUInt32BE(300,4),w.type===1){h.writeUInt16BE(4,8),J.push(h);let Z=A.split(".").map((f)=>Number.parseInt(f,10));J.push(Buffer.from(Z))}else if(w.type===28)h.writeUInt16BE(16,8),J.push(h),J.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return U.writeUInt16BE(33155,2),U.writeUInt16BE(0,6),Buffer.concat([U,UU(w.name),Y]);return Buffer.concat(J)}function M7($,w){let A=[],J=Buffer.alloc(12);J.writeUInt16BE($,0),J.writeUInt16BE(33155,2),J.writeUInt16BE(1,4),J.writeUInt16BE(0,6),J.writeUInt16BE(0,8),J.writeUInt16BE(0,10),A.push(J),A.push(UU(w.name));let U=Buffer.alloc(4);return U.writeUInt16BE(w.type,0),U.writeUInt16BE(w.class,2),A.push(U),Buffer.concat(A)}async function I7($,w){if(i$)return z("dns","DNS server already running",w),!0;return yF=new Set($.map((A)=>A.toLowerCase())),new Promise((A)=>{i$=q7.createSocket("udp4"),i$.on("error",(J)=>{if(z("dns",`DNS server error: ${J.message}`,w),J.message.includes("EACCES")||J.message.includes("permission"))z("dns","DNS server requires root privileges to bind to port 53",w);i$?.close(),i$=null,A(!1)}),i$.on("message",(J,U)=>{try{let Y=R7(J),{question:h}=N7(J,12);z("dns",`Query for ${h.name} type ${h.type} from ${U.address}`,w);let Z=h.name.toLowerCase(),f=!1;for(let W of yF)if(Z===W||Z.endsWith(`.${W}`)){f=!0;break}let E;if(f&&(h.type===1||h.type===28))E=K7(Y.id,h,"127.0.0.1"),z("dns",`Responding with localhost for ${h.name}`,w);else E=M7(Y.id,h),z("dns",`NXDOMAIN for ${h.name}`,w);i$?.send(E,U.port,U.address)}catch(Y){z("dns",`Error processing DNS query: ${Y}`,w)}}),i$.on("listening",()=>{let J=i$?.address();z("dns",`DNS server listening on ${J?.address}:${J?.port}`,w),A(!0)});try{i$.bind(LF,"127.0.0.1")}catch(J){z("dns",`Failed to bind DNS server: ${J}`,w),A(!1)}})}function y7($){if(i$)z("dns","Stopping DNS server",$),i$.close(),i$=null}function L7(){return i$!==null}function C7($){let w=new Set;for(let A of $){let J=A.split(".");if(J.length>=2)w.add(J[J.length-1])}return Array.from(w)}async function S7($){if(process.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A}=await Promise.resolve().then(() => (T$(),lJ));if(!A()){z("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),z("dns","DNS cache flushed",$)}catch(U){z("dns",`Could not flush DNS cache: ${U}`,$)}}async function V7($,w){if(process.platform!=="darwin")return z("dns","Resolver setup only needed on macOS",$),!0;let{execSudoSync:A,getSudoPassword:J}=await Promise.resolve().then(() => (T$(),lJ));if(!J())return z("dns","SUDO_PASSWORD not set, cannot create resolver files",$),!1;let Y=w?C7(w):["test"];try{for(let h of Y){if(YU.has(h))continue;let Z=`bash -c 'mkdir -p /etc/resolver && echo -e "nameserver 127.0.0.1\\nport ${LF}" > /etc/resolver/${h}'`;A(Z),YU.add(h),z("dns",`Created /etc/resolver/${h} for .${h} TLD`,$)}return await S7($),!0}catch(h){return z("dns",`Failed to create resolver file: ${h}`,$),!1}}async function D7($){if(process.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A}=await Promise.resolve().then(() => (T$(),lJ));try{if(A()){for(let U of YU)w(`rm -f /etc/resolver/${U}`),z("dns",`Removed /etc/resolver/${U}`,$);YU.clear()}}catch(J){z("dns",`Failed to remove resolver files: ${J}`,$)}}var LF=15353,i$=null,yF,YU;var fU=FU(()=>{T$();yF=new Set;YU=new Set});import*as l$ from"process";import{existsSync as nF}from"node:fs";import BU from"node:fs/promises";import q8 from"node:os";import jU from"node:path";import o0 from"node:process";import{EventEmitter as vF}from"node:events";import u0 from"node:process";import R8 from"node:process";import GU from"node:process";import v1 from"node:process";import f1 from"node:process";import M8 from"node:tty";import DB,{stdin as w5,stdout as A5}from"node:process";import y8,{stdin as XB,stdout as kB}from"node:process";import QB from"node:readline";class C8{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=q8.homedir(),w=jU.join($,".config","clapp");this.configPath=jU.join(w,"telemetry.json")}async isEnabled(){if(o0.env.DO_NOT_TRACK==="1"||o0.env.DO_NOT_TRACK==="true")return!1;if(o0.env.NO_TELEMETRY==="1"||o0.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,w){if(!await this.isEnabled())return;let J={event:$,...w,timestamp:Date.now(),platform:q8.platform(),nodeVersion:o0.version};if(this.events.push(J),this.events.length>=10)await this.send()}async trackCommand($,w){await this.track("command",{command:$,duration:w})}async trackError($,w){await this.track("error",{error:$,command:w})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let w=await this.loadConfig();return w.lastSent=Date.now(),await this.saveConfig(w),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let w=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(w),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((w)=>setTimeout(w,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:o0.env.DO_NOT_TRACK==="1"||o0.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(nF(this.configPath)){let $=await BU.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let w=jU.dirname(this.configPath);await BU.mkdir(w,{recursive:!0}),await BU.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),w=Date.now().toString(36);return`${$}-${w}`}}var m7=new C8;function mF($,w={}){let A={_:[]},J=w.alias||{},U=new Set(w.boolean||[]),Y={};for(let Z of Object.keys(J))for(let f of J[Z])Y[f]=Z;for(let Z of U)if(J[Z])for(let f of J[Z])U.add(f);function h(Z,f){let E=Y[Z]||Z;if(A[E]=f,J[E])for(let W of J[E])A[W]=f;if(Y[Z]&&J[Y[Z]])for(let W of J[Y[Z]])A[W]=f;A[Z]=f}for(let Z=0;Z<$.length;Z++){let f=$[Z];if(f==="--"){A._.push(...$.slice(Z+1));break}if(f.startsWith("--")){let E=f.indexOf("=");if(E!==-1){let W=f.slice(2,E),F=f.slice(E+1);h(W,F)}else{let W=f.slice(2);if(W.startsWith("no-")){let j=W.slice(3);h(j,!1);continue}let F=Y[W]||W;if(U.has(F)||U.has(W))h(W,!0);else{let j=$[Z+1];if(j!==void 0&&!j.startsWith("-"))h(W,j),Z++;else h(W,!0)}}}else if(f.startsWith("-")&&f.length>1){let E=f.slice(1);for(let W=0;W<E.length;W++){let F=E[W],j=Y[F]||F;if(W===E.length-1&&!U.has(j)&&!U.has(F)){let B=$[Z+1];if(B!==void 0&&!B.startsWith("-"))h(F,B),Z++;else h(F,!0)}else h(F,!0)}}else A._.push(f)}return A}function TU($){return $.replace(/[<[].+/,"").trim()}function dF($){let w=/<([^>]+)>/g,A=/\[([^\]]+)\]/g,J=[],U=(Z)=>{let f=!1,E=Z[1];if(E.startsWith("..."))E=E.slice(3),f=!0;return{required:Z[0].startsWith("<"),value:E,variadic:f}},Y;while(Y=w.exec($))J.push(U(Y));let h;while(h=A.exec($))J.push(U(h));return J}function gF($){let w={alias:{},boolean:[]};for(let[A,J]of $.entries()){if(J.names.length>1)w.alias[J.names[0]]=J.names.slice(1);if(J.isBoolean)if(J.negated){if(!$.some((Y,h)=>{return h!==A&&Y.names.some((Z)=>J.names.includes(Z))&&typeof Y.required==="boolean"}))w.boolean.push(J.names[0])}else w.boolean.push(J.names[0])}return w}function N8($){return $.reduce((w,A)=>w.length>=A.length?w:A,"")}function zU($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function lF($){return $.replace(/([a-z])-([a-z])/g,(w,A,J)=>{return A+J.toUpperCase()})}function tF($,w,A){let J=0,U=w.length,Y=$,h;for(;J<U;++J)h=Y[w[J]],Y=Y[w[J]]=J===U-1?A:h!=null?h:!!~w[J+1].indexOf(".")||!(+w[J+1]>-1)?{}:[]}function pF($,w){for(let A of Object.keys(w)){let J=w[A];if(J.shouldTransform){if($[A]=Array.prototype.concat.call([],$[A]),typeof J.transformFunction==="function")$[A]=$[A].map(J.transformFunction)}}}function rF($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function S8($){return $.split(".").map((w,A)=>{return A===0?lF(w):w}).join(".")}class n1 extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
|
|
42
|
+
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}function Q2($,w={}){let A=mJ.cwd();while(A.includes("storage"))A=Oh(A,"..");let J=Oh(A,$||"");if(w?.relative)return k2(mJ.cwd(),J);return J}function F$(){if(b0.env.NODE_ENV==="test"||b0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function g2(){if(b0.env.NODE_ENV==="test"||b0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof b0<"u"){let $=b0.type;if($==="renderer"||$==="worker")return!1;return!!(b0.versions&&(b0.versions.node||b0.versions.bun))}return!1}class UF{async format($){let w=await g2(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:ew.pid,hostname:w(),environment:ew.env.NODE_ENV||"development",platform:ew.platform,version:ew.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ew.env.NODE_ENV||ew.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Aw{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...dJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new UF,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...Pf,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Pf};return{...Pf,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:dJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!F$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,Z=1000;while(Y<f)try{try{try{await u2(this.config.logDirectory,kh.F_OK|kh.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await n2(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let E=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Q0.from($);try{if(!CJ(this.currentLogFile))await xf(this.currentLogFile,"",{mode:420});if(U=Xh(this.currentLogFile,"a",420),c2(U,E,{flag:"a"}),_h(U),U!==void 0)Qf(U),U=void 0;if((await sw(this.currentLogFile)).size===0){if(await xf(this.currentLogFile,E,{flag:"w",mode:420}),(await sw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let h=W;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(Y<f-1){let F=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(U!==void 0)try{Qf(U)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(E){if(Y===f-1){let h=E,F=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),E}Y++;let W=Z*2**(Y-1);await new Promise((h)=>setTimeout(h,W))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 ow(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 ow(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return ow(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(F$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,E])=>E.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[Z]of U.slice(f))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return kf(16).toString("hex")}generateKey(){return kf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=kf(16),J=P2("aes-256-gcm",w,A),U=Q0.isBuffer($)?$:Q0.from($,"utf8"),Y=J.update(U),f=J.final(),Z=Y.length+f.length,E=J.getAuthTag(),W=Q0.allocUnsafe(16+Z+16);return A.copy(W,0),Y.copy(W,16),f.copy(W,16+Y.length),E.copy(W,16+Z),{encrypted:W,iv:A}}async compressData($){return new Promise((w,A)=>{let J=xh(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(Q0.from(Q0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(F$())return;if(!this.shouldWriteToFile())return;let $=await sw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await SJ(this.config.logDirectory),Y=U.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,W)=>{let h=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${f}`;if(await sw(A).catch(()=>null))try{if(await Qh(A,Z),w.compress)try{let E=`${Z}.gz`;await this.compressLogFile(Z,E),await VJ(Z)}catch(E){console.error("Error compressing rotated file:",E)}if(Y.length===0&&!U.some((E)=>E.endsWith(".log.1")))try{let E=`${A}.1`;await xf(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await sw(A).catch(()=>null))await Qh(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await SJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,Z)=>Z.localeCompare(f));for(let f of Y.slice(w.maxFiles))await VJ(ow(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=Dh($),J=i2(w),U=xh();await d2(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),CJ(this.currentLogFile))try{let $=Xh(this.currentLogFile,"r+");_h($),Qf($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!F$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await SJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await VJ(ow(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?P.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F$())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(f)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let E=D.stdout.columns||120,W="";if(Y==="warning"||Y==="error")W=`${A} ${U}`;else if(Y==="info"||Y==="success")W=`${A} ${J} ${U}`;else W=`${A} ${J} ${P.cyan(U)}`;if(!f)return W.trim();let h=Z(W).trim().length,F=Z(w).length,j=Math.max(1,E-2-h-F);return`${W.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let Z=Number.parseInt(f,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(f){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 Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=P.underline(P.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(f)}`,E="\x1B]8;;",W="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>P.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>P.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>P.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>P.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>P.strikethrough(J)),w}supportsHyperlinks(){if(F$())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=D.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(v2(w)||w.startsWith("./")||w.startsWith("../"))w=m2(w);else return null;return CJ(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,Z;if(w instanceof Error)f=w.message,Z=w.stack;else f=this.formatMessage(w,A);let{consoleText:E,fileText:W}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":a2[$],j=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:P.gray(E),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:P.green(E),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.error(B),Z){let H=Z.split(`
|
|
43
|
+
`);for(let T of H)if(T.trim()&&!T.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:P.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!F$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),Z)console.error(Z)}let h=`${Y} ${this.environment}.${$.toUpperCase()}: ${W}
|
|
44
|
+
`;if(Z)h+=`${Z}
|
|
45
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress($,w=""){let A={update:(Z,E)=>{},finish:(Z)=>{},interrupt:(Z,E)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!F$()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Z,E)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Z),this.activeProgressBar.total),E!==void 0)this.activeProgressBar.message=E;if(this.shouldStyleConsole()&&!F$()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Z)},interrupt:(Z,E="info")=>{if(!F$()&&D.stdout.isTTY)D.stdout.write(`
|
|
46
|
+
`);if(this[E==="warning"?"warn":E](Z),this.activeProgressBar&&this.shouldStyleConsole()&&!F$()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":P.blue("◐"),tag:A,message:`${P.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,Z=this.formatConsoleTimestamp(f),W=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)W+=` ${JSON.stringify(A)}`;if(W+=`
|
|
47
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":P.green("✓"),tag:h,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!F$())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new Aw(w,{...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(A),A}createReadStream(){if(F$())throw Error("createReadStream is not supported in browser environments");if(!CJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Dh(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=Q0.isBuffer($)?$:Q0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),Z=b2("aes-256-gcm",A,U);Z.setAuthTag(Y);let E=Z.update(f),W=Z.final(),h=E.length+W.length,F=Q0.allocUnsafe(h);return E.copy(F,0),W.copy(F,E.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F$()}isServerMode(){return!F$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=U.split(`
|
|
48
|
+
`),E=Math.max(...Z.map((j)=>j.length))+2,W=`┌${"─".repeat(E)}┐`,h=`└${"─".repeat(E)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:P.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(W),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(h),showTimestamp:!1}))}else if(!F$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
49
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(F$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${P.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();D.stdin.removeListener("data",A);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let E=/%([sdijfo%])/g,W=0;if(A=$.replace(E,(h,F)=>{if(F==="%")return"%";if(W>=w.length)return h;let j=w[W++];switch(F){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return h}}),W<w.length)A+=` ${w.slice(W).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${P.blue("◐")} `;console.error(`${W}${E} ${P.cyan(J)}`)}let Z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
50
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=P.green("━".repeat(J)),f=P.gray("━".repeat(U)),Z=`[${Y}${f}]`,E=`${A}%`.padStart(4),W=$.message?` ${$.message}`:"",h=this.options.showIcons===!1?"":w||A===100?P.green("✓"):P.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",j=`\r${h}${F} ${Z} ${E}${W}`,B=D.stdout.columns||80,H=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${H}`,D.stdout.write($.lastRenderedLine),w)D.stdout.write(`
|
|
51
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F$()||!D.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(F$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await SJ(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=ow(this.config.logDirectory,J);if($.before)try{if((await sw(Y)).mtime>=$.before)continue}catch(f){console.error(`Failed to get stats for file ${Y}:`,f);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await VJ(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var $G,wG=($)=>$,JG=($,w)=>{for(var A in w)$G($,A,{get:w[A],enumerable:!0,configurable:!0,set:AG.bind(w,A)})},UG=($,w)=>()=>($&&(w=$($=0)),w),ih,rh,$1,S1,ah,U2,Y2,Rh,DJ,nf,y$,g,f2,Nh,E2,Kh,Z2,W2,Of,h2,Mh,Ih,Df,F2,B2,j2,z2,_J,sh,T2,C$,H2,G2,Lh,XJ,vf,h$,k,q2,yh,R2,Ch,N2,K2,_f,M2,Sh,Vh,I2,Xf,L2,y2,C2,S2,V2,kJ,oh,O2,D2="0.15.6",d$,nJ,y1,mf,df,vJ,gf,lf,C1,tf,pf,p0,eh,$F,h0,i0,wF,AF,_2,x2,JF,dJ,HM,H$,P,SM,l2,VM,t2,OM,DM,Ph,_M,p2,r2,XM,bh,kM,QM,xM,PM,bM,Pf,a2,iM;var A8=qU(()=>{$G=Object.defineProperty;ih={};JG(ih,{withErrorRecovery:()=>mh,tryLoadConfig:()=>$2,loadConfigWithResult:()=>oG,loadConfig:()=>ph,isRetryableError:()=>lG,isConfigNotFoundError:()=>gG,isBunfigError:()=>dh,globalPerformanceMonitor:()=>S1,globalCache:()=>$1,getEnvOrDefault:()=>tG,generateConfigTypes:()=>w2,defaultGeneratedDir:()=>AF,defaultConfigDir:()=>wF,deepMergeWithArrayStrategy:()=>ef,deepMerge:()=>gh,createLibraryConfig:()=>A2,config:()=>eG,bunfigPlugin:()=>J2,applyEnvVarsToConfig:()=>I1,TypeGenerationError:()=>lf,SchemaValidationError:()=>C1,PluginError:()=>pf,PerformanceMonitor:()=>af,FileSystemError:()=>gf,ErrorFactory:()=>p0,EnvVarError:()=>vJ,EnvProcessor:()=>gJ,ConfigValidator:()=>$8,ConfigValidationError:()=>mf,ConfigNotFoundError:()=>nJ,ConfigMergeError:()=>df,ConfigLoader:()=>w8,ConfigLoadError:()=>y1,ConfigFileLoader:()=>lJ,ConfigCache:()=>rf,CacheUtils:()=>ah,BunfigError:()=>d$,BrowserConfigError:()=>tf,ArrayMergeStrategies:()=>eh});_2=UG(async()=>{rh=import.meta.require,$1=new rf,S1=new af,ah={createKey:XG,isEquivalent:kG,estimateMemoryUsage:QG},U2=PJ(cf.cwd(),"config"),Y2=PJ(cf.cwd(),"src/generated"),Rh=xJ.env.CLARITY_LOG_DIR||hG(bG(),"logs"),DJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},nf=await iG(),y$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},g=y$,f2=y$.red,Nh=y$.green,E2=y$.yellow,Kh=y$.blue,Z2=y$.magenta,W2=y$.cyan,Of=y$.white,h2=y$.gray,Mh=y$.bgRed,Ih=y$.bgYellow,Df=y$.bold,F2=y$.dim,B2=y$.italic,j2=y$.underline,z2=y$.reset,_J={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sh={debug:"\uD83D\uDD0D",info:Kh("ℹ"),success:Nh("✓"),warning:Ih(Of(Df(" WARN "))),error:Mh(Of(Df(" ERROR ")))},T2=new iJ("stacks"),C$=new iJ("bunfig",{showTags:!0}),H2=Q$(L1.cwd(),"config"),G2=Q$(L1.cwd(),"src/generated"),Lh=QJ.env.CLARITY_LOG_DIR||ZG(vG(),"logs"),XJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Lh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},vf=await mG(),h$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},k=h$,q2=h$.red,yh=h$.green,R2=h$.yellow,Ch=h$.blue,N2=h$.magenta,K2=h$.cyan,_f=h$.white,M2=h$.gray,Sh=h$.bgRed,Vh=h$.bgYellow,I2=h$.bgGray,Xf=h$.bold,L2=h$.dim,y2=h$.italic,C2=h$.underline,S2=h$.strikethrough,V2=h$.reset,kJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oh={debug:"\uD83D\uDD0D",info:Ch("ℹ"),success:yh("✓"),warning:Vh(_f(Xf(" WARN "))),error:Sh(_f(Xf(" ERROR ")))},O2=new uJ("stacks"),d$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,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 w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,J])=>`${A}: ${J}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},nJ=class extends d${code="CONFIG_NOT_FOUND";constructor(w,A,J){let U=J?` or alias "${J}"`:"";super(`Configuration "${w}"${U} not found`,{configName:w,alias:J,searchPaths:A,searchPathCount:A.length})}},y1=class extends d${code="CONFIG_LOAD_ERROR";constructor(w,A,J){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},mf=class extends d${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},df=class extends d${code="CONFIG_MERGE_ERROR";constructor(w,A,J,U){super(`Failed to merge configuration from "${w}" with "${A}": ${J.message}`,{sourcePath:w,targetPath:A,configName:U,originalError:J.name,originalMessage:J.message});this.cause=J}},vJ=class extends d${code="ENV_VAR_ERROR";constructor(w,A,J,U){super(`Failed to parse environment variable "${w}" with value "${A}" as ${J}`,{envKey:w,envValue:A,expectedType:J,configName:U})}},gf=class extends d${code="FILE_SYSTEM_ERROR";constructor(w,A,J){super(`File system ${w} failed for "${A}": ${J.message}`,{operation:w,path:A,originalError:J.name,originalMessage:J.message});this.cause=J}},lf=class extends d${code="TYPE_GENERATION_ERROR";constructor(w,A,J){super(`Failed to generate types from "${w}" to "${A}": ${J.message}`,{configDir:w,outputPath:A,originalError:J.name,originalMessage:J.message});this.cause=J}},C1=class extends d${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,J){super(`Schema validation failed${J?` for config "${J}"`:""}`,{schemaPath:w,configName:J,validationErrors:A,errorCount:A.length})}},tf=class extends d${code="BROWSER_CONFIG_ERROR";constructor(w,A,J,U){super(`Failed to fetch configuration from "${w}": ${A} ${J}`,{endpoint:w,status:A,statusText:J,configName:U})}},pf=class extends d${code="PLUGIN_ERROR";constructor(w,A,J){super(`Plugin "${w}" failed during ${A}: ${J.message}`,{pluginName:w,operation:A,originalError:J.name,originalMessage:J.message});this.cause=J}},p0={configNotFound($,w,A){return new nJ($,w,A)},configLoad($,w,A){return new y1($,w,A)},configValidation($,w,A){return new mf($,w,A)},configMerge($,w,A,J){return new df($,w,A,J)},envVar($,w,A,J){return new vJ($,w,A,J)},fileSystem($,w,A){return new gf($,w,A)},typeGeneration($,w,A){return new lf($,w,A)},schemaValidation($,w,A){return new C1($,w,A)},browserConfig($,w,A,J){return new tf($,w,A,J)},plugin($,w,A){return new pf($,w,A)}},eh={replace:"replace",concat:"concat",smart:"smart"},$F=/^https?:\/\//,h0=new uJ("bunfig",{showTags:!0}),i0=new w8,wF=x$(ww.cwd(),"config"),AF=x$(ww.cwd(),"src/generated")});x2=mJ.env.CLARITY_LOG_DIR||X2(Q2(),"logs"),JF={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:x2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},dJ={...JF},HM=(async()=>{try{let{loadConfig:$}=await _2().then(()=>ih),w=await $({name:"clarity",alias:"logging",defaultConfig:JF,cwd:mJ.cwd()});if(w)Object.assign(dJ,w)}catch{}return dJ})();H$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P=H$,SM=H$.red,l2=H$.green,VM=H$.yellow,t2=H$.blue,OM=H$.magenta,DM=H$.cyan,Ph=H$.white,_M=H$.gray,p2=H$.bgRed,r2=H$.bgYellow,XM=H$.bgGray,bh=H$.bold,kM=H$.dim,QM=H$.italic,xM=H$.underline,PM=H$.strikethrough,bM=H$.reset,Pf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},a2={debug:"\uD83D\uDD0D",info:t2("ℹ"),success:l2("✓"),warning:r2(Ph(bh(" WARN "))),error:p2(Ph(bh(" ERROR ")))};iM=new Aw("stacks")});var rJ={};V8(rJ,{safeStringify:()=>w0,safeDeleteFile:()=>Y8,resolvePathRewrite:()=>U8,redactSensitive:()=>tJ,isValidRootCA:()=>J8,isSingleProxyOptions:()=>O1,isSingleProxyConfig:()=>A7,isMultiProxyOptions:()=>Uw,isMultiProxyConfig:()=>ZF,getSudoPassword:()=>Jw,getPrimaryDomain:()=>pJ,extractHostname:()=>w7,execSudoSync:()=>V1,debugLog:()=>z});import{execSync as YF}from"node:child_process";import*as EF from"node:fs/promises";function Jw(){return process.env.SUDO_PASSWORD}function V1($){let w=Jw(),A=$.replace(/'/g,"'\\''");if(w)return YF(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return YF(`sudo sh -c '${A}'`,{encoding:"utf-8"})}function z($,w,A){if(A)s2.debug(`[rpx:${$}] ${w}`)}function $7($){let w=$.toLowerCase();return o2.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function tJ($){if(Array.isArray($))return $.map((A)=>tJ(A));if(typeof $==="string")return e2.test($)?fF:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if($7(A)){w[A]=fF;continue}w[A]=tJ(J)}return w}function w0($,w){return JSON.stringify(tJ($),null,w)}function w7($){if(Uw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if(O1($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function J8($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function pJ($){if(!$)return"stacks.localhost";if(Uw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(O1($))return $.to||"stacks.localhost";return"stacks.localhost"}function ZF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function Uw($){return"proxies"in $&&Array.isArray($.proxies)}function O1($){return"to"in $&&typeof $.to==="string"}function A7($){return!!($&&("to"in $)&&!("proxies"in $))}function U8($,w){if(!w||w.length===0)return null;for(let A of w)if($===A.from||$.startsWith(`${A.from}/`)){let J=A.to.startsWith("http")?new URL(A.to).host:A.to,U=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:J,targetPath:U}}return null}async function Y8($,w){try{await EF.unlink($),z("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")z("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var s2,fF="[redacted]",o2,e2;var B$=qU(()=>{A8();s2=new Aw("rpx",{showTags:!1});o2=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),e2=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});var jU={};V8(jU,{stopDnsServer:()=>u7,startDnsServer:()=>c7,setupResolver:()=>d7,removeResolver:()=>g7,isDnsServerRunning:()=>n7});import Q7 from"node:dgram";function x7($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function iF($,w){let A=[],J=w;while(!0){let U=$[J];if(U===0){J++;break}if((U&192)===192){let Y=$.readUInt16BE(J)&16383,{name:f}=iF($,Y);A.push(f),J+=2;break}J++,A.push($.subarray(J,J+U).toString("ascii")),J+=U}return{name:A.join("."),newOffset:J}}function P7($,w){let{name:A,newOffset:J}=iF($,w),U=$.readUInt16BE(J),Y=$.readUInt16BE(J+2);return{question:{name:A,type:U,class:Y},newOffset:J+4}}function FU($){let w=$.split("."),A=[];for(let J of w)A.push(Buffer.from([J.length])),A.push(Buffer.from(J,"ascii"));return A.push(Buffer.from([0])),Buffer.concat(A)}function b7($,w,A){let J=[],U=Buffer.alloc(12);U.writeUInt16BE($,0),U.writeUInt16BE(33152,2),U.writeUInt16BE(1,4),U.writeUInt16BE(1,6),U.writeUInt16BE(0,8),U.writeUInt16BE(0,10),J.push(U),J.push(FU(w.name));let Y=Buffer.alloc(4);Y.writeUInt16BE(w.type,0),Y.writeUInt16BE(w.class,2),J.push(Y),J.push(FU(w.name));let f=Buffer.alloc(10);if(f.writeUInt16BE(w.type,0),f.writeUInt16BE(1,2),f.writeUInt32BE(300,4),w.type===1){f.writeUInt16BE(4,8),J.push(f);let Z=A.split(".").map((E)=>Number.parseInt(E,10));J.push(Buffer.from(Z))}else if(w.type===28)f.writeUInt16BE(16,8),J.push(f),J.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return U.writeUInt16BE(33155,2),U.writeUInt16BE(0,6),Buffer.concat([U,FU(w.name),Y]);return Buffer.concat(J)}function i7($,w){let A=[],J=Buffer.alloc(12);J.writeUInt16BE($,0),J.writeUInt16BE(33155,2),J.writeUInt16BE(1,4),J.writeUInt16BE(0,6),J.writeUInt16BE(0,8),J.writeUInt16BE(0,10),A.push(J),A.push(FU(w.name));let U=Buffer.alloc(4);return U.writeUInt16BE(w.type,0),U.writeUInt16BE(w.class,2),A.push(U),Buffer.concat(A)}async function c7($,w){if(i$)return z("dns","DNS server already running",w),!0;return PF=new Set($.map((A)=>A.toLowerCase())),new Promise((A)=>{i$=Q7.createSocket("udp4"),i$.on("error",(J)=>{if(z("dns",`DNS server error: ${J.message}`,w),J.message.includes("EACCES")||J.message.includes("permission"))z("dns","DNS server requires root privileges to bind to port 53",w);i$?.close(),i$=null,A(!1)}),i$.on("message",(J,U)=>{try{let Y=x7(J),{question:f}=P7(J,12);z("dns",`Query for ${f.name} type ${f.type} from ${U.address}`,w);let Z=f.name.toLowerCase(),E=!1;for(let h of PF)if(Z===h||Z.endsWith(`.${h}`)){E=!0;break}let W;if(E&&(f.type===1||f.type===28))W=b7(Y.id,f,"127.0.0.1"),z("dns",`Responding with localhost for ${f.name}`,w);else W=i7(Y.id,f),z("dns",`NXDOMAIN for ${f.name}`,w);i$?.send(W,U.port,U.address)}catch(Y){z("dns",`Error processing DNS query: ${Y}`,w)}}),i$.on("listening",()=>{let J=i$?.address();z("dns",`DNS server listening on ${J?.address}:${J?.port}`,w),A(!0)});try{i$.bind(bF,"127.0.0.1")}catch(J){z("dns",`Failed to bind DNS server: ${J}`,w),A(!1)}})}function u7($){if(i$)z("dns","Stopping DNS server",$),i$.close(),i$=null}function n7(){return i$!==null}function v7($){let w=new Set;for(let A of $){let J=A.split(".");if(J.length>=2)w.add(J[J.length-1])}return Array.from(w)}async function m7($){if(process.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A}=await Promise.resolve().then(() => (B$(),rJ));if(!A()){z("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),z("dns","DNS cache flushed",$)}catch(U){z("dns",`Could not flush DNS cache: ${U}`,$)}}async function d7($,w){if(process.platform!=="darwin")return z("dns","Resolver setup only needed on macOS",$),!0;let{execSudoSync:A,getSudoPassword:J}=await Promise.resolve().then(() => (B$(),rJ));if(!J())return z("dns","SUDO_PASSWORD not set, cannot create resolver files",$),!1;let Y=w?v7(w):["test"];try{for(let f of Y){if(BU.has(f))continue;let Z=`bash -c 'mkdir -p /etc/resolver && echo -e "nameserver 127.0.0.1\\nport ${bF}" > /etc/resolver/${f}'`;A(Z),BU.add(f),z("dns",`Created /etc/resolver/${f} for .${f} TLD`,$)}return await m7($),!0}catch(f){return z("dns",`Failed to create resolver file: ${f}`,$),!1}}async function g7($){if(process.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A}=await Promise.resolve().then(() => (B$(),rJ));try{if(A()){for(let U of BU)w(`rm -f /etc/resolver/${U}`),z("dns",`Removed /etc/resolver/${U}`,$);BU.clear()}}catch(J){z("dns",`Failed to remove resolver files: ${J}`,$)}}var bF=15353,i$=null,PF,BU;var zU=qU(()=>{B$();PF=new Set;BU=new Set});import*as l$ from"process";import{existsSync as eF}from"node:fs";import RU from"node:fs/promises";import O8 from"node:os";import NU from"node:path";import o0 from"node:process";import{EventEmitter as $B}from"node:events";import u0 from"node:process";import D8 from"node:process";import LU from"node:process";import d1 from"node:process";import W1 from"node:process";import k8 from"node:tty";import nB,{stdin as Gq,stdout as qq}from"node:process";import x8,{stdin as dB,stdout as gB}from"node:process";import lB from"node:readline";class b8{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=O8.homedir(),w=NU.join($,".config","clapp");this.configPath=NU.join(w,"telemetry.json")}async isEnabled(){if(o0.env.DO_NOT_TRACK==="1"||o0.env.DO_NOT_TRACK==="true")return!1;if(o0.env.NO_TELEMETRY==="1"||o0.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,w){if(!await this.isEnabled())return;let J={event:$,...w,timestamp:Date.now(),platform:O8.platform(),nodeVersion:o0.version};if(this.events.push(J),this.events.length>=10)await this.send()}async trackCommand($,w){await this.track("command",{command:$,duration:w})}async trackError($,w){await this.track("error",{error:$,command:w})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let w=await this.loadConfig();return w.lastSent=Date.now(),await this.saveConfig(w),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let w=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(w),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((w)=>setTimeout(w,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:o0.env.DO_NOT_TRACK==="1"||o0.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(eF(this.configPath)){let $=await RU.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let w=NU.dirname(this.configPath);await RU.mkdir(w,{recursive:!0}),await RU.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),w=Date.now().toString(36);return`${$}-${w}`}}var Yq=new b8;function wB($,w={}){let A={_:[]},J=w.alias||{},U=new Set(w.boolean||[]),Y={};for(let Z of Object.keys(J))for(let E of J[Z])Y[E]=Z;for(let Z of U)if(J[Z])for(let E of J[Z])U.add(E);function f(Z,E){let W=Y[Z]||Z;if(A[W]=E,J[W])for(let h of J[W])A[h]=E;if(Y[Z]&&J[Y[Z]])for(let h of J[Y[Z]])A[h]=E;A[Z]=E}for(let Z=0;Z<$.length;Z++){let E=$[Z];if(E==="--"){A._.push(...$.slice(Z+1));break}if(E.startsWith("--")){let W=E.indexOf("=");if(W!==-1){let h=E.slice(2,W),F=E.slice(W+1);f(h,F)}else{let h=E.slice(2);if(h.startsWith("no-")){let j=h.slice(3);f(j,!1);continue}let F=Y[h]||h;if(U.has(F)||U.has(h))f(h,!0);else{let j=$[Z+1];if(j!==void 0&&!j.startsWith("-"))f(h,j),Z++;else f(h,!0)}}}else if(E.startsWith("-")&&E.length>1){let W=E.slice(1);for(let h=0;h<W.length;h++){let F=W[h],j=Y[F]||F;if(h===W.length-1&&!U.has(j)&&!U.has(F)){let B=$[Z+1];if(B!==void 0&&!B.startsWith("-"))f(F,B),Z++;else f(F,!0)}else f(F,!0)}}else A._.push(E)}return A}function IU($){return $.replace(/[<[].+/,"").trim()}function AB($){let w=/<([^>]+)>/g,A=/\[([^\]]+)\]/g,J=[],U=(Z)=>{let E=!1,W=Z[1];if(W.startsWith("..."))W=W.slice(3),E=!0;return{required:Z[0].startsWith("<"),value:W,variadic:E}},Y;while(Y=w.exec($))J.push(U(Y));let f;while(f=A.exec($))J.push(U(f));return J}function JB($){let w={alias:{},boolean:[]};for(let[A,J]of $.entries()){if(J.names.length>1)w.alias[J.names[0]]=J.names.slice(1);if(J.isBoolean)if(J.negated){if(!$.some((Y,f)=>{return f!==A&&Y.names.some((Z)=>J.names.includes(Z))&&typeof Y.required==="boolean"}))w.boolean.push(J.names[0])}else w.boolean.push(J.names[0])}return w}function _8($){return $.reduce((w,A)=>w.length>=A.length?w:A,"")}function KU($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function UB($){return $.replace(/([a-z])-([a-z])/g,(w,A,J)=>{return A+J.toUpperCase()})}function YB($,w,A){let J=0,U=w.length,Y=$,f;for(;J<U;++J)f=Y[w[J]],Y=Y[w[J]]=J===U-1?A:f!=null?f:!!~w[J+1].indexOf(".")||!(+w[J+1]>-1)?{}:[]}function fB($,w){for(let A of Object.keys(w)){let J=w[A];if(J.shouldTransform){if($[A]=Array.prototype.concat.call([],$[A]),typeof J.transformFunction==="function")$[A]=$[A].map(J.transformFunction)}}}function EB($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function i8($){return $.split(".").map((w,A)=>{return A===0?UB(w):w}).join(".")}class m1 extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
|
|
52
52
|
|
|
53
53
|
Stack trace:
|
|
54
|
-
${this.stack}`;return this.message}}function
|
|
55
|
-
`);let j=Array.from(
|
|
54
|
+
${this.stack}`;return this.message}}function ZB(){let{env:$}=D8,{TERM:w,TERM_PROGRAM:A}=$;if(D8.platform!=="win32")return w!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||A==="Terminus-Sublime"||A==="vscode"||w==="xterm-256color"||w==="alacritty"||w==="rxvt-unicode"||w==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var t1="\x1B",w$=`${t1}[`;var G0={to($,w){if(!w)return`${w$}${$+1}G`;return`${w$}${w+1};${$+1}H`},move($,w){let A="";if($<0)A+=`${w$}${-$}D`;else if($>0)A+=`${w$}${$}C`;if(w<0)A+=`${w$}${-w}A`;else if(w>0)A+=`${w$}${w}B`;return A},up:($=1)=>`${w$}${$}A`,down:($=1)=>`${w$}${$}B`,forward:($=1)=>`${w$}${$}C`,backward:($=1)=>`${w$}${$}D`,nextLine:($=1)=>`${w$}E`.repeat($),prevLine:($=1)=>`${w$}F`.repeat($),left:`${w$}G`,hide:`${w$}?25l`,show:`${w$}?25h`,save:`${t1}7`,restore:`${t1}8`};var MU={screen:`${w$}2J`,up:($=1)=>`${w$}1J`.repeat($),down:($=1)=>`${w$}J`.repeat($),line:`${w$}2K`,lineEnd:`${w$}K`,lineStart:`${w$}1K`,lines($){let w="";for(let A=0;A<$;A++)w+=this.line+(A<$-1?G0.up():"");if($)w+=G0.left;return w}},Wq={screen:`${t1}c`};function WB($,w){let A=[];for(let J=0;J<=w.length;J++)A[J]=[J];for(let J=0;J<=$.length;J++)A[0][J]=J;for(let J=1;J<=w.length;J++)for(let U=1;U<=$.length;U++)if(w.charAt(J-1)===$.charAt(U-1))A[J][U]=A[J-1][U-1];else A[J][U]=Math.min(A[J-1][U-1]+1,A[J][U-1]+1,A[J-1][U]+1);return A[w.length][$.length]}function c8($,w,A=2,J=3){return w.map((U)=>({cmd:U,distance:WB($,U)})).filter(({distance:U})=>U<=A).sort((U,Y)=>U.distance-Y.distance).slice(0,J).map(({cmd:U})=>U)}class u8{rawName;description;name;names;isBoolean;required;config;negated;constructor($,w,A){if(this.rawName=$,this.description=w,this.config=Object.assign({},A),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=IU($).split(",").map((J)=>{let U=J.trim().replace(/^-{1,2}/,"");if(U.startsWith("no-"))this.negated=!0,U=U.replace(/^no-/,"");return i8(U)}).sort((J,U)=>J.length>U.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var Fq=LU.argv,hB=`${LU.platform}-${LU.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,X8=d1.argv,FB=`${d1.platform}-${d1.arch} node-${d1.version}`;class yU{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,A,J){this.rawName=$,this.description=w,this.config=A,this.cli=J,this.options=[],this.aliasNames=[],this.name=IU($);let U=IU($),Y=U.indexOf(":");if(Y>0)this.namespace=U.substring(0,Y),this.name=U.substring(Y+1);if(this.args=AB($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!A)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,w="-v, --version"){return this.versionNumber=$,this.option(w,"Display version number"),this}example($){return this.examples.push($),this}option($,w,A){let J=new u8($,w,A);return this.options.push(J),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===$;return this.name===$}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof CU}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption($){return $=$.split(".")[0],!!this.options.find((w)=>{return w.names.includes($)})}outputHelp(){let{name:$,commands:w}=this.cli,{versionNumber:A,options:J,helpCallback:U}=this.cli.globalCommand,Y=[{body:`${$}${A?`/${A}`:""}`}];if(Y.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let E=_8(w.map((B)=>B.rawName)),W=new Map,h=[];for(let B of w)if(B.namespace){if(!W.has(B.namespace))W.set(B.namespace,[]);W.get(B.namespace).push(B)}else h.push(B);let F="";if(h.length>0)F+=h.map((B)=>{return` ${KU(B.rawName,E.length)} ${B.description}`}).join(`
|
|
55
|
+
`);let j=Array.from(W.keys()).sort();for(let B of j){let H=W.get(B);if(F.length>0)F+=`
|
|
56
56
|
|
|
57
57
|
`;F+=` ${B}:
|
|
58
|
-
`,F+=
|
|
58
|
+
`,F+=H.map((T)=>{return` ${KU(T.rawName,E.length-2)} ${T.description}`}).join(`
|
|
59
59
|
`)}Y.push({title:"Commands",body:F}),Y.push({title:"For more info, run any command with the `--help` flag",body:w.map((B)=>` $ ${$}${B.displayName===""?"":` ${B.displayName}`} --help`).join(`
|
|
60
|
-
`)})}let Z=this.isGlobalCommand?J:[...this.options,...J||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)Z=Z.filter((
|
|
61
|
-
`)})}if(this.examples.length>0)Y.push({title:"Examples",body:this.examples.map((
|
|
62
|
-
`)});if(U)Y=U(Y)||Y;console.log(Y.map((
|
|
63
|
-
${
|
|
60
|
+
`)})}let Z=this.isGlobalCommand?J:[...this.options,...J||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)Z=Z.filter((E)=>E.name!=="version");if(Z.length>0){let E=_8(Z.map((W)=>W.rawName));Y.push({title:"Options",body:Z.map((W)=>{return` ${KU(W.rawName,E.length)} ${W.description} ${W.config.default===void 0?"":`(default: ${W.config.default})`}`}).join(`
|
|
61
|
+
`)})}if(this.examples.length>0)Y.push({title:"Examples",body:this.examples.map((E)=>{if(typeof E==="function")return E($);return E}).join(`
|
|
62
|
+
`)});if(U)Y=U(Y)||Y;console.log(Y.map((E)=>{return E.title?`${E.title}:
|
|
63
|
+
${E.body}`:E.body}).join(`
|
|
64
64
|
|
|
65
|
-
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?
|
|
65
|
+
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?hB:FB}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let A=this.args.filter((U)=>U.required).slice(this.cli.args.length),J=A.map((U)=>`<${U.value}>`).join(" ");throw new m1(`Missing required argument${A.length>1?"s":""}: ${J}
|
|
66
66
|
|
|
67
|
-
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let A of Object.keys($))if(A!=="--"&&!this.hasOption(A)&&!w.hasOption(A)){let U=[...w.options,...this.options].flatMap((
|
|
67
|
+
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let A of Object.keys($))if(A!=="--"&&!this.hasOption(A)&&!w.hasOption(A)){let U=[...w.options,...this.options].flatMap((E)=>E.names),Y=A.length>1?`--${A}`:`-${A}`,f=c8(A,U),Z=`Unknown option \`${Y}\``;if(f.length>0)Z+=`
|
|
68
68
|
|
|
69
|
-
Did you mean one of these?`,
|
|
70
|
-
• ${
|
|
69
|
+
Did you mean one of these?`,f.forEach((E)=>{let W=E.length>1?`--${E}`:`-${E}`;Z+=`
|
|
70
|
+
• ${W}`});throw Z+=`
|
|
71
71
|
|
|
72
|
-
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new
|
|
72
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new m1(Z)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,A=[...w.options,...this.options];for(let J of A){let U=$[J.name.split(".")[0]];if(J.required){let Y=A.some((f)=>f.negated&&f.names.includes(J.name));if(U===!0||U===!1&&!Y)throw new m1(`Option \`${J.rawName}\` requires a value.
|
|
73
73
|
|
|
74
|
-
Example: ${this.cli.name} ${this.rawName} ${J.rawName} <value>`)}}}}class
|
|
74
|
+
Example: ${this.cli.name} ${this.rawName} ${J.rawName} <value>`)}}}}class CU extends yU{constructor($){super("@@global@@","",{},$)}}var BB=yU,n0={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var E1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function jB(){return!0}function zB(){let $={};$.supportsColor=jB();function w(J,U=[]){let Y=J===""?[]:[...U,J],f=function(E){if(!$.supportsColor)return E;let W="",h="";for(let F of Y)if(F in E1&&E1[F]in n0){let j=E1[F];W+=n0[j][0],h=n0[j][1]+h}else if(F in n0)W+=n0[F][0],h=n0[F][1]+h;return W+E+h},Z=[...Object.keys(n0),...Object.keys(E1)];for(let E of Z)if(!(E in f))Object.defineProperty(f,E,{get(){return w(E,Y)}});return f}let A=[...Object.keys(n0),...Object.keys(E1)];for(let J of A)if(!(J in $))Object.defineProperty($,J,{get(){return w(J)}});return $}var Z1=zB();class SU extends $B{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new CU(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(A)=>{if(console.log(`
|
|
75
75
|
|
|
76
|
-
Received ${A}, cleaning up...`),$)try{await $()}catch(J){console.error("Error during cleanup:",J)}u0.exit(0)};return u0.on("SIGINT",()=>w("SIGINT")),u0.on("SIGTERM",()=>w("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,w,A){if(!A)A={};let J=new
|
|
76
|
+
Received ${A}, cleaning up...`),$)try{await $()}catch(J){console.error("Error during cleanup:",J)}u0.exit(0)};return u0.on("SIGINT",()=>w("SIGINT")),u0.on("SIGTERM",()=>w("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,w,A){if(!A)A={};let J=new BB($,w||"",A,this);return J.globalCommand=this.globalCommand,this.commands.push(J),J}option($,w,A){return this.globalCommand.option($,w,A),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,w="-v, --version"){return this.globalCommand.version($,w),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:w},A,J){if(this.args=$,this.options=w,A)this.matchedCommand=A;if(J)this.matchedCommandName=J;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(Z1.red(`
|
|
77
77
|
✗ Command "${$}" not found.
|
|
78
|
-
`)),this.enableDidYouMean){let w=[];for(let J of this.commands){if(J.displayName)w.push(J.displayName);if(J.aliasNames)w.push(...J.aliasNames)}let A=
|
|
79
|
-
Run \`${this.name??"cli"} --help\` for usage.`;u0.stderr.write(`${Y}${U}${
|
|
80
|
-
`),u0.exit(J.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:A}=this;if(!A||!A.commandAction)return;A.checkUnknownOptions(),A.checkOptionValue(),A.checkRequiredArgs();let J=[];A.args.forEach((Z,
|
|
78
|
+
`)),this.enableDidYouMean){let w=[];for(let J of this.commands){if(J.displayName)w.push(J.displayName);if(J.aliasNames)w.push(...J.aliasNames)}let A=c8($,w);if(A.length>0)console.log(Z1.yellow("Did you mean one of these?")),A.forEach((J)=>console.log(` ${Z1.dim("•")} ${this.name} ${J}`)),console.log("")}console.log(Z1.dim("Run"),`${this.name} --help`,Z1.dim("to see all available commands")),u0.exit(1)}async parse($=X8,w={}){let{run:A=!0,exitOnError:J=!1}=w;if(J)try{return await this.parse($,{run:A})}catch(E){throw this.handleUsageError(E),E}if(this.rawArgs=$,!this.name)this.name=$[1]?EB($[1]):"cli";let U=!0,Y=$.slice(2),f=Y[0];if(f&&!f.startsWith("-")){for(let E of this.commands)if(E.isMatched(f)){let W=this.mri(Y,E);U=!1;let h={...W,args:W.args.slice(1)};this.setParsedInfo(h,E,f),this.emit(`command:${f}`,E);break}}if(U){for(let E of this.commands)if(E.name===""){U=!1;let W=this.mri(Y,E);this.setParsedInfo(W,E),this.emit("command:!",E);break}}if(U){let E=this.mri($.slice(2));this.setParsedInfo(E)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),A=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),A=!1,this.unsetMatchedCommand();let Z={args:this.args,options:this.options};if(A)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return Z}mri($,w){let A=[...this.globalCommand.options,...w?w.options:[]],J=JB(A),U=[],Y=$.indexOf("--");if(Y>-1)U=$.slice(Y+1),$=$.slice(0,Y);let f=wB($,J),Z={_:f._};for(let j of Object.keys(f))if(j!=="_")Z[i8(j)]=f[j];let E=Z._,W={"--":U},h=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,F=Object.create(null);for(let j of A){if(!h&&j.config.default!==void 0)for(let B of j.names)W[B]=j.config.default;if(Array.isArray(j.config.type)){if(F[j.name]===void 0)F[j.name]={shouldTransform:!0,transformFunction:j.config.type[0]}}}for(let j of Object.keys(Z))if(j!=="_"){let B=j.split(".");YB(W,B,Z[j]),fB(W,F)}return{args:E,options:W}}async run($=X8){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let J=$,U=J.message??"command-line error",Y=this.name?`${this.name}: `:"",f=/--help/.test(U)?"":`
|
|
79
|
+
Run \`${this.name??"cli"} --help\` for usage.`;u0.stderr.write(`${Y}${U}${f}
|
|
80
|
+
`),u0.exit(J.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:A}=this;if(!A||!A.commandAction)return;A.checkUnknownOptions(),A.checkOptionValue(),A.checkRequiredArgs();let J=[];A.args.forEach((Z,E)=>{if(Z.variadic)J.push($.slice(E));else J.push($[E])}),J.push(w);let U={command:A,args:J,options:w};for(let Z of A.beforeHooks)await Z(U);let Y,f=async()=>{let Z=A.commandAction.apply(this,J);if(Z instanceof Promise)Y=await Z;else Y=Z;return Y};if(A.middleware.length>0){let Z=0,E=async()=>{if(Z<A.middleware.length){let W=A.middleware[Z++];await W({...U,next:E})}else await f()};await E()}else await f();for(let Z of A.afterHooks)await Z(U);return Y}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return u0.removeAllListeners("SIGINT"),u0.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class n8{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let w=this.cache.get($);if(!w){this.misses++;return}if(Date.now()-w.timestamp>w.ttl){this.cache.delete($),this.misses++;return}return this.hits++,w.value}set($,w,A=5000){if(!this.enabled)return;this.cache.set($,{value:w,timestamp:Date.now(),ttl:A})}has($){if(!this.enabled)return!1;let w=this.cache.get($);if(!w)return!1;if(Date.now()-w.timestamp>w.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[w,A]of this.cache.entries())if($-A.timestamp>A.ttl)this.cache.delete(w)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var jq=new n8;function TB(){if("FORCE_COLOR"in W1.env)return W1.env.FORCE_COLOR!=="0";if("NO_COLOR"in W1.env||W1.env.TERM==="dumb")return!1;if(W1.platform==="win32")return!0;return k8.isatty(1)&&k8.isatty(2)}var v8=TB();function a($,w){if(!v8)return(A)=>A;return(A)=>$+A+w}var HB=a("\x1B[0m","\x1B[0m"),GB=a("\x1B[31m","\x1B[39m"),qB=a("\x1B[32m","\x1B[39m"),RB=a("\x1B[33m","\x1B[39m"),NB=a("\x1B[34m","\x1B[39m"),KB=a("\x1B[35m","\x1B[39m"),MB=a("\x1B[36m","\x1B[39m"),IB=a("\x1B[37m","\x1B[39m"),LB=a("\x1B[90m","\x1B[39m"),yB=a("\x1B[1m","\x1B[22m"),CB=a("\x1B[3m","\x1B[23m"),SB=a("\x1B[4m","\x1B[24m"),VB=a("\x1B[2m","\x1B[22m"),OB=a("\x1B[7m","\x1B[27m"),DB=a("\x1B[8m","\x1B[28m"),_B=a("\x1B[9m","\x1B[29m"),XB=a("\x1B[41m","\x1B[49m"),kB=a("\x1B[42m","\x1B[49m"),QB=a("\x1B[43m","\x1B[49m"),xB=a("\x1B[44m","\x1B[49m"),PB=a("\x1B[45m","\x1B[49m"),bB=a("\x1B[46m","\x1B[49m"),iB=a("\x1B[47m","\x1B[49m"),cB=v8,uB={reset:HB,red:GB,green:qB,yellow:RB,blue:NB,magenta:KB,cyan:MB,white:IB,gray:LB,bold:yB,italic:CB,underline:SB,dim:VB,inverse:OB,hidden:DB,strikethrough:_B,bgRed:XB,bgGreen:kB,bgYellow:QB,bgBlue:xB,bgMagenta:PB,bgCyan:bB,bgWhite:iB,isColorSupported:cB},g1=uB,vB=["up","down","left","right","space","enter","cancel"],l1={actions:new Set(vB),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function m8($,w){if(typeof $==="string")return l1.aliases.get($)===w;for(let A of $){if(A===void 0)continue;if(m8(A,w))return!0}return!1}function mB($,w){if($===w)return[];let A=$.split(`
|
|
81
81
|
`),J=w.split(`
|
|
82
|
-
`),U=[];for(let Y=0;Y<Math.max(A.length,J.length);Y++)if(A[Y]!==J[Y])U.push(Y);return U}var
|
|
83
|
-
`),
|
|
84
|
-
`)}class
|
|
85
|
-
`),
|
|
86
|
-
`).length-1;this.output.write(G0.move(-999,$*-1))}render(){let $=
|
|
87
|
-
`);this.output.write(J[A]),this._prevFrame=$,this.output.write(G0.move(0,J.length-A-1));return}if(w&&w?.length>1){let A=w[0];this.output.write(G0.move(0,A)),this.output.write(
|
|
82
|
+
`),U=[];for(let Y=0;Y<Math.max(A.length,J.length);Y++)if(A[Y]!==J[Y])U.push(Y);return U}var Rq=nB.platform.startsWith("win"),Q8=Symbol("clapp:cancel");function v1($,w){let A=$;if(A.isTTY)A.setRawMode(w)}function tB($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function pB($){return tB($).length}function P8($,w,A){if(!w||w<1)return $;let J=A?.hard??!1,U=A?.trim??!0,Y=$.split(`
|
|
83
|
+
`),f=[];for(let Z of Y){if(pB(Z)<=w){f.push(U?Z.trimEnd():Z);continue}if(J){let E="",W=0,h=0;while(h<Z.length){let F=Z.slice(h).match(/^\x1b\[[0-9;]*m/);if(F){E+=F[0],h+=F[0].length;continue}if(W>=w)f.push(U?E.trimEnd():E),E="",W=0;E+=Z[h],W++,h++}if(E)f.push(U?E.trimEnd():E)}else f.push(U?Z.trimEnd():Z)}return f.join(`
|
|
84
|
+
`)}class VU{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor($,w=!0){let{input:A=dB,output:J=gB,render:U,signal:Y,...f}=$;this.opts=f,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=U.bind(this),this._track=w,this._abortSignal=Y,this.input=A,this.output=J}unsubscribe(){this._subscribers.clear()}setSubscriber($,w){let A=this._subscribers.get($)??[];A.push(w),this._subscribers.set($,A)}on($,w){return this.setSubscriber($,{cb:w}),this}once($,w){return this.setSubscriber($,{cb:w,once:!0}),this}emit($,...w){let A=this._subscribers.get($)??[],J=[];for(let U of A)if(U.cb(...w),U.once)J.push(()=>A.splice(A.indexOf(U),1));for(let U of J)U();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(Q8);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=lB.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),v1(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(G0.show),this.output.off("resize",this.render),v1(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(G0.show),this.output.off("resize",this.render),v1(this.input,!1),$(Q8)})})}_isActionKey($,w){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,w){if(this.userInput=$??"",this.emit("userInput",this.userInput),w&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,w){if(this._track&&w.name!=="return"){if(w.name&&this._isActionKey($,w))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let A=w.name==="tab"||w.name==="escape"||w.name==="backspace"||w.name==="delete"||w.name==="enter"||w.name==="return"||w.name&&["up","down","left","right"].includes(w.name);if($&&!A&&$.length===1&&$>=" ")this._manualLine+=$;else if(w.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let J=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(J)}if(this.state==="error")this.state="active",this.error="";if(w?.name){if(!this._track&&l1.aliases.has(w.name))this.emit("cursor",l1.aliases.get(w.name));if(l1.actions.has(w.name))this.emit("cursor",w.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),w),w?.name==="return"){if(this.opts.validate){let A=this.opts.validate(this.value);if(A)this.error=A instanceof Error?A.message:A,this.state="error"}if(this.state!=="error")this.state="submit"}if(m8([$,w?.name,w?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
85
|
+
`),v1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let $=P8(this._prevFrame,x8.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
86
|
+
`).length-1;this.output.write(G0.move(-999,$*-1))}render(){let $=P8(this._render(this)??"",x8.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(G0.hide);else{let w=mB(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let A=w[0];this.output.write(G0.move(0,A)),this.output.write(MU.lines(1));let J=$.split(`
|
|
87
|
+
`);this.output.write(J[A]),this._prevFrame=$,this.output.write(G0.move(0,J.length-A-1));return}if(w&&w?.length>1){let A=w[0];this.output.write(G0.move(0,A)),this.output.write(MU.down());let U=$.split(`
|
|
88
88
|
`).slice(A);this.output.write(U.join(`
|
|
89
|
-
`)),this._prevFrame=$;return}this.output.write(HU.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function bB($,w){if($===void 0)return 0;if(w.length===0)return 0;let J=w.findIndex((U)=>U.value===$);return J!==-1?J:0}function iB($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function cB($,w){if(!w)return;if($)return w;return w[0]}class uB extends KU{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#A="";#J;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return m1.inverse(m1.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[w,...A]=this.userInput.slice(this._cursor);return`${$}${m1.inverse(w)}${A.join("")}`}get options(){if(typeof this.#w==="function")return this.#w();return this.#w}constructor($){super($);this.#w=$.options;let w=this.options;this.filteredOptions=[...w],this.multiple=$.multiple===!0,this.#J=$.filter??iB;let A;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)A=$.initialValue;else A=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)A=[this.options[0].value];if(A)for(let J of A){let U=w.findIndex((Y)=>Y.value===J);if(U!==-1)this.toggleSelected(J),this.#$=U}this.focusedValue=this.options[this.#$]?.value,this.on("key",(J,U)=>this.#U(J,U)),this.on("userInput",(J)=>this.#Y(J))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#U($,w){let A=w.name==="up",J=w.name==="down",U=w.name==="return";if(A||J){if(this.#$=Math.max(0,Math.min(this.#$+(A?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(U)this.value=cB(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(w.name==="tab"||this.isNavigating&&w.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((w)=>w!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#Y($){if($!==this.#A){this.#A=$;let w=this.options;if($)this.filteredOptions=w.filter((A)=>this.#J($,A));else this.filteredOptions=[...w];if(this.#$=bB(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class nB extends KU{options;cursor=0;#$;getGroupItems($){return this.options.filter((w)=>w.group===$)}isGroupSelected($){let w=this.getGroupItems($),A=this.value;if(A===void 0)return!1;return w.every((J)=>A.includes(J.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let w=String($.value),A=this.getGroupItems(w);if(this.isGroupSelected(w))this.value=this.value.filter((J)=>A.findIndex((U)=>U.value===J)===-1);else this.value=[...this.value,...A.map((J)=>J.value)];this.value=Array.from(new Set(this.value))}else{let w=this.value.includes($.value);this.value=w?this.value.filter((A)=>A!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:w}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(w).flatMap(([A,J])=>[{value:A,group:!0,label:A},...J.map((U)=>({...U,group:A}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:A})=>A===$.cursorAt),this.#$?0:1),this.on("cursor",(A)=>{switch(A){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let J=this.options[this.cursor]?.group===!0;if(!this.#$&&J)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let J=this.options[this.cursor]?.group===!0;if(!this.#$&&J)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var vB=aF();var l=($,w)=>vB?$:w,h5=l("◆","*"),f5=l("■","x"),Z5=l("▲","x"),E5=l("◇","o"),W5=l("┌","T"),mB=l("│","|"),F5=l("└","—"),B5=l("●",">"),j5=l("○"," "),z5=l("◻","[•]"),H5=l("◼","[+]"),T5=l("◻","[ ]"),G5=l("▪","•"),q5=l("─","-"),R5=l("╮","+"),N5=l("├","+"),K5=l("╯","+"),M5=l("●","•"),I5=l("◆","*"),y5=l("▲","!"),L5=l("■","x");var C5={light:l("─","-"),heavy:l("━","="),block:l("█","#")};function dB(){return`${m1.gray(mB)} `}var S5=dB();import{homedir as EY}from"node:os";import{join as WY,resolve as T6}from"node:path";import{existsSync as k8,statSync as Q8}from"fs";import{existsSync as gB,mkdirSync as _5,readdirSync as X5,readFileSync as lB,writeFileSync as k5}from"fs";import{homedir as Tw}from"os";import{dirname as P5,resolve as p$}from"path";import LA from"process";import{existsSync as x8,statSync as P8}from"fs";import{existsSync as nU,mkdirSync as tB,readdirSync as pB,writeFileSync as rB}from"fs";import{homedir as Gw}from"os";import{dirname as b8,resolve as O$}from"path";import e0 from"process";import{join as aB,relative as sB,resolve as i8}from"path";import BA from"process";import{existsSync as Kf,mkdirSync as l5,readdirSync as t5,writeFileSync as p5}from"fs";import{homedir as MU}from"os";import{dirname as s5,resolve as D$}from"path";import E1 from"process";import{join as oB,relative as eB,resolve as c8}from"path";import jA from"process";import{existsSync as Mf,mkdirSync as Aq,readdirSync as Jq,writeFileSync as Uq}from"fs";import{dirname as hq,resolve as zA}from"path";import vU from"process";import{Buffer as v0}from"buffer";import{createCipheriv as $j,createDecipheriv as wj,randomBytes as IU}from"crypto";import{closeSync as yU,createReadStream as u8,createWriteStream as Aj,existsSync as LU,fsyncSync as n8,openSync as v8,writeFileSync as Jj}from"fs";import{access as Uj,constants as m8,mkdir as Yj,readdir as l1,rename as d8,stat as qw,unlink as t1,writeFile as CU}from"fs/promises";import{join as Rw}from"path";import q$ from"process";import{pipeline as hj}from"stream/promises";import{createGzip as g8}from"zlib";import Nw from"process";import K0 from"process";import{Buffer as q0}from"buffer";import{createCipheriv as fj,createDecipheriv as Zj,randomBytes as SU}from"crypto";import{closeSync as VU,createReadStream as l8,createWriteStream as Ej,existsSync as p1,fsyncSync as t8,openSync as p8,writeFileSync as Wj}from"fs";import{access as Fj,constants as r8,mkdir as Bj,readdir as r1,rename as a8,stat as Kw,unlink as a1,writeFile as DU}from"fs/promises";import{isAbsolute as jj,join as Mw,resolve as zj}from"path";import S from"process";import{pipeline as Hj}from"stream/promises";import{createGzip as s8}from"zlib";import Iw from"process";import M0 from"process";import s1 from"process";import{existsSync as o1}from"fs";import{resolve as OU}from"path";import{existsSync as Tj}from"fs";import{existsSync as Gj,readdirSync as qj}from"fs";import{extname as _U,resolve as o8}from"path";import Rj from"process";import{join as Nj,relative as Kj,resolve as e8}from"path";import HA from"process";import{Buffer as R0}from"buffer";import{createCipheriv as Mj,createDecipheriv as Ij,randomBytes as XU}from"crypto";import{closeSync as kU,createReadStream as $f,createWriteStream as yj,existsSync as e1,fsyncSync as wf,openSync as Af,writeFileSync as Lj}from"fs";import{access as Cj,constants as Jf,mkdir as Sj,readdir as $A,rename as Uf,stat as yw,unlink as wA,writeFile as QU}from"fs/promises";import{isAbsolute as Vj,join as Lw,resolve as Dj}from"path";import V from"process";import{pipeline as Oj}from"stream/promises";import{createGzip as Yf}from"zlib";import Cw from"process";import I0 from"process";import JA from"process";import{existsSync as UA}from"fs";import{resolve as uU}from"path";import{existsSync as az}from"fs";class Rf{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,h=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:h}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!k8($))return!0;return Q8($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=k8(A)?Q8(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class Nf{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),h=performance.now()-J;return this.recordMetric({operation:$,duration:h,timestamp:U,...A}),Y}catch(Y){let h=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:h,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}var FA=new Rf,eU=new Nf;var _j=Object.defineProperty,Xj=($)=>$;function kj($,w){this[$]=Xj.bind(null,w)}var Qj=($,w)=>{for(var A in w)_j($,A,{get:w[A],enumerable:!0,configurable:!0,set:kj.bind(w,A)})},xj=($,w)=>()=>($&&(w=$($=0)),w),If={};Qj(If,{withErrorRecovery:()=>Cf,tryLoadConfig:()=>Uz,loadConfigWithResult:()=>Az,loadConfig:()=>_f,isRetryableError:()=>aj,isConfigNotFoundError:()=>rj,isBunfigError:()=>Sf,globalPerformanceMonitor:()=>B1,globalCache:()=>Sw,getEnvOrDefault:()=>sj,generateConfigTypes:()=>Yz,defaultGeneratedDir:()=>uf,defaultConfigDir:()=>cf,deepMergeWithArrayStrategy:()=>UY,deepMerge:()=>Vf,createLibraryConfig:()=>hz,config:()=>Jz,bunfigPlugin:()=>fz,applyEnvVarsToConfig:()=>Z1,TypeGenerationError:()=>rU,SchemaValidationError:()=>F1,PluginError:()=>sU,PerformanceMonitor:()=>wY,FileSystemError:()=>pU,ErrorFactory:()=>m0,EnvVarError:()=>KA,EnvProcessor:()=>CA,ConfigValidator:()=>YY,ConfigValidationError:()=>lU,ConfigNotFoundError:()=>NA,ConfigMergeError:()=>tU,ConfigLoader:()=>hY,ConfigLoadError:()=>W1,ConfigFileLoader:()=>SA,ConfigCache:()=>$Y,CacheUtils:()=>kf,BunfigError:()=>u$,BrowserConfigError:()=>aU,ArrayMergeStrategies:()=>Pf});class $Y{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,h=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:h}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!x8($))return!0;return P8($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=x8(A)?P8(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class wY{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),h=performance.now()-J;return this.recordMetric({operation:$,duration:h,timestamp:U,...A}),Y}catch(Y){let h=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:h,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function Pj($,w={}){let J=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return J?`${$}:${J}`:$}function bj($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function ij($){return $.getStats().size*2}function AY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&t(w[0])&&"id"in w[0]&&w[0].id===3&&t(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(t(w)&&t($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(t($)&&"arr"in $&&Array.isArray($.arr)&&t(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&t(w[0])&&t($[0])){let J=[...w];for(let U of $)if(t(U)&&"name"in U){if(!J.find((h)=>t(h)&&("name"in h)&&h.name===U.name))J.push(U)}else if(t(U)&&"path"in U){if(!J.find((h)=>t(h)&&("path"in h)&&h.path===U.path))J.push(U)}else if(!J.some((Y)=>TA(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!t(w)||!t($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(t(U)&&t(A[J]))A[J]=AY(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&t(U[0])&&t(A[J][0])){let Y=[...U];for(let h of A[J])if(t(h)&&"name"in h){if(!Y.find((f)=>t(f)&&("name"in f)&&f.name===h.name))Y.push(h)}else if(t(h)&&"path"in h){if(!Y.find((f)=>t(f)&&("path"in f)&&f.path===h.path))Y.push(h)}else if(!Y.some((Z)=>TA(Z,h)))Y.push(h);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let h of A[J])if(!Y.includes(h))Y.push(h);A[J]=Y}else A[J]=U;else A[J]=U}return A}function TA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!TA($[A],w[A]))return!1;return!0}if(t($)&&t(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!TA($[U],w[U]))return!1}return!0}return!1}function t($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function cj($,w){if(!Mf($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return AY(w,J)}catch{return null}}catch{return null}}async function uj({name:$="",cwd:w,defaultConfig:A}){let J=w||vU.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let h of Y)for(let Z of U){let f=zA(J,`${h}${Z}`),E=await cj(f,A);if(E!==null)return E}try{let h=zA(J,"package.json");if(Mf(h)){let f=(await import(h))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return AY(A,f)}catch{}}}catch{}return A}function nj($,w={}){let A=jA.cwd();while(A.includes("storage"))A=c8(A,"..");let J=c8(A,$||"");if(w?.relative)return eB(jA.cwd(),J);return J}async function vj(){try{let $=await uj({name:"clarity",defaultConfig:fA,cwd:jA.cwd(),endpoint:"",headers:{}});return{...fA,...$}}catch{return fA}}function o(){if(K0.env.NODE_ENV==="test"||K0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function mj(){if(K0.env.NODE_ENV==="test"||K0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof K0<"u"){let $=K0.type;if($==="renderer"||$==="worker")return!1;return!!(K0.versions&&(K0.versions.node||K0.versions.bun))}return!1}class yf{async format($){let w=await mj(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Nw.pid,hostname:w(),environment:Nw.env.NODE_ENV||"development",platform:Nw.platform,version:Nw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Nw.env.NODE_ENV||Nw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class GA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...dU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new yf,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??q$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...ZA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...ZA};return{...ZA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:dU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let U,Y=0,h=3,Z=1000;while(Y<h)try{try{try{await Uj(this.config.logDirectory,m8.F_OK|m8.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Yj(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:v0.from($);try{if(!LU(this.currentLogFile))await CU(this.currentLogFile,"",{mode:420});if(U=v8(this.currentLogFile,"a",420),Jj(U,f,{flag:"a"}),n8(U),U!==void 0)yU(U),U=void 0;if((await qw(this.currentLogFile)).size===0){if(await CU(this.currentLogFile,f,{flag:"w",mode:420}),(await qw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(Y<h-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${h}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(U!==void 0)try{yU(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(Y===h-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}Y++;let E=Z*2**(Y-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 Rw(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 Rw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Rw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(o())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,h=Math.max(1,Y);if(U.length>h)for(let[Z]of U.slice(h))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return IU(16).toString("hex")}generateKey(){return IU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=IU(16),J=$j("aes-256-gcm",w,A),U=v0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:v0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=g8(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(v0.from(v0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(o())return;let $=await qw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await l1(this.config.logDirectory),Y=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),h=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${h}`;if(await qw(A).catch(()=>null))try{if(await d8(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await t1(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(Y.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await CU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await qw(A).catch(()=>null))await d8(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await l1(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,Z)=>Z.localeCompare(h));for(let h of Y.slice(w.maxFiles))await t1(Rw(this.config.logDirectory,h))}}}async compressLogFile($,w){let A=u8($),J=Aj(w),U=g8();await hj(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),LU(this.currentLogFile))try{let $=v8(this.currentLogFile,"r+");n8($),yU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!o()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await l1(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await t1(Rw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?m.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:h=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(h)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let f=q$.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${m.cyan(U)}`;if(!h)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,h)=>{let Z=Number.parseInt(h,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,h)=>{if(h==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(h){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),h,Z;if(w instanceof Error)h=w.message,Z=w.stack;else h=this.formatMessage(w,A);if(this.fancy&&!o()){let E=Qf[$],W=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:m.gray(h),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:h,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:m.green(h),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:h,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:h,level:$}),console.error(F),Z){let j=Z.split(`
|
|
90
|
-
`);for(let B of j)if(B.trim()&&!B.includes(
|
|
91
|
-
`;if(Z)
|
|
92
|
-
`;
|
|
93
|
-
`,
|
|
94
|
-
`),
|
|
95
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(o())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${m.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();q$.stdin.removeListener("data",A);try{if(typeof q$.stdin.setRawMode==="function")q$.stdin.setRawMode(!1)}catch{}q$.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof q$.stdin.setRawMode==="function")q$.stdin.setRawMode(!0)}catch{}q$.stdin.resume(),q$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let
|
|
96
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress($,w=""){if(!this.enabled||!this.fancy||o()||$<=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 A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(
|
|
97
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||o()||!q$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(o()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await l1(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=Rw(this.config.logDirectory,J);if($.before)try{if((await qw(Y)).mtime>=$.before)continue}catch(h){console.error(`Failed to get stats for file ${Y}:`,h);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await t1(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function hA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&i(w[0])&&"id"in w[0]&&w[0].id===3&&i(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(i(w)&&i($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(i($)&&"arr"in $&&Array.isArray($.arr)&&i(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&i(w[0])&&i($[0])){let J=[...w];for(let U of $)if(i(U)&&"name"in U){if(!J.find((h)=>i(h)&&("name"in h)&&h.name===U.name))J.push(U)}else if(i(U)&&"path"in U){if(!J.find((h)=>i(h)&&("path"in h)&&h.path===U.path))J.push(U)}else if(!J.some((Y)=>qA(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!i(w)||!i($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(i(U)&&i(A[J]))A[J]=hA(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&i(U[0])&&i(A[J][0])){let Y=[...U];for(let h of A[J])if(i(h)&&"name"in h){if(!Y.find((f)=>i(f)&&("name"in f)&&f.name===h.name))Y.push(h)}else if(i(h)&&"path"in h){if(!Y.find((f)=>i(f)&&("path"in f)&&f.path===h.path))Y.push(h)}else if(!Y.some((Z)=>qA(Z,h)))Y.push(h);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let h of A[J])if(!Y.includes(h))Y.push(h);A[J]=Y}else A[J]=U;else A[J]=U}return A}function JY($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:hA($,w);if(Array.isArray($))return A==="replace"?w:hA($,w);if(!i(w)||!i($))return w;let J={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let Y=w[U],h=J[U];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(h))if(A==="replace")J[U]=Y;else J[U]=hA(h,Y);else if(i(Y)&&i(h))J[U]=JY(h,Y,A);else J[U]=Y}return J}function qA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!qA($[A],w[A]))return!1;return!0}if(i($)&&i(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!qA($[U],w[U]))return!1}return!0}return!1}function i($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function AA($,w,A="replace"){if(!Kf($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return JY(w,U,A)}catch{return null}}catch{return null}}function dj($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(h,Z=[]){let f={...h};for(let[E,W]of Object.entries(h)){let F=[...Z,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),B=`${J}_${F.map(j).join("_")}`,T=`${J}_${F.map((H)=>H.toUpperCase()).join("_")}`;if(A)N$.info(`Checking environment variable ${B} for config ${$}.${F.join(".")}`);if(typeof W==="object"&&W!==null&&!Array.isArray(W))f[E]=Y(W,F);else{let H=E1.env[B]||E1.env[T];if(H!==void 0){if(A)N$.info(`Using environment variable ${H?B:T} for config ${$}.${F.join(".")}`);if(typeof W==="number")f[E]=Number(H);else if(typeof W==="boolean")f[E]=H.toLowerCase()==="true";else if(Array.isArray(W))try{let q=JSON.parse(H);if(Array.isArray(q))f[E]=q;else f[E]=H.split(",").map((G)=>G.trim())}catch{f[E]=H.split(",").map((q)=>q.trim())}else f[E]=H}}}return f}return Y(U)}async function gj({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:U,verbose:Y=!1,checkEnv:h=!0,arrayStrategy:Z="replace"}){let f=h&&typeof U==="object"&&U!==null&&!Array.isArray(U)?dj($,U,Y):U,E=A||E1.cwd(),W=[".ts",".js",".mjs",".cjs",".json"];if(Y)N$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let F=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),B=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,D$(E,"config"),D$(E,".config"),J?D$(E,J):void 0].filter(Boolean)));for(let q of H){if(Y)N$.info(`Searching for configuration in: ${q}`);let R=[D$(E,"config"),D$(E,".config")].concat(J?[D$(E,J)]:[]).includes(q)?[...F,...j,...B,...T]:[...j,...F,...T,...B];for(let K of R)for(let L of W){let C=D$(q,`${K}${L}`),M=await AA(C,f,Z);if(M!==null){if(Y)N$.success(`Configuration loaded from: ${C}`);return M}}}if($){let q=D$(MU(),".config",$),G=["config",`${$}.config`];if(w)G.push(`${w}.config`);if(Y)N$.info(`Checking user config directory: ${q}`);for(let R of G)for(let K of W){let L=D$(q,`${R}${K}`),C=await AA(L,f,Z);if(C!==null){if(Y)N$.success(`Configuration loaded from user config directory: ${L}`);return C}}}if($){let q=D$(MU(),".config"),G=[`.${$}.config`];if(w)G.push(`.${w}.config`);if(Y)N$.info(`Checking user config directory for dotfile configs: ${q}`);for(let R of G)for(let K of W){let L=D$(q,`${R}${K}`),C=await AA(L,f,Z);if(C!==null){if(Y)N$.success(`Configuration loaded from user config directory dotfile: ${L}`);return C}}}if($){let q=MU(),G=[`.${$}.config`,`.${$}`];if(w)G.push(`.${w}.config`),G.push(`.${w}`);if(Y)N$.info(`Checking user home directory for dotfile configs: ${q}`);for(let R of G)for(let K of W){let L=D$(q,`${R}${K}`),C=await AA(L,f,Z);if(C!==null){if(Y)N$.success(`Configuration loaded from user home directory: ${L}`);return C}}}try{let q=D$(E,"package.json");if(Kf(q)){let G=await import(q),R=G[$];if(!R&&w){if(R=G[w],R&&Y)N$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(Y)N$.success(`Configuration loaded from package.json: ${R===G[$]?$:w}`);return JY(f,R,Z)}catch(K){if(Y)N$.warn("Failed to merge package.json config:",K)}}}catch(q){if(Y)N$.warn("Failed to load package.json:",q)}if(Y)N$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function lj($,w={}){let A=BA.cwd();while(A.includes("storage"))A=i8(A,"..");let J=i8(A,$||"");if(w?.relative)return sB(BA.cwd(),J);return J}async function tj(){try{let $=await gj({name:"clarity",alias:"logging",defaultConfig:EA,cwd:BA.cwd()});return{...EA,...$||{}}}catch{return EA}}function J$(){if(M0.env.NODE_ENV==="test"||M0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function pj(){if(M0.env.NODE_ENV==="test"||M0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof M0<"u"){let $=M0.type;if($==="renderer"||$==="worker")return!1;return!!(M0.versions&&(M0.versions.node||M0.versions.bun))}return!1}class Lf{async format($){let w=await pj(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Iw.pid,hostname:w(),environment:Iw.env.NODE_ENV||"development",platform:Iw.platform,version:Iw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Iw.env.NODE_ENV||Iw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class RA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...gU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Lf,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??S.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...WA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...WA};return{...WA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:gU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!J$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,h=3,Z=1000;while(Y<h)try{try{try{await Fj(this.config.logDirectory,r8.F_OK|r8.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Bj(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:q0.from($);try{if(!p1(this.currentLogFile))await DU(this.currentLogFile,"",{mode:420});if(U=p8(this.currentLogFile,"a",420),Wj(U,f,{flag:"a"}),t8(U),U!==void 0)VU(U),U=void 0;if((await Kw(this.currentLogFile)).size===0){if(await DU(this.currentLogFile,f,{flag:"w",mode:420}),(await Kw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(Y<h-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${h}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(U!==void 0)try{VU(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(Y===h-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}Y++;let E=Z*2**(Y-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 Mw(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 Mw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Mw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(J$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,h=Math.max(1,Y);if(U.length>h)for(let[Z]of U.slice(h))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return SU(16).toString("hex")}generateKey(){return SU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=SU(16),J=fj("aes-256-gcm",w,A),U=q0.isBuffer($)?$:q0.from($,"utf8"),Y=J.update(U),h=J.final(),Z=Y.length+h.length,f=J.getAuthTag(),E=q0.allocUnsafe(16+Z+16);return A.copy(E,0),Y.copy(E,16),h.copy(E,16+Y.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=s8(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(q0.from(q0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(J$())return;if(!this.shouldWriteToFile())return;let $=await Kw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await r1(this.config.logDirectory),Y=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),h=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${h}`;if(await Kw(A).catch(()=>null))try{if(await a8(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await a1(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(Y.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await DU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await Kw(A).catch(()=>null))await a8(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await r1(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,Z)=>Z.localeCompare(h));for(let h of Y.slice(w.maxFiles))await a1(Mw(this.config.logDirectory,h))}}}async compressLogFile($,w){let A=l8($),J=Ej(w),U=s8();await Hj(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),p1(this.currentLogFile))try{let $=p8(this.currentLogFile,"r+");t8($),VU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!J$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await r1(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await a1(Mw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?_.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||J$())return!1;let $=typeof S.env.NO_COLOR<"u",w=S.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof S.stderr<"u"&&S.stderr.isTTY||typeof S.stdout<"u"&&S.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:h=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(h)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let f=S.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${_.cyan(U)}`;if(!h)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,h)=>{let Z=Number.parseInt(h,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,h)=>{if(h==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(h){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=_.underline(_.blue(J)),h=this.toAbsoluteFilePath(U);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(h)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>_.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>_.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>_.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>_.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>_.strikethrough(J)),w}supportsHyperlinks(){if(J$())return!1;let $=S.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=S.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(jj(w)||w.startsWith("./")||w.startsWith("../"))w=zj(w);else return null;return p1(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),h,Z;if(w instanceof Error)h=w.message,Z=w.stack;else h=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":xf[$],j=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:_.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:_.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
|
|
98
|
-
`);for(let
|
|
99
|
-
`;if(Z)
|
|
100
|
-
`;if(
|
|
101
|
-
`);if(this[
|
|
102
|
-
`,
|
|
103
|
-
`),
|
|
104
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
105
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!S.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=_.green("━".repeat(J)),
|
|
106
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||J$()||!S.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(J$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await
|
|
89
|
+
`)),this._prevFrame=$;return}this.output.write(MU.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function rB($,w){if($===void 0)return 0;if(w.length===0)return 0;let J=w.findIndex((U)=>U.value===$);return J!==-1?J:0}function aB($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function sB($,w){if(!w)return;if($)return w;return w[0]}class oB extends VU{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#A="";#J;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return g1.inverse(g1.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[w,...A]=this.userInput.slice(this._cursor);return`${$}${g1.inverse(w)}${A.join("")}`}get options(){if(typeof this.#w==="function")return this.#w();return this.#w}constructor($){super($);this.#w=$.options;let w=this.options;this.filteredOptions=[...w],this.multiple=$.multiple===!0,this.#J=$.filter??aB;let A;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)A=$.initialValue;else A=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)A=[this.options[0].value];if(A)for(let J of A){let U=w.findIndex((Y)=>Y.value===J);if(U!==-1)this.toggleSelected(J),this.#$=U}this.focusedValue=this.options[this.#$]?.value,this.on("key",(J,U)=>this.#U(J,U)),this.on("userInput",(J)=>this.#Y(J))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#U($,w){let A=w.name==="up",J=w.name==="down",U=w.name==="return";if(A||J){if(this.#$=Math.max(0,Math.min(this.#$+(A?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(U)this.value=sB(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(w.name==="tab"||this.isNavigating&&w.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((w)=>w!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#Y($){if($!==this.#A){this.#A=$;let w=this.options;if($)this.filteredOptions=w.filter((A)=>this.#J($,A));else this.filteredOptions=[...w];if(this.#$=rB(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class eB extends VU{options;cursor=0;#$;getGroupItems($){return this.options.filter((w)=>w.group===$)}isGroupSelected($){let w=this.getGroupItems($),A=this.value;if(A===void 0)return!1;return w.every((J)=>A.includes(J.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let w=String($.value),A=this.getGroupItems(w);if(this.isGroupSelected(w))this.value=this.value.filter((J)=>A.findIndex((U)=>U.value===J)===-1);else this.value=[...this.value,...A.map((J)=>J.value)];this.value=Array.from(new Set(this.value))}else{let w=this.value.includes($.value);this.value=w?this.value.filter((A)=>A!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:w}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(w).flatMap(([A,J])=>[{value:A,group:!0,label:A},...J.map((U)=>({...U,group:A}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:A})=>A===$.cursorAt),this.#$?0:1),this.on("cursor",(A)=>{switch(A){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let J=this.options[this.cursor]?.group===!0;if(!this.#$&&J)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let J=this.options[this.cursor]?.group===!0;if(!this.#$&&J)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var $j=ZB();var l=($,w)=>$j?$:w,Mq=l("◆","*"),Iq=l("■","x"),Lq=l("▲","x"),yq=l("◇","o"),Cq=l("┌","T"),wj=l("│","|"),Sq=l("└","—"),Vq=l("●",">"),Oq=l("○"," "),Dq=l("◻","[•]"),_q=l("◼","[+]"),Xq=l("◻","[ ]"),kq=l("▪","•"),Qq=l("─","-"),xq=l("╮","+"),Pq=l("├","+"),bq=l("╯","+"),iq=l("●","•"),cq=l("◆","*"),uq=l("▲","!"),nq=l("■","x");var vq={light:l("─","-"),heavy:l("━","="),block:l("█","#")};function Aj(){return`${g1.gray(wj)} `}var mq=Aj();import{homedir as HY}from"node:os";import{join as GY,resolve as X6}from"node:path";import{existsSync as d8,statSync as g8}from"fs";import{existsSync as Jj,mkdirSync as tq,readdirSync as pq,readFileSync as Uj,writeFileSync as rq}from"fs";import{homedir as Tw}from"os";import{dirname as oq,resolve as p$}from"path";import SA from"process";import{existsSync as l8,statSync as t8}from"fs";import{existsSync as pU,mkdirSync as Yj,readdirSync as fj,writeFileSync as Ej}from"fs";import{homedir as Hw}from"os";import{dirname as p8,resolve as D$}from"path";import e0 from"process";import{join as Zj,relative as Wj,resolve as r8}from"path";import zA from"process";import{existsSync as XE,mkdirSync as Z5,readdirSync as W5,writeFileSync as h5}from"fs";import{homedir as OU}from"os";import{dirname as j5,resolve as O$}from"path";import F1 from"process";import{join as hj,relative as Fj,resolve as a8}from"path";import TA from"process";import{existsSync as kE,mkdirSync as q5,readdirSync as R5,writeFileSync as N5}from"fs";import{dirname as M5,resolve as HA}from"path";import rU from"process";import{Buffer as v0}from"buffer";import{createCipheriv as Bj,createDecipheriv as jj,randomBytes as DU}from"crypto";import{closeSync as _U,createReadStream as s8,createWriteStream as zj,existsSync as XU,fsyncSync as o8,openSync as e8,writeFileSync as Tj}from"fs";import{access as Hj,constants as $E,mkdir as Gj,readdir as p1,rename as wE,stat as Gw,unlink as r1,writeFile as kU}from"fs/promises";import{join as qw}from"path";import q$ from"process";import{pipeline as qj}from"stream/promises";import{createGzip as AE}from"zlib";import Rw from"process";import K0 from"process";import{Buffer as q0}from"buffer";import{createCipheriv as Rj,createDecipheriv as Nj,randomBytes as QU}from"crypto";import{closeSync as xU,createReadStream as JE,createWriteStream as Kj,existsSync as a1,fsyncSync as UE,openSync as YE,writeFileSync as Mj}from"fs";import{access as Ij,constants as fE,mkdir as Lj,readdir as s1,rename as EE,stat as Nw,unlink as o1,writeFile as PU}from"fs/promises";import{isAbsolute as yj,join as Kw,resolve as Cj}from"path";import S from"process";import{pipeline as Sj}from"stream/promises";import{createGzip as ZE}from"zlib";import Mw from"process";import M0 from"process";import e1 from"process";import{existsSync as $A}from"fs";import{resolve as bU}from"path";import{existsSync as Vj}from"fs";import{existsSync as Oj,readdirSync as Dj}from"fs";import{extname as iU,resolve as WE}from"path";import _j from"process";import{join as Xj,relative as kj,resolve as hE}from"path";import GA from"process";import{Buffer as R0}from"buffer";import{createCipheriv as Qj,createDecipheriv as xj,randomBytes as cU}from"crypto";import{closeSync as uU,createReadStream as FE,createWriteStream as Pj,existsSync as wA,fsyncSync as BE,openSync as jE,writeFileSync as bj}from"fs";import{access as ij,constants as zE,mkdir as cj,readdir as AA,rename as TE,stat as Iw,unlink as JA,writeFile as nU}from"fs/promises";import{isAbsolute as uj,join as Lw,resolve as nj}from"path";import V from"process";import{pipeline as vj}from"stream/promises";import{createGzip as HE}from"zlib";import yw from"process";import I0 from"process";import YA from"process";import{existsSync as fA}from"fs";import{resolve as tU}from"path";import{existsSync as Z9}from"fs";class DE{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,f=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:f}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!d8($))return!0;return g8($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=d8(A)?g8(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class _E{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),f=performance.now()-J;return this.recordMetric({operation:$,duration:f,timestamp:U,...A}),Y}catch(Y){let f=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:f,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}var jA=new DE,fY=new _E;var mj=Object.defineProperty,dj=($)=>$;function gj($,w){this[$]=dj.bind(null,w)}var lj=($,w)=>{for(var A in w)mj($,A,{get:w[A],enumerable:!0,configurable:!0,set:gj.bind(w,A)})},tj=($,w)=>()=>($&&(w=$($=0)),w),QE={};lj(QE,{withErrorRecovery:()=>bE,tryLoadConfig:()=>Hz,loadConfigWithResult:()=>zz,loadConfig:()=>vE,isRetryableError:()=>Zz,isConfigNotFoundError:()=>Ez,isBunfigError:()=>iE,globalPerformanceMonitor:()=>z1,globalCache:()=>Cw,getEnvOrDefault:()=>Wz,generateConfigTypes:()=>Gz,defaultGeneratedDir:()=>aE,defaultConfigDir:()=>rE,deepMergeWithArrayStrategy:()=>FY,deepMerge:()=>cE,createLibraryConfig:()=>qz,config:()=>Tz,bunfigPlugin:()=>Rz,applyEnvVarsToConfig:()=>h1,TypeGenerationError:()=>AY,SchemaValidationError:()=>j1,PluginError:()=>UY,PerformanceMonitor:()=>ZY,FileSystemError:()=>wY,ErrorFactory:()=>m0,EnvVarError:()=>IA,EnvProcessor:()=>VA,ConfigValidator:()=>BY,ConfigValidationError:()=>eU,ConfigNotFoundError:()=>MA,ConfigMergeError:()=>$Y,ConfigLoader:()=>jY,ConfigLoadError:()=>B1,ConfigFileLoader:()=>OA,ConfigCache:()=>EY,CacheUtils:()=>dE,BunfigError:()=>u$,BrowserConfigError:()=>JY,ArrayMergeStrategies:()=>tE});class EY{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,f=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:f}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!l8($))return!0;return t8($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=l8(A)?t8(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class ZY{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),f=performance.now()-J;return this.recordMetric({operation:$,duration:f,timestamp:U,...A}),Y}catch(Y){let f=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:f,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function pj($,w={}){let J=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return J?`${$}:${J}`:$}function rj($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function aj($){return $.getStats().size*2}function WY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&t(w[0])&&"id"in w[0]&&w[0].id===3&&t(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(t(w)&&t($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(t($)&&"arr"in $&&Array.isArray($.arr)&&t(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&t(w[0])&&t($[0])){let J=[...w];for(let U of $)if(t(U)&&"name"in U){if(!J.find((f)=>t(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(t(U)&&"path"in U){if(!J.find((f)=>t(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>qA(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!t(w)||!t($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(t(U)&&t(A[J]))A[J]=WY(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&t(U[0])&&t(A[J][0])){let Y=[...U];for(let f of A[J])if(t(f)&&"name"in f){if(!Y.find((E)=>t(E)&&("name"in E)&&E.name===f.name))Y.push(f)}else if(t(f)&&"path"in f){if(!Y.find((E)=>t(E)&&("path"in E)&&E.path===f.path))Y.push(f)}else if(!Y.some((Z)=>qA(Z,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function qA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!qA($[A],w[A]))return!1;return!0}if(t($)&&t(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!qA($[U],w[U]))return!1}return!0}return!1}function t($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function sj($,w){if(!kE($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return WY(w,J)}catch{return null}}catch{return null}}async function oj({name:$="",cwd:w,defaultConfig:A}){let J=w||rU.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let f of Y)for(let Z of U){let E=HA(J,`${f}${Z}`),W=await sj(E,A);if(W!==null)return W}try{let f=HA(J,"package.json");if(kE(f)){let E=(await import(f))[$];if(E&&typeof E==="object"&&!Array.isArray(E))try{return WY(A,E)}catch{}}}catch{}return A}function ej($,w={}){let A=TA.cwd();while(A.includes("storage"))A=a8(A,"..");let J=a8(A,$||"");if(w?.relative)return Fj(TA.cwd(),J);return J}async function $z(){try{let $=await oj({name:"clarity",defaultConfig:WA,cwd:TA.cwd(),endpoint:"",headers:{}});return{...WA,...$}}catch{return WA}}function o(){if(K0.env.NODE_ENV==="test"||K0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wz(){if(K0.env.NODE_ENV==="test"||K0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof K0<"u"){let $=K0.type;if($==="renderer"||$==="worker")return!1;return!!(K0.versions&&(K0.versions.node||K0.versions.bun))}return!1}class xE{async format($){let w=await wz(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Rw.pid,hostname:w(),environment:Rw.env.NODE_ENV||"development",platform:Rw.platform,version:Rw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Rw.env.NODE_ENV||Rw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class RA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...sU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new xE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??q$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...hA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...hA};return{...hA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:sU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,Z=1000;while(Y<f)try{try{try{await Hj(this.config.logDirectory,$E.F_OK|$E.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await Gj(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let E=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:v0.from($);try{if(!XU(this.currentLogFile))await kU(this.currentLogFile,"",{mode:420});if(U=e8(this.currentLogFile,"a",420),Tj(U,E,{flag:"a"}),o8(U),U!==void 0)_U(U),U=void 0;if((await Gw(this.currentLogFile)).size===0){if(await kU(this.currentLogFile,E,{flag:"w",mode:420}),(await Gw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let h=W;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(Y<f-1){let F=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(U!==void 0)try{_U(U)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(E){if(Y===f-1){let h=E,F=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),E}Y++;let W=Z*2**(Y-1);await new Promise((h)=>setTimeout(h,W))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 qw(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 qw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return qw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(o())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,E])=>E.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[Z]of U.slice(f))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return DU(16).toString("hex")}generateKey(){return DU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=DU(16),J=Bj("aes-256-gcm",w,A),U=v0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:v0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=AE(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(v0.from(v0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(o())return;let $=await Gw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await p1(this.config.logDirectory),Y=U.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,W)=>{let h=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${f}`;if(await Gw(A).catch(()=>null))try{if(await wE(A,Z),w.compress)try{let E=`${Z}.gz`;await this.compressLogFile(Z,E),await r1(Z)}catch(E){console.error("Error compressing rotated file:",E)}if(Y.length===0&&!U.some((E)=>E.endsWith(".log.1")))try{let E=`${A}.1`;await kU(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await Gw(A).catch(()=>null))await wE(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await p1(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,Z)=>Z.localeCompare(f));for(let f of Y.slice(w.maxFiles))await r1(qw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=s8($),J=zj(w),U=AE();await qj(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),XU(this.currentLogFile))try{let $=e8(this.currentLogFile,"r+");o8($),_U($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!o()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await p1(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await r1(qw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?m.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(f)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let E=q$.stdout.columns||120,W="";if(Y==="warning"||Y==="error")W=`${A} ${U}`;else if(Y==="info"||Y==="success")W=`${A} ${J} ${U}`;else W=`${A} ${J} ${m.cyan(U)}`;if(!f)return W.trim();let h=Z(W).trim().length,F=Z(w).length,j=Math.max(1,E-2-h-F);return`${W.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let Z=Number.parseInt(f,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(f){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 Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,Z;if(w instanceof Error)f=w.message,Z=w.stack;else f=this.formatMessage(w,A);if(this.fancy&&!o()){let W=gE[$],h=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:m.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:f,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:m.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:f,level:$}),console.error(F),Z){let j=Z.split(`
|
|
90
|
+
`);for(let B of j)if(B.trim()&&!B.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:m.gray(` ${B}`),level:$,showTimestamp:!1}))}break}}else if(!o()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),Z)console.error(Z)}if(!this.shouldLog($))return;let E=`${Y} ${this.environment}.${$.toUpperCase()}: ${f}
|
|
91
|
+
`;if(Z)E+=`${Z}
|
|
92
|
+
`;E=E.replace(this.ANSI_PATTERN,""),await this.writeToFile(E)}time($){let w=performance.now();if(this.fancy&&!o()){let A=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:m.blue("◐"),tag:A,message:`${m.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,Z=this.formatConsoleTimestamp(f),W=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)W+=` ${JSON.stringify(A)}`;if(W+=`
|
|
93
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.fancy&&!o()){let h=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:m.green("✓"),tag:h,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!o())console.error(W.trim());await this.writeToFile(W)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new RA(w,{...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(A),A}createReadStream(){if(o())throw Error("createReadStream is not supported in browser environments");if(!XU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return s8(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=v0.isBuffer($)?$:v0.from($,"base64"),U=J.slice(0,16),Y=J.slice(-16),f=J.slice(16,-16),Z=jj("aes-256-gcm",A,U);return Z.setAuthTag(Y),v0.concat([Z.update(f),Z.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return o()}isServerMode(){return!o()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w);if(this.fancy&&!o()){let Y=$.split(`
|
|
94
|
+
`),f=Math.max(...Y.map((h)=>h.length))+2,Z=`┌${"─".repeat(f)}┐`,E=`└${"─".repeat(f)}┘`,W=Y.map((h)=>{let F=" ".repeat(f-h.length-2);return`│ ${h}${F} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:m.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:m.cyan(Z)})),W.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:A,message:m.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:m.cyan(E),showTimestamp:!1}))}else if(!o())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let U=`${J} ${this.environment}.INFO: [BOX] ${$}
|
|
95
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(o())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${m.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();q$.stdin.removeListener("data",A);try{if(typeof q$.stdin.setRawMode==="function")q$.stdin.setRawMode(!1)}catch{}q$.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof q$.stdin.setRawMode==="function")q$.stdin.setRawMode(!0)}catch{}q$.stdin.resume(),q$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,Z=0;if(A=$.replace(f,(E,W)=>{if(W==="%")return"%";if(Z>=w.length)return E;let h=w[Z++];switch(W){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return E}}),Z<w.length)A+=` ${w.slice(Z).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}if(this.fancy&&!o()){let f=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",Z=m.blue("◐");console.error(`${Z} ${f} ${m.cyan(A)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
96
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress($,w=""){if(!this.enabled||!this.fancy||o()||$<=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 A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(f,Z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,f)),Z!==void 0)this.activeProgressBar.message=Z;let E=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,E)},finish:(f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;if(this.activeProgressBar.current=this.activeProgressBar.total,f!==void 0)this.activeProgressBar.message=f;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(f,Z="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;q$.stdout.write(`${"\r".padEnd(q$.stdout.columns||80)}\r`),this.log(Z,f),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||o()||!q$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=m.green("━".repeat(J)),f=m.gray("━".repeat(U)),Z=`[${Y}${f}]`,E=`${A}%`.padStart(4),W=$.message?` ${$.message}`:"",h=w||A===100?m.green("✓"):m.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",j=`\r${h}${F} ${Z} ${E}${W}`,B=q$.stdout.columns||80,H=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${H}`,q$.stdout.write($.lastRenderedLine),w)q$.stdout.write(`
|
|
97
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||o()||!q$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(o()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await p1(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=qw(this.config.logDirectory,J);if($.before)try{if((await Gw(Y)).mtime>=$.before)continue}catch(f){console.error(`Failed to get stats for file ${Y}:`,f);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await r1(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function ZA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&i(w[0])&&"id"in w[0]&&w[0].id===3&&i(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(i(w)&&i($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(i($)&&"arr"in $&&Array.isArray($.arr)&&i(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&i(w[0])&&i($[0])){let J=[...w];for(let U of $)if(i(U)&&"name"in U){if(!J.find((f)=>i(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(i(U)&&"path"in U){if(!J.find((f)=>i(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>NA(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!i(w)||!i($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(i(U)&&i(A[J]))A[J]=ZA(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&i(U[0])&&i(A[J][0])){let Y=[...U];for(let f of A[J])if(i(f)&&"name"in f){if(!Y.find((E)=>i(E)&&("name"in E)&&E.name===f.name))Y.push(f)}else if(i(f)&&"path"in f){if(!Y.find((E)=>i(E)&&("path"in E)&&E.path===f.path))Y.push(f)}else if(!Y.some((Z)=>NA(Z,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function hY($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:ZA($,w);if(Array.isArray($))return A==="replace"?w:ZA($,w);if(!i(w)||!i($))return w;let J={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let Y=w[U],f=J[U];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(f))if(A==="replace")J[U]=Y;else J[U]=ZA(f,Y);else if(i(Y)&&i(f))J[U]=hY(f,Y,A);else J[U]=Y}return J}function NA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!NA($[A],w[A]))return!1;return!0}if(i($)&&i(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!NA($[U],w[U]))return!1}return!0}return!1}function i($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function UA($,w,A="replace"){if(!XE($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return hY(w,U,A)}catch{return null}}catch{return null}}function Az($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,Z=[]){let E={...f};for(let[W,h]of Object.entries(f)){let F=[...Z,W],j=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),B=`${J}_${F.map(j).join("_")}`,H=`${J}_${F.map((T)=>T.toUpperCase()).join("_")}`;if(A)N$.info(`Checking environment variable ${B} for config ${$}.${F.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))E[W]=Y(h,F);else{let T=F1.env[B]||F1.env[H];if(T!==void 0){if(A)N$.info(`Using environment variable ${T?B:H} for config ${$}.${F.join(".")}`);if(typeof h==="number")E[W]=Number(T);else if(typeof h==="boolean")E[W]=T.toLowerCase()==="true";else if(Array.isArray(h))try{let q=JSON.parse(T);if(Array.isArray(q))E[W]=q;else E[W]=T.split(",").map((G)=>G.trim())}catch{E[W]=T.split(",").map((q)=>q.trim())}else E[W]=T}}}return E}return Y(U)}async function Jz({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:U,verbose:Y=!1,checkEnv:f=!0,arrayStrategy:Z="replace"}){let E=f&&typeof U==="object"&&U!==null&&!Array.isArray(U)?Az($,U,Y):U,W=A||F1.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(Y)N$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${W}`);let F=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),B=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],T=Array.from(new Set([W,O$(W,"config"),O$(W,".config"),J?O$(W,J):void 0].filter(Boolean)));for(let q of T){if(Y)N$.info(`Searching for configuration in: ${q}`);let R=[O$(W,"config"),O$(W,".config")].concat(J?[O$(W,J)]:[]).includes(q)?[...F,...j,...B,...H]:[...j,...F,...H,...B];for(let K of R)for(let y of h){let C=O$(q,`${K}${y}`),M=await UA(C,E,Z);if(M!==null){if(Y)N$.success(`Configuration loaded from: ${C}`);return M}}}if($){let q=O$(OU(),".config",$),G=["config",`${$}.config`];if(w)G.push(`${w}.config`);if(Y)N$.info(`Checking user config directory: ${q}`);for(let R of G)for(let K of h){let y=O$(q,`${R}${K}`),C=await UA(y,E,Z);if(C!==null){if(Y)N$.success(`Configuration loaded from user config directory: ${y}`);return C}}}if($){let q=O$(OU(),".config"),G=[`.${$}.config`];if(w)G.push(`.${w}.config`);if(Y)N$.info(`Checking user config directory for dotfile configs: ${q}`);for(let R of G)for(let K of h){let y=O$(q,`${R}${K}`),C=await UA(y,E,Z);if(C!==null){if(Y)N$.success(`Configuration loaded from user config directory dotfile: ${y}`);return C}}}if($){let q=OU(),G=[`.${$}.config`,`.${$}`];if(w)G.push(`.${w}.config`),G.push(`.${w}`);if(Y)N$.info(`Checking user home directory for dotfile configs: ${q}`);for(let R of G)for(let K of h){let y=O$(q,`${R}${K}`),C=await UA(y,E,Z);if(C!==null){if(Y)N$.success(`Configuration loaded from user home directory: ${y}`);return C}}}try{let q=O$(W,"package.json");if(XE(q)){let G=await import(q),R=G[$];if(!R&&w){if(R=G[w],R&&Y)N$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(Y)N$.success(`Configuration loaded from package.json: ${R===G[$]?$:w}`);return hY(E,R,Z)}catch(K){if(Y)N$.warn("Failed to merge package.json config:",K)}}}catch(q){if(Y)N$.warn("Failed to load package.json:",q)}if(Y)N$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return E}function Uz($,w={}){let A=zA.cwd();while(A.includes("storage"))A=r8(A,"..");let J=r8(A,$||"");if(w?.relative)return Wj(zA.cwd(),J);return J}async function Yz(){try{let $=await Jz({name:"clarity",alias:"logging",defaultConfig:FA,cwd:zA.cwd()});return{...FA,...$||{}}}catch{return FA}}function J$(){if(M0.env.NODE_ENV==="test"||M0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fz(){if(M0.env.NODE_ENV==="test"||M0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof M0<"u"){let $=M0.type;if($==="renderer"||$==="worker")return!1;return!!(M0.versions&&(M0.versions.node||M0.versions.bun))}return!1}class PE{async format($){let w=await fz(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Mw.pid,hostname:w(),environment:Mw.env.NODE_ENV||"development",platform:Mw.platform,version:Mw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Mw.env.NODE_ENV||Mw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class KA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...oU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new PE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??S.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...BA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...BA};return{...BA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:oU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!J$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,Z=1000;while(Y<f)try{try{try{await Ij(this.config.logDirectory,fE.F_OK|fE.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await Lj(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let E=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:q0.from($);try{if(!a1(this.currentLogFile))await PU(this.currentLogFile,"",{mode:420});if(U=YE(this.currentLogFile,"a",420),Mj(U,E,{flag:"a"}),UE(U),U!==void 0)xU(U),U=void 0;if((await Nw(this.currentLogFile)).size===0){if(await PU(this.currentLogFile,E,{flag:"w",mode:420}),(await Nw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let h=W;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(Y<f-1){let F=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(U!==void 0)try{xU(U)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(E){if(Y===f-1){let h=E,F=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),E}Y++;let W=Z*2**(Y-1);await new Promise((h)=>setTimeout(h,W))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 Kw(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 Kw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Kw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(J$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,E])=>E.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[Z]of U.slice(f))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return QU(16).toString("hex")}generateKey(){return QU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=QU(16),J=Rj("aes-256-gcm",w,A),U=q0.isBuffer($)?$:q0.from($,"utf8"),Y=J.update(U),f=J.final(),Z=Y.length+f.length,E=J.getAuthTag(),W=q0.allocUnsafe(16+Z+16);return A.copy(W,0),Y.copy(W,16),f.copy(W,16+Y.length),E.copy(W,16+Z),{encrypted:W,iv:A}}async compressData($){return new Promise((w,A)=>{let J=ZE(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(q0.from(q0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(J$())return;if(!this.shouldWriteToFile())return;let $=await Nw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await s1(this.config.logDirectory),Y=U.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,W)=>{let h=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${f}`;if(await Nw(A).catch(()=>null))try{if(await EE(A,Z),w.compress)try{let E=`${Z}.gz`;await this.compressLogFile(Z,E),await o1(Z)}catch(E){console.error("Error compressing rotated file:",E)}if(Y.length===0&&!U.some((E)=>E.endsWith(".log.1")))try{let E=`${A}.1`;await PU(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await Nw(A).catch(()=>null))await EE(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await s1(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,Z)=>Z.localeCompare(f));for(let f of Y.slice(w.maxFiles))await o1(Kw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=JE($),J=Kj(w),U=ZE();await Sj(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),a1(this.currentLogFile))try{let $=YE(this.currentLogFile,"r+");UE($),xU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!J$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await s1(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await o1(Kw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?_.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||J$())return!1;let $=typeof S.env.NO_COLOR<"u",w=S.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof S.stderr<"u"&&S.stderr.isTTY||typeof S.stdout<"u"&&S.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(f)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let E=S.stdout.columns||120,W="";if(Y==="warning"||Y==="error")W=`${A} ${U}`;else if(Y==="info"||Y==="success")W=`${A} ${J} ${U}`;else W=`${A} ${J} ${_.cyan(U)}`;if(!f)return W.trim();let h=Z(W).trim().length,F=Z(w).length,j=Math.max(1,E-2-h-F);return`${W.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let Z=Number.parseInt(f,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(f){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 Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=_.underline(_.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(f)}`,E="\x1B]8;;",W="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>_.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>_.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>_.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>_.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>_.strikethrough(J)),w}supportsHyperlinks(){if(J$())return!1;let $=S.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=S.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(yj(w)||w.startsWith("./")||w.startsWith("../"))w=Cj(w);else return null;return a1(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,Z;if(w instanceof Error)f=w.message,Z=w.stack;else f=this.formatMessage(w,A);let{consoleText:E,fileText:W}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":lE[$],j=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:_.gray(E),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:_.green(E),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.error(B),Z){let H=Z.split(`
|
|
98
|
+
`);for(let T of H)if(T.trim()&&!T.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:_.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!J$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),Z)console.error(Z)}if(!this.shouldLog($))return;let h=`${Y} ${this.environment}.${$.toUpperCase()}: ${W}
|
|
99
|
+
`;if(Z)h+=`${Z}
|
|
100
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress($,w=""){let A={update:(Z,E)=>{},finish:(Z)=>{},interrupt:(Z,E)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!J$()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Z,E)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Z),this.activeProgressBar.total),E!==void 0)this.activeProgressBar.message=E;if(this.shouldStyleConsole()&&!J$()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Z)},interrupt:(Z,E="info")=>{if(!J$()&&S.stdout.isTTY)S.stdout.write(`
|
|
101
|
+
`);if(this[E==="warning"?"warn":E](Z),this.activeProgressBar&&this.shouldStyleConsole()&&!J$()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":_.blue("◐"),tag:A,message:`${_.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,Z=this.formatConsoleTimestamp(f),W=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)W+=` ${JSON.stringify(A)}`;if(W+=`
|
|
102
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":_.green("✓"),tag:h,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!J$())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new KA(w,{...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(A),A}createReadStream(){if(J$())throw Error("createReadStream is not supported in browser environments");if(!a1(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return JE(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=q0.isBuffer($)?$:q0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),Z=Nj("aes-256-gcm",A,U);Z.setAuthTag(Y);let E=Z.update(f),W=Z.final(),h=E.length+W.length,F=q0.allocUnsafe(h);return E.copy(F,0),W.copy(F,E.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return J$()}isServerMode(){return!J$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=U.split(`
|
|
103
|
+
`),E=Math.max(...Z.map((j)=>j.length))+2,W=`┌${"─".repeat(E)}┐`,h=`└${"─".repeat(E)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:_.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:_.cyan(W),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:_.cyan(h),showTimestamp:!1}))}else if(!J$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
104
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(J$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${_.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();S.stdin.removeListener("data",A);try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!1)}catch{}S.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!0)}catch{}S.stdin.resume(),S.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let E=/%([sdijfo%])/g,W=0;if(A=$.replace(E,(h,F)=>{if(F==="%")return"%";if(W>=w.length)return h;let j=w[W++];switch(F){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return h}}),W<w.length)A+=` ${w.slice(W).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${_.blue("◐")} `;console.error(`${W}${E} ${_.cyan(J)}`)}let Z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
105
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!S.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=_.green("━".repeat(J)),f=_.gray("━".repeat(U)),Z=`[${Y}${f}]`,E=`${A}%`.padStart(4),W=$.message?` ${$.message}`:"",h=this.options.showIcons===!1?"":w||A===100?_.green("✓"):_.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${_.gray(this.formatTag(this.name))}`:"",j=`\r${h}${F} ${Z} ${E}${W}`,B=S.stdout.columns||80,H=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${H}`,S.stdout.write($.lastRenderedLine),w)S.stdout.write(`
|
|
106
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||J$()||!S.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(J$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await s1(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=Kw(this.config.logDirectory,J);if($.before)try{if((await Nw(Y)).mtime>=$.before)continue}catch(f){console.error(`Failed to get stats for file ${Y}:`,f);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await o1(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function bE($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let Z=0;Z<=A;Z++)try{return await $()}catch(E){if(f=E instanceof Error?E:Error(String(E)),Z===A||!U(f))break;if(J>0)await new Promise((W)=>setTimeout(W,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}function iE($){return $ instanceof u$}function Ez($){return $ instanceof MA}function Zz($){if(iE($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((A)=>$.message.toLowerCase().includes(A.toLowerCase()))}class VA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:J,useCamelCase:U=!0,useBackwardCompatibility:Y=!0,customParsers:f={},verbose:Z=!1,trackPerformance:E=!0}=A,W=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let h=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],h,{useCamelCase:U,useBackwardCompatibility:Y,customParsers:f,verbose:Z,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(E)return z1.track("applyEnvironmentVariables",W,{configName:$});return W()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],Z=f.map((h)=>this.formatEnvKey(h,J.useCamelCase)),E=`${A}_${Z.join("_")}`,W=J.useBackwardCompatibility?`${A}_${f.map((h)=>h.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,f,A,J);else{let h=e1.env[E]||(W?e1.env[W]:void 0);if(h!==void 0){if(J.verbose){let F=e1.env[E]?E:W}try{$[U]=this.parseEnvironmentValue(h,typeof Y,E,J.customParsers,J.configName)}catch(F){if(F instanceof IA)throw F;throw m0.envVar(E,h,typeof Y,J.configName)}}}}}parseEnvironmentValue($,w,A,J,U){for(let[Y,f]of Object.entries(J))try{return f($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,w))try{return Y.parse($)}catch{throw m0.envVar(A,$,`${w} (via ${Y.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,U]of Object.entries(e1.env))if(J.startsWith(A)&&U!==void 0)w[J]=U;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(U){J.push(`Cannot parse value "${w}" as ${A}: ${U}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:U="text"}=A,Y=J||this.generateEnvPrefix($),f=[];switch(this.extractEnvVarInfo(w,[],Y,f),U){case"markdown":return this.formatAsMarkdown(f,$);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,$)}}extractEnvVarInfo($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],Z=`${A}_${f.map((E)=>this.formatEnvKey(E,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,f,A,J);else J.push({key:Z,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${f.join(".")}`,example:this.generateExample(Y)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
107
107
|
|
|
108
108
|
`;for(let J of $)A+=`${J.key}
|
|
109
109
|
`,A+=` Type: ${J.type}
|
|
@@ -115,25 +115,25 @@ Run \`${this.name??"cli"} --help\` for usage.`;u0.stderr.write(`${Y}${U}${h}
|
|
|
115
115
|
`;A+=`| Variable | Type | Description | Example |
|
|
116
116
|
`,A+=`|----------|------|-------------|----------|
|
|
117
117
|
`;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
|
|
118
|
-
`;return A}}function sj($,w){let A=Xf("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function Vf($,w,A={}){return Df($,w,A,new WeakMap)}function Df($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:h}=A;if(w===null||w===void 0)return Y?$:w;if(h){let Z=h($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return Of($,w,U,J);if(!r$(w)||!r$($))return w;return wz($,w,A,J)}function Of($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return oj($,w);case"smart":return ej($,w,J);default:return w}return w}function oj($,w){let A=[...w];for(let J of $)if(!A.some((U)=>mU(U,J)))A.push(J);return A}function ej($,w,A){if(w.length===0)return $;if($.length===0)return w;if(r$(w[0])&&r$($[0]))return $z($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function $z($,w,A){let J=[...w];for(let U of $){if(!r$(U)){J.push(U);continue}let Y=["id","name","key","path","type"],h=!1;for(let Z of Y)if(Z in U){if(J.find((E)=>r$(E)&&(Z in E)&&E[Z]===U[Z])){h=!0;break}}if(!h)J.push(U)}return J}function wz($,w,A,J){let U=w;if(r$(U)&&J.has(U))return J.get(U);let Y={...$};if(r$(U))J.set(U,Y);for(let h in U){if(!Object.prototype.hasOwnProperty.call(U,h))continue;let Z=U[h],f=Y[h];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){Y[h]=Z;continue}if(r$(Z)&&r$(f))Y[h]=Df(f,Z,A,J);else if(Array.isArray(Z)||Array.isArray(f))Y[h]=Of(f,Z,A.arrayMergeMode||"smart",J);else Y[h]=Z}return Y}function UY($,w,A="replace"){return Vf($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function mU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!mU($[A],w[A]))return!1;return!0}if(r$($)&&r$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!mU($[U],w[U]))return!1}return!0}return!1}function r$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class SA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:h=!0,verbose:Z=!1}=A;if(U){let E=Sw.getWithFileCheck("file",$);if(E){if(Z)console.log(`Configuration loaded from cache: ${$}`);return E}}let f=async()=>{if(!o1($))return null;try{let E=`?t=${Date.now()}`,W=await import($+E),F=W.default||W,j="default"in W,B=Object.keys(W).length>0;if(!j&&!B)throw new W1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new W1($,Error("Configuration must export a valid object"),"unknown");let q={config:UY(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)Sw.setWithFileCheck("file",q,$,Y);return q}catch(E){throw E instanceof Error?m0.configLoad($,E):m0.configLoad($,Error(String(E)))}};if(h)return B1.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let h of this.extensions)U.push(OU(w,`${Y}${h}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return Cf(async()=>{return o1($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!o1($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let h of this.extensions){let Z=OU($,`${Y}${h}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let h of Y)if(this.looksLikeConfigFile(h)){let Z=OU($,h);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){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((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!o1($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class YY{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:h=[],trackPerformance:Z=!0,verbose:f=!1}=A,E=async()=>{let W=[],F=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:h,trackPerformance:Z,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...h],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return W.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:W,warnings:F}}};if(Z)return await B1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!Tj(w))throw new F1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new F1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let h=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(h)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${h}`,expected:Z.join(" or "),actual:h,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let h=0;h<$.length;h++){let Z=A?`${A}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema($[h],w.items,Z,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let h=$;if(Y.validateRequired&&w.required){for(let Z of w.required)if(!(Z in h)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[Z,f]of Object.entries(w.properties))if(Z in h){let E=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(h[Z],f,E,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(h))if(!Z.has(f))U.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let h=this.getValueByPath($,Y.path),Z=this.validateWithRule(h,Y,Y.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(h){J.push({path:Y.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,h]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(h)})}return w}mapTypeScriptType($){switch($.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:bf},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class hY{fileLoader=new SA;envProcessor=new CA;validator=new YY;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...h}=$;try{if(A?.enabled){let f=this.checkCache(h.name||"",h);if(f)return f}let Z;try{Z=await this.loadConfigurationStrategies(h,!0,A)}catch(f){let E=h.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(E)throw f;Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let W=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),F=!W&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),j=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(E&&(j||W))throw f;if(F&&(!E||!j))Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||Y)await this.validateConfiguration(Z.config,U,Y,h.name);if(A?.enabled&&Z)this.cacheResult(h.name||"",Z,A,h);if(J?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:h.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(f);if(J.slowThreshold&&f.duration>J.slowThreshold)J0.warn(`Slow configuration loading detected: ${f.duration}ms for ${h.name}`);Z.metrics=f}return Z}catch(Z){let f=Date.now()-w;throw J0.error(`Configuration loading failed after ${f}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:h,defaultConfig:Z,checkEnv:f=!0,arrayStrategy:E="replace",verbose:W=!1}=$,F=Y||e0.cwd(),j=[],B=await this.loadLocalConfiguration(J,U,F,h,Z,E,W,f,A);if(B)return j.push(...this.getLocalSearchPaths(J,U,F,h)),this.finalizeResult(B,j,f,J,W);let T=await this.loadHomeConfiguration(J,U,Z,E,W,f);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,f,J,W);let H=await this.loadPackageJsonConfiguration(J,U,F,Z,E,W,f);if(H)return j.push(O$(F,"package.json")),this.finalizeResult(H,j,f,J,W);if(j.push(...this.getAllSearchPaths(J,U,F,h)),w)throw m0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,Z,f,W),warnings:[`No configuration file found for "${J}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,h,Z,f){let E=Z?Z1($,U,h):U,W=this.getLocalDirectories(A,J);for(let F of W){if(h)J0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:h,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(B){if(h)J0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let h=Y?Z1($,A,U):A,Z=[O$(Gw(),".config",$),O$(Gw(),".config"),Gw()];for(let f of Z){if(U)J0.info(`Checking home directory: ${f}`);let E=this.fileLoader.generateConfigPaths($,f,w),W=await this.fileLoader.tryLoadFromPaths(E,h,{arrayStrategy:J,verbose:U});if(W){if(U)J0.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,h){let Z=h?Z1($,J,Y):J;try{let f=O$(A,"package.json");if(!nU(f))return null;let E=await import(f),W=E[$],F=$;if(!W&&w)W=E[w],F=w;if(W&&typeof W==="object"&&!Array.isArray(W)){if(Y)J0.success(`Configuration loaded from package.json: ${F}`);return{config:UY(Z,W,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(Y)J0.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:Z1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(U.length>0)throw m0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return Sw.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);Sw.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,O$($,"config"),O$($,".config"),w?O$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(O$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let h of U)Y.push(...this.fileLoader.generateConfigPaths($,h,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[O$(Gw(),".config",$),O$(Gw(),".config"),Gw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function hf($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),J=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||J}async function Az($){return y0.loadConfig({...$,__strictErrorHandling:!0})}async function _f($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await y0.loadConfig($);else J=await y0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let U=J instanceof Error?J.name:"UnknownError",Y=J instanceof Error?J.message:String(J);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||Y.includes("config"))&&$.verbose)J0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let Z=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await y0.applyEnvironmentVariables(Z.name||"",w,!0,Z.verbose||!1))?.config??w;return w}}async function Jz($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await y0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&hf(A)))return(await y0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await y0.loadConfig({...$,cwd:$.cwd||e0.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&hf(w)))return(await y0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function Uz($,w,A="replace"){let J=new SA;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function Z1($,w,A=!1){let J=new CA,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(h,Z=[]){let f={...h};for(let[E,W]of Object.entries(h)){let F=[...Z,E],j=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((H)=>H.toUpperCase()).join("")}`,`${U}_${F.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,T;for(let H of j)if(B=e0.env[H],B!==void 0){T=H;break}if(B!==void 0&&T)if(typeof W==="boolean")f[E]=["true","1","yes"].includes(B.toLowerCase());else if(typeof W==="number"){let H=Number(B);if(!Number.isNaN(H))f[E]=H}else if(Array.isArray(W))try{f[E]=JSON.parse(B)}catch{f[E]=B.split(",").map((H)=>H.trim())}else f[E]=B;else if(W&&typeof W==="object"&&!Array.isArray(W))f[E]=Y(W,F)}return f}return Y(w)}function Yz($){let w=O$(e0.cwd(),$.configDir),A=O$(e0.cwd(),$.generatedDir),J=O$(A,"config-types.ts");if(!nU(b8(J)))tB(b8(J),{recursive:!0,mode:511});let U=nU(w)?pB(w).map((h)=>h.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${Qz}
|
|
118
|
+
`;return A}}function Wz($,w){let A=mE("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function cE($,w,A={}){return uE($,w,A,new WeakMap)}function uE($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:f}=A;if(w===null||w===void 0)return Y?$:w;if(f){let Z=f($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return nE($,w,U,J);if(!r$(w)||!r$($))return w;return jz($,w,A,J)}function nE($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return hz($,w);case"smart":return Fz($,w,J);default:return w}return w}function hz($,w){let A=[...w];for(let J of $)if(!A.some((U)=>aU(U,J)))A.push(J);return A}function Fz($,w,A){if(w.length===0)return $;if($.length===0)return w;if(r$(w[0])&&r$($[0]))return Bz($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function Bz($,w,A){let J=[...w];for(let U of $){if(!r$(U)){J.push(U);continue}let Y=["id","name","key","path","type"],f=!1;for(let Z of Y)if(Z in U){if(J.find((W)=>r$(W)&&(Z in W)&&W[Z]===U[Z])){f=!0;break}}if(!f)J.push(U)}return J}function jz($,w,A,J){let U=w;if(r$(U)&&J.has(U))return J.get(U);let Y={...$};if(r$(U))J.set(U,Y);for(let f in U){if(!Object.prototype.hasOwnProperty.call(U,f))continue;let Z=U[f],E=Y[f];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){Y[f]=Z;continue}if(r$(Z)&&r$(E))Y[f]=uE(E,Z,A,J);else if(Array.isArray(Z)||Array.isArray(E))Y[f]=nE(E,Z,A.arrayMergeMode||"smart",J);else Y[f]=Z}return Y}function FY($,w,A="replace"){return cE($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function aU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!aU($[A],w[A]))return!1;return!0}if(r$($)&&r$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!aU($[U],w[U]))return!1}return!0}return!1}function r$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class OA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:f=!0,verbose:Z=!1}=A;if(U){let W=Cw.getWithFileCheck("file",$);if(W){if(Z)console.log(`Configuration loaded from cache: ${$}`);return W}}let E=async()=>{if(!$A($))return null;try{let W=`?t=${Date.now()}`,h=await import($+W),F=h.default||h,j="default"in h,B=Object.keys(h).length>0;if(!j&&!B)throw new B1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new B1($,Error("Configuration must export a valid object"),"unknown");let q={config:FY(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)Cw.setWithFileCheck("file",q,$,Y);return q}catch(W){throw W instanceof Error?m0.configLoad($,W):m0.configLoad($,Error(String(W)))}};if(f)return z1.track("loadFromPath",E,{path:$});return E()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let f of this.extensions)U.push(bU(w,`${Y}${f}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return bE(async()=>{return $A($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!$A($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let Z=bU($,`${Y}${f}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let f of Y)if(this.looksLikeConfigFile(f)){let Z=bU($,f);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){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((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!$A($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class BY{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:Z=!0,verbose:E=!1}=A,W=async()=>{let h=[],F=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:Z,verbose:E};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return h.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:h,warnings:F}}};if(Z)return await z1.track("validateConfiguration",W);return W()}async validateWithSchemaFile($,w,A){try{if(!Vj(w))throw new j1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new j1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let f=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(f)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${f}`,expected:Z.join(" or "),actual:f,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let f=0;f<$.length;f++){let Z=A?`${A}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema($[f],w.items,Z,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let f=$;if(Y.validateRequired&&w.required){for(let Z of w.required)if(!(Z in f)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[Z,E]of Object.entries(w.properties))if(Z in f){let W=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(f[Z],E,W,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let E of Object.keys(f))if(!Z.has(E))U.push({path:A?`${A}.${E}`:E,message:`Additional property '${E}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let f=this.getValueByPath($,Y.path),Z=this.validateWithRule(f,Y,Y.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(f){J.push({path:Y.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,f]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(f)})}return w}mapTypeScriptType($){switch($.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:pE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class jY{fileLoader=new OA;envProcessor=new VA;validator=new BY;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...f}=$;try{if(A?.enabled){let E=this.checkCache(f.name||"",f);if(E)return E}let Z;try{Z=await this.loadConfigurationStrategies(f,!0,A)}catch(E){let W=f.__strictErrorHandling;if(E instanceof Error&&E.name==="ConfigNotFoundError"){if(W)throw E;Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(E instanceof Error&&E.name==="ConfigLoadError"){let h=E.message.includes("EACCES")||E.message.includes("EPERM")||E.message.includes("permission denied"),F=!h&&(E.message.includes("syntax")||E.message.includes("Expected")||E.message.includes("Unexpected")||E.message.includes("BuildMessage")||E.message.includes("errors building")),j=E.message.includes("Configuration must export a valid object")||E.message.includes("Configuration file is empty and exports nothing");if(W&&(j||h))throw E;if(F&&(!W||!j))Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!W)Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${E.message}`]};else throw E}else Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${E instanceof Error?E.message:String(E)}`]}}if(U||Y)await this.validateConfiguration(Z.config,U,Y,f.name);if(A?.enabled&&Z)this.cacheResult(f.name||"",Z,A,f);if(J?.enabled){let E={operation:"loadConfig",duration:Date.now()-w,configName:f.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(E);if(J.slowThreshold&&E.duration>J.slowThreshold)J0.warn(`Slow configuration loading detected: ${E.duration}ms for ${f.name}`);Z.metrics=E}return Z}catch(Z){let E=Date.now()-w;throw J0.error(`Configuration loading failed after ${E}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:f,defaultConfig:Z,checkEnv:E=!0,arrayStrategy:W="replace",verbose:h=!1}=$,F=Y||e0.cwd(),j=[],B=await this.loadLocalConfiguration(J,U,F,f,Z,W,h,E,A);if(B)return j.push(...this.getLocalSearchPaths(J,U,F,f)),this.finalizeResult(B,j,E,J,h);let H=await this.loadHomeConfiguration(J,U,Z,W,h,E);if(H)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(H,j,E,J,h);let T=await this.loadPackageJsonConfiguration(J,U,F,Z,W,h,E);if(T)return j.push(D$(F,"package.json")),this.finalizeResult(T,j,E,J,h);if(j.push(...this.getAllSearchPaths(J,U,F,f)),w)throw m0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,Z,E,h),warnings:[`No configuration file found for "${J}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,Z,E){let W=Z?h1($,U,f):U,h=this.getLocalDirectories(A,J);for(let F of h){if(f)J0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,W,{arrayStrategy:Y,verbose:f,cacheTtl:E?.ttl,useCache:!E?.ttl||E.ttl>100});if(B){if(f)J0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?h1($,A,U):A,Z=[D$(Hw(),".config",$),D$(Hw(),".config"),Hw()];for(let E of Z){if(U)J0.info(`Checking home directory: ${E}`);let W=this.fileLoader.generateConfigPaths($,E,w),h=await this.fileLoader.tryLoadFromPaths(W,f,{arrayStrategy:J,verbose:U});if(h){if(U)J0.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let Z=f?h1($,J,Y):J;try{let E=D$(A,"package.json");if(!pU(E))return null;let W=await import(E),h=W[$],F=$;if(!h&&w)h=W[w],F=w;if(h&&typeof h==="object"&&!Array.isArray(h)){if(Y)J0.success(`Configuration loaded from package.json: ${F}`);return{config:FY(Z,h,U),source:{type:"package.json",path:E,priority:30,timestamp:new Date}}}}catch(E){if(Y)J0.warn("Failed to load package.json:",[E instanceof Error?E:Error(String(E))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:h1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(U.length>0)throw m0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return Cw.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);Cw.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,D$($,"config"),D$($,".config"),w?D$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(D$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let f of U)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[D$(Hw(),".config",$),D$(Hw(),".config"),Hw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function GE($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),J=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||J}async function zz($){return L0.loadConfig({...$,__strictErrorHandling:!0})}async function vE($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await L0.loadConfig($);else J=await L0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let U=J instanceof Error?J.name:"UnknownError",Y=J instanceof Error?J.message:String(J);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||Y.includes("config"))&&$.verbose)J0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let Z=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await L0.applyEnvironmentVariables(Z.name||"",w,!0,Z.verbose||!1))?.config??w;return w}}async function Tz($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await L0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&GE(A)))return(await L0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await L0.loadConfig({...$,cwd:$.cwd||e0.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&GE(w)))return(await L0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function Hz($,w,A="replace"){let J=new OA;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function h1($,w,A=!1){let J=new VA,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,Z=[]){let E={...f};for(let[W,h]of Object.entries(f)){let F=[...Z,W],j=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((T)=>T.toUpperCase()).join("")}`,`${U}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,H;for(let T of j)if(B=e0.env[T],B!==void 0){H=T;break}if(B!==void 0&&H)if(typeof h==="boolean")E[W]=["true","1","yes"].includes(B.toLowerCase());else if(typeof h==="number"){let T=Number(B);if(!Number.isNaN(T))E[W]=T}else if(Array.isArray(h))try{E[W]=JSON.parse(B)}catch{E[W]=B.split(",").map((T)=>T.trim())}else E[W]=B;else if(h&&typeof h==="object"&&!Array.isArray(h))E[W]=Y(h,F)}return E}return Y(w)}function Gz($){let w=D$(e0.cwd(),$.configDir),A=D$(e0.cwd(),$.generatedDir),J=D$(A,"config-types.ts");if(!pU(p8(J)))Yj(p8(J),{recursive:!0,mode:511});let U=pU(w)?fj(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${lz}
|
|
119
119
|
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
120
|
-
`;
|
|
121
|
-
${U.map((
|
|
120
|
+
`;Ej(J,Y,{mode:438})}function qz($){let w=null,A=null,J=()=>{if(!A)A=vE($).then((Y)=>{return w=Y,Y},(Y)=>{let f="defaultConfig"in $?$.defaultConfig:{};if(w=f,"verbose"in $&&$.verbose)J0.warn("Config loading failed, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);return f});return A},U="defaultConfig"in $?$.defaultConfig:{};return w=U,J(),new Proxy({},{get(Y,f){if(w)return w[f];let Z=U[f];return J(),Z},has(Y,f){return f in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(Y,f){return Object.getOwnPropertyDescriptor(w||U,f)},set(Y,f,Z){if(!w)w={...U};return w[f]=Z,!0}})}function Rz($){let w=WE(_j.cwd(),$?.configDir||"./config");function A(){if(!Oj(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),Y=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],f=Dj(w).filter((E)=>U.has(iU(E))).map((E)=>({base:E.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:E})),Z=new Map;for(let{base:E,file:W}of f){let h=iU(W).toLowerCase(),F=Z.get(E);if(!F){Z.set(E,W);continue}let j=iU(F).toLowerCase();if(Y.indexOf(h)<Y.indexOf(j))Z.set(E,W)}return Array.from(Z.entries()).map(([E,W])=>({base:E,file:W})).sort((E,W)=>E.base.localeCompare(W.base))}function J(){let U=A(),Y=U.map((W)=>W.base),f=Y.length?Y.map((W)=>`'${W}'`).join(" | "):"string",Z=U.length?`{
|
|
121
|
+
${U.map((W)=>{let h=WE(w,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${h}').default`}).join(`,
|
|
122
122
|
`)}
|
|
123
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
123
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${f}
|
|
124
124
|
export type ConfigByName = ${Z}
|
|
125
125
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
126
126
|
export type ConfigOf = Config
|
|
127
|
-
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}var Xf,Sw,B1,kf,Zz,Ez,ff,fA,dU,R$,m,Wz,Zf,Fz,Ef,Bz,jz,xU,zz,Wf,Ff,PU,Hz,Tz,Gz,qz,ZA,Qf,Rz,N$,Nz,Kz,Bf,EA,gU,U$,_,Mz,jf,Iz,zf,yz,Lz,bU,Cz,Hf,Tf,Sz,iU,Vz,Dz,Oz,_z,Xz,WA,xf,kz,Qz="0.15.6",u$,NA,W1,lU,tU,KA,pU,rU,F1,aU,sU,m0,Pf,bf,J0,y0,cf,uf,xz=xj(async()=>{Xf=import.meta.require,Sw=new $Y,B1=new wY,kf={createKey:Pj,isEquivalent:bj,estimateMemoryUsage:ij},Zz=zA(vU.cwd(),"config"),Ez=zA(vU.cwd(),"src/generated"),ff=jA.env.CLARITY_LOG_DIR||oB(nj(),"logs"),fA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ff,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},dU=await vj(),R$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},m=R$,Wz=R$.red,Zf=R$.green,Fz=R$.yellow,Ef=R$.blue,Bz=R$.magenta,jz=R$.cyan,xU=R$.white,zz=R$.gray,Wf=R$.bgRed,Ff=R$.bgYellow,PU=R$.bold,Hz=R$.dim,Tz=R$.italic,Gz=R$.underline,qz=R$.reset,ZA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Qf={debug:"\uD83D\uDD0D",info:Ef("ℹ"),success:Zf("✓"),warning:Ff(xU(PU(" WARN "))),error:Wf(xU(PU(" ERROR ")))},Rz=new GA("stacks"),N$=new GA("bunfig",{showTags:!0}),Nz=D$(E1.cwd(),"config"),Kz=D$(E1.cwd(),"src/generated"),Bf=BA.env.CLARITY_LOG_DIR||aB(lj(),"logs"),EA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Bf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},gU=await tj(),U$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},_=U$,Mz=U$.red,jf=U$.green,Iz=U$.yellow,zf=U$.blue,yz=U$.magenta,Lz=U$.cyan,bU=U$.white,Cz=U$.gray,Hf=U$.bgRed,Tf=U$.bgYellow,Sz=U$.bgGray,iU=U$.bold,Vz=U$.dim,Dz=U$.italic,Oz=U$.underline,_z=U$.strikethrough,Xz=U$.reset,WA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xf={debug:"\uD83D\uDD0D",info:zf("ℹ"),success:jf("✓"),warning:Tf(bU(iU(" WARN "))),error:Hf(bU(iU(" ERROR ")))},kz=new RA("stacks"),u$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,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 w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,J])=>`${A}: ${J}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},NA=class extends u${code="CONFIG_NOT_FOUND";constructor(w,A,J){let U=J?` or alias "${J}"`:"";super(`Configuration "${w}"${U} not found`,{configName:w,alias:J,searchPaths:A,searchPathCount:A.length})}},W1=class extends u${code="CONFIG_LOAD_ERROR";constructor(w,A,J){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},lU=class extends u${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},tU=class extends u${code="CONFIG_MERGE_ERROR";constructor(w,A,J,U){super(`Failed to merge configuration from "${w}" with "${A}": ${J.message}`,{sourcePath:w,targetPath:A,configName:U,originalError:J.name,originalMessage:J.message});this.cause=J}},KA=class extends u${code="ENV_VAR_ERROR";constructor(w,A,J,U){super(`Failed to parse environment variable "${w}" with value "${A}" as ${J}`,{envKey:w,envValue:A,expectedType:J,configName:U})}},pU=class extends u${code="FILE_SYSTEM_ERROR";constructor(w,A,J){super(`File system ${w} failed for "${A}": ${J.message}`,{operation:w,path:A,originalError:J.name,originalMessage:J.message});this.cause=J}},rU=class extends u${code="TYPE_GENERATION_ERROR";constructor(w,A,J){super(`Failed to generate types from "${w}" to "${A}": ${J.message}`,{configDir:w,outputPath:A,originalError:J.name,originalMessage:J.message});this.cause=J}},F1=class extends u${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,J){super(`Schema validation failed${J?` for config "${J}"`:""}`,{schemaPath:w,configName:J,validationErrors:A,errorCount:A.length})}},aU=class extends u${code="BROWSER_CONFIG_ERROR";constructor(w,A,J,U){super(`Failed to fetch configuration from "${w}": ${A} ${J}`,{endpoint:w,status:A,statusText:J,configName:U})}},sU=class extends u${code="PLUGIN_ERROR";constructor(w,A,J){super(`Plugin "${w}" failed during ${A}: ${J.message}`,{pluginName:w,operation:A,originalError:J.name,originalMessage:J.message});this.cause=J}},m0={configNotFound($,w,A){return new NA($,w,A)},configLoad($,w,A){return new W1($,w,A)},configValidation($,w,A){return new lU($,w,A)},configMerge($,w,A,J){return new tU($,w,A,J)},envVar($,w,A,J){return new KA($,w,A,J)},fileSystem($,w,A){return new pU($,w,A)},typeGeneration($,w,A){return new rU($,w,A)},schemaValidation($,w,A){return new F1($,w,A)},browserConfig($,w,A,J){return new aU($,w,A,J)},plugin($,w,A){return new sU($,w,A)}},Pf={replace:"replace",concat:"concat",smart:"smart"},bf=/^https?:\/\//,J0=new RA("bunfig",{showTags:!0}),y0=new hY,cf=O$(e0.cwd(),"config"),uf=O$(e0.cwd(),"src/generated")});function Pz($,w={}){let A=HA.cwd();while(A.includes("storage"))A=e8(A,"..");let J=e8(A,$||"");if(w?.relative)return Kj(HA.cwd(),J);return J}var bz=HA.env.CLARITY_LOG_DIR||Nj(Pz(),"logs"),nf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:bz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},MA={...nf},tq=(async()=>{try{let{loadConfig:$}=await xz().then(()=>If),w=await $({name:"clarity",alias:"logging",defaultConfig:nf,cwd:HA.cwd()});if(w)Object.assign(MA,w)}catch{}return MA})();function Y$(){if(I0.env.NODE_ENV==="test"||I0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function iz(){if(I0.env.NODE_ENV==="test"||I0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof I0<"u"){let $=I0.type;if($==="renderer"||$==="worker")return!1;return!!(I0.versions&&(I0.versions.node||I0.versions.bun))}return!1}class vf{async format($){let w=await iz(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Cw.pid,hostname:w(),environment:Cw.env.NODE_ENV||"development",platform:Cw.platform,version:Cw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Cw.env.NODE_ENV||Cw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var j$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},Q=j$,pq=j$.red,cz=j$.green,rq=j$.yellow,uz=j$.blue,aq=j$.magenta,sq=j$.cyan,Gf=j$.white,oq=j$.gray,nz=j$.bgRed,vz=j$.bgYellow,eq=j$.bgGray,qf=j$.bold,$6=j$.dim,w6=j$.italic,A6=j$.underline,J6=j$.strikethrough,U6=j$.reset,cU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},mz={debug:"\uD83D\uDD0D",info:uz("ℹ"),success:cz("✓"),warning:vz(Gf(qf(" WARN "))),error:nz(Gf(qf(" ERROR ")))};class VA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...MA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new vf,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??V.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...cU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...cU};return{...cU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:MA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!Y$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,h=3,Z=1000;while(Y<h)try{try{try{await Cj(this.config.logDirectory,Jf.F_OK|Jf.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Sj(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:R0.from($);try{if(!e1(this.currentLogFile))await QU(this.currentLogFile,"",{mode:420});if(U=Af(this.currentLogFile,"a",420),Lj(U,f,{flag:"a"}),wf(U),U!==void 0)kU(U),U=void 0;if((await yw(this.currentLogFile)).size===0){if(await QU(this.currentLogFile,f,{flag:"w",mode:420}),(await yw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(Y<h-1){let F=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${h}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(U!==void 0)try{kU(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(f){if(Y===h-1){let W=f,F=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),f}Y++;let E=Z*2**(Y-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 Lw(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 Lw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Lw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(Y$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,f])=>f.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,h=Math.max(1,Y);if(U.length>h)for(let[Z]of U.slice(h))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return XU(16).toString("hex")}generateKey(){return XU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=XU(16),J=Mj("aes-256-gcm",w,A),U=R0.isBuffer($)?$:R0.from($,"utf8"),Y=J.update(U),h=J.final(),Z=Y.length+h.length,f=J.getAuthTag(),E=R0.allocUnsafe(16+Z+16);return A.copy(E,0),Y.copy(E,16),h.copy(E,16+Y.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=Yf(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(R0.from(R0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(Y$())return;if(!this.shouldWriteToFile())return;let $=await yw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await $A(this.config.logDirectory),Y=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),h=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${h}`;if(await yw(A).catch(()=>null))try{if(await Uf(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await wA(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(Y.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await QU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await yw(A).catch(()=>null))await Uf(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await $A(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,Z)=>Z.localeCompare(h));for(let h of Y.slice(w.maxFiles))await wA(Lw(this.config.logDirectory,h))}}}async compressLogFile($,w){let A=$f($),J=yj(w),U=Yf();await Oj(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),e1(this.currentLogFile))try{let $=Af(this.currentLogFile,"r+");wf($),kU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!Y$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await $A(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await wA(Lw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?Q.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Y$())return!1;let $=typeof V.env.NO_COLOR<"u",w=V.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof V.stderr<"u"&&V.stderr.isTTY||typeof V.stdout<"u"&&V.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:h=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(h)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let f=V.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${Q.cyan(U)}`;if(!h)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,h)=>{let Z=Number.parseInt(h,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,h)=>{if(h==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(h){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=Q.underline(Q.blue(J)),h=this.toAbsoluteFilePath(U);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(h)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>Q.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>Q.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>Q.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>Q.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>Q.strikethrough(J)),w}supportsHyperlinks(){if(Y$())return!1;let $=V.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=V.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(Vj(w)||w.startsWith("./")||w.startsWith("../"))w=Dj(w);else return null;return e1(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),h,Z;if(w instanceof Error)h=w.message,Z=w.stack;else h=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":mz[$],j=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:Q.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:Q.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
|
|
128
|
-
`);for(let
|
|
129
|
-
`;if(Z)
|
|
130
|
-
`;if(
|
|
131
|
-
`);if(this[
|
|
132
|
-
`,
|
|
133
|
-
`),
|
|
134
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
135
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!V.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=Q.green("━".repeat(J)),
|
|
136
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Y$()||!V.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(Y$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await
|
|
127
|
+
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}var mE,Cw,z1,dE,Nz,Kz,qE,WA,sU,R$,m,Mz,RE,Iz,NE,Lz,yz,vU,Cz,KE,ME,mU,Sz,Vz,Oz,Dz,hA,gE,_z,N$,Xz,kz,IE,FA,oU,U$,_,Qz,LE,xz,yE,Pz,bz,dU,iz,CE,SE,cz,gU,uz,nz,vz,mz,dz,BA,lE,gz,lz="0.15.6",u$,MA,B1,eU,$Y,IA,wY,AY,j1,JY,UY,m0,tE,pE,J0,L0,rE,aE,tz=tj(async()=>{mE=import.meta.require,Cw=new EY,z1=new ZY,dE={createKey:pj,isEquivalent:rj,estimateMemoryUsage:aj},Nz=HA(rU.cwd(),"config"),Kz=HA(rU.cwd(),"src/generated"),qE=TA.env.CLARITY_LOG_DIR||hj(ej(),"logs"),WA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:qE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},sU=await $z(),R$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},m=R$,Mz=R$.red,RE=R$.green,Iz=R$.yellow,NE=R$.blue,Lz=R$.magenta,yz=R$.cyan,vU=R$.white,Cz=R$.gray,KE=R$.bgRed,ME=R$.bgYellow,mU=R$.bold,Sz=R$.dim,Vz=R$.italic,Oz=R$.underline,Dz=R$.reset,hA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},gE={debug:"\uD83D\uDD0D",info:NE("ℹ"),success:RE("✓"),warning:ME(vU(mU(" WARN "))),error:KE(vU(mU(" ERROR ")))},_z=new RA("stacks"),N$=new RA("bunfig",{showTags:!0}),Xz=O$(F1.cwd(),"config"),kz=O$(F1.cwd(),"src/generated"),IE=zA.env.CLARITY_LOG_DIR||Zj(Uz(),"logs"),FA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:IE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},oU=await Yz(),U$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},_=U$,Qz=U$.red,LE=U$.green,xz=U$.yellow,yE=U$.blue,Pz=U$.magenta,bz=U$.cyan,dU=U$.white,iz=U$.gray,CE=U$.bgRed,SE=U$.bgYellow,cz=U$.bgGray,gU=U$.bold,uz=U$.dim,nz=U$.italic,vz=U$.underline,mz=U$.strikethrough,dz=U$.reset,BA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lE={debug:"\uD83D\uDD0D",info:yE("ℹ"),success:LE("✓"),warning:SE(dU(gU(" WARN "))),error:CE(dU(gU(" ERROR ")))},gz=new KA("stacks"),u$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,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 w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,J])=>`${A}: ${J}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},MA=class extends u${code="CONFIG_NOT_FOUND";constructor(w,A,J){let U=J?` or alias "${J}"`:"";super(`Configuration "${w}"${U} not found`,{configName:w,alias:J,searchPaths:A,searchPathCount:A.length})}},B1=class extends u${code="CONFIG_LOAD_ERROR";constructor(w,A,J){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},eU=class extends u${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},$Y=class extends u${code="CONFIG_MERGE_ERROR";constructor(w,A,J,U){super(`Failed to merge configuration from "${w}" with "${A}": ${J.message}`,{sourcePath:w,targetPath:A,configName:U,originalError:J.name,originalMessage:J.message});this.cause=J}},IA=class extends u${code="ENV_VAR_ERROR";constructor(w,A,J,U){super(`Failed to parse environment variable "${w}" with value "${A}" as ${J}`,{envKey:w,envValue:A,expectedType:J,configName:U})}},wY=class extends u${code="FILE_SYSTEM_ERROR";constructor(w,A,J){super(`File system ${w} failed for "${A}": ${J.message}`,{operation:w,path:A,originalError:J.name,originalMessage:J.message});this.cause=J}},AY=class extends u${code="TYPE_GENERATION_ERROR";constructor(w,A,J){super(`Failed to generate types from "${w}" to "${A}": ${J.message}`,{configDir:w,outputPath:A,originalError:J.name,originalMessage:J.message});this.cause=J}},j1=class extends u${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,J){super(`Schema validation failed${J?` for config "${J}"`:""}`,{schemaPath:w,configName:J,validationErrors:A,errorCount:A.length})}},JY=class extends u${code="BROWSER_CONFIG_ERROR";constructor(w,A,J,U){super(`Failed to fetch configuration from "${w}": ${A} ${J}`,{endpoint:w,status:A,statusText:J,configName:U})}},UY=class extends u${code="PLUGIN_ERROR";constructor(w,A,J){super(`Plugin "${w}" failed during ${A}: ${J.message}`,{pluginName:w,operation:A,originalError:J.name,originalMessage:J.message});this.cause=J}},m0={configNotFound($,w,A){return new MA($,w,A)},configLoad($,w,A){return new B1($,w,A)},configValidation($,w,A){return new eU($,w,A)},configMerge($,w,A,J){return new $Y($,w,A,J)},envVar($,w,A,J){return new IA($,w,A,J)},fileSystem($,w,A){return new wY($,w,A)},typeGeneration($,w,A){return new AY($,w,A)},schemaValidation($,w,A){return new j1($,w,A)},browserConfig($,w,A,J){return new JY($,w,A,J)},plugin($,w,A){return new UY($,w,A)}},tE={replace:"replace",concat:"concat",smart:"smart"},pE=/^https?:\/\//,J0=new KA("bunfig",{showTags:!0}),L0=new jY,rE=D$(e0.cwd(),"config"),aE=D$(e0.cwd(),"src/generated")});function pz($,w={}){let A=GA.cwd();while(A.includes("storage"))A=hE(A,"..");let J=hE(A,$||"");if(w?.relative)return kj(GA.cwd(),J);return J}var rz=GA.env.CLARITY_LOG_DIR||Xj(pz(),"logs"),sE={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:rz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},LA={...sE},W6=(async()=>{try{let{loadConfig:$}=await tz().then(()=>QE),w=await $({name:"clarity",alias:"logging",defaultConfig:sE,cwd:GA.cwd()});if(w)Object.assign(LA,w)}catch{}return LA})();function Y$(){if(I0.env.NODE_ENV==="test"||I0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function az(){if(I0.env.NODE_ENV==="test"||I0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof I0<"u"){let $=I0.type;if($==="renderer"||$==="worker")return!1;return!!(I0.versions&&(I0.versions.node||I0.versions.bun))}return!1}class oE{async format($){let w=await az(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:yw.pid,hostname:w(),environment:yw.env.NODE_ENV||"development",platform:yw.platform,version:yw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:yw.env.NODE_ENV||yw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var z$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},Q=z$,h6=z$.red,sz=z$.green,F6=z$.yellow,oz=z$.blue,B6=z$.magenta,j6=z$.cyan,VE=z$.white,z6=z$.gray,ez=z$.bgRed,$9=z$.bgYellow,T6=z$.bgGray,OE=z$.bold,H6=z$.dim,G6=z$.italic,q6=z$.underline,R6=z$.strikethrough,N6=z$.reset,lU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},w9={debug:"\uD83D\uDD0D",info:oz("ℹ"),success:sz("✓"),warning:$9(VE(OE(" WARN "))),error:ez(VE(OE(" ERROR ")))};class DA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...LA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new oE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??V.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...lU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...lU};return{...lU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:LA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!Y$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,Z=1000;while(Y<f)try{try{try{await ij(this.config.logDirectory,zE.F_OK|zE.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await cj(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let E=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:R0.from($);try{if(!wA(this.currentLogFile))await nU(this.currentLogFile,"",{mode:420});if(U=jE(this.currentLogFile,"a",420),bj(U,E,{flag:"a"}),BE(U),U!==void 0)uU(U),U=void 0;if((await Iw(this.currentLogFile)).size===0){if(await nU(this.currentLogFile,E,{flag:"w",mode:420}),(await Iw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let h=W;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(Y<f-1){let F=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let j=Z*2**Y;await new Promise((B)=>setTimeout(B,j)),Y++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(U!==void 0)try{uU(U)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(E){if(Y===f-1){let h=E,F=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),E}Y++;let W=Z*2**(Y-1);await new Promise((h)=>setTimeout(h,W))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 Lw(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 Lw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Lw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(Y$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,Z],[,E])=>E.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[Z]of U.slice(f))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return cU(16).toString("hex")}generateKey(){return cU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=cU(16),J=Qj("aes-256-gcm",w,A),U=R0.isBuffer($)?$:R0.from($,"utf8"),Y=J.update(U),f=J.final(),Z=Y.length+f.length,E=J.getAuthTag(),W=R0.allocUnsafe(16+Z+16);return A.copy(W,0),Y.copy(W,16),f.copy(W,16+Y.length),E.copy(W,16+Z),{encrypted:W,iv:A}}async compressData($){return new Promise((w,A)=>{let J=HE(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(R0.from(R0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(Y$())return;if(!this.shouldWriteToFile())return;let $=await Iw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await AA(this.config.logDirectory),Y=U.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,W)=>{let h=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${f}`;if(await Iw(A).catch(()=>null))try{if(await TE(A,Z),w.compress)try{let E=`${Z}.gz`;await this.compressLogFile(Z,E),await JA(Z)}catch(E){console.error("Error compressing rotated file:",E)}if(Y.length===0&&!U.some((E)=>E.endsWith(".log.1")))try{let E=`${A}.1`;await nU(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await Iw(A).catch(()=>null))await TE(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await AA(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,Z)=>Z.localeCompare(f));for(let f of Y.slice(w.maxFiles))await JA(Lw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=FE($),J=Pj(w),U=HE();await vj(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),wA(this.currentLogFile))try{let $=jE(this.currentLogFile,"r+");BE($),uU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!Y$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await AA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await JA(Lw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?Q.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Y$())return!1;let $=typeof V.env.NO_COLOR<"u",w=V.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof V.stderr<"u"&&V.stderr.isTTY||typeof V.stdout<"u"&&V.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(f)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let E=V.stdout.columns||120,W="";if(Y==="warning"||Y==="error")W=`${A} ${U}`;else if(Y==="info"||Y==="success")W=`${A} ${J} ${U}`;else W=`${A} ${J} ${Q.cyan(U)}`;if(!f)return W.trim();let h=Z(W).trim().length,F=Z(w).length,j=Math.max(1,E-2-h-F);return`${W.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let Z=Number.parseInt(f,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(f){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 Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=Q.underline(Q.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(f)}`,E="\x1B]8;;",W="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>Q.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>Q.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>Q.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>Q.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>Q.strikethrough(J)),w}supportsHyperlinks(){if(Y$())return!1;let $=V.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=V.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(uj(w)||w.startsWith("./")||w.startsWith("../"))w=nj(w);else return null;return wA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,Z;if(w instanceof Error)f=w.message,Z=w.stack;else f=this.formatMessage(w,A);let{consoleText:E,fileText:W}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":w9[$],j=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:Q.gray(E),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:Q.green(E),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.error(B),Z){let H=Z.split(`
|
|
128
|
+
`);for(let T of H)if(T.trim()&&!T.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:Q.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!Y$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),Z)console.error(Z)}let h=`${Y} ${this.environment}.${$.toUpperCase()}: ${W}
|
|
129
|
+
`;if(Z)h+=`${Z}
|
|
130
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress($,w=""){let A={update:(Z,E)=>{},finish:(Z)=>{},interrupt:(Z,E)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!Y$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Z,E)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Z),this.activeProgressBar.total),E!==void 0)this.activeProgressBar.message=E;if(this.shouldStyleConsole()&&!Y$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Z)},interrupt:(Z,E="info")=>{if(!Y$()&&V.stdout.isTTY)V.stdout.write(`
|
|
131
|
+
`);if(this[E==="warning"?"warn":E](Z),this.activeProgressBar&&this.shouldStyleConsole()&&!Y$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":Q.blue("◐"),tag:A,message:`${Q.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,Z=this.formatConsoleTimestamp(f),W=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)W+=` ${JSON.stringify(A)}`;if(W+=`
|
|
132
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":Q.green("✓"),tag:h,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!Y$())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new DA(w,{...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(A),A}createReadStream(){if(Y$())throw Error("createReadStream is not supported in browser environments");if(!wA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return FE(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=R0.isBuffer($)?$:R0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),Z=xj("aes-256-gcm",A,U);Z.setAuthTag(Y);let E=Z.update(f),W=Z.final(),h=E.length+W.length,F=R0.allocUnsafe(h);return E.copy(F,0),W.copy(F,E.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Y$()}isServerMode(){return!Y$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=U.split(`
|
|
133
|
+
`),E=Math.max(...Z.map((j)=>j.length))+2,W=`┌${"─".repeat(E)}┐`,h=`└${"─".repeat(E)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:Q.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:Q.cyan(W),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:Q.cyan(h),showTimestamp:!1}))}else if(!Y$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
134
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(Y$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${Q.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();V.stdin.removeListener("data",A);try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!1)}catch{}V.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!0)}catch{}V.stdin.resume(),V.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let E=/%([sdijfo%])/g,W=0;if(A=$.replace(E,(h,F)=>{if(F==="%")return"%";if(W>=w.length)return h;let j=w[W++];switch(F){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return h}}),W<w.length)A+=` ${w.slice(W).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${Q.blue("◐")} `;console.error(`${W}${E} ${Q.cyan(J)}`)}let Z=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
135
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!V.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=Q.green("━".repeat(J)),f=Q.gray("━".repeat(U)),Z=`[${Y}${f}]`,E=`${A}%`.padStart(4),W=$.message?` ${$.message}`:"",h=this.options.showIcons===!1?"":w||A===100?Q.green("✓"):Q.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${Q.gray(this.formatTag(this.name))}`:"",j=`\r${h}${F} ${Z} ${E}${W}`,B=V.stdout.columns||80,H=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${H}`,V.stdout.write($.lastRenderedLine),w)V.stdout.write(`
|
|
136
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Y$()||!V.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(Y$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await AA(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=Lw(this.config.logDirectory,J);if($.before)try{if((await Iw(Y)).mtime>=$.before)continue}catch(f){console.error(`Failed to get stats for file ${Y}:`,f);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await JA(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var K6=new DA("stacks");class U0 extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}}class eE extends U0{code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],U="";if(J.length===1)U=` or alias "${J[0]}"`;else if(J.length>1)U=` or aliases ${J.map((Y)=>`"${Y}"`).join(", ")}`;super(`Configuration "${$}"${U} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}}class yA extends U0{code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}}class $Z extends U0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}}class wZ extends U0{code="CONFIG_MERGE_ERROR";constructor($,w,A,J){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}}class zY extends U0{code="ENV_VAR_ERROR";constructor($,w,A,J){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:J})}}class AZ extends U0{code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}}class JZ extends U0{code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}}class CA extends U0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}}class UZ extends U0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}}class YZ extends U0{code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}}var Sw={configNotFound($,w,A){return new eE($,w,A)},configLoad($,w,A){return new yA($,w,A)},configValidation($,w,A){return new $Z($,w,A)},configMerge($,w,A,J){return new wZ($,w,A,J)},envVar($,w,A,J){return new zY($,w,A,J)},fileSystem($,w,A){return new AZ($,w,A)},typeGeneration($,w,A){return new JZ($,w,A)},schemaValidation($,w,A){return new CA($,w,A)},browserConfig($,w,A,J){return new UZ($,w,A,J)},plugin($,w,A){return new YZ($,w,A)}};async function A9($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let Z=0;Z<=A;Z++)try{return await $()}catch(E){if(f=E instanceof Error?E:Error(String(E)),Z===A||!U(f))break;if(J>0)await new Promise((W)=>setTimeout(W,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}class TY{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:J,useCamelCase:U=!0,useBackwardCompatibility:Y=!0,customParsers:f={},verbose:Z=!1,trackPerformance:E=!0}=A,W=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let h=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],h,{useCamelCase:U,useBackwardCompatibility:Y,customParsers:f,verbose:Z,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(E)return fY.track("applyEnvironmentVariables",W,{configName:$});return W()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],Z=f.map((h)=>this.formatEnvKey(h,J.useCamelCase)),E=`${A}_${Z.join("_")}`,W=J.useBackwardCompatibility?`${A}_${f.map((h)=>h.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,f,A,J);else{let h=YA.env[E]||(W?YA.env[W]:void 0);if(h!==void 0){if(J.verbose){let F=YA.env[E]?E:W}try{$[U]=this.parseEnvironmentValue(h,typeof Y,E,J.customParsers,J.configName)}catch(F){if(F instanceof zY)throw F;throw Sw.envVar(E,h,typeof Y,J.configName)}}}}}parseEnvironmentValue($,w,A,J,U){for(let[Y,f]of Object.entries(J))try{return f($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,w))try{return Y.parse($)}catch{throw Sw.envVar(A,$,`${w} (via ${Y.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,U]of Object.entries(YA.env))if(J.startsWith(A)&&U!==void 0)w[J]=U;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(U){J.push(`Cannot parse value "${w}" as ${A}: ${U}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:U="text"}=A,Y=J||this.generateEnvPrefix($),f=[];switch(this.extractEnvVarInfo(w,[],Y,f),U){case"markdown":return this.formatAsMarkdown(f,$);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,$)}}extractEnvVarInfo($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],Z=`${A}_${f.map((E)=>this.formatEnvKey(E,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,f,A,J);else J.push({key:Z,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${f.join(".")}`,example:this.generateExample(Y)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
137
137
|
|
|
138
138
|
`;for(let J of $)A+=`${J.key}
|
|
139
139
|
`,A+=` Type: ${J.type}
|
|
@@ -145,24 +145,24 @@ export type ConfigOf = Config
|
|
|
145
145
|
`;A+=`| Variable | Type | Description | Example |
|
|
146
146
|
`,A+=`|----------|------|-------------|----------|
|
|
147
147
|
`;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
|
|
148
|
-
`;return A}}function gz($,w,A={}){return af($,w,A,new WeakMap)}function af($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:h}=A;if(w===null||w===void 0)return Y?$:w;if(h){let Z=h($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return sf($,w,U,J);if(!a$(w)||!a$($))return w;return rz($,w,A,J)}function sf($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return lz($,w);case"smart":return tz($,w,J);default:return w}return w}function lz($,w){let A=[...w];for(let J of $)if(!A.some((U)=>oU(U,J)))A.push(J);return A}function tz($,w,A){if(w.length===0)return $;if($.length===0)return w;if(a$(w[0])&&a$($[0]))return pz($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function pz($,w,A){let J=[...w];for(let U of $){if(!a$(U)){J.push(U);continue}let Y=["id","name","key","path","type"],h=!1;for(let Z of Y)if(Z in U){if(J.find((E)=>a$(E)&&(Z in E)&&E[Z]===U[Z])){h=!0;break}}if(!h)J.push(U)}return J}function rz($,w,A,J){let U=w;if(a$(U)&&J.has(U))return J.get(U);let Y={...$};if(a$(U))J.set(U,Y);for(let h in U){if(!Object.prototype.hasOwnProperty.call(U,h))continue;let Z=U[h],f=Y[h];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){Y[h]=Z;continue}if(a$(Z)&&a$(f))Y[h]=af(f,Z,A,J);else if(Array.isArray(Z)||Array.isArray(f))Y[h]=sf(f,Z,A.arrayMergeMode||"smart",J);else Y[h]=Z}return Y}function of($,w,A="replace"){return gz($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function oU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!oU($[A],w[A]))return!1;return!0}if(a$($)&&a$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!oU($[U],w[U]))return!1}return!0}return!1}function a$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class ef{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:h=!0,verbose:Z=!1}=A;if(U){let E=FA.getWithFileCheck("file",$);if(E){if(Z)console.log(`Configuration loaded from cache: ${$}`);return E}}let f=async()=>{if(!UA($))return null;try{let E=`?t=${Date.now()}`,W=await import($+E),F=W.default||W,j="default"in W,B=Object.keys(W).length>0;if(!j&&!B)throw new IA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new IA($,Error("Configuration must export a valid object"),"unknown");let q={config:of(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)FA.setWithFileCheck("file",q,$,Y);return q}catch(E){throw E instanceof Error?Vw.configLoad($,E):Vw.configLoad($,Error(String(E)))}};if(h)return eU.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let h of this.extensions)U.push(uU(w,`${Y}${h}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let J=w===void 0?[]:Array.isArray(w)?w:[w];for(let Y of J){if(!Y)continue;if(A.push(Y,`.${Y}.config`,`${Y}.config`,`.${Y}`),$)A.push(`${$}.${Y}.config`,`.${$}.${Y}.config`)}let U=new Set;return A.filter((Y)=>{if(!Y||U.has(Y))return!1;return U.add(Y),!0})}checkFileAccess($){return dz(async()=>{return UA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!UA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let h of this.extensions){let Z=uU($,`${Y}${h}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let h of Y)if(this.looksLikeConfigFile(h)){let Z=uU($,h);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){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((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!UA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}var sz=/^https?:\/\//;class $Z{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:h=[],trackPerformance:Z=!0,verbose:f=!1}=A,E=async()=>{let W=[],F=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:h,trackPerformance:Z,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...h],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return W.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:W,warnings:F}}};if(Z)return await eU.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!az(w))throw new yA(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new yA(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let h=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(h)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${h}`,expected:Z.join(" or "),actual:h,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let h=0;h<$.length;h++){let Z=A?`${A}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema($[h],w.items,Z,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let h=$;if(Y.validateRequired&&w.required){for(let Z of w.required)if(!(Z in h)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[Z,f]of Object.entries(w.properties))if(Z in h){let E=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(h[Z],f,E,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(h))if(!Z.has(f))U.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let h=this.getValueByPath($,Y.path),Z=this.validateWithRule(h,Y,Y.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(h){J.push({path:Y.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,h]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(h)})}return w}mapTypeScriptType($){switch($.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:sz},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var N0=new VA("bunfig",{showTags:!0});function oz($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class wZ{fileLoader=new ef;envProcessor=new ZY;validator=new $Z;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...h}=$;try{if(A?.enabled){let f=this.checkCache(h.name||"",h);if(f)return f}let Z;try{Z=await this.loadConfigurationStrategies(h,!0,A)}catch(f){let E=h.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(E)throw f;Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let W=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),F=!W&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),j=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(E&&(j||W))throw f;if(F&&(!E||!j))Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||Y)await this.validateConfiguration(Z.config,U,Y,h.name);if(A?.enabled&&Z)this.cacheResult(h.name||"",Z,A,h);if(J?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:h.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(f);if(J.slowThreshold&&f.duration>J.slowThreshold)N0.warn(`Slow configuration loading detected: ${f.duration}ms for ${h.name}`);Z.metrics=f}return Z}catch(Z){if(Z instanceof Error&&Z.name==="ConfigNotFoundError")throw Z;let f=Date.now()-w;throw N0.error(`Configuration loading failed after ${f}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:h,defaultConfig:Z,checkEnv:f=!0,arrayStrategy:E="replace",verbose:W=!1}=$,F=Y||LA.cwd(),j=[],B=await this.loadLocalConfiguration(J,U,F,h,Z,E,W,f,A);if(B)return j.push(...this.getLocalSearchPaths(J,U,F,h)),this.finalizeResult(B,j,f,J,W);let T=await this.loadHomeConfiguration(J,U,Z,E,W,f);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,f,J,W);let H=await this.loadPackageJsonConfiguration(J,U,F,Z,E,W,f);if(H)return j.push(p$(F,"package.json")),this.finalizeResult(H,j,f,J,W);if(j.push(...this.getAllSearchPaths(J,U,F,h)),w)throw Vw.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,Z,f,W),warnings:[`No configuration file found for "${J}"${oz(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,h,Z,f){let E=Z?YA($,U,h):U,W=this.getLocalDirectories(A,J);for(let F of W){if(h)N0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:h,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(B){if(h)N0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let h=Y?YA($,A,U):A,Z=[p$(Tw(),".config",$),p$(Tw(),".config"),Tw()];for(let f of Z){if(U)N0.info(`Checking home directory: ${f}`);let E=this.fileLoader.generateConfigPaths($,f,w),W=await this.fileLoader.tryLoadFromPaths(E,h,{arrayStrategy:J,verbose:U});if(W){if(U)N0.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,h){let Z=h?YA($,J,Y):J;try{let f=p$(A,"package.json");if(!gB(f))return null;let E={};try{E=JSON.parse(lB(f,"utf8"))}catch(j){if(Y)N0.warn("Failed to parse package.json:",[j instanceof Error?j:Error(String(j))]);return null}let W=E[$],F=$;if(!W&&w){let j=Array.isArray(w)?w:[w];for(let B of j){if(!B)continue;if(E[B]){W=E[B],F=B;break}}}if(W&&typeof W==="object"&&!Array.isArray(W)){if(Y)N0.success(`Configuration loaded from package.json: ${F}`);return{config:of(Z,W,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(Y)N0.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:YA($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(U.length>0)throw Vw.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return FA.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);FA.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let J=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${J}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,p$($,"config"),p$($,".config"),w?p$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(p$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let h of U)Y.push(...this.fileLoader.generateConfigPaths($,h,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[p$(Tw(),".config",$),p$(Tw(),".config"),Tw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}var W6=new wZ;function YA($,w,A=!1){let J=new ZY,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(h,Z=[]){let f={...h};for(let[E,W]of Object.entries(h)){let F=[...Z,E],j=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((H)=>H.toUpperCase()).join("")}`,`${U}_${F.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,T;for(let H of j)if(B=LA.env[H],B!==void 0){T=H;break}if(B!==void 0&&T)if(typeof W==="boolean")f[E]=["true","1","yes"].includes(B.toLowerCase());else if(typeof W==="number"){let H=Number(B);if(!Number.isNaN(H))f[E]=H}else if(Array.isArray(W))try{f[E]=JSON.parse(B)}catch{f[E]=B.split(",").map((H)=>H.trim())}else f[E]=B;else if(W&&typeof W==="object"&&!Array.isArray(W))f[E]=Y(W,F)}return f}return Y(w)}var F6=p$(LA.cwd(),"config"),B6=p$(LA.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",$9={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:WY(EY(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:WY(EY(),".stacks","ssl","stacks.localhost.crt"),keyPath:WY(EY(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Dw=$9;import{spawn as o2}from"node:child_process";import*as j0 from"node:fs/promises";import{homedir as hF}from"node:os";import*as B0 from"node:path";import*as G$ from"node:process";var N={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)};import{execSync as Yw}from"node:child_process";import B$ from"node:fs/promises";import*as eh from"node:os";import{homedir as S1}from"node:os";import{join as S$}from"node:path";import*as r0 from"node:process";import{createRequire as w9}from"node:module";import FY from"node:os";import BY from"node:path";import{existsSync as AZ,statSync as JZ}from"fs";import{existsSync as A9,mkdirSync as C6,readdirSync as S6,readFileSync as J9,writeFileSync as V6}from"fs";import{homedir as Ow}from"os";import{dirname as _6,resolve as s$}from"path";import WJ from"process";import{existsSync as UZ,statSync as YZ}from"fs";import{existsSync as XY,mkdirSync as U9,readdirSync as Y9,writeFileSync as h9}from"fs";import{homedir as _w}from"os";import{dirname as hZ,resolve as X$}from"path";import $w from"process";import{join as f9,relative as Z9,resolve as fZ}from"path";import pA from"process";import{existsSync as pZ,mkdirSync as n6,readdirSync as v6,writeFileSync as m6}from"fs";import{homedir as jY}from"os";import{dirname as l6,resolve as _$}from"path";import T1 from"process";import{join as E9,relative as W9,resolve as ZZ}from"path";import rA from"process";import{existsSync as rZ,mkdirSync as s6,readdirSync as o6,writeFileSync as e6}from"fs";import{dirname as wR,resolve as aA}from"path";import kY from"process";import{Buffer as d0}from"buffer";import{createCipheriv as F9,createDecipheriv as B9,randomBytes as zY}from"crypto";import{closeSync as HY,createReadStream as EZ,createWriteStream as j9,existsSync as TY,fsyncSync as WZ,openSync as FZ,writeFileSync as z9}from"fs";import{access as H9,constants as BZ,mkdir as T9,readdir as DA,rename as jZ,stat as Xw,unlink as OA,writeFile as GY}from"fs/promises";import{join as kw}from"path";import K$ from"process";import{pipeline as G9}from"stream/promises";import{createGzip as zZ}from"zlib";import Qw from"process";import V0 from"process";import{Buffer as L0}from"buffer";import{createCipheriv as q9,createDecipheriv as R9,randomBytes as qY}from"crypto";import{closeSync as RY,createReadStream as HZ,createWriteStream as N9,existsSync as _A,fsyncSync as TZ,openSync as GZ,writeFileSync as K9}from"fs";import{access as M9,constants as qZ,mkdir as I9,readdir as XA,rename as RZ,stat as xw,unlink as kA,writeFile as NY}from"fs/promises";import{isAbsolute as y9,join as Pw,resolve as L9}from"path";import c from"process";import{pipeline as C9}from"stream/promises";import{createGzip as NZ}from"zlib";import bw from"process";import D0 from"process";import QA from"process";import{existsSync as xA}from"fs";import{resolve as KY}from"path";import{existsSync as S9}from"fs";import{existsSync as V9,readdirSync as D9}from"fs";import{extname as MY,resolve as KZ}from"path";import O9 from"process";import{join as _9,relative as X9,resolve as MZ}from"path";import sA from"process";import{Buffer as C0}from"buffer";import{createCipheriv as k9,createDecipheriv as Q9,randomBytes as IY}from"crypto";import{closeSync as yY,createReadStream as IZ,createWriteStream as x9,existsSync as PA,fsyncSync as yZ,openSync as LZ,writeFileSync as P9}from"fs";import{access as b9,constants as CZ,mkdir as i9,readdir as bA,rename as SZ,stat as iw,unlink as iA,writeFile as LY}from"fs/promises";import{isAbsolute as c9,join as cw,resolve as u9}from"path";import u from"process";import{pipeline as n9}from"stream/promises";import{createGzip as VZ}from"zlib";import uw from"process";import O0 from"process";import cA from"process";import{existsSync as uA}from"fs";import{resolve as CY}from"path";import{existsSync as v9}from"fs";import{exec as WT}from"node:child_process";import vZ from"node:fs";import FT from"node:os";import Y0 from"node:path";import _E from"node:process";import{promisify as BT}from"node:util";import dw from"node:crypto";import _0 from"node:fs";import lY from"node:path";import{execSync as tZ}from"node:child_process";import EJ from"node:os";var K6=w9(import.meta.url);class aZ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,h=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:h}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!AZ($))return!0;return JZ($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=AZ(A)?JZ(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class sZ{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),h=performance.now()-J;return this.recordMetric({operation:$,duration:h,timestamp:U,...A}),Y}catch(Y){let h=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:h,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}var oA=new aZ,tY=new sZ,m9=Object.defineProperty,d9=($)=>$;function g9($,w){this[$]=d9.bind(null,w)}var l9=($,w)=>{for(var A in w)m9($,A,{get:w[A],enumerable:!0,configurable:!0,set:g9.bind(w,A)})},t9=($,w)=>()=>($&&(w=$($=0)),w),oZ={};l9(oZ,{withErrorRecovery:()=>wE,tryLoadConfig:()=>TH,loadConfigWithResult:()=>zH,loadConfig:()=>hE,isRetryableError:()=>ZH,isConfigNotFoundError:()=>fH,isBunfigError:()=>AE,globalPerformanceMonitor:()=>N1,globalCache:()=>vw,getEnvOrDefault:()=>EH,generateConfigTypes:()=>GH,defaultGeneratedDir:()=>zE,defaultConfigDir:()=>jE,deepMergeWithArrayStrategy:()=>oY,deepMerge:()=>JE,createLibraryConfig:()=>qH,config:()=>HH,bunfigPlugin:()=>RH,applyEnvVarsToConfig:()=>z1,TypeGenerationError:()=>uY,SchemaValidationError:()=>q1,PluginError:()=>vY,PerformanceMonitor:()=>rY,FileSystemError:()=>cY,ErrorFactory:()=>l0,EnvVarError:()=>UJ,EnvProcessor:()=>FJ,ConfigValidator:()=>eY,ConfigValidationError:()=>bY,ConfigNotFoundError:()=>JJ,ConfigMergeError:()=>iY,ConfigLoader:()=>$h,ConfigLoadError:()=>G1,ConfigFileLoader:()=>BJ,ConfigCache:()=>pY,CacheUtils:()=>ZE,BunfigError:()=>n$,BrowserConfigError:()=>nY,ArrayMergeStrategies:()=>FE});class pY{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,h=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:h}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!UZ($))return!0;return YZ($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=UZ(A)?YZ(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class rY{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),h=performance.now()-J;return this.recordMetric({operation:$,duration:h,timestamp:U,...A}),Y}catch(Y){let h=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:h,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function p9($,w={}){let A=Object.keys(w).sort().map((J)=>`${J}:${w[J]}`).join("|");return A?`${$}:${A}`:$}function r9($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function a9($){return $.getStats().size*2}function aY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let J=[...w];for(let U of $)if(p(U)&&"name"in U){if(!J.find((Y)=>p(Y)&&("name"in Y)&&Y.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((Y)=>p(Y)&&("path"in Y)&&Y.path===U.path))J.push(U)}else if(!J.some((Y)=>eA(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!p(w)||!p($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(p(U)&&p(A[J]))A[J]=aY(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&p(U[0])&&p(A[J][0])){let Y=[...U];for(let h of A[J])if(p(h)&&"name"in h){if(!Y.find((Z)=>p(Z)&&("name"in Z)&&Z.name===h.name))Y.push(h)}else if(p(h)&&"path"in h){if(!Y.find((Z)=>p(Z)&&("path"in Z)&&Z.path===h.path))Y.push(h)}else if(!Y.some((Z)=>eA(Z,h)))Y.push(h);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let h of A[J])if(!Y.includes(h))Y.push(h);A[J]=Y}else A[J]=U;else A[J]=U}return A}function eA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!eA($[A],w[A]))return!1;return!0}if(p($)&&p(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!eA($[U],w[U]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function s9($,w){if(!rZ($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return aY(w,J)}catch{return null}}catch{return null}}async function o9({name:$="",cwd:w,defaultConfig:A}){let J=w||kY.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let h of Y)for(let Z of U){let f=aA(J,`${h}${Z}`),E=await s9(f,A);if(E!==null)return E}try{let h=aA(J,"package.json");if(rZ(h)){let Z=(await import(h))[$];if(Z&&typeof Z==="object"&&!Array.isArray(Z))try{return aY(A,Z)}catch{}}}catch{}return A}function e9($,w={}){let A=rA.cwd();while(A.includes("storage"))A=ZZ(A,"..");let J=ZZ(A,$||"");if(w?.relative)return W9(rA.cwd(),J);return J}async function $H(){try{let $=await o9({name:"clarity",defaultConfig:dA,cwd:rA.cwd(),endpoint:"",headers:{}});return{...dA,...$}}catch{return dA}}function e(){if(V0.env.NODE_ENV==="test"||V0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wH(){if(V0.env.NODE_ENV==="test"||V0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof V0<"u"){let $=V0.type;if($==="renderer"||$==="worker")return!1;return!!(V0.versions&&(V0.versions.node||V0.versions.bun))}return!1}class eZ{async format($){let w=await wH(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Qw.pid,hostname:w(),environment:Qw.env.NODE_ENV||"development",platform:Qw.platform,version:Qw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qw.env.NODE_ENV||Qw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $J{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...xY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new eZ,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??K$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...gA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...gA};return{...gA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:xY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let w=(async()=>{let J,U=0,Y=3,h=1000;while(U<Y)try{try{try{await H9(this.config.logDirectory,BZ.F_OK|BZ.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await T9(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:d0.from($);try{if(!TY(this.currentLogFile))await GY(this.currentLogFile,"",{mode:420});if(J=FZ(this.currentLogFile,"a",420),z9(J,Z,{flag:"a"}),WZ(J),J!==void 0)HY(J),J=void 0;if((await Xw(this.currentLogFile)).size===0){if(await GY(this.currentLogFile,Z,{flag:"w",mode:420}),(await Xw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let E=f;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(U<Y-1){let W=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,W);let F=h*2**U;await new Promise((j)=>setTimeout(j,F)),U++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(J!==void 0)try{HY(J)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(Z){if(U===Y-1){let E=Z,W=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),Z}U++;let f=h*2**(U-1);await new Promise((E)=>setTimeout(E,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return kw(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 kw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return kw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(e())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,h],[,Z])=>Z.createdAt.getTime()-h.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,Y=Math.max(1,U);if(J.length>Y)for(let[h]of J.slice(Y))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return zY(16).toString("hex")}generateKey(){return zY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=zY(16),J=F9("aes-256-gcm",w,A),U=d0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:d0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=zZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(d0.from(d0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(e())return;let $=await Xw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await DA(this.config.logDirectory),Y=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),h=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${h}`;if(await Xw(A).catch(()=>null))try{if(await jZ(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await OA(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(Y.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await GY(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await Xw(A).catch(()=>null))await jZ(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await DA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,h)=>h.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await OA(kw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=EZ($),J=j9(w),U=zZ();await G9(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),TY(this.currentLogFile))try{let $=FZ(this.currentLogFile,"r+");WZ($),HY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await DA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await OA(kw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?d.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:h=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(h)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let f=K$.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${d.cyan(U)}`;if(!h)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,h)=>{let Z=Number.parseInt(h,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,h)=>{if(h==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(h){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),h,Z;if(w instanceof Error)h=w.message,Z=w.stack;else h=this.formatMessage(w,A);if(this.fancy&&!e()){let E=EE[$],W=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:d.gray(h),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:h,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:d.green(h),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:h,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:E,tag:W,message:h,level:$}),console.error(F),Z){let j=Z.split(`
|
|
149
|
-
`);for(let B of j)if(B.trim()&&!B.includes(
|
|
150
|
-
`;if(Z)
|
|
151
|
-
`;
|
|
152
|
-
`,
|
|
153
|
-
`),
|
|
154
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(e())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${d.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();K$.stdin.removeListener("data",A);try{if(typeof K$.stdin.setRawMode==="function")K$.stdin.setRawMode(!1)}catch{}K$.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof K$.stdin.setRawMode==="function")K$.stdin.setRawMode(!0)}catch{}K$.stdin.resume(),K$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,Y=0;if(A=$.replace(U,(
|
|
155
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||e()||$<=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 A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,J)),U!==void 0)this.activeProgressBar.message=U;let Y=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Y)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;if(this.activeProgressBar.current=this.activeProgressBar.total,J!==void 0)this.activeProgressBar.message=J;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(J,U="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;K$.stdout.write(`${"\r".padEnd(K$.stdout.columns||80)}\r`),this.log(U,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||e()||!K$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=d.green("━".repeat(J)),
|
|
156
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||e()||!K$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await DA(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=kw(this.config.logDirectory,J);if($.before)try{if((await Xw(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await OA(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function mA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&n(w[0])&&"id"in w[0]&&w[0].id===3&&n(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(n(w)&&n($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(n($)&&"arr"in $&&Array.isArray($.arr)&&n(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&n(w[0])&&n($[0])){let J=[...w];for(let U of $)if(n(U)&&"name"in U){if(!J.find((Y)=>n(Y)&&("name"in Y)&&Y.name===U.name))J.push(U)}else if(n(U)&&"path"in U){if(!J.find((Y)=>n(Y)&&("path"in Y)&&Y.path===U.path))J.push(U)}else if(!J.some((Y)=>wJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!n(w)||!n($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(n(U)&&n(A[J]))A[J]=mA(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&n(U[0])&&n(A[J][0])){let Y=[...U];for(let h of A[J])if(n(h)&&"name"in h){if(!Y.find((Z)=>n(Z)&&("name"in Z)&&Z.name===h.name))Y.push(h)}else if(n(h)&&"path"in h){if(!Y.find((Z)=>n(Z)&&("path"in Z)&&Z.path===h.path))Y.push(h)}else if(!Y.some((Z)=>wJ(Z,h)))Y.push(h);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let h of A[J])if(!Y.includes(h))Y.push(h);A[J]=Y}else A[J]=U;else A[J]=U}return A}function sY($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:mA($,w);if(Array.isArray($))return A==="replace"?w:mA($,w);if(!n(w)||!n($))return w;let J={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let Y=w[U],h=J[U];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(h))if(A==="replace")J[U]=Y;else J[U]=mA(h,Y);else if(n(Y)&&n(h))J[U]=sY(h,Y,A);else J[U]=Y}return J}function wJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!wJ($[A],w[A]))return!1;return!0}if(n($)&&n(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!wJ($[U],w[U]))return!1}return!0}return!1}function n($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function nA($,w,A="replace"){if(!pZ($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return sY(w,U,A)}catch{return null}}catch{return null}}function AH($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(h,Z=[]){let f={...h};for(let[E,W]of Object.entries(h)){let F=[...Z,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),B=`${J}_${F.map(j).join("_")}`,T=`${J}_${F.map((H)=>H.toUpperCase()).join("_")}`;if(A)I$.info(`Checking environment variable ${B} for config ${$}.${F.join(".")}`);if(typeof W==="object"&&W!==null&&!Array.isArray(W))f[E]=Y(W,F);else{let H=T1.env[B]||T1.env[T];if(H!==void 0){if(A)I$.info(`Using environment variable ${H?B:T} for config ${$}.${F.join(".")}`);if(typeof W==="number")f[E]=Number(H);else if(typeof W==="boolean")f[E]=H.toLowerCase()==="true";else if(Array.isArray(W))try{let q=JSON.parse(H);if(Array.isArray(q))f[E]=q;else f[E]=H.split(",").map((G)=>G.trim())}catch{f[E]=H.split(",").map((q)=>q.trim())}else f[E]=H}}}return f}return Y(U)}async function JH({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:U,verbose:Y=!1,checkEnv:h=!0,arrayStrategy:Z="replace"}){let f=h&&typeof U==="object"&&U!==null&&!Array.isArray(U)?AH($,U,Y):U,E=A||T1.cwd(),W=[".ts",".js",".mjs",".cjs",".json"];if(Y)I$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let F=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),B=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,_$(E,"config"),_$(E,".config"),J?_$(E,J):void 0].filter(Boolean)));for(let q of H){if(Y)I$.info(`Searching for configuration in: ${q}`);let G=[_$(E,"config"),_$(E,".config")].concat(J?[_$(E,J)]:[]).includes(q)?[...F,...j,...B,...T]:[...j,...F,...T,...B];for(let R of G)for(let K of W){let L=_$(q,`${R}${K}`),C=await nA(L,f,Z);if(C!==null){if(Y)I$.success(`Configuration loaded from: ${L}`);return C}}}if($){let q=_$(jY(),".config",$),G=["config",`${$}.config`];if(w)G.push(`${w}.config`);if(Y)I$.info(`Checking user config directory: ${q}`);for(let R of G)for(let K of W){let L=_$(q,`${R}${K}`),C=await nA(L,f,Z);if(C!==null){if(Y)I$.success(`Configuration loaded from user config directory: ${L}`);return C}}}if($){let q=_$(jY(),".config"),G=[`.${$}.config`];if(w)G.push(`.${w}.config`);if(Y)I$.info(`Checking user config directory for dotfile configs: ${q}`);for(let R of G)for(let K of W){let L=_$(q,`${R}${K}`),C=await nA(L,f,Z);if(C!==null){if(Y)I$.success(`Configuration loaded from user config directory dotfile: ${L}`);return C}}}if($){let q=jY(),G=[`.${$}.config`,`.${$}`];if(w)G.push(`.${w}.config`),G.push(`.${w}`);if(Y)I$.info(`Checking user home directory for dotfile configs: ${q}`);for(let R of G)for(let K of W){let L=_$(q,`${R}${K}`),C=await nA(L,f,Z);if(C!==null){if(Y)I$.success(`Configuration loaded from user home directory: ${L}`);return C}}}try{let q=_$(E,"package.json");if(pZ(q)){let G=await import(q),R=G[$];if(!R&&w){if(R=G[w],R&&Y)I$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(Y)I$.success(`Configuration loaded from package.json: ${R===G[$]?$:w}`);return sY(f,R,Z)}catch(K){if(Y)I$.warn("Failed to merge package.json config:",K)}}}catch(q){if(Y)I$.warn("Failed to load package.json:",q)}if(Y)I$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function UH($,w={}){let A=pA.cwd();while(A.includes("storage"))A=fZ(A,"..");let J=fZ(A,$||"");if(w?.relative)return Z9(pA.cwd(),J);return J}async function YH(){try{let $=await JH({name:"clarity",alias:"logging",defaultConfig:lA,cwd:pA.cwd()});return{...lA,...$||{}}}catch{return lA}}function h$(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hH(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D0<"u"){let $=D0.type;if($==="renderer"||$==="worker")return!1;return!!(D0.versions&&(D0.versions.node||D0.versions.bun))}return!1}class $E{async format($){let w=await hH(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:bw.pid,hostname:w(),environment:bw.env.NODE_ENV||"development",platform:bw.platform,version:bw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:bw.env.NODE_ENV||bw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class AJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...PY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new $E,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??c.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...tA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...tA};return{...tA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:PY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!h$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let J,U=0,Y=3,h=1000;while(U<Y)try{try{try{await M9(this.config.logDirectory,qZ.F_OK|qZ.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await I9(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:L0.from($);try{if(!_A(this.currentLogFile))await NY(this.currentLogFile,"",{mode:420});if(J=GZ(this.currentLogFile,"a",420),K9(J,Z,{flag:"a"}),TZ(J),J!==void 0)RY(J),J=void 0;if((await xw(this.currentLogFile)).size===0){if(await NY(this.currentLogFile,Z,{flag:"w",mode:420}),(await xw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let E=f;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(U<Y-1){let W=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,W);let F=h*2**U;await new Promise((j)=>setTimeout(j,F)),U++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(J!==void 0)try{RY(J)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(Z){if(U===Y-1){let E=Z,W=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),Z}U++;let f=h*2**(U-1);await new Promise((E)=>setTimeout(E,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Pw(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 Pw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Pw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(h$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,h],[,Z])=>Z.createdAt.getTime()-h.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,Y=Math.max(1,U);if(J.length>Y)for(let[h]of J.slice(Y))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return qY(16).toString("hex")}generateKey(){return qY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=qY(16),J=q9("aes-256-gcm",w,A),U=L0.isBuffer($)?$:L0.from($,"utf8"),Y=J.update(U),h=J.final(),Z=Y.length+h.length,f=J.getAuthTag(),E=L0.allocUnsafe(16+Z+16);return A.copy(E,0),Y.copy(E,16),h.copy(E,16+Y.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=NZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(L0.from(L0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(h$())return;if(!this.shouldWriteToFile())return;let $=await xw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await XA(this.config.logDirectory),Y=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),h=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${h}`;if(await xw(A).catch(()=>null))try{if(await RZ(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await kA(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(Y.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await NY(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await xw(A).catch(()=>null))await RZ(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await XA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,h)=>h.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await kA(Pw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=HZ($),J=N9(w),U=NZ();await C9(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),_A(this.currentLogFile))try{let $=GZ(this.currentLogFile,"r+");TZ($),RY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!h$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await XA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await kA(Pw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?X.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||h$())return!1;let $=typeof c.env.NO_COLOR<"u",w=c.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof c.stderr<"u"&&c.stderr.isTTY||typeof c.stdout<"u"&&c.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:h=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(h)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let f=c.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${X.cyan(U)}`;if(!h)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,h)=>{let Z=Number.parseInt(h,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,h)=>{if(h==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(h){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=X.underline(X.blue(J)),h=this.toAbsoluteFilePath(U);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(h)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>X.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>X.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>X.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>X.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>X.strikethrough(J)),w}supportsHyperlinks(){if(h$())return!1;let $=c.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=c.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(y9(w)||w.startsWith("./")||w.startsWith("../"))w=L9(w);else return null;return _A(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),h,Z;if(w instanceof Error)h=w.message,Z=w.stack;else h=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":WE[$],j=this.options.showTags!==!1&&this.name?X.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:X.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:X.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
|
|
157
|
-
`);for(let
|
|
158
|
-
`;if(Z)
|
|
159
|
-
`;if(
|
|
160
|
-
`);if(this[Y==="warning"?"warn":Y](U),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
161
|
-
`,
|
|
162
|
-
`),
|
|
163
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
164
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!c.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=X.green("━".repeat(J)),
|
|
165
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
148
|
+
`;return A}}function J9($,w,A={}){return fZ($,w,A,new WeakMap)}function fZ($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:f}=A;if(w===null||w===void 0)return Y?$:w;if(f){let Z=f($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return EZ($,w,U,J);if(!a$(w)||!a$($))return w;return E9($,w,A,J)}function EZ($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return U9($,w);case"smart":return Y9($,w,J);default:return w}return w}function U9($,w){let A=[...w];for(let J of $)if(!A.some((U)=>YY(U,J)))A.push(J);return A}function Y9($,w,A){if(w.length===0)return $;if($.length===0)return w;if(a$(w[0])&&a$($[0]))return f9($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function f9($,w,A){let J=[...w];for(let U of $){if(!a$(U)){J.push(U);continue}let Y=["id","name","key","path","type"],f=!1;for(let Z of Y)if(Z in U){if(J.find((W)=>a$(W)&&(Z in W)&&W[Z]===U[Z])){f=!0;break}}if(!f)J.push(U)}return J}function E9($,w,A,J){let U=w;if(a$(U)&&J.has(U))return J.get(U);let Y={...$};if(a$(U))J.set(U,Y);for(let f in U){if(!Object.prototype.hasOwnProperty.call(U,f))continue;let Z=U[f],E=Y[f];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){Y[f]=Z;continue}if(a$(Z)&&a$(E))Y[f]=fZ(E,Z,A,J);else if(Array.isArray(Z)||Array.isArray(E))Y[f]=EZ(E,Z,A.arrayMergeMode||"smart",J);else Y[f]=Z}return Y}function ZZ($,w,A="replace"){return J9($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function YY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!YY($[A],w[A]))return!1;return!0}if(a$($)&&a$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!YY($[U],w[U]))return!1}return!0}return!1}function a$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class WZ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:f=!0,verbose:Z=!1}=A;if(U){let W=jA.getWithFileCheck("file",$);if(W){if(Z)console.log(`Configuration loaded from cache: ${$}`);return W}}let E=async()=>{if(!fA($))return null;try{let W=`?t=${Date.now()}`,h=await import($+W),F=h.default||h,j="default"in h,B=Object.keys(h).length>0;if(!j&&!B)throw new yA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new yA($,Error("Configuration must export a valid object"),"unknown");let q={config:ZZ(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)jA.setWithFileCheck("file",q,$,Y);return q}catch(W){throw W instanceof Error?Sw.configLoad($,W):Sw.configLoad($,Error(String(W)))}};if(f)return fY.track("loadFromPath",E,{path:$});return E()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let f of this.extensions)U.push(tU(w,`${Y}${f}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let J=w===void 0?[]:Array.isArray(w)?w:[w];for(let Y of J){if(!Y)continue;if(A.push(Y,`.${Y}.config`,`${Y}.config`,`.${Y}`),$)A.push(`${$}.${Y}.config`,`.${$}.${Y}.config`)}let U=new Set;return A.filter((Y)=>{if(!Y||U.has(Y))return!1;return U.add(Y),!0})}checkFileAccess($){return A9(async()=>{return fA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!fA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let Z=tU($,`${Y}${f}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let f of Y)if(this.looksLikeConfigFile(f)){let Z=tU($,f);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){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((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!fA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}var W9=/^https?:\/\//;class hZ{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:Z=!0,verbose:E=!1}=A,W=async()=>{let h=[],F=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:Z,verbose:E};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return h.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:h,warnings:F}}};if(Z)return await fY.track("validateConfiguration",W);return W()}async validateWithSchemaFile($,w,A){try{if(!Z9(w))throw new CA(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new CA(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let f=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(f)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${f}`,expected:Z.join(" or "),actual:f,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let f=0;f<$.length;f++){let Z=A?`${A}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema($[f],w.items,Z,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let f=$;if(Y.validateRequired&&w.required){for(let Z of w.required)if(!(Z in f)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[Z,E]of Object.entries(w.properties))if(Z in f){let W=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(f[Z],E,W,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let E of Object.keys(f))if(!Z.has(E))U.push({path:A?`${A}.${E}`:E,message:`Additional property '${E}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let f=this.getValueByPath($,Y.path),Z=this.validateWithRule(f,Y,Y.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(f){J.push({path:Y.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,f]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(f)})}return w}mapTypeScriptType($){switch($.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:W9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var N0=new DA("bunfig",{showTags:!0});function h9($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class FZ{fileLoader=new WZ;envProcessor=new TY;validator=new hZ;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...f}=$;try{if(A?.enabled){let E=this.checkCache(f.name||"",f);if(E)return E}let Z;try{Z=await this.loadConfigurationStrategies(f,!0,A)}catch(E){let W=f.__strictErrorHandling;if(E instanceof Error&&E.name==="ConfigNotFoundError"){if(W)throw E;Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(E instanceof Error&&E.name==="ConfigLoadError"){let h=E.message.includes("EACCES")||E.message.includes("EPERM")||E.message.includes("permission denied"),F=!h&&(E.message.includes("syntax")||E.message.includes("Expected")||E.message.includes("Unexpected")||E.message.includes("BuildMessage")||E.message.includes("errors building")),j=E.message.includes("Configuration must export a valid object")||E.message.includes("Configuration file is empty and exports nothing");if(W&&(j||h))throw E;if(F&&(!W||!j))Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!W)Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${E.message}`]};else throw E}else Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${E instanceof Error?E.message:String(E)}`]}}if(U||Y)await this.validateConfiguration(Z.config,U,Y,f.name);if(A?.enabled&&Z)this.cacheResult(f.name||"",Z,A,f);if(J?.enabled){let E={operation:"loadConfig",duration:Date.now()-w,configName:f.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(E);if(J.slowThreshold&&E.duration>J.slowThreshold)N0.warn(`Slow configuration loading detected: ${E.duration}ms for ${f.name}`);Z.metrics=E}return Z}catch(Z){if(Z instanceof Error&&Z.name==="ConfigNotFoundError")throw Z;let E=Date.now()-w;throw N0.error(`Configuration loading failed after ${E}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:f,defaultConfig:Z,checkEnv:E=!0,arrayStrategy:W="replace",verbose:h=!1}=$,F=Y||SA.cwd(),j=[],B=await this.loadLocalConfiguration(J,U,F,f,Z,W,h,E,A);if(B)return j.push(...this.getLocalSearchPaths(J,U,F,f)),this.finalizeResult(B,j,E,J,h);let H=await this.loadHomeConfiguration(J,U,Z,W,h,E);if(H)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(H,j,E,J,h);let T=await this.loadPackageJsonConfiguration(J,U,F,Z,W,h,E);if(T)return j.push(p$(F,"package.json")),this.finalizeResult(T,j,E,J,h);if(j.push(...this.getAllSearchPaths(J,U,F,f)),w)throw Sw.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,Z,E,h),warnings:[`No configuration file found for "${J}"${h9(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,Z,E){let W=Z?EA($,U,f):U,h=this.getLocalDirectories(A,J);for(let F of h){if(f)N0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,W,{arrayStrategy:Y,verbose:f,cacheTtl:E?.ttl,useCache:!E?.ttl||E.ttl>100});if(B){if(f)N0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?EA($,A,U):A,Z=[p$(Tw(),".config",$),p$(Tw(),".config"),Tw()];for(let E of Z){if(U)N0.info(`Checking home directory: ${E}`);let W=this.fileLoader.generateConfigPaths($,E,w),h=await this.fileLoader.tryLoadFromPaths(W,f,{arrayStrategy:J,verbose:U});if(h){if(U)N0.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let Z=f?EA($,J,Y):J;try{let E=p$(A,"package.json");if(!Jj(E))return null;let W={};try{W=JSON.parse(Uj(E,"utf8"))}catch(j){if(Y)N0.warn("Failed to parse package.json:",[j instanceof Error?j:Error(String(j))]);return null}let h=W[$],F=$;if(!h&&w){let j=Array.isArray(w)?w:[w];for(let B of j){if(!B)continue;if(W[B]){h=W[B],F=B;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(Y)N0.success(`Configuration loaded from package.json: ${F}`);return{config:ZZ(Z,h,U),source:{type:"package.json",path:E,priority:30,timestamp:new Date}}}}catch(E){if(Y)N0.warn("Failed to load package.json:",[E instanceof Error?E:Error(String(E))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:EA($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(U.length>0)throw Sw.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return jA.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);jA.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let J=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${J}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,p$($,"config"),p$($,".config"),w?p$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(p$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let f of U)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[p$(Tw(),".config",$),p$(Tw(),".config"),Tw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}var C6=new FZ;function EA($,w,A=!1){let J=new TY,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,Z=[]){let E={...f};for(let[W,h]of Object.entries(f)){let F=[...Z,W],j=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((T)=>T.toUpperCase()).join("")}`,`${U}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,H;for(let T of j)if(B=SA.env[T],B!==void 0){H=T;break}if(B!==void 0&&H)if(typeof h==="boolean")E[W]=["true","1","yes"].includes(B.toLowerCase());else if(typeof h==="number"){let T=Number(B);if(!Number.isNaN(T))E[W]=T}else if(Array.isArray(h))try{E[W]=JSON.parse(B)}catch{E[W]=B.split(",").map((T)=>T.trim())}else E[W]=B;else if(h&&typeof h==="object"&&!Array.isArray(h))E[W]=Y(h,F)}return E}return Y(w)}var S6=p$(SA.cwd(),"config"),V6=p$(SA.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",B9={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:GY(HY(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:GY(HY(),".stacks","ssl","stacks.localhost.crt"),keyPath:GY(HY(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Vw=B9;import{spawn as z7}from"node:child_process";import*as j0 from"node:fs/promises";import{homedir as qF}from"node:os";import*as B0 from"node:path";import*as G$ from"node:process";var N={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)};import{execSync as J1}from"node:child_process";import j$ from"node:fs/promises";import*as h8 from"node:os";import{homedir as eJ}from"node:os";import{join as S$}from"node:path";import*as r0 from"node:process";import{createRequire as j9}from"node:module";import qY from"node:os";import RY from"node:path";import{existsSync as BZ,statSync as jZ}from"fs";import{existsSync as z9,mkdirSync as v6,readdirSync as m6,readFileSync as T9,writeFileSync as d6}from"fs";import{homedir as Ow}from"os";import{dirname as t6,resolve as s$}from"path";import BJ from"process";import{existsSync as zZ,statSync as TZ}from"fs";import{existsSync as cY,mkdirSync as H9,readdirSync as G9,writeFileSync as q9}from"fs";import{homedir as Dw}from"os";import{dirname as HZ,resolve as X$}from"path";import $w from"process";import{join as R9,relative as N9,resolve as GZ}from"path";import aA from"process";import{existsSync as UW,mkdirSync as JR,readdirSync as UR,writeFileSync as YR}from"fs";import{homedir as NY}from"os";import{dirname as ZR,resolve as _$}from"path";import q1 from"process";import{join as K9,relative as M9,resolve as qZ}from"path";import sA from"process";import{existsSync as YW,mkdirSync as jR,readdirSync as zR,writeFileSync as TR}from"fs";import{dirname as GR,resolve as oA}from"path";import uY from"process";import{Buffer as d0}from"buffer";import{createCipheriv as I9,createDecipheriv as L9,randomBytes as KY}from"crypto";import{closeSync as MY,createReadStream as RZ,createWriteStream as y9,existsSync as IY,fsyncSync as NZ,openSync as KZ,writeFileSync as C9}from"fs";import{access as S9,constants as MZ,mkdir as V9,readdir as _A,rename as IZ,stat as _w,unlink as XA,writeFile as LY}from"fs/promises";import{join as Xw}from"path";import K$ from"process";import{pipeline as O9}from"stream/promises";import{createGzip as LZ}from"zlib";import kw from"process";import V0 from"process";import{Buffer as y0}from"buffer";import{createCipheriv as D9,createDecipheriv as _9,randomBytes as yY}from"crypto";import{closeSync as CY,createReadStream as yZ,createWriteStream as X9,existsSync as kA,fsyncSync as CZ,openSync as SZ,writeFileSync as k9}from"fs";import{access as Q9,constants as VZ,mkdir as x9,readdir as QA,rename as OZ,stat as Qw,unlink as xA,writeFile as SY}from"fs/promises";import{isAbsolute as P9,join as xw,resolve as b9}from"path";import c from"process";import{pipeline as i9}from"stream/promises";import{createGzip as DZ}from"zlib";import Pw from"process";import O0 from"process";import PA from"process";import{existsSync as bA}from"fs";import{resolve as VY}from"path";import{existsSync as c9}from"fs";import{existsSync as u9,readdirSync as n9}from"fs";import{extname as OY,resolve as _Z}from"path";import v9 from"process";import{join as m9,relative as d9,resolve as XZ}from"path";import eA from"process";import{Buffer as C0}from"buffer";import{createCipheriv as g9,createDecipheriv as l9,randomBytes as DY}from"crypto";import{closeSync as _Y,createReadStream as kZ,createWriteStream as t9,existsSync as iA,fsyncSync as QZ,openSync as xZ,writeFileSync as p9}from"fs";import{access as r9,constants as PZ,mkdir as a9,readdir as cA,rename as bZ,stat as bw,unlink as uA,writeFile as XY}from"fs/promises";import{isAbsolute as s9,join as iw,resolve as o9}from"path";import u from"process";import{pipeline as e9}from"stream/promises";import{createGzip as iZ}from"zlib";import cw from"process";import D0 from"process";import nA from"process";import{existsSync as vA}from"fs";import{resolve as kY}from"path";import{existsSync as $T}from"fs";import{exec as MH}from"node:child_process";import oZ from"node:fs";import IH from"node:os";import Y0 from"node:path";import nW from"node:process";import{promisify as LH}from"node:util";import mw from"node:crypto";import _0 from"node:fs";import eY from"node:path";import{execSync as JW}from"node:child_process";import FJ from"node:os";var b6=j9(import.meta.url);class fW{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,f=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:f}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!BZ($))return!0;return jZ($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=BZ(A)?jZ(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class EW{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),f=performance.now()-J;return this.recordMetric({operation:$,duration:f,timestamp:U,...A}),Y}catch(Y){let f=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:f,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}var $J=new fW,$f=new EW,wT=Object.defineProperty,AT=($)=>$;function JT($,w){this[$]=AT.bind(null,w)}var UT=($,w)=>{for(var A in w)wT($,A,{get:w[A],enumerable:!0,configurable:!0,set:JT.bind(w,A)})},YT=($,w)=>()=>($&&(w=$($=0)),w),ZW={};UT(ZW,{withErrorRecovery:()=>FW,tryLoadConfig:()=>VT,loadConfigWithResult:()=>CT,loadConfig:()=>HW,isRetryableError:()=>NT,isConfigNotFoundError:()=>RT,isBunfigError:()=>BW,globalPerformanceMonitor:()=>M1,globalCache:()=>nw,getEnvOrDefault:()=>KT,generateConfigTypes:()=>OT,defaultGeneratedDir:()=>LW,defaultConfigDir:()=>IW,deepMergeWithArrayStrategy:()=>Yf,deepMerge:()=>jW,createLibraryConfig:()=>DT,config:()=>ST,bunfigPlugin:()=>_T,applyEnvVarsToConfig:()=>H1,TypeGenerationError:()=>tY,SchemaValidationError:()=>N1,PluginError:()=>rY,PerformanceMonitor:()=>Af,FileSystemError:()=>lY,ErrorFactory:()=>l0,EnvVarError:()=>fJ,EnvProcessor:()=>jJ,ConfigValidator:()=>ff,ConfigValidationError:()=>dY,ConfigNotFoundError:()=>YJ,ConfigMergeError:()=>gY,ConfigLoader:()=>Ef,ConfigLoadError:()=>R1,ConfigFileLoader:()=>zJ,ConfigCache:()=>wf,CacheUtils:()=>qW,BunfigError:()=>n$,BrowserConfigError:()=>pY,ArrayMergeStrategies:()=>KW});class wf{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,f=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:f}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!zZ($))return!0;return TZ($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=zZ(A)?TZ(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class Af{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),f=performance.now()-J;return this.recordMetric({operation:$,duration:f,timestamp:U,...A}),Y}catch(Y){let f=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:f,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function fT($,w={}){let A=Object.keys(w).sort().map((J)=>`${J}:${w[J]}`).join("|");return A?`${$}:${A}`:$}function ET($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function ZT($){return $.getStats().size*2}function Jf($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let J=[...w];for(let U of $)if(p(U)&&"name"in U){if(!J.find((Y)=>p(Y)&&("name"in Y)&&Y.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((Y)=>p(Y)&&("path"in Y)&&Y.path===U.path))J.push(U)}else if(!J.some((Y)=>wJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!p(w)||!p($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(p(U)&&p(A[J]))A[J]=Jf(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&p(U[0])&&p(A[J][0])){let Y=[...U];for(let f of A[J])if(p(f)&&"name"in f){if(!Y.find((Z)=>p(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(p(f)&&"path"in f){if(!Y.find((Z)=>p(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((Z)=>wJ(Z,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function wJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!wJ($[A],w[A]))return!1;return!0}if(p($)&&p(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!wJ($[U],w[U]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function WT($,w){if(!YW($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return Jf(w,J)}catch{return null}}catch{return null}}async function hT({name:$="",cwd:w,defaultConfig:A}){let J=w||uY.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let f of Y)for(let Z of U){let E=oA(J,`${f}${Z}`),W=await WT(E,A);if(W!==null)return W}try{let f=oA(J,"package.json");if(YW(f)){let Z=(await import(f))[$];if(Z&&typeof Z==="object"&&!Array.isArray(Z))try{return Jf(A,Z)}catch{}}}catch{}return A}function FT($,w={}){let A=sA.cwd();while(A.includes("storage"))A=qZ(A,"..");let J=qZ(A,$||"");if(w?.relative)return M9(sA.cwd(),J);return J}async function BT(){try{let $=await hT({name:"clarity",defaultConfig:lA,cwd:sA.cwd(),endpoint:"",headers:{}});return{...lA,...$}}catch{return lA}}function e(){if(V0.env.NODE_ENV==="test"||V0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jT(){if(V0.env.NODE_ENV==="test"||V0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof V0<"u"){let $=V0.type;if($==="renderer"||$==="worker")return!1;return!!(V0.versions&&(V0.versions.node||V0.versions.bun))}return!1}class WW{async format($){let w=await jT(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:kw.pid,hostname:w(),environment:kw.env.NODE_ENV||"development",platform:kw.platform,version:kw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:kw.env.NODE_ENV||kw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class AJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...vY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new WW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??K$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...tA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...tA};return{...tA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:vY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let w=(async()=>{let J,U=0,Y=3,f=1000;while(U<Y)try{try{try{await S9(this.config.logDirectory,MZ.F_OK|MZ.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await V9(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:d0.from($);try{if(!IY(this.currentLogFile))await LY(this.currentLogFile,"",{mode:420});if(J=KZ(this.currentLogFile,"a",420),C9(J,Z,{flag:"a"}),NZ(J),J!==void 0)MY(J),J=void 0;if((await _w(this.currentLogFile)).size===0){if(await LY(this.currentLogFile,Z,{flag:"w",mode:420}),(await _w(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(U<Y-1){let h=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,h);let F=f*2**U;await new Promise((j)=>setTimeout(j,F)),U++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{MY(J)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(U===Y-1){let W=Z,h=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}U++;let E=f*2**(U-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Xw(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 Xw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Xw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(e())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,f],[,Z])=>Z.createdAt.getTime()-f.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,Y=Math.max(1,U);if(J.length>Y)for(let[f]of J.slice(Y))this.encryptionKeys.delete(f),this.keys.delete(f)}generateKeyId(){return KY(16).toString("hex")}generateKey(){return KY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=KY(16),J=I9("aes-256-gcm",w,A),U=d0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:d0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=LZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(d0.from(d0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(e())return;let $=await _w(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await _A(this.config.logDirectory),Y=U.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,W)=>{let h=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${f}`;if(await _w(A).catch(()=>null))try{if(await IZ(A,Z),w.compress)try{let E=`${Z}.gz`;await this.compressLogFile(Z,E),await XA(Z)}catch(E){console.error("Error compressing rotated file:",E)}if(Y.length===0&&!U.some((E)=>E.endsWith(".log.1")))try{let E=`${A}.1`;await LY(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await _w(A).catch(()=>null))await IZ(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await _A(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,f)=>f.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await XA(Xw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=RZ($),J=y9(w),U=LZ();await O9(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),IY(this.currentLogFile))try{let $=KZ(this.currentLogFile,"r+");NZ($),MY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await _A(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await XA(Xw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?d.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(f)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let E=K$.stdout.columns||120,W="";if(Y==="warning"||Y==="error")W=`${A} ${U}`;else if(Y==="info"||Y==="success")W=`${A} ${J} ${U}`;else W=`${A} ${J} ${d.cyan(U)}`;if(!f)return W.trim();let h=Z(W).trim().length,F=Z(w).length,j=Math.max(1,E-2-h-F);return`${W.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let Z=Number.parseInt(f,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(f){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 Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,Z;if(w instanceof Error)f=w.message,Z=w.stack;else f=this.formatMessage(w,A);if(this.fancy&&!e()){let W=RW[$],h=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:d.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:f,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:d.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:W,tag:h,message:f,level:$}),console.error(F),Z){let j=Z.split(`
|
|
149
|
+
`);for(let B of j)if(B.trim()&&!B.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:d.gray(` ${B}`),level:$,showTimestamp:!1}))}break}}else if(!e()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),Z)console.error(Z)}if(!this.shouldLog($))return;let E=`${Y} ${this.environment}.${$.toUpperCase()}: ${f}
|
|
150
|
+
`;if(Z)E+=`${Z}
|
|
151
|
+
`;E=E.replace(this.ANSI_PATTERN,""),await this.writeToFile(E)}time($){let w=performance.now();if(this.fancy&&!e()){let A=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:d.blue("◐"),tag:A,message:`${d.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,Z=this.formatConsoleTimestamp(f),E=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
152
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!e()){let W=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:d.green("✓"),tag:W,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!e())console.error(E.trim());await this.writeToFile(E)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new AJ(w,{...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(A),A}createReadStream(){if(e())throw Error("createReadStream is not supported in browser environments");if(!IY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return RZ(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=d0.isBuffer($)?$:d0.from($,"base64"),U=J.slice(0,16),Y=J.slice(-16),f=J.slice(16,-16),Z=L9("aes-256-gcm",A,U);return Z.setAuthTag(Y),d0.concat([Z.update(f),Z.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return e()}isServerMode(){return!e()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w);if(this.fancy&&!e()){let Y=$.split(`
|
|
153
|
+
`),f=Math.max(...Y.map((h)=>h.length))+2,Z=`┌${"─".repeat(f)}┐`,E=`└${"─".repeat(f)}┘`,W=Y.map((h)=>{let F=" ".repeat(f-h.length-2);return`│ ${h}${F} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:d.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:d.cyan(Z)})),W.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:A,message:d.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:d.cyan(E),showTimestamp:!1}))}else if(!e())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let U=`${J} ${this.environment}.INFO: [BOX] ${$}
|
|
154
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(e())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${d.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();K$.stdin.removeListener("data",A);try{if(typeof K$.stdin.setRawMode==="function")K$.stdin.setRawMode(!1)}catch{}K$.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof K$.stdin.setRawMode==="function")K$.stdin.setRawMode(!0)}catch{}K$.stdin.resume(),K$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,Y=0;if(A=$.replace(U,(f,Z)=>{if(Z==="%")return"%";if(Y>=w.length)return f;let E=w[Y++];switch(Z){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return f}}),Y<w.length)A+=` ${w.slice(Y).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!e()){let U=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",Y=d.blue("◐");console.error(`${Y} ${U} ${d.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
155
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||e()||$<=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 A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,J)),U!==void 0)this.activeProgressBar.message=U;let Y=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Y)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;if(this.activeProgressBar.current=this.activeProgressBar.total,J!==void 0)this.activeProgressBar.message=J;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(J,U="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;K$.stdout.write(`${"\r".padEnd(K$.stdout.columns||80)}\r`),this.log(U,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||e()||!K$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=d.green("━".repeat(J)),f=d.gray("━".repeat(U)),Z=`[${Y}${f}]`,E=`${A}%`.padStart(4),W=$.message?` ${$.message}`:"",h=w||A===100?d.green("✓"):d.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${d.gray(this.formatTag(this.name))}`:"",j=`\r${h}${F} ${Z} ${E}${W}`,B=K$.stdout.columns||80,H=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${H}`,K$.stdout.write($.lastRenderedLine),w)K$.stdout.write(`
|
|
156
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||e()||!K$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await _A(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=Xw(this.config.logDirectory,J);if($.before)try{if((await _w(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await XA(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function gA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&n(w[0])&&"id"in w[0]&&w[0].id===3&&n(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(n(w)&&n($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(n($)&&"arr"in $&&Array.isArray($.arr)&&n(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&n(w[0])&&n($[0])){let J=[...w];for(let U of $)if(n(U)&&"name"in U){if(!J.find((Y)=>n(Y)&&("name"in Y)&&Y.name===U.name))J.push(U)}else if(n(U)&&"path"in U){if(!J.find((Y)=>n(Y)&&("path"in Y)&&Y.path===U.path))J.push(U)}else if(!J.some((Y)=>JJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!n(w)||!n($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(n(U)&&n(A[J]))A[J]=gA(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&n(U[0])&&n(A[J][0])){let Y=[...U];for(let f of A[J])if(n(f)&&"name"in f){if(!Y.find((Z)=>n(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(n(f)&&"path"in f){if(!Y.find((Z)=>n(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((Z)=>JJ(Z,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function Uf($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:gA($,w);if(Array.isArray($))return A==="replace"?w:gA($,w);if(!n(w)||!n($))return w;let J={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let Y=w[U],f=J[U];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(f))if(A==="replace")J[U]=Y;else J[U]=gA(f,Y);else if(n(Y)&&n(f))J[U]=Uf(f,Y,A);else J[U]=Y}return J}function JJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!JJ($[A],w[A]))return!1;return!0}if(n($)&&n(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!JJ($[U],w[U]))return!1}return!0}return!1}function n($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function mA($,w,A="replace"){if(!UW($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return Uf(w,U,A)}catch{return null}}catch{return null}}function zT($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,Z=[]){let E={...f};for(let[W,h]of Object.entries(f)){let F=[...Z,W],j=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),B=`${J}_${F.map(j).join("_")}`,H=`${J}_${F.map((T)=>T.toUpperCase()).join("_")}`;if(A)I$.info(`Checking environment variable ${B} for config ${$}.${F.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))E[W]=Y(h,F);else{let T=q1.env[B]||q1.env[H];if(T!==void 0){if(A)I$.info(`Using environment variable ${T?B:H} for config ${$}.${F.join(".")}`);if(typeof h==="number")E[W]=Number(T);else if(typeof h==="boolean")E[W]=T.toLowerCase()==="true";else if(Array.isArray(h))try{let q=JSON.parse(T);if(Array.isArray(q))E[W]=q;else E[W]=T.split(",").map((G)=>G.trim())}catch{E[W]=T.split(",").map((q)=>q.trim())}else E[W]=T}}}return E}return Y(U)}async function TT({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:U,verbose:Y=!1,checkEnv:f=!0,arrayStrategy:Z="replace"}){let E=f&&typeof U==="object"&&U!==null&&!Array.isArray(U)?zT($,U,Y):U,W=A||q1.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(Y)I$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${W}`);let F=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),B=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],T=Array.from(new Set([W,_$(W,"config"),_$(W,".config"),J?_$(W,J):void 0].filter(Boolean)));for(let q of T){if(Y)I$.info(`Searching for configuration in: ${q}`);let G=[_$(W,"config"),_$(W,".config")].concat(J?[_$(W,J)]:[]).includes(q)?[...F,...j,...B,...H]:[...j,...F,...H,...B];for(let R of G)for(let K of h){let y=_$(q,`${R}${K}`),C=await mA(y,E,Z);if(C!==null){if(Y)I$.success(`Configuration loaded from: ${y}`);return C}}}if($){let q=_$(NY(),".config",$),G=["config",`${$}.config`];if(w)G.push(`${w}.config`);if(Y)I$.info(`Checking user config directory: ${q}`);for(let R of G)for(let K of h){let y=_$(q,`${R}${K}`),C=await mA(y,E,Z);if(C!==null){if(Y)I$.success(`Configuration loaded from user config directory: ${y}`);return C}}}if($){let q=_$(NY(),".config"),G=[`.${$}.config`];if(w)G.push(`.${w}.config`);if(Y)I$.info(`Checking user config directory for dotfile configs: ${q}`);for(let R of G)for(let K of h){let y=_$(q,`${R}${K}`),C=await mA(y,E,Z);if(C!==null){if(Y)I$.success(`Configuration loaded from user config directory dotfile: ${y}`);return C}}}if($){let q=NY(),G=[`.${$}.config`,`.${$}`];if(w)G.push(`.${w}.config`),G.push(`.${w}`);if(Y)I$.info(`Checking user home directory for dotfile configs: ${q}`);for(let R of G)for(let K of h){let y=_$(q,`${R}${K}`),C=await mA(y,E,Z);if(C!==null){if(Y)I$.success(`Configuration loaded from user home directory: ${y}`);return C}}}try{let q=_$(W,"package.json");if(UW(q)){let G=await import(q),R=G[$];if(!R&&w){if(R=G[w],R&&Y)I$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(Y)I$.success(`Configuration loaded from package.json: ${R===G[$]?$:w}`);return Uf(E,R,Z)}catch(K){if(Y)I$.warn("Failed to merge package.json config:",K)}}}catch(q){if(Y)I$.warn("Failed to load package.json:",q)}if(Y)I$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return E}function HT($,w={}){let A=aA.cwd();while(A.includes("storage"))A=GZ(A,"..");let J=GZ(A,$||"");if(w?.relative)return N9(aA.cwd(),J);return J}async function GT(){try{let $=await TT({name:"clarity",alias:"logging",defaultConfig:pA,cwd:aA.cwd()});return{...pA,...$||{}}}catch{return pA}}function f$(){if(O0.env.NODE_ENV==="test"||O0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function qT(){if(O0.env.NODE_ENV==="test"||O0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof O0<"u"){let $=O0.type;if($==="renderer"||$==="worker")return!1;return!!(O0.versions&&(O0.versions.node||O0.versions.bun))}return!1}class hW{async format($){let w=await qT(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Pw.pid,hostname:w(),environment:Pw.env.NODE_ENV||"development",platform:Pw.platform,version:Pw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Pw.env.NODE_ENV||Pw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class UJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...mY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new hW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??c.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...rA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...rA};return{...rA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:mY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!f$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let J,U=0,Y=3,f=1000;while(U<Y)try{try{try{await Q9(this.config.logDirectory,VZ.F_OK|VZ.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await x9(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:y0.from($);try{if(!kA(this.currentLogFile))await SY(this.currentLogFile,"",{mode:420});if(J=SZ(this.currentLogFile,"a",420),k9(J,Z,{flag:"a"}),CZ(J),J!==void 0)CY(J),J=void 0;if((await Qw(this.currentLogFile)).size===0){if(await SY(this.currentLogFile,Z,{flag:"w",mode:420}),(await Qw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(U<Y-1){let h=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,h);let F=f*2**U;await new Promise((j)=>setTimeout(j,F)),U++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{CY(J)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(U===Y-1){let W=Z,h=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}U++;let E=f*2**(U-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return xw(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 xw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return xw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(f$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,f],[,Z])=>Z.createdAt.getTime()-f.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,Y=Math.max(1,U);if(J.length>Y)for(let[f]of J.slice(Y))this.encryptionKeys.delete(f),this.keys.delete(f)}generateKeyId(){return yY(16).toString("hex")}generateKey(){return yY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=yY(16),J=D9("aes-256-gcm",w,A),U=y0.isBuffer($)?$:y0.from($,"utf8"),Y=J.update(U),f=J.final(),Z=Y.length+f.length,E=J.getAuthTag(),W=y0.allocUnsafe(16+Z+16);return A.copy(W,0),Y.copy(W,16),f.copy(W,16+Y.length),E.copy(W,16+Z),{encrypted:W,iv:A}}async compressData($){return new Promise((w,A)=>{let J=DZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(y0.from(y0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(f$())return;if(!this.shouldWriteToFile())return;let $=await Qw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await QA(this.config.logDirectory),Y=U.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,W)=>{let h=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${f}`;if(await Qw(A).catch(()=>null))try{if(await OZ(A,Z),w.compress)try{let E=`${Z}.gz`;await this.compressLogFile(Z,E),await xA(Z)}catch(E){console.error("Error compressing rotated file:",E)}if(Y.length===0&&!U.some((E)=>E.endsWith(".log.1")))try{let E=`${A}.1`;await SY(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await Qw(A).catch(()=>null))await OZ(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await QA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,f)=>f.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await xA(xw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=yZ($),J=X9(w),U=DZ();await i9(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),kA(this.currentLogFile))try{let $=SZ(this.currentLogFile,"r+");CZ($),CY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!f$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await QA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await xA(xw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?X.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||f$())return!1;let $=typeof c.env.NO_COLOR<"u",w=c.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof c.stderr<"u"&&c.stderr.isTTY||typeof c.stdout<"u"&&c.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(f)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let E=c.stdout.columns||120,W="";if(Y==="warning"||Y==="error")W=`${A} ${U}`;else if(Y==="info"||Y==="success")W=`${A} ${J} ${U}`;else W=`${A} ${J} ${X.cyan(U)}`;if(!f)return W.trim();let h=Z(W).trim().length,F=Z(w).length,j=Math.max(1,E-2-h-F);return`${W.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let Z=Number.parseInt(f,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(f){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 Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=X.underline(X.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(f)}`,E="\x1B]8;;",W="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>X.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>X.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>X.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>X.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>X.strikethrough(J)),w}supportsHyperlinks(){if(f$())return!1;let $=c.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=c.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(P9(w)||w.startsWith("./")||w.startsWith("../"))w=b9(w);else return null;return kA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,Z;if(w instanceof Error)f=w.message,Z=w.stack;else f=this.formatMessage(w,A);let{consoleText:E,fileText:W}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":NW[$],j=this.options.showTags!==!1&&this.name?X.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:X.gray(E),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:X.green(E),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.error(B),Z){let H=Z.split(`
|
|
157
|
+
`);for(let T of H)if(T.trim()&&!T.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:X.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!f$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),Z)console.error(Z)}if(!this.shouldLog($))return;let h=`${Y} ${this.environment}.${$.toUpperCase()}: ${W}
|
|
158
|
+
`;if(Z)h+=`${Z}
|
|
159
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress($,w=""){let A={update:(U,Y)=>{},finish:(U)=>{},interrupt:(U,Y)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!f$()&&c.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,Y)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),Y!==void 0)this.activeProgressBar.message=Y;if(this.shouldStyleConsole()&&!f$()&&c.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,Y="info")=>{if(!f$()&&c.stdout.isTTY)c.stdout.write(`
|
|
160
|
+
`);if(this[Y==="warning"?"warn":Y](U),this.activeProgressBar&&this.shouldStyleConsole()&&!f$()&&c.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?X.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":X.blue("◐"),tag:A,message:`${X.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,Z=this.formatConsoleTimestamp(f),E=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
161
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?X.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":X.green("✓"),tag:W,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!f$())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new UJ(w,{...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(A),A}createReadStream(){if(f$())throw Error("createReadStream is not supported in browser environments");if(!kA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return yZ(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=y0.isBuffer($)?$:y0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),Z=_9("aes-256-gcm",A,U);Z.setAuthTag(Y);let E=Z.update(f),W=Z.final(),h=E.length+W.length,F=y0.allocUnsafe(h);return E.copy(F,0),W.copy(F,E.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return f$()}isServerMode(){return!f$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=U.split(`
|
|
162
|
+
`),E=Math.max(...Z.map((j)=>j.length))+2,W=`┌${"─".repeat(E)}┐`,h=`└${"─".repeat(E)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:X.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:X.cyan(W),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:X.cyan(h),showTimestamp:!1}))}else if(!f$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
163
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(f$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${X.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();c.stdin.removeListener("data",A);try{if(typeof c.stdin.setRawMode==="function")c.stdin.setRawMode(!1)}catch{}c.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof c.stdin.setRawMode==="function")c.stdin.setRawMode(!0)}catch{}c.stdin.resume(),c.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,Z=0;if(A=$.replace(f,(E,W)=>{if(W==="%")return"%";if(Z>=w.length)return E;let h=w[Z++];switch(W){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return E}}),Z<w.length)A+=` ${w.slice(Z).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?X.gray(this.formatTag(this.name)):"",Z=this.options.showIcons===!1?"":`${X.blue("◐")} `;console.error(`${Z}${f} ${X.cyan(J)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
164
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!c.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=X.green("━".repeat(J)),f=X.gray("━".repeat(U)),Z=`[${Y}${f}]`,E=`${A}%`.padStart(4),W=$.message?` ${$.message}`:"",h=this.options.showIcons===!1?"":w||A===100?X.green("✓"):X.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${X.gray(this.formatTag(this.name))}`:"",j=`\r${h}${F} ${Z} ${E}${W}`,B=c.stdout.columns||80,H=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${H}`,c.stdout.write($.lastRenderedLine),w)c.stdout.write(`
|
|
165
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||f$()||!c.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(f$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await QA(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=xw(this.config.logDirectory,J);if($.before)try{if((await Qw(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await xA(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function FW($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let Z=0;Z<=A;Z++)try{return await $()}catch(E){if(f=E instanceof Error?E:Error(String(E)),Z===A||!U(f))break;if(J>0)await new Promise((W)=>setTimeout(W,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}function BW($){return $ instanceof n$}function RT($){return $ instanceof YJ}function NT($){if(BW($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((w)=>$.message.toLowerCase().includes(w.toLowerCase()))}class jJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:J,useCamelCase:U=!0,useBackwardCompatibility:Y=!0,customParsers:f={},verbose:Z=!1,trackPerformance:E=!0}=A,W=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let h=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],h,{useCamelCase:U,useBackwardCompatibility:Y,customParsers:f,verbose:Z,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(E)return M1.track("applyEnvironmentVariables",W,{configName:$});return W()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],Z=f.map((h)=>this.formatEnvKey(h,J.useCamelCase)),E=`${A}_${Z.join("_")}`,W=J.useBackwardCompatibility?`${A}_${f.map((h)=>h.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,f,A,J);else{let h=PA.env[E]||(W?PA.env[W]:void 0);if(h!==void 0){if(J.verbose){let F=PA.env[E]?E:W}try{$[U]=this.parseEnvironmentValue(h,typeof Y,E,J.customParsers,J.configName)}catch(F){if(F instanceof fJ)throw F;throw l0.envVar(E,h,typeof Y,J.configName)}}}}}parseEnvironmentValue($,w,A,J,U){for(let[Y,f]of Object.entries(J))try{return f($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,w))try{return Y.parse($)}catch{throw l0.envVar(A,$,`${w} (via ${Y.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,U]of Object.entries(PA.env))if(J.startsWith(A)&&U!==void 0)w[J]=U;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(U){J.push(`Cannot parse value "${w}" as ${A}: ${U}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:U="text"}=A,Y=J||this.generateEnvPrefix($),f=[];switch(this.extractEnvVarInfo(w,[],Y,f),U){case"markdown":return this.formatAsMarkdown(f,$);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,$)}}extractEnvVarInfo($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],Z=`${A}_${f.map((E)=>this.formatEnvKey(E,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,f,A,J);else J.push({key:Z,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${f.join(".")}`,example:this.generateExample(Y)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
166
166
|
|
|
167
167
|
`;for(let J of $)A+=`${J.key}
|
|
168
168
|
`,A+=` Type: ${J.type}
|
|
@@ -174,25 +174,25 @@ export type ConfigOf = Config
|
|
|
174
174
|
`;A+=`| Variable | Type | Description | Example |
|
|
175
175
|
`,A+=`|----------|------|-------------|----------|
|
|
176
176
|
`;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
|
|
177
|
-
`;return A}}function EH($,w){let A=fE("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function JE($,w,A={}){return UE($,w,A,new WeakMap)}function UE($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:h}=A;if(w===null||w===void 0)return Y?$:w;if(h){let Z=h($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return YE($,w,U,J);if(!o$(w)||!o$($))return w;return jH($,w,A,J)}function YE($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return WH($,w);case"smart":return FH($,w,J);default:return w}return w}function WH($,w){let A=[...w];for(let J of $)if(!A.some((U)=>QY(U,J)))A.push(J);return A}function FH($,w,A){if(w.length===0)return $;if($.length===0)return w;if(o$(w[0])&&o$($[0]))return BH($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function BH($,w,A){let J=[...w];for(let U of $){if(!o$(U)){J.push(U);continue}let Y=["id","name","key","path","type"],h=!1;for(let Z of Y)if(Z in U){if(J.find((f)=>o$(f)&&(Z in f)&&f[Z]===U[Z])){h=!0;break}}if(!h)J.push(U)}return J}function jH($,w,A,J){let U=w;if(o$(U)&&J.has(U))return J.get(U);let Y={...$};if(o$(U))J.set(U,Y);for(let h in U){if(!Object.prototype.hasOwnProperty.call(U,h))continue;let Z=U[h],f=Y[h];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){Y[h]=Z;continue}if(o$(Z)&&o$(f))Y[h]=UE(f,Z,A,J);else if(Array.isArray(Z)||Array.isArray(f))Y[h]=YE(f,Z,A.arrayMergeMode||"smart",J);else Y[h]=Z}return Y}function oY($,w,A="replace"){return JE($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function QY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!QY($[A],w[A]))return!1;return!0}if(o$($)&&o$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!QY($[U],w[U]))return!1}return!0}return!1}function o$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class BJ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:h=!0,verbose:Z=!1}=A;if(U){let E=vw.getWithFileCheck("file",$);if(E){if(Z)console.log(`Configuration loaded from cache: ${$}`);return E}}let f=async()=>{if(!xA($))return null;try{let E=`?t=${Date.now()}`,W=await import($+E),F=W.default||W,j="default"in W,B=Object.keys(W).length>0;if(!j&&!B)throw new G1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new G1($,Error("Configuration must export a valid object"),"unknown");let T={config:oY(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)vw.setWithFileCheck("file",T,$,Y);return T}catch(E){throw E instanceof Error?l0.configLoad($,E):l0.configLoad($,Error(String(E)))}};if(h)return N1.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let h of this.extensions)U.push(KY(w,`${Y}${h}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return wE(async()=>{return xA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!xA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let h of this.extensions){let Z=KY($,`${Y}${h}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let h of Y)if(this.looksLikeConfigFile(h)){let Z=KY($,h);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){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((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!xA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class eY{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:h=[],trackPerformance:Z=!0,verbose:f=!1}=A,E=async()=>{let W=[],F=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:h,trackPerformance:Z,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...h],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return W.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:W,warnings:F}}};if(Z)return await N1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!S9(w))throw new q1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new q1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let h=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(h)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${h}`,expected:Z.join(" or "),actual:h,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let h=0;h<$.length;h++){let Z=A?`${A}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema($[h],w.items,Z,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let h=$;if(Y.validateRequired&&w.required){for(let Z of w.required)if(!(Z in h)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[Z,f]of Object.entries(w.properties))if(Z in h){let E=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(h[Z],f,E,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(h))if(!Z.has(f))U.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let h=this.getValueByPath($,Y.path),Z=this.validateWithRule(h,Y,Y.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(h){J.push({path:Y.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,h]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(h)})}return w}mapTypeScriptType($){switch($.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:BE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class $h{fileLoader=new BJ;envProcessor=new FJ;validator=new eY;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...h}=$;try{if(A?.enabled){let f=this.checkCache(h.name||"",h);if(f)return f}let Z;try{Z=await this.loadConfigurationStrategies(h,!0,A)}catch(f){let E=h.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(E)throw f;Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let W=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),F=!W&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),j=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(E&&(j||W))throw f;if(F&&(!E||!j))Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||Y)await this.validateConfiguration(Z.config,U,Y,h.name);if(A?.enabled&&Z)this.cacheResult(h.name||"",Z,A,h);if(J?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:h.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(f);if(J.slowThreshold&&f.duration>J.slowThreshold)h0.warn(`Slow configuration loading detected: ${f.duration}ms for ${h.name}`);Z.metrics=f}return Z}catch(Z){let f=Date.now()-w;throw h0.error(`Configuration loading failed after ${f}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:h,defaultConfig:Z,checkEnv:f=!0,arrayStrategy:E="replace",verbose:W=!1}=$,F=Y||$w.cwd(),j=[],B=await this.loadLocalConfiguration(J,U,F,h,Z,E,W,f,A);if(B)return j.push(...this.getLocalSearchPaths(J,U,F,h)),this.finalizeResult(B,j,f,J,W);let T=await this.loadHomeConfiguration(J,U,Z,E,W,f);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,f,J,W);let H=await this.loadPackageJsonConfiguration(J,U,F,Z,E,W,f);if(H)return j.push(X$(F,"package.json")),this.finalizeResult(H,j,f,J,W);if(j.push(...this.getAllSearchPaths(J,U,F,h)),w)throw l0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,Z,f,W),warnings:[`No configuration file found for "${J}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,h,Z,f){let E=Z?z1($,U,h):U,W=this.getLocalDirectories(A,J);for(let F of W){if(h)h0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:h,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(B){if(h)h0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let h=Y?z1($,A,U):A,Z=[X$(_w(),".config",$),X$(_w(),".config"),_w()];for(let f of Z){if(U)h0.info(`Checking home directory: ${f}`);let E=this.fileLoader.generateConfigPaths($,f,w),W=await this.fileLoader.tryLoadFromPaths(E,h,{arrayStrategy:J,verbose:U});if(W){if(U)h0.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,h){let Z=h?z1($,J,Y):J;try{let f=X$(A,"package.json");if(!XY(f))return null;let E=await import(f),W=E[$],F=$;if(!W&&w)W=E[w],F=w;if(W&&typeof W==="object"&&!Array.isArray(W)){if(Y)h0.success(`Configuration loaded from package.json: ${F}`);return{config:oY(Z,W,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(Y)h0.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:z1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(U.length>0)throw l0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return vw.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);vw.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,X$($,"config"),X$($,".config"),w?X$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(X$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let h of U)Y.push(...this.fileLoader.generateConfigPaths($,h,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[X$(_w(),".config",$),X$(_w(),".config"),_w()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function DZ($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||A}async function zH($){return X0.loadConfig({...$,__strictErrorHandling:!0})}async function hE($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await X0.loadConfig($);else J=await X0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let U=J instanceof Error?J.name:"UnknownError",Y=J instanceof Error?J.message:String(J);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||Y.includes("config"))&&$.verbose)h0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let h=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await X0.applyEnvironmentVariables(h.name||"",w,!0,h.verbose||!1))?.config??w;return w}}async function HH($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await X0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&DZ(A)))return(await X0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await X0.loadConfig({...$,cwd:$.cwd||$w.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&DZ(w)))return(await X0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function TH($,w,A="replace"){let J=new BJ;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function z1($,w,A=!1){let J=new FJ,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(h,Z=[]){let f={...h};for(let[E,W]of Object.entries(h)){let F=[...Z,E],j=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((H)=>H.toUpperCase()).join("")}`,`${U}_${F.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,T;for(let H of j)if(B=$w.env[H],B!==void 0){T=H;break}if(B!==void 0&&T)if(typeof W==="boolean")f[E]=["true","1","yes"].includes(B.toLowerCase());else if(typeof W==="number"){let H=Number(B);if(!Number.isNaN(H))f[E]=H}else if(Array.isArray(W))try{f[E]=JSON.parse(B)}catch{f[E]=B.split(",").map((H)=>H.trim())}else f[E]=B;else if(W&&typeof W==="object"&&!Array.isArray(W))f[E]=Y(W,F)}return f}return Y(w)}function GH($){let w=X$($w.cwd(),$.configDir),A=X$($w.cwd(),$.generatedDir),J=X$(A,"config-types.ts");if(!XY(hZ(J)))U9(hZ(J),{recursive:!0,mode:511});let U=XY(w)?Y9(w).map((h)=>h.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${lH}
|
|
177
|
+
`;return A}}function KT($,w){let A=GW("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function jW($,w,A={}){return zW($,w,A,new WeakMap)}function zW($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:f}=A;if(w===null||w===void 0)return Y?$:w;if(f){let Z=f($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return TW($,w,U,J);if(!o$(w)||!o$($))return w;return yT($,w,A,J)}function TW($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return MT($,w);case"smart":return IT($,w,J);default:return w}return w}function MT($,w){let A=[...w];for(let J of $)if(!A.some((U)=>nY(U,J)))A.push(J);return A}function IT($,w,A){if(w.length===0)return $;if($.length===0)return w;if(o$(w[0])&&o$($[0]))return LT($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function LT($,w,A){let J=[...w];for(let U of $){if(!o$(U)){J.push(U);continue}let Y=["id","name","key","path","type"],f=!1;for(let Z of Y)if(Z in U){if(J.find((E)=>o$(E)&&(Z in E)&&E[Z]===U[Z])){f=!0;break}}if(!f)J.push(U)}return J}function yT($,w,A,J){let U=w;if(o$(U)&&J.has(U))return J.get(U);let Y={...$};if(o$(U))J.set(U,Y);for(let f in U){if(!Object.prototype.hasOwnProperty.call(U,f))continue;let Z=U[f],E=Y[f];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){Y[f]=Z;continue}if(o$(Z)&&o$(E))Y[f]=zW(E,Z,A,J);else if(Array.isArray(Z)||Array.isArray(E))Y[f]=TW(E,Z,A.arrayMergeMode||"smart",J);else Y[f]=Z}return Y}function Yf($,w,A="replace"){return jW($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function nY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!nY($[A],w[A]))return!1;return!0}if(o$($)&&o$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!nY($[U],w[U]))return!1}return!0}return!1}function o$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class zJ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:f=!0,verbose:Z=!1}=A;if(U){let W=nw.getWithFileCheck("file",$);if(W){if(Z)console.log(`Configuration loaded from cache: ${$}`);return W}}let E=async()=>{if(!bA($))return null;try{let W=`?t=${Date.now()}`,h=await import($+W),F=h.default||h,j="default"in h,B=Object.keys(h).length>0;if(!j&&!B)throw new R1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new R1($,Error("Configuration must export a valid object"),"unknown");let H={config:Yf(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)nw.setWithFileCheck("file",H,$,Y);return H}catch(W){throw W instanceof Error?l0.configLoad($,W):l0.configLoad($,Error(String(W)))}};if(f)return M1.track("loadFromPath",E,{path:$});return E()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let f of this.extensions)U.push(VY(w,`${Y}${f}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return FW(async()=>{return bA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!bA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let Z=VY($,`${Y}${f}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let f of Y)if(this.looksLikeConfigFile(f)){let Z=VY($,f);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){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((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!bA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class ff{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:Z=!0,verbose:E=!1}=A,W=async()=>{let h=[],F=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:Z,verbose:E};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return h.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:h,warnings:F}}};if(Z)return await M1.track("validateConfiguration",W);return W()}async validateWithSchemaFile($,w,A){try{if(!c9(w))throw new N1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new N1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let f=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(f)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${f}`,expected:Z.join(" or "),actual:f,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let f=0;f<$.length;f++){let Z=A?`${A}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema($[f],w.items,Z,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let f=$;if(Y.validateRequired&&w.required){for(let Z of w.required)if(!(Z in f)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[Z,E]of Object.entries(w.properties))if(Z in f){let W=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(f[Z],E,W,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let E of Object.keys(f))if(!Z.has(E))U.push({path:A?`${A}.${E}`:E,message:`Additional property '${E}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let f=this.getValueByPath($,Y.path),Z=this.validateWithRule(f,Y,Y.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(f){J.push({path:Y.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,f]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(f)})}return w}mapTypeScriptType($){switch($.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:MW},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ef{fileLoader=new zJ;envProcessor=new jJ;validator=new ff;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...f}=$;try{if(A?.enabled){let E=this.checkCache(f.name||"",f);if(E)return E}let Z;try{Z=await this.loadConfigurationStrategies(f,!0,A)}catch(E){let W=f.__strictErrorHandling;if(E instanceof Error&&E.name==="ConfigNotFoundError"){if(W)throw E;Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(E instanceof Error&&E.name==="ConfigLoadError"){let h=E.message.includes("EACCES")||E.message.includes("EPERM")||E.message.includes("permission denied"),F=!h&&(E.message.includes("syntax")||E.message.includes("Expected")||E.message.includes("Unexpected")||E.message.includes("BuildMessage")||E.message.includes("errors building")),j=E.message.includes("Configuration must export a valid object")||E.message.includes("Configuration file is empty and exports nothing");if(W&&(j||h))throw E;if(F&&(!W||!j))Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!W)Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${E.message}`]};else throw E}else Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${E instanceof Error?E.message:String(E)}`]}}if(U||Y)await this.validateConfiguration(Z.config,U,Y,f.name);if(A?.enabled&&Z)this.cacheResult(f.name||"",Z,A,f);if(J?.enabled){let E={operation:"loadConfig",duration:Date.now()-w,configName:f.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(E);if(J.slowThreshold&&E.duration>J.slowThreshold)f0.warn(`Slow configuration loading detected: ${E.duration}ms for ${f.name}`);Z.metrics=E}return Z}catch(Z){let E=Date.now()-w;throw f0.error(`Configuration loading failed after ${E}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:f,defaultConfig:Z,checkEnv:E=!0,arrayStrategy:W="replace",verbose:h=!1}=$,F=Y||$w.cwd(),j=[],B=await this.loadLocalConfiguration(J,U,F,f,Z,W,h,E,A);if(B)return j.push(...this.getLocalSearchPaths(J,U,F,f)),this.finalizeResult(B,j,E,J,h);let H=await this.loadHomeConfiguration(J,U,Z,W,h,E);if(H)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(H,j,E,J,h);let T=await this.loadPackageJsonConfiguration(J,U,F,Z,W,h,E);if(T)return j.push(X$(F,"package.json")),this.finalizeResult(T,j,E,J,h);if(j.push(...this.getAllSearchPaths(J,U,F,f)),w)throw l0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,Z,E,h),warnings:[`No configuration file found for "${J}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,Z,E){let W=Z?H1($,U,f):U,h=this.getLocalDirectories(A,J);for(let F of h){if(f)f0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,W,{arrayStrategy:Y,verbose:f,cacheTtl:E?.ttl,useCache:!E?.ttl||E.ttl>100});if(B){if(f)f0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?H1($,A,U):A,Z=[X$(Dw(),".config",$),X$(Dw(),".config"),Dw()];for(let E of Z){if(U)f0.info(`Checking home directory: ${E}`);let W=this.fileLoader.generateConfigPaths($,E,w),h=await this.fileLoader.tryLoadFromPaths(W,f,{arrayStrategy:J,verbose:U});if(h){if(U)f0.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let Z=f?H1($,J,Y):J;try{let E=X$(A,"package.json");if(!cY(E))return null;let W=await import(E),h=W[$],F=$;if(!h&&w)h=W[w],F=w;if(h&&typeof h==="object"&&!Array.isArray(h)){if(Y)f0.success(`Configuration loaded from package.json: ${F}`);return{config:Yf(Z,h,U),source:{type:"package.json",path:E,priority:30,timestamp:new Date}}}}catch(E){if(Y)f0.warn("Failed to load package.json:",[E instanceof Error?E:Error(String(E))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:H1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(U.length>0)throw l0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return nw.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);nw.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,X$($,"config"),X$($,".config"),w?X$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(X$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let f of U)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[X$(Dw(),".config",$),X$(Dw(),".config"),Dw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function cZ($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||A}async function CT($){return X0.loadConfig({...$,__strictErrorHandling:!0})}async function HW($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await X0.loadConfig($);else J=await X0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let U=J instanceof Error?J.name:"UnknownError",Y=J instanceof Error?J.message:String(J);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||Y.includes("config"))&&$.verbose)f0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let f=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await X0.applyEnvironmentVariables(f.name||"",w,!0,f.verbose||!1))?.config??w;return w}}async function ST($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await X0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&cZ(A)))return(await X0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await X0.loadConfig({...$,cwd:$.cwd||$w.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&cZ(w)))return(await X0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function VT($,w,A="replace"){let J=new zJ;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function H1($,w,A=!1){let J=new jJ,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,Z=[]){let E={...f};for(let[W,h]of Object.entries(f)){let F=[...Z,W],j=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((T)=>T.toUpperCase()).join("")}`,`${U}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,H;for(let T of j)if(B=$w.env[T],B!==void 0){H=T;break}if(B!==void 0&&H)if(typeof h==="boolean")E[W]=["true","1","yes"].includes(B.toLowerCase());else if(typeof h==="number"){let T=Number(B);if(!Number.isNaN(T))E[W]=T}else if(Array.isArray(h))try{E[W]=JSON.parse(B)}catch{E[W]=B.split(",").map((T)=>T.trim())}else E[W]=B;else if(h&&typeof h==="object"&&!Array.isArray(h))E[W]=Y(h,F)}return E}return Y(w)}function OT($){let w=X$($w.cwd(),$.configDir),A=X$($w.cwd(),$.generatedDir),J=X$(A,"config-types.ts");if(!cY(HZ(J)))H9(HZ(J),{recursive:!0,mode:511});let U=cY(w)?G9(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${UH}
|
|
178
178
|
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
179
|
-
`;
|
|
180
|
-
${U.map((
|
|
179
|
+
`;q9(J,Y,{mode:438})}function DT($){let w=null,A=null,J=()=>{if(!A)A=HW($).then((Y)=>{return w=Y,Y},(Y)=>{let f="defaultConfig"in $?$.defaultConfig:{};if(w=f,"verbose"in $&&$.verbose)f0.warn("Config loading failed, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);return f});return A},U="defaultConfig"in $?$.defaultConfig:{};return w=U,J(),new Proxy({},{get(Y,f){if(w)return w[f];let Z=U[f];return J(),Z},has(Y,f){return f in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(Y,f){return Object.getOwnPropertyDescriptor(w||U,f)},set(Y,f,Z){if(!w)w={...U};return w[f]=Z,!0}})}function _T($){let w=_Z(v9.cwd(),$?.configDir||"./config");function A(){if(!u9(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),Y=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],f=n9(w).filter((E)=>U.has(OY(E))).map((E)=>({base:E.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:E})),Z=new Map;for(let{base:E,file:W}of f){let h=OY(W).toLowerCase(),F=Z.get(E);if(!F){Z.set(E,W);continue}let j=OY(F).toLowerCase();if(Y.indexOf(h)<Y.indexOf(j))Z.set(E,W)}return Array.from(Z.entries()).map(([E,W])=>({base:E,file:W})).sort((E,W)=>E.base.localeCompare(W.base))}function J(){let U=A(),Y=U.map((E)=>E.base),f=Y.length?Y.map((E)=>`'${E}'`).join(" | "):"string",Z=U.length?`{
|
|
180
|
+
${U.map((E)=>{let W=_Z(w,E.file).replace(/\\/g,"/");return` '${E.base}': typeof import('${W}').default`}).join(`,
|
|
181
181
|
`)}
|
|
182
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
182
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${f}
|
|
183
183
|
export type ConfigByName = ${Z}
|
|
184
184
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
185
185
|
export type ConfigOf = Config
|
|
186
|
-
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}var fE,vw,N1,ZE,NH,KH,OZ,dA,xY,M$,d,MH,_Z,IH,XZ,yH,LH,SY,CH,kZ,QZ,VY,SH,VH,DH,OH,gA,EE,_H,I$,XH,kH,xZ,lA,PY,f$,X,QH,PZ,xH,bZ,PH,bH,DY,iH,iZ,cZ,cH,OY,uH,nH,vH,mH,dH,tA,WE,gH,lH="0.15.6",n$,JJ,G1,bY,iY,UJ,cY,uY,q1,nY,vY,l0,FE,BE,h0,X0,jE,zE,tH=t9(async()=>{fE=import.meta.require,vw=new pY,N1=new rY,ZE={createKey:p9,isEquivalent:r9,estimateMemoryUsage:a9},NH=aA(kY.cwd(),"config"),KH=aA(kY.cwd(),"src/generated"),OZ=rA.env.CLARITY_LOG_DIR||E9(e9(),"logs"),dA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:OZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},xY=await $H(),M$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},d=M$,MH=M$.red,_Z=M$.green,IH=M$.yellow,XZ=M$.blue,yH=M$.magenta,LH=M$.cyan,SY=M$.white,CH=M$.gray,kZ=M$.bgRed,QZ=M$.bgYellow,VY=M$.bold,SH=M$.dim,VH=M$.italic,DH=M$.underline,OH=M$.reset,gA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EE={debug:"\uD83D\uDD0D",info:XZ("ℹ"),success:_Z("✓"),warning:QZ(SY(VY(" WARN "))),error:kZ(SY(VY(" ERROR ")))},_H=new $J("stacks"),I$=new $J("bunfig",{showTags:!0}),XH=_$(T1.cwd(),"config"),kH=_$(T1.cwd(),"src/generated"),xZ=pA.env.CLARITY_LOG_DIR||f9(UH(),"logs"),lA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},PY=await YH(),f$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},X=f$,QH=f$.red,PZ=f$.green,xH=f$.yellow,bZ=f$.blue,PH=f$.magenta,bH=f$.cyan,DY=f$.white,iH=f$.gray,iZ=f$.bgRed,cZ=f$.bgYellow,cH=f$.bgGray,OY=f$.bold,uH=f$.dim,nH=f$.italic,vH=f$.underline,mH=f$.strikethrough,dH=f$.reset,tA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},WE={debug:"\uD83D\uDD0D",info:bZ("ℹ"),success:PZ("✓"),warning:cZ(DY(OY(" WARN "))),error:iZ(DY(OY(" ERROR ")))},gH=new AJ("stacks"),n$=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},JJ=class extends n${code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A?` or alias "${A}"`:"";super(`Configuration "${$}"${J} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}},G1=class extends n${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}},bY=class extends n${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},iY=class extends n${code="CONFIG_MERGE_ERROR";constructor($,w,A,J){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},UJ=class extends n${code="ENV_VAR_ERROR";constructor($,w,A,J){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:J})}},cY=class extends n${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}},uY=class extends n${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}},q1=class extends n${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},nY=class extends n${code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}},vY=class extends n${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}},l0={configNotFound($,w,A){return new JJ($,w,A)},configLoad($,w,A){return new G1($,w,A)},configValidation($,w,A){return new bY($,w,A)},configMerge($,w,A,J){return new iY($,w,A,J)},envVar($,w,A,J){return new UJ($,w,A,J)},fileSystem($,w,A){return new cY($,w,A)},typeGeneration($,w,A){return new uY($,w,A)},schemaValidation($,w,A){return new q1($,w,A)},browserConfig($,w,A,J){return new nY($,w,A,J)},plugin($,w,A){return new vY($,w,A)}},FE={replace:"replace",concat:"concat",smart:"smart"},BE=/^https?:\/\//,h0=new AJ("bunfig",{showTags:!0}),X0=new $h,jE=X$($w.cwd(),"config"),zE=X$($w.cwd(),"src/generated")});function pH($,w={}){let A=sA.cwd();while(A.includes("storage"))A=MZ(A,"..");let J=MZ(A,$||"");if(w?.relative)return X9(sA.cwd(),J);return J}var rH=sA.env.CLARITY_LOG_DIR||_9(pH(),"logs"),HE={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:rH,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},YJ={...HE},lR=(async()=>{try{let{loadConfig:$}=await tH().then(()=>oZ),w=await $({name:"clarity",alias:"logging",defaultConfig:HE,cwd:sA.cwd()});if(w)Object.assign(YJ,w)}catch{}return YJ})();function Z$(){if(O0.env.NODE_ENV==="test"||O0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function aH(){if(O0.env.NODE_ENV==="test"||O0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof O0<"u"){let $=O0.type;if($==="renderer"||$==="worker")return!1;return!!(O0.versions&&(O0.versions.node||O0.versions.bun))}return!1}class TE{async format($){let w=await aH(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:uw.pid,hostname:w(),environment:uw.env.NODE_ENV||"development",platform:uw.platform,version:uw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:uw.env.NODE_ENV||uw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var z$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},x=z$,tR=z$.red,sH=z$.green,pR=z$.yellow,oH=z$.blue,rR=z$.magenta,aR=z$.cyan,uZ=z$.white,sR=z$.gray,eH=z$.bgRed,$T=z$.bgYellow,oR=z$.bgGray,nZ=z$.bold,eR=z$.dim,$N=z$.italic,wN=z$.underline,AN=z$.strikethrough,JN=z$.reset,_Y={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},wT={debug:"\uD83D\uDD0D",info:oH("ℹ"),success:sH("✓"),warning:$T(uZ(nZ(" WARN "))),error:eH(uZ(nZ(" ERROR ")))};class jJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...YJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new TE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??u.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{..._Y,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{..._Y};return{..._Y,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:YJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!Z$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let J,U=0,Y=3,h=1000;while(U<Y)try{try{try{await b9(this.config.logDirectory,CZ.F_OK|CZ.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await i9(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:C0.from($);try{if(!PA(this.currentLogFile))await LY(this.currentLogFile,"",{mode:420});if(J=LZ(this.currentLogFile,"a",420),P9(J,Z,{flag:"a"}),yZ(J),J!==void 0)yY(J),J=void 0;if((await iw(this.currentLogFile)).size===0){if(await LY(this.currentLogFile,Z,{flag:"w",mode:420}),(await iw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let E=f;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(U<Y-1){let W=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,W);let F=h*2**U;await new Promise((j)=>setTimeout(j,F)),U++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(J!==void 0)try{yY(J)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(Z){if(U===Y-1){let E=Z,W=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",W),Z}U++;let f=h*2**(U-1);await new Promise((E)=>setTimeout(E,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return cw(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 cw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return cw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(Z$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,h],[,Z])=>Z.createdAt.getTime()-h.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,Y=Math.max(1,U);if(J.length>Y)for(let[h]of J.slice(Y))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return IY(16).toString("hex")}generateKey(){return IY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=IY(16),J=k9("aes-256-gcm",w,A),U=C0.isBuffer($)?$:C0.from($,"utf8"),Y=J.update(U),h=J.final(),Z=Y.length+h.length,f=J.getAuthTag(),E=C0.allocUnsafe(16+Z+16);return A.copy(E,0),Y.copy(E,16),h.copy(E,16+Y.length),f.copy(E,16+Z),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=VZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(C0.from(C0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(Z$())return;if(!this.shouldWriteToFile())return;let $=await iw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await bA(this.config.logDirectory),Y=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,E)=>{let W=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-W}),h=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${h}`;if(await iw(A).catch(()=>null))try{if(await SZ(A,Z),w.compress)try{let f=`${Z}.gz`;await this.compressLogFile(Z,f),await iA(Z)}catch(f){console.error("Error compressing rotated file:",f)}if(Y.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await LY(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await iw(A).catch(()=>null))await SZ(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await bA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,h)=>h.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await iA(cw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=IZ($),J=x9(w),U=VZ();await n9(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),PA(this.currentLogFile))try{let $=LZ(this.currentLogFile,"r+");yZ($),yY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!Z$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await bA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await iA(cw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?x.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Z$())return!1;let $=typeof u.env.NO_COLOR<"u",w=u.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof u.stderr<"u"&&u.stderr.isTTY||typeof u.stdout<"u"&&u.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:h=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(h)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let f=u.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${x.cyan(U)}`;if(!h)return E.trim();let W=Z(E).trim().length,F=Z(w).length,j=Math.max(1,f-2-W-F);return`${E.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,h)=>{let Z=Number.parseInt(h,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,h)=>{if(h==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(h){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=x.underline(x.blue(J)),h=this.toAbsoluteFilePath(U);if(h&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(h)}`,f="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>x.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>x.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>x.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>x.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>x.strikethrough(J)),w}supportsHyperlinks(){if(Z$())return!1;let $=u.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=u.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(c9(w)||w.startsWith("./")||w.startsWith("../"))w=u9(w);else return null;return PA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),h,Z;if(w instanceof Error)h=w.message,Z=w.stack;else h=this.formatMessage(w,A);let{consoleText:f,fileText:E}=this.buildOutputTexts(h);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":wT[$],j=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:x.gray(f),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:x.green(f),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:f,level:$}),console.error(B),Z){let T=Z.split(`
|
|
187
|
-
`);for(let
|
|
188
|
-
`;if(Z)
|
|
189
|
-
`;if(
|
|
190
|
-
`);if(this[Y==="warning"?"warn":Y](U),this.activeProgressBar&&this.shouldStyleConsole()&&!Z$()&&u.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":x.blue("◐"),tag:A,message:`${x.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,
|
|
191
|
-
`,
|
|
192
|
-
`),
|
|
193
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
194
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!u.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=x.green("━".repeat(J)),
|
|
195
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Z$()||!u.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(Z$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await
|
|
186
|
+
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}var GW,nw,M1,qW,XT,kT,uZ,lA,vY,M$,d,QT,nZ,xT,vZ,PT,bT,QY,iT,mZ,dZ,xY,cT,uT,nT,vT,tA,RW,mT,I$,dT,gT,gZ,pA,mY,E$,X,lT,lZ,tT,tZ,pT,rT,PY,aT,pZ,rZ,sT,bY,oT,eT,$H,wH,AH,rA,NW,JH,UH="0.15.6",n$,YJ,R1,dY,gY,fJ,lY,tY,N1,pY,rY,l0,KW,MW,f0,X0,IW,LW,YH=YT(async()=>{GW=import.meta.require,nw=new wf,M1=new Af,qW={createKey:fT,isEquivalent:ET,estimateMemoryUsage:ZT},XT=oA(uY.cwd(),"config"),kT=oA(uY.cwd(),"src/generated"),uZ=sA.env.CLARITY_LOG_DIR||K9(FT(),"logs"),lA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},vY=await BT(),M$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},d=M$,QT=M$.red,nZ=M$.green,xT=M$.yellow,vZ=M$.blue,PT=M$.magenta,bT=M$.cyan,QY=M$.white,iT=M$.gray,mZ=M$.bgRed,dZ=M$.bgYellow,xY=M$.bold,cT=M$.dim,uT=M$.italic,nT=M$.underline,vT=M$.reset,tA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},RW={debug:"\uD83D\uDD0D",info:vZ("ℹ"),success:nZ("✓"),warning:dZ(QY(xY(" WARN "))),error:mZ(QY(xY(" ERROR ")))},mT=new AJ("stacks"),I$=new AJ("bunfig",{showTags:!0}),dT=_$(q1.cwd(),"config"),gT=_$(q1.cwd(),"src/generated"),gZ=aA.env.CLARITY_LOG_DIR||R9(HT(),"logs"),pA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mY=await GT(),E$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},X=E$,lT=E$.red,lZ=E$.green,tT=E$.yellow,tZ=E$.blue,pT=E$.magenta,rT=E$.cyan,PY=E$.white,aT=E$.gray,pZ=E$.bgRed,rZ=E$.bgYellow,sT=E$.bgGray,bY=E$.bold,oT=E$.dim,eT=E$.italic,$H=E$.underline,wH=E$.strikethrough,AH=E$.reset,rA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},NW={debug:"\uD83D\uDD0D",info:tZ("ℹ"),success:lZ("✓"),warning:rZ(PY(bY(" WARN "))),error:pZ(PY(bY(" ERROR ")))},JH=new UJ("stacks"),n$=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},YJ=class extends n${code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A?` or alias "${A}"`:"";super(`Configuration "${$}"${J} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}},R1=class extends n${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}},dY=class extends n${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},gY=class extends n${code="CONFIG_MERGE_ERROR";constructor($,w,A,J){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},fJ=class extends n${code="ENV_VAR_ERROR";constructor($,w,A,J){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:J})}},lY=class extends n${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}},tY=class extends n${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}},N1=class extends n${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},pY=class extends n${code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}},rY=class extends n${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}},l0={configNotFound($,w,A){return new YJ($,w,A)},configLoad($,w,A){return new R1($,w,A)},configValidation($,w,A){return new dY($,w,A)},configMerge($,w,A,J){return new gY($,w,A,J)},envVar($,w,A,J){return new fJ($,w,A,J)},fileSystem($,w,A){return new lY($,w,A)},typeGeneration($,w,A){return new tY($,w,A)},schemaValidation($,w,A){return new N1($,w,A)},browserConfig($,w,A,J){return new pY($,w,A,J)},plugin($,w,A){return new rY($,w,A)}},KW={replace:"replace",concat:"concat",smart:"smart"},MW=/^https?:\/\//,f0=new UJ("bunfig",{showTags:!0}),X0=new Ef,IW=X$($w.cwd(),"config"),LW=X$($w.cwd(),"src/generated")});function fH($,w={}){let A=eA.cwd();while(A.includes("storage"))A=XZ(A,"..");let J=XZ(A,$||"");if(w?.relative)return d9(eA.cwd(),J);return J}var EH=eA.env.CLARITY_LOG_DIR||m9(fH(),"logs"),yW={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:EH,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},EJ={...yW},ZN=(async()=>{try{let{loadConfig:$}=await YH().then(()=>ZW),w=await $({name:"clarity",alias:"logging",defaultConfig:yW,cwd:eA.cwd()});if(w)Object.assign(EJ,w)}catch{}return EJ})();function Z$(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ZH(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D0<"u"){let $=D0.type;if($==="renderer"||$==="worker")return!1;return!!(D0.versions&&(D0.versions.node||D0.versions.bun))}return!1}class CW{async format($){let w=await ZH(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:cw.pid,hostname:w(),environment:cw.env.NODE_ENV||"development",platform:cw.platform,version:cw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:cw.env.NODE_ENV||cw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var T$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},x=T$,WN=T$.red,WH=T$.green,hN=T$.yellow,hH=T$.blue,FN=T$.magenta,BN=T$.cyan,aZ=T$.white,jN=T$.gray,FH=T$.bgRed,BH=T$.bgYellow,zN=T$.bgGray,sZ=T$.bold,TN=T$.dim,HN=T$.italic,GN=T$.underline,qN=T$.strikethrough,RN=T$.reset,iY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jH={debug:"\uD83D\uDD0D",info:hH("ℹ"),success:WH("✓"),warning:BH(aZ(sZ(" WARN "))),error:FH(aZ(sZ(" ERROR ")))};class TJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...EJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new CW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??u.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...iY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...iY};return{...iY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:EJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!Z$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let J,U=0,Y=3,f=1000;while(U<Y)try{try{try{await r9(this.config.logDirectory,PZ.F_OK|PZ.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await a9(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:C0.from($);try{if(!iA(this.currentLogFile))await XY(this.currentLogFile,"",{mode:420});if(J=xZ(this.currentLogFile,"a",420),p9(J,Z,{flag:"a"}),QZ(J),J!==void 0)_Y(J),J=void 0;if((await bw(this.currentLogFile)).size===0){if(await XY(this.currentLogFile,Z,{flag:"w",mode:420}),(await bw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let W=E;if(W.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(W.code)){if(U<Y-1){let h=typeof W.message==="string"?W.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,h);let F=f*2**U;await new Promise((j)=>setTimeout(j,F)),U++;continue}}if(W?.code&&["ENOSPC","EDQUOT"].includes(W.code))throw Error(`Disk quota exceeded or no space left on device: ${W.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",W),W}finally{if(J!==void 0)try{_Y(J)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(U===Y-1){let W=Z,h=typeof W.message==="string"?W.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}U++;let E=f*2**(U-1);await new Promise((W)=>setTimeout(W,E))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return iw(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 iw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return iw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(Z$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,f],[,Z])=>Z.createdAt.getTime()-f.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,Y=Math.max(1,U);if(J.length>Y)for(let[f]of J.slice(Y))this.encryptionKeys.delete(f),this.keys.delete(f)}generateKeyId(){return DY(16).toString("hex")}generateKey(){return DY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=DY(16),J=g9("aes-256-gcm",w,A),U=C0.isBuffer($)?$:C0.from($,"utf8"),Y=J.update(U),f=J.final(),Z=Y.length+f.length,E=J.getAuthTag(),W=C0.allocUnsafe(16+Z+16);return A.copy(W,0),Y.copy(W,16),f.copy(W,16+Y.length),E.copy(W,16+Z),{encrypted:W,iv:A}}async compressData($){return new Promise((w,A)=>{let J=iZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(C0.from(C0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(Z$())return;if(!this.shouldWriteToFile())return;let $=await bw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await cA(this.config.logDirectory),Y=U.filter((E)=>E.startsWith(this.name)&&/\.log\.\d+$/.test(E)).sort((E,W)=>{let h=Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Z=`${A}.${f}`;if(await bw(A).catch(()=>null))try{if(await bZ(A,Z),w.compress)try{let E=`${Z}.gz`;await this.compressLogFile(Z,E),await uA(Z)}catch(E){console.error("Error compressing rotated file:",E)}if(Y.length===0&&!U.some((E)=>E.endsWith(".log.1")))try{let E=`${A}.1`;await XY(E,"")}catch(E){console.error("Error creating backup file:",E)}}catch(E){console.error(`Error during rotation: ${E instanceof Error?E.message:String(E)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await bw(A).catch(()=>null))await bZ(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await cA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,f)=>f.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await uA(iw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=kZ($),J=t9(w),U=iZ();await e9(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),iA(this.currentLogFile))try{let $=xZ(this.currentLogFile,"r+");QZ($),_Y($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!Z$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await cA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await uA(iw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?x.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Z$())return!1;let $=typeof u.env.NO_COLOR<"u",w=u.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof u.stderr<"u"&&u.stderr.isTTY||typeof u.stdout<"u"&&u.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,Z=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(f)B.push(w);if(Y==="warning")B.push("WARN");else if(Y==="error")B.push("ERROR");else if(A)B.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)B.push(J.replace(/[[\]]/g,""));return B.push(U),B.join(" ")}let E=u.stdout.columns||120,W="";if(Y==="warning"||Y==="error")W=`${A} ${U}`;else if(Y==="info"||Y==="success")W=`${A} ${J} ${U}`;else W=`${A} ${J} ${x.cyan(U)}`;if(!f)return W.trim();let h=Z(W).trim().length,F=Z(w).length,j=Math.max(1,E-2-h-F);return`${W.trim()}${" ".repeat(j)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let Z=Number.parseInt(f,10);return Z<w[0].length?String(w[0][Z]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let Z=w[J++];switch(f){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 Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=x.underline(x.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Z=`file://${encodeURI(f)}`,E="\x1B]8;;",W="\x1B\\";return`\x1B]8;;${Z}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>x.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>x.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>x.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>x.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>x.strikethrough(J)),w}supportsHyperlinks(){if(Z$())return!1;let $=u.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=u.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(s9(w)||w.startsWith("./")||w.startsWith("../"))w=o9(w);else return null;return iA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,Z;if(w instanceof Error)f=w.message,Z=w.stack;else f=this.formatMessage(w,A);let{consoleText:E,fileText:W}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":jH[$],j=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:x.gray(E),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:x.green(E),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:U,icon:F,tag:j,message:E,level:$}),console.error(B),Z){let H=Z.split(`
|
|
187
|
+
`);for(let T of H)if(T.trim()&&!T.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:x.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!Z$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),Z)console.error(Z)}let h=`${Y} ${this.environment}.${$.toUpperCase()}: ${W}
|
|
188
|
+
`;if(Z)h+=`${Z}
|
|
189
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress($,w=""){let A={update:(U,Y)=>{},finish:(U)=>{},interrupt:(U,Y)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!Z$()&&u.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,Y)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),Y!==void 0)this.activeProgressBar.message=Y;if(this.shouldStyleConsole()&&!Z$()&&u.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,Y="info")=>{if(!Z$()&&u.stdout.isTTY)u.stdout.write(`
|
|
190
|
+
`);if(this[Y==="warning"?"warn":Y](U),this.activeProgressBar&&this.shouldStyleConsole()&&!Z$()&&u.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":x.blue("◐"),tag:A,message:`${x.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,Z=this.formatConsoleTimestamp(f),E=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
191
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":x.green("✓"),tag:W,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!Z$())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new TJ(w,{...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(A),A}createReadStream(){if(Z$())throw Error("createReadStream is not supported in browser environments");if(!iA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return kZ(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=C0.isBuffer($)?$:C0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),Z=l9("aes-256-gcm",A,U);Z.setAuthTag(Y);let E=Z.update(f),W=Z.final(),h=E.length+W.length,F=C0.allocUnsafe(h);return E.copy(F,0),W.copy(F,E.length),F.toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Z$()}isServerMode(){return!Z$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let Z=U.split(`
|
|
192
|
+
`),E=Math.max(...Z.map((j)=>j.length))+2,W=`┌${"─".repeat(E)}┐`,h=`└${"─".repeat(E)}┘`,F=Z.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:x.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:x.cyan(W),showTimestamp:!1})),F.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:x.cyan(h),showTimestamp:!1}))}else if(!Z$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
193
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(Z$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${x.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();u.stdin.removeListener("data",A);try{if(typeof u.stdin.setRawMode==="function")u.stdin.setRawMode(!1)}catch{}u.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof u.stdin.setRawMode==="function")u.stdin.setRawMode(!0)}catch{}u.stdin.resume(),u.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,Z=0;if(A=$.replace(f,(E,W)=>{if(W==="%")return"%";if(Z>=w.length)return E;let h=w[Z++];switch(W){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return E}}),Z<w.length)A+=` ${w.slice(Z).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",Z=this.options.showIcons===!1?"":`${x.blue("◐")} `;console.error(`${Z}${f} ${x.cyan(J)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
194
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!u.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=x.green("━".repeat(J)),f=x.gray("━".repeat(U)),Z=`[${Y}${f}]`,E=`${A}%`.padStart(4),W=$.message?` ${$.message}`:"",h=this.options.showIcons===!1?"":w||A===100?x.green("✓"):x.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",j=`\r${h}${F} ${Z} ${E}${W}`,B=u.stdout.columns||80,H=" ".repeat(Math.max(0,B-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${H}`,u.stdout.write($.lastRenderedLine),w)u.stdout.write(`
|
|
195
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Z$()||!u.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(Z$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await cA(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=iw(this.config.logDirectory,J);if($.before)try{if((await bw(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await uA(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var NN=new TJ("stacks");class W0 extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}}class SW extends W0{code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],U="";if(J.length===1)U=` or alias "${J[0]}"`;else if(J.length>1)U=` or aliases ${J.map((Y)=>`"${Y}"`).join(", ")}`;super(`Configuration "${$}"${U} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}}class ZJ extends W0{code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}}class VW extends W0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}}class OW extends W0{code="CONFIG_MERGE_ERROR";constructor($,w,A,J){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}}class Zf extends W0{code="ENV_VAR_ERROR";constructor($,w,A,J){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:J})}}class DW extends W0{code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}}class _W extends W0{code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}}class WJ extends W0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}}class XW extends W0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}}class kW extends W0{code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}}var vw={configNotFound($,w,A){return new SW($,w,A)},configLoad($,w,A){return new ZJ($,w,A)},configValidation($,w,A){return new VW($,w,A)},configMerge($,w,A,J){return new OW($,w,A,J)},envVar($,w,A,J){return new Zf($,w,A,J)},fileSystem($,w,A){return new DW($,w,A)},typeGeneration($,w,A){return new _W($,w,A)},schemaValidation($,w,A){return new WJ($,w,A)},browserConfig($,w,A,J){return new XW($,w,A,J)},plugin($,w,A){return new kW($,w,A)}};async function zH($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let Z=0;Z<=A;Z++)try{return await $()}catch(E){if(f=E instanceof Error?E:Error(String(E)),Z===A||!U(f))break;if(J>0)await new Promise((W)=>setTimeout(W,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}class Wf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:J,useCamelCase:U=!0,useBackwardCompatibility:Y=!0,customParsers:f={},verbose:Z=!1,trackPerformance:E=!0}=A,W=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let h=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],h,{useCamelCase:U,useBackwardCompatibility:Y,customParsers:f,verbose:Z,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(E)return $f.track("applyEnvironmentVariables",W,{configName:$});return W()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],Z=f.map((h)=>this.formatEnvKey(h,J.useCamelCase)),E=`${A}_${Z.join("_")}`,W=J.useBackwardCompatibility?`${A}_${f.map((h)=>h.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,f,A,J);else{let h=nA.env[E]||(W?nA.env[W]:void 0);if(h!==void 0){if(J.verbose){let F=nA.env[E]?E:W}try{$[U]=this.parseEnvironmentValue(h,typeof Y,E,J.customParsers,J.configName)}catch(F){if(F instanceof Zf)throw F;throw vw.envVar(E,h,typeof Y,J.configName)}}}}}parseEnvironmentValue($,w,A,J,U){for(let[Y,f]of Object.entries(J))try{return f($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,w))try{return Y.parse($)}catch{throw vw.envVar(A,$,`${w} (via ${Y.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,U]of Object.entries(nA.env))if(J.startsWith(A)&&U!==void 0)w[J]=U;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(U){J.push(`Cannot parse value "${w}" as ${A}: ${U}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:U="text"}=A,Y=J||this.generateEnvPrefix($),f=[];switch(this.extractEnvVarInfo(w,[],Y,f),U){case"markdown":return this.formatAsMarkdown(f,$);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,$)}}extractEnvVarInfo($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],Z=`${A}_${f.map((E)=>this.formatEnvKey(E,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,f,A,J);else J.push({key:Z,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${f.join(".")}`,example:this.generateExample(Y)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
196
196
|
|
|
197
197
|
`;for(let J of $)A+=`${J.key}
|
|
198
198
|
`,A+=` Type: ${J.type}
|
|
@@ -204,41 +204,42 @@ export type ConfigOf = Config
|
|
|
204
204
|
`;A+=`| Variable | Type | Description | Example |
|
|
205
205
|
`,A+=`|----------|------|-------------|----------|
|
|
206
206
|
`;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
|
|
207
|
-
`;return A}}function JT($,w,A={}){return yE($,w,A,new WeakMap)}function yE($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:h}=A;if(w===null||w===void 0)return Y?$:w;if(h){let Z=h($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return LE($,w,U,J);if(!e$(w)||!e$($))return w;return fT($,w,A,J)}function LE($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return UT($,w);case"smart":return YT($,w,J);default:return w}return w}function UT($,w){let A=[...w];for(let J of $)if(!A.some((U)=>mY(U,J)))A.push(J);return A}function YT($,w,A){if(w.length===0)return $;if($.length===0)return w;if(e$(w[0])&&e$($[0]))return hT($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function hT($,w,A){let J=[...w];for(let U of $){if(!e$(U)){J.push(U);continue}let Y=["id","name","key","path","type"],h=!1;for(let Z of Y)if(Z in U){if(J.find((f)=>e$(f)&&(Z in f)&&f[Z]===U[Z])){h=!0;break}}if(!h)J.push(U)}return J}function fT($,w,A,J){let U=w;if(e$(U)&&J.has(U))return J.get(U);let Y={...$};if(e$(U))J.set(U,Y);for(let h in U){if(!Object.prototype.hasOwnProperty.call(U,h))continue;let Z=U[h],f=Y[h];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){Y[h]=Z;continue}if(e$(Z)&&e$(f))Y[h]=yE(f,Z,A,J);else if(Array.isArray(Z)||Array.isArray(f))Y[h]=LE(f,Z,A.arrayMergeMode||"smart",J);else Y[h]=Z}return Y}function CE($,w,A="replace"){return JT($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function mY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!mY($[A],w[A]))return!1;return!0}if(e$($)&&e$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!mY($[U],w[U]))return!1}return!0}return!1}function e$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class SE{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:h=!0,verbose:Z=!1}=A;if(U){let E=oA.getWithFileCheck("file",$);if(E){if(Z)console.log(`Configuration loaded from cache: ${$}`);return E}}let f=async()=>{if(!uA($))return null;try{let E=`?t=${Date.now()}`,W=await import($+E),F=W.default||W,j="default"in W,B=Object.keys(W).length>0;if(!j&&!B)throw new hJ($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new hJ($,Error("Configuration must export a valid object"),"unknown");let T={config:CE(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)oA.setWithFileCheck("file",T,$,Y);return T}catch(E){throw E instanceof Error?mw.configLoad($,E):mw.configLoad($,Error(String(E)))}};if(h)return tY.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let h of this.extensions)U.push(CY(w,`${Y}${h}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let J=w===void 0?[]:Array.isArray(w)?w:[w];for(let Y of J){if(!Y)continue;if(A.push(Y,`.${Y}.config`,`${Y}.config`,`.${Y}`),$)A.push(`${$}.${Y}.config`,`.${$}.${Y}.config`)}let U=new Set;return A.filter((Y)=>{if(!Y||U.has(Y))return!1;return U.add(Y),!0})}checkFileAccess($){return AT(async()=>{return uA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!uA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let h of this.extensions){let Z=CY($,`${Y}${h}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let h of Y)if(this.looksLikeConfigFile(h)){let Z=CY($,h);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){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((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!uA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}var ZT=/^https?:\/\//;class VE{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:h=[],trackPerformance:Z=!0,verbose:f=!1}=A,E=async()=>{let W=[],F=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:h,trackPerformance:Z,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...h],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return W.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:W,warnings:F}}};if(Z)return await tY.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!v9(w))throw new fJ(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new fJ(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let h=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(h)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${h}`,expected:Z.join(" or "),actual:h,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let h=0;h<$.length;h++){let Z=A?`${A}[${h}]`:`[${h}]`;if(this.validateObjectAgainstSchema($[h],w.items,Z,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let h=$;if(Y.validateRequired&&w.required){for(let Z of w.required)if(!(Z in h)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[Z,f]of Object.entries(w.properties))if(Z in h){let E=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(h[Z],f,E,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(h))if(!Z.has(f))U.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let h=this.getValueByPath($,Y.path),Z=this.validateWithRule(h,Y,Y.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(h){J.push({path:Y.path,message:`Rule validation failed: ${h}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,h]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(h)})}return w}mapTypeScriptType($){switch($.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:ZT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var S0=new jJ("bunfig",{showTags:!0});function ET($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class DE{fileLoader=new SE;envProcessor=new Ah;validator=new VE;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...h}=$;try{if(A?.enabled){let f=this.checkCache(h.name||"",h);if(f)return f}let Z;try{Z=await this.loadConfigurationStrategies(h,!0,A)}catch(f){let E=h.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(E)throw f;Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`No configuration file found for "${h.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let W=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),F=!W&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),j=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(E&&(j||W))throw f;if(F&&(!E||!j))Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else Z={...await this.applyEnvironmentVariables(h.name||"",h.defaultConfig,h.checkEnv!==!1,h.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||Y)await this.validateConfiguration(Z.config,U,Y,h.name);if(A?.enabled&&Z)this.cacheResult(h.name||"",Z,A,h);if(J?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:h.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(f);if(J.slowThreshold&&f.duration>J.slowThreshold)S0.warn(`Slow configuration loading detected: ${f.duration}ms for ${h.name}`);Z.metrics=f}return Z}catch(Z){if(Z instanceof Error&&Z.name==="ConfigNotFoundError")throw Z;let f=Date.now()-w;throw S0.error(`Configuration loading failed after ${f}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:h,defaultConfig:Z,checkEnv:f=!0,arrayStrategy:E="replace",verbose:W=!1}=$,F=Y||WJ.cwd(),j=[],B=await this.loadLocalConfiguration(J,U,F,h,Z,E,W,f,A);if(B)return j.push(...this.getLocalSearchPaths(J,U,F,h)),this.finalizeResult(B,j,f,J,W);let T=await this.loadHomeConfiguration(J,U,Z,E,W,f);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,f,J,W);let H=await this.loadPackageJsonConfiguration(J,U,F,Z,E,W,f);if(H)return j.push(s$(F,"package.json")),this.finalizeResult(H,j,f,J,W);if(j.push(...this.getAllSearchPaths(J,U,F,h)),w)throw mw.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,Z,f,W),warnings:[`No configuration file found for "${J}"${ET(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,h,Z,f){let E=Z?vA($,U,h):U,W=this.getLocalDirectories(A,J);for(let F of W){if(h)S0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:h,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(B){if(h)S0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let h=Y?vA($,A,U):A,Z=[s$(Ow(),".config",$),s$(Ow(),".config"),Ow()];for(let f of Z){if(U)S0.info(`Checking home directory: ${f}`);let E=this.fileLoader.generateConfigPaths($,f,w),W=await this.fileLoader.tryLoadFromPaths(E,h,{arrayStrategy:J,verbose:U});if(W){if(U)S0.success(`Configuration loaded from home directory: ${W.source.path}`);return W}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,h){let Z=h?vA($,J,Y):J;try{let f=s$(A,"package.json");if(!A9(f))return null;let E={};try{E=JSON.parse(J9(f,"utf8"))}catch(j){if(Y)S0.warn("Failed to parse package.json:",[j instanceof Error?j:Error(String(j))]);return null}let W=E[$],F=$;if(!W&&w){let j=Array.isArray(w)?w:[w];for(let B of j){if(!B)continue;if(E[B]){W=E[B],F=B;break}}}if(W&&typeof W==="object"&&!Array.isArray(W)){if(Y)S0.success(`Configuration loaded from package.json: ${F}`);return{config:CE(Z,W,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(Y)S0.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:vA($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((h)=>h.path?`${h.path}: ${h.message}`:h.message))}if(U.length>0)throw mw.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return oA.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);oA.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let J=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${J}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,s$($,"config"),s$($,".config"),w?s$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(s$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let h of U)Y.push(...this.fileLoader.generateConfigPaths($,h,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[s$(Ow(),".config",$),s$(Ow(),".config"),Ow()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}var YN=new DE;function vA($,w,A=!1){let J=new Ah,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(h,Z=[]){let f={...h};for(let[E,W]of Object.entries(h)){let F=[...Z,E],j=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((H)=>H.toUpperCase()).join("")}`,`${U}_${F.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,T;for(let H of j)if(B=WJ.env[H],B!==void 0){T=H;break}if(B!==void 0&&T)if(typeof W==="boolean")f[E]=["true","1","yes"].includes(B.toLowerCase());else if(typeof W==="number"){let H=Number(B);if(!Number.isNaN(H))f[E]=H}else if(Array.isArray(W))try{f[E]=JSON.parse(B)}catch{f[E]=B.split(",").map((H)=>H.trim())}else f[E]=B;else if(W&&typeof W==="object"&&!Array.isArray(W))f[E]=Y(W,F)}return f}return Y(w)}var hN=s$(WJ.cwd(),"config"),fN=s$(WJ.cwd(),"src/generated"),OE={altNameIPs:["127.0.0.1"],altNameURIs:["localhost"],organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:"tlsx.localhost",validityDays:825,hostCertCN:"tlsx.localhost",domain:"tlsx.localhost",rootCA:{certificate:"",privateKey:""},basePath:"",caCertPath:BY.join(FY.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:BY.join(FY.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:BY.join(FY.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},A$=OE,f0={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var y={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},nw={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};function dY($,w){let A=[];function J(U){let Y;try{Y=vZ.readdirSync(U)}catch{return}for(let h of Y){let Z=Y0.join(U,h);try{if(vZ.statSync(Z).isDirectory())J(Z);else if(h===w)A.push(U)}catch{continue}}}return J($),A}function I($,w,A){if(A||A$.verbose)console.debug(`[tlsx:${$}] ${w}`)}var jT=BT(WT);function XE(){return _E.env.SUDO_PASSWORD}var mZ="[redacted]",zT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),HT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function TT($){let w=$.toLowerCase();return zT.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function ZJ($){if(Array.isArray($))return $.map((A)=>ZJ(A));if(typeof $==="string")return HT.test($)?mZ:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(TT(A)){w[A]=mZ;continue}w[A]=ZJ(J)}return w}function zJ($){return JSON.stringify(ZJ($))}function GT($){let w=XE();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let A=w.replace(/'/g,"'\\''"),J=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${A}' | ${J}`}async function g0($,w={}){let A=GT($);try{let{stdout:J,stderr:U}=await jT(A,{cwd:w.cwd||_E.cwd(),timeout:w.timeout||30000});return{stdout:J.trim(),stderr:U.trim()}}catch(J){let U=Error(`Failed to execute command: ${$}
|
|
208
|
-
Error: ${J.message}`);throw U.stack=J.stack,U}}function
|
|
207
|
+
`;return A}}function TH($,w,A={}){return QW($,w,A,new WeakMap)}function QW($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:f}=A;if(w===null||w===void 0)return Y?$:w;if(f){let Z=f($,w);if(Z!==void 0)return Z}if(Array.isArray(w)||Array.isArray($))return xW($,w,U,J);if(!e$(w)||!e$($))return w;return RH($,w,A,J)}function xW($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return HH($,w);case"smart":return GH($,w,J);default:return w}return w}function HH($,w){let A=[...w];for(let J of $)if(!A.some((U)=>aY(U,J)))A.push(J);return A}function GH($,w,A){if(w.length===0)return $;if($.length===0)return w;if(e$(w[0])&&e$($[0]))return qH($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function qH($,w,A){let J=[...w];for(let U of $){if(!e$(U)){J.push(U);continue}let Y=["id","name","key","path","type"],f=!1;for(let Z of Y)if(Z in U){if(J.find((E)=>e$(E)&&(Z in E)&&E[Z]===U[Z])){f=!0;break}}if(!f)J.push(U)}return J}function RH($,w,A,J){let U=w;if(e$(U)&&J.has(U))return J.get(U);let Y={...$};if(e$(U))J.set(U,Y);for(let f in U){if(!Object.prototype.hasOwnProperty.call(U,f))continue;let Z=U[f],E=Y[f];if(A.skipNullish&&(Z===null||Z===void 0))continue;if(Z===null||Z===void 0){Y[f]=Z;continue}if(e$(Z)&&e$(E))Y[f]=QW(E,Z,A,J);else if(Array.isArray(Z)||Array.isArray(E))Y[f]=xW(E,Z,A.arrayMergeMode||"smart",J);else Y[f]=Z}return Y}function PW($,w,A="replace"){return TH($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function aY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!aY($[A],w[A]))return!1;return!0}if(e$($)&&e$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!aY($[U],w[U]))return!1}return!0}return!1}function e$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class bW{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:f=!0,verbose:Z=!1}=A;if(U){let W=$J.getWithFileCheck("file",$);if(W){if(Z)console.log(`Configuration loaded from cache: ${$}`);return W}}let E=async()=>{if(!vA($))return null;try{let W=`?t=${Date.now()}`,h=await import($+W),F=h.default||h,j="default"in h,B=Object.keys(h).length>0;if(!j&&!B)throw new ZJ($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new ZJ($,Error("Configuration must export a valid object"),"unknown");let H={config:PW(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)$J.setWithFileCheck("file",H,$,Y);return H}catch(W){throw W instanceof Error?vw.configLoad($,W):vw.configLoad($,Error(String(W)))}};if(f)return $f.track("loadFromPath",E,{path:$});return E()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let f of this.extensions)U.push(kY(w,`${Y}${f}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let J=w===void 0?[]:Array.isArray(w)?w:[w];for(let Y of J){if(!Y)continue;if(A.push(Y,`.${Y}.config`,`${Y}.config`,`.${Y}`),$)A.push(`${$}.${Y}.config`,`.${$}.${Y}.config`)}let U=new Set;return A.filter((Y)=>{if(!Y||U.has(Y))return!1;return U.add(Y),!0})}checkFileAccess($){return zH(async()=>{return vA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!vA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let Z=kY($,`${Y}${f}`);if(await this.checkFileAccess(Z))J.push(Z)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let f of Y)if(this.looksLikeConfigFile(f)){let Z=kY($,f);if(await this.checkFileAccess(Z))J.push(Z)}}catch{return[]}return J}looksLikeConfigFile($){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((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!vA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}var NH=/^https?:\/\//;class iW{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:Z=!0,verbose:E=!1}=A,W=async()=>{let h=[],F=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:Z,verbose:E};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(B){return h.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:h,warnings:F}}};if(Z)return await $f.track("validateConfiguration",W);return W()}async validateWithSchemaFile($,w,A){try{if(!$T(w))throw new WJ(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new WJ(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let f=Array.isArray($)?"array":typeof $,Z=Array.isArray(w.type)?w.type:[w.type];if(!Z.includes(f)){if(J.push({path:A,message:`Expected type ${Z.join(" or ")}, got ${f}`,expected:Z.join(" or "),actual:f,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let f=0;f<$.length;f++){let Z=A?`${A}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema($[f],w.items,Z,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let f=$;if(Y.validateRequired&&w.required){for(let Z of w.required)if(!(Z in f)){if(J.push({path:A?`${A}.${Z}`:Z,message:`Missing required property '${Z}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[Z,E]of Object.entries(w.properties))if(Z in f){let W=A?`${A}.${Z}`:Z;if(this.validateObjectAgainstSchema(f[Z],E,W,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let Z=new Set(Object.keys(w.properties||{}));for(let E of Object.keys(f))if(!Z.has(E))U.push({path:A?`${A}.${E}`:E,message:`Additional property '${E}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let f=this.getValueByPath($,Y.path),Z=this.validateWithRule(f,Y,Y.path);if(J.push(...Z),A.stopOnFirstError&&J.length>0)break}catch(f){J.push({path:Y.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,f]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(f)})}return w}mapTypeScriptType($){switch($.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:NH},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var S0=new TJ("bunfig",{showTags:!0});function KH($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class cW{fileLoader=new bW;envProcessor=new Wf;validator=new iW;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...f}=$;try{if(A?.enabled){let E=this.checkCache(f.name||"",f);if(E)return E}let Z;try{Z=await this.loadConfigurationStrategies(f,!0,A)}catch(E){let W=f.__strictErrorHandling;if(E instanceof Error&&E.name==="ConfigNotFoundError"){if(W)throw E;Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(E instanceof Error&&E.name==="ConfigLoadError"){let h=E.message.includes("EACCES")||E.message.includes("EPERM")||E.message.includes("permission denied"),F=!h&&(E.message.includes("syntax")||E.message.includes("Expected")||E.message.includes("Unexpected")||E.message.includes("BuildMessage")||E.message.includes("errors building")),j=E.message.includes("Configuration must export a valid object")||E.message.includes("Configuration file is empty and exports nothing");if(W&&(j||h))throw E;if(F&&(!W||!j))Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!W)Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${E.message}`]};else throw E}else Z={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${E instanceof Error?E.message:String(E)}`]}}if(U||Y)await this.validateConfiguration(Z.config,U,Y,f.name);if(A?.enabled&&Z)this.cacheResult(f.name||"",Z,A,f);if(J?.enabled){let E={operation:"loadConfig",duration:Date.now()-w,configName:f.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(E);if(J.slowThreshold&&E.duration>J.slowThreshold)S0.warn(`Slow configuration loading detected: ${E.duration}ms for ${f.name}`);Z.metrics=E}return Z}catch(Z){if(Z instanceof Error&&Z.name==="ConfigNotFoundError")throw Z;let E=Date.now()-w;throw S0.error(`Configuration loading failed after ${E}ms:`,[Z instanceof Error?Z:Error(String(Z))]),Z}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:f,defaultConfig:Z,checkEnv:E=!0,arrayStrategy:W="replace",verbose:h=!1}=$,F=Y||BJ.cwd(),j=[],B=await this.loadLocalConfiguration(J,U,F,f,Z,W,h,E,A);if(B)return j.push(...this.getLocalSearchPaths(J,U,F,f)),this.finalizeResult(B,j,E,J,h);let H=await this.loadHomeConfiguration(J,U,Z,W,h,E);if(H)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(H,j,E,J,h);let T=await this.loadPackageJsonConfiguration(J,U,F,Z,W,h,E);if(T)return j.push(s$(F,"package.json")),this.finalizeResult(T,j,E,J,h);if(j.push(...this.getAllSearchPaths(J,U,F,f)),w)throw vw.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,Z,E,h),warnings:[`No configuration file found for "${J}"${KH(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,Z,E){let W=Z?dA($,U,f):U,h=this.getLocalDirectories(A,J);for(let F of h){if(f)S0.info(`Searching for configuration in: ${F}`);let j=this.fileLoader.generateConfigPaths($,F,w),B=await this.fileLoader.tryLoadFromPaths(j,W,{arrayStrategy:Y,verbose:f,cacheTtl:E?.ttl,useCache:!E?.ttl||E.ttl>100});if(B){if(f)S0.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?dA($,A,U):A,Z=[s$(Ow(),".config",$),s$(Ow(),".config"),Ow()];for(let E of Z){if(U)S0.info(`Checking home directory: ${E}`);let W=this.fileLoader.generateConfigPaths($,E,w),h=await this.fileLoader.tryLoadFromPaths(W,f,{arrayStrategy:J,verbose:U});if(h){if(U)S0.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let Z=f?dA($,J,Y):J;try{let E=s$(A,"package.json");if(!z9(E))return null;let W={};try{W=JSON.parse(T9(E,"utf8"))}catch(j){if(Y)S0.warn("Failed to parse package.json:",[j instanceof Error?j:Error(String(j))]);return null}let h=W[$],F=$;if(!h&&w){let j=Array.isArray(w)?w:[w];for(let B of j){if(!B)continue;if(W[B]){h=W[B],F=B;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(Y)S0.success(`Configuration loaded from package.json: ${F}`);return{config:PW(Z,h,U),source:{type:"package.json",path:E,priority:30,timestamp:new Date}}}}catch(E){if(Y)S0.warn("Failed to load package.json:",[E instanceof Error?E:Error(String(E))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:dA($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(U.length>0)throw vw.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return $J.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);$J.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let J=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${J}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,s$($,"config"),s$($,".config"),w?s$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(s$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let f of U)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[s$(Ow(),".config",$),s$(Ow(),".config"),Ow()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}var KN=new cW;function dA($,w,A=!1){let J=new Wf,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,Z=[]){let E={...f};for(let[W,h]of Object.entries(f)){let F=[...Z,W],j=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((T)=>T.toUpperCase()).join("")}`,`${U}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,H;for(let T of j)if(B=BJ.env[T],B!==void 0){H=T;break}if(B!==void 0&&H)if(typeof h==="boolean")E[W]=["true","1","yes"].includes(B.toLowerCase());else if(typeof h==="number"){let T=Number(B);if(!Number.isNaN(T))E[W]=T}else if(Array.isArray(h))try{E[W]=JSON.parse(B)}catch{E[W]=B.split(",").map((T)=>T.trim())}else E[W]=B;else if(h&&typeof h==="object"&&!Array.isArray(h))E[W]=Y(h,F)}return E}return Y(w)}var MN=s$(BJ.cwd(),"config"),IN=s$(BJ.cwd(),"src/generated"),uW={altNameIPs:["127.0.0.1"],altNameURIs:["localhost"],organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:"tlsx.localhost",validityDays:825,hostCertCN:"tlsx.localhost",domain:"tlsx.localhost",rootCA:{certificate:"",privateKey:""},basePath:"",caCertPath:RY.join(qY.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:RY.join(qY.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:RY.join(qY.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},A$=uW,E0={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var L={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},uw={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};function sY($,w){let A=[];function J(U){let Y;try{Y=oZ.readdirSync(U)}catch{return}for(let f of Y){let Z=Y0.join(U,f);try{if(oZ.statSync(Z).isDirectory())J(Z);else if(f===w)A.push(U)}catch{continue}}}return J($),A}function I($,w,A){if(A||A$.verbose)console.debug(`[tlsx:${$}] ${w}`)}var yH=LH(MH);function vW(){return nW.env.SUDO_PASSWORD}var eZ="[redacted]",CH=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),SH=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function VH($){let w=$.toLowerCase();return CH.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function hJ($){if(Array.isArray($))return $.map((A)=>hJ(A));if(typeof $==="string")return SH.test($)?eZ:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(VH(A)){w[A]=eZ;continue}w[A]=hJ(J)}return w}function HJ($){return JSON.stringify(hJ($))}function OH($){let w=vW();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let A=w.replace(/'/g,"'\\''"),J=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${A}' | ${J}`}async function g0($,w={}){let A=OH($);try{let{stdout:J,stderr:U}=await yH(A,{cwd:w.cwd||nW.cwd(),timeout:w.timeout||30000});return{stdout:J.trim(),stderr:U.trim()}}catch(J){let U=Error(`Failed to execute command: ${$}
|
|
208
|
+
Error: ${J.message}`);throw U.stack=J.stack,U}}function mW($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function hf($){let w=Y0.join(IH.homedir(),".stacks","ssl"),A=$.basePath&&$.basePath.trim()!==""?$.basePath:A$.basePath&&A$.basePath.trim()!==""?A$.basePath:w,J=$.certPath?Y0.isAbsolute($.certPath)?$.certPath:Y0.join(A,$.certPath):Y0.join(A,A$.certPath),U=$.keyPath?Y0.isAbsolute($.keyPath)?$.keyPath:Y0.join(A,$.keyPath):Y0.join(A,A$.keyPath),Y=$.caCertPath?Y0.isAbsolute($.caCertPath)?$.caCertPath:Y0.join(A,$.caCertPath):Y0.join(A,A$.caCertPath);return{certPath:J,keyPath:U,caCertPath:Y,basePath:A}}function dW($){let w=[],A=new Set;if($.domain)A.add($.domain);if($.domains?.length)$.domains.forEach((J)=>A.add(J));for(let J of A)w.push({type:2,value:J});if($.altNameIPs?.length)for(let J of $.altNameIPs)w.push({type:7,ip:J});if($.altNameURIs?.length)for(let J of $.altNameURIs)w.push({type:6,value:J});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return I(L.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function Ff($){let w=$.notBeforeDays??E0.DEFAULT_NOT_BEFORE_DAYS,A=$.validityDays??($.validityYears?$.validityYears*365:E0.DEFAULT_VALIDITY_DAYS);I(L.CERT,"Calculating certificate validity dates",$.verbose);let J=new Date(Date.now()-86400*w*1000),U=new Date(J.getTime()+A*24*60*60*1000);return J.setUTCHours(0,0,0,0),U.setUTCHours(23,59,59,999),I(L.CERT,`Validity period: ${J.toISOString()} to ${U.toISOString()}`,$.verbose),{notBefore:J,notAfter:U}}var Z0={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},k$={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};function G1($){if($<128)return Buffer.from([$]);let w=[],A=$;while(A>0)w.unshift(A&255),A>>=8;return Buffer.from([128|w.length,...w])}function m$($,w){let A=G1(w.length);return Buffer.concat([Buffer.from([$]),A,w])}function K1($){let w=$.split(".").map(Number),A=[];A.push(40*w[0]+w[1]);for(let J=2;J<w.length;J++){let U=w[J],Y=[];Y.unshift(U&127),U>>=7;while(U>0)Y.unshift(U&127|128),U>>=7;A.push(...Y)}return m$(Z0.OID,Buffer.from(A))}function oY($){let w;if(typeof $==="bigint"){let A=$.toString(16).padStart(2,"0");w=Buffer.from(A.length%2?`0${A}`:A,"hex")}else if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let A=$.toString(16).padStart(2,"0");w=Buffer.from(A.length%2?`0${A}`:A,"hex")}else w=$;if(w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return m$(Z0.INTEGER,w)}function gW($,w=0){return m$(Z0.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function lW($){return m$(Z0.OCTET_STRING,$)}function v$(...$){return m$(Z0.SEQUENCE,Buffer.concat($))}function DH(...$){return m$(Z0.SET,Buffer.concat($))}function _H($){return m$(Z0.PRINTABLE_STRING,Buffer.from($,"ascii"))}function XH($){return m$(Z0.UTF8_STRING,Buffer.from($,"utf8"))}function kH(){return Buffer.from([Z0.NULL,0])}function $W($,w,A=!0){let J=160|$|(A?0:0),U=G1(w.length);return Buffer.concat([Buffer.from([J]),U,w])}function wW($){let w=$.getUTCFullYear();if(w>=2050){let A=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return m$(Z0.GENERALIZED_TIME,Buffer.from(A,"ascii"))}else{let A=(w%100).toString().padStart(2,"0"),J=($.getUTCMonth()+1).toString().padStart(2,"0"),U=$.getUTCDate().toString().padStart(2,"0"),Y=$.getUTCHours().toString().padStart(2,"0"),f=$.getUTCMinutes().toString().padStart(2,"0"),Z=$.getUTCSeconds().toString().padStart(2,"0"),E=`${A}${J}${U}${Y}${f}${Z}Z`;return m$(Z0.UTC_TIME,Buffer.from(E,"ascii"))}}function QH($,w){return v$(wW($),wW(w))}function AW($){let w=[];for(let A of $){let J;switch(A.shortName){case"CN":J=k$.COMMON_NAME;break;case"C":J=k$.COUNTRY;break;case"L":J=k$.LOCALITY;break;case"ST":J=k$.STATE;break;case"O":J=k$.ORGANIZATION;break;case"OU":J=k$.ORGANIZATIONAL_UNIT;break;default:continue}let U=A.shortName==="C"?_H(A.value):XH(A.value),Y=v$(K1(J),U);w.push(DH(Y))}return v$(...w)}function tW($){return v$(K1($),kH())}function xH($){return $.export({type:"spki",format:"der"})}function PH($){if($.includes(":")){let w=$;if($.includes("::")){let U=$.split("::"),Y=U[0]?U[0].split(":"):[],f=U[1]?U[1].split(":"):[],Z=8-Y.length-f.length,E=Array.from({length:Z},()=>"0");w=[...Y,...E,...f].join(":")}let A=w.split(":"),J=Buffer.alloc(16);for(let U=0;U<8;U++){let Y=Number.parseInt(A[U]||"0",16);J.writeUInt16BE(Y,U*2)}return J}else{let w=$.split(".").map((A)=>Number.parseInt(A,10));return Buffer.from(w)}}function bH($){let w=[];for(let A of $)if(A.type===2&&A.value){let J=G1(A.value.length);w.push(Buffer.concat([Buffer.from([130]),J,Buffer.from(A.value,"ascii")]))}else if(A.type===7&&A.ip){let J=PH(A.ip),U=G1(J.length);w.push(Buffer.concat([Buffer.from([135]),U,J]))}else if(A.type===6&&A.value){let J=G1(A.value.length);w.push(Buffer.concat([Buffer.from([134]),J,Buffer.from(A.value,"ascii")]))}return v$(...w)}function iH($,w){if($){if(w!==void 0)return v$(m$(1,Buffer.from([255])),oY(w));return v$(m$(1,Buffer.from([255])))}return v$()}function cH($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let A=0,J=w;while(J>0&&(J&1)===0)A++,J>>=1;if(w===0)A=7;return gW(Buffer.from([w]),A)}function uH($){let w=[];if($.serverAuth)w.push(K1(k$.SERVER_AUTH));if($.clientAuth)w.push(K1(k$.CLIENT_AUTH));return v$(...w)}function T1($,w,A){let J=[K1($)];if(w)J.push(m$(1,Buffer.from([255])));return J.push(lW(A)),v$(...J)}function nH($){let w=[];if(w.push($W(0,oY(2))),w.push(oY($.serialNumber)),w.push(tW(k$.SHA256_WITH_RSA)),w.push(AW($.issuer)),w.push(QH($.notBefore,$.notAfter)),w.push(AW($.subject)),w.push(xH($.publicKey)),$.extensions){let A=[];if($.extensions.basicConstraints)A.push(T1(k$.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,iH($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)A.push(T1(k$.KEY_USAGE,$.extensions.keyUsage.critical??!0,cH($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)A.push(T1(k$.EXTENDED_KEY_USAGE,!1,uH($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)A.push(T1(k$.SUBJECT_ALT_NAME,!1,bH($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)A.push(T1(k$.SUBJECT_KEY_IDENTIFIER,!1,lW($.extensions.subjectKeyIdentifier)));if(A.length>0)w.push($W(3,v$(...A)))}return v$(...w)}function vH($,w){let A=mw.createSign("SHA256");A.update($);let J=A.sign(w);return v$($,tW(k$.SHA256_WITH_RSA),gW(J))}function mH($,w){let A=$.toString("base64"),J=[];for(let U=0;U<A.length;U+=64)J.push(A.slice(U,U+64));return`-----BEGIN ${w}-----
|
|
209
209
|
${J.join(`
|
|
210
210
|
`)}
|
|
211
211
|
-----END ${w}-----
|
|
212
|
-
`}function
|
|
213
|
-
`);for(let Y of U){let[h,...Z]=Y.split("="),f=Z.join("=");if(h&&f)J.push({shortName:h.trim(),value:f.trim()})}return{publicKey:A,subject:J}}async function hh($={}){I("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||f0.DEFAULT_KEY_SIZE;I("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:J}=iE(w),U=[{shortName:"C",value:$.countryName||A$.countryName},{shortName:"ST",value:$.stateName||A$.stateName},{shortName:"L",value:$.localityName||A$.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:Y,notAfter:h}=Uh({validityYears:$.validityYears||f0.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:Z}=cE({serialNumber:Yh(),notBefore:Y,notAfter:h,subject:U,publicKey:J,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:Z,privateKey:uE(A),notBefore:Y,notAfter:h}}async function fh($){if(I("ca","Generating new certificate",$.verbose),I("ca",`Options: ${zJ($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=QT($.rootCA.certificate),A=kT($.rootCA.privateKey);I("ca",`Generating ${f0.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let J=f0.DEFAULT_KEY_SIZE,{privateKey:U,publicKey:Y}=iE(J),h=$.commonName||kE($),Z=$.certificateAttributes||[{shortName:"C",value:$.countryName||A$.countryName},{shortName:"ST",value:$.stateName||A$.stateName},{shortName:"L",value:$.localityName||A$.localityName},{shortName:"O",value:$.organizationName||A$.organizationName},{shortName:"CN",value:h}],{notBefore:f,notAfter:E}=Uh({validityDays:$.validityDays||f0.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),W=QE($),F=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},j=$.extKeyUsage||{serverAuth:!0},{certificate:B}=cE({serialNumber:Yh(),notBefore:f,notAfter:E,subject:Z,issuer:w,publicKey:Y,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:F,extendedKeyUsage:j,subjectAltName:W});return{certificate:B,privateKey:uE(U),notBefore:f,notAfter:E}}function nE($,w){I(y.STORAGE,`Storing certificate and private key with options: ${zJ(w)}`,w?.verbose);let{certPath:A,keyPath:J}=Jh({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});I(y.STORAGE,`Certificate path: ${A}`,w?.verbose),I(y.STORAGE,`Private key path: ${J}`,w?.verbose);let U=lY.dirname(A);if(!_0.existsSync(U))I(y.STORAGE,`Creating certificate directory: ${U}`,w?.verbose),_0.mkdirSync(U,{recursive:!0});I(y.STORAGE,"Writing certificate file",w?.verbose),_0.writeFileSync(A,$.certificate);let Y=lY.dirname(J);if(!_0.existsSync(Y))I(y.STORAGE,`Creating private key directory: ${Y}`,w?.verbose),_0.mkdirSync(Y,{recursive:!0});return I(y.STORAGE,"Writing private key file",w?.verbose),_0.writeFileSync(J,$.privateKey),I(y.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function vE($,w){I(y.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=Jh({basePath:w?.basePath,caCertPath:w?.caCertPath});I(y.STORAGE,`CA certificate path: ${A}`,w?.verbose);let J=lY.dirname(A);if(!_0.existsSync(J))I(y.STORAGE,`Creating CA certificate directory: ${J}`,w?.verbose),_0.mkdirSync(J,{recursive:!0});return I(y.STORAGE,"Writing CA certificate file",w?.verbose),_0.writeFileSync(A,$),I(y.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function xT($,w){if(EJ.platform()!=="darwin")return!1;try{let A=tZ(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return I(y.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(tZ("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return I(y.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return I(y.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return I(y.TRUST,`Error checking certificate trust: ${A}`,w),!1}}var PT={platform:"darwin",async addCertificate($,w){if(await xT($,w?.verbose)){I(y.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),nw.success("Certificate is already trusted in system keychain");return}I(y.TRUST,"Adding certificate to macOS keychain",w?.verbose),await g0(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let J=A||A$.commonName;I(y.TRUST,`Removing certificate ${J} from macOS keychain`,w?.verbose);try{await g0(`sudo security delete-certificate -c "${J}" /Library/Keychains/System.keychain`),I(y.TRUST,`Removed certificate ${J} from macOS keychain`,w?.verbose)}catch(U){throw I(y.TRUST,`Error removing certificate: ${U}`,w?.verbose),U}}},bT={platform:"win32",async addCertificate($,w){I(y.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await g0(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let J=A||A$.commonName;I(y.TRUST,`Removing certificate ${J} from Windows certificate store`,w?.verbose);try{await g0(`certutil -delstore -enterprise Root "${J}"`),I(y.TRUST,`Removed certificate ${J} from Windows certificate store`,w?.verbose)}catch(U){throw I(y.TRUST,`Error removing certificate: ${U}`,w?.verbose),U}}},iT={platform:"linux",async addCertificate($,w){I(y.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=EJ.homedir(),J=f0.LINUX_CERT_DB_FILENAME,U=f0.LINUX_TRUST_ARGS;I(y.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let Y=dY(A,J);if(Y.length===0){nw.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let h of Y){I(y.TRUST,`Processing certificate database in ${h}`,w?.verbose);try{I(y.TRUST,`Attempting to delete existing cert for ${A$.commonName}`,w?.verbose),await g0(`certutil -d sql:${h} -D -n ${A$.commonName}`)}catch(Z){I(y.TRUST,`Warning: Error deleting existing cert: ${Z}`,w?.verbose),console.warn(`Error deleting existing cert: ${Z}`)}I(y.TRUST,`Adding new certificate to ${h}`,w?.verbose),await g0(`certutil -d sql:${h} -A -t ${U} -n ${A$.commonName} -i ${$}`),nw.info(`Cert added to ${h}`)}},async removeCertificate($,w,A){let J=A||A$.commonName;I(y.TRUST,`Removing certificate ${J} from Linux certificate store`,w?.verbose);let U=EJ.homedir(),Y=f0.LINUX_CERT_DB_FILENAME;I(y.TRUST,`Searching for certificate databases in ${U}`,w?.verbose);let h=dY(U,Y);if(h.length===0){nw.warn("No certificate databases found. Cannot remove certificate.");return}for(let Z of h){I(y.TRUST,`Processing certificate database in ${Z}`,w?.verbose);try{await g0(`certutil -d sql:${Z} -D -n "${J}"`),nw.info(`Cert removed from ${Z}`)}catch(f){I(y.TRUST,`Error removing cert from ${Z}: ${f}`,w?.verbose),console.warn(`Error removing cert from ${Z}: ${f}`)}}}},cT={darwin:PT,win32:bT,linux:iT};async function Zh($,w,A){I(y.TRUST,`Adding certificate to system trust store with options: ${zJ(A)}`,A?.verbose),I(y.TRUST,"Storing certificate and private key",A?.verbose);let J=nE($,A);I(y.TRUST,"Storing CA certificate",A?.verbose);let U=vE(w,A),Y=EJ.platform();I(y.TRUST,`Detected platform: ${Y}`,A?.verbose);let h=cT[Y];if(!h){let Z=`Unsupported platform: ${Y}`;throw I(y.TRUST,`Error: ${Z}`,A?.verbose),Error(Z)}return await h.addCertificate(U,A),I(y.TRUST,"Certificate successfully added to system trust store",A?.verbose),J}import{homedir as Eh}from"node:os";import{join as Wh,resolve as aN}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",uT={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Wh(Eh(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Wh(Eh(),".stacks","ssl","stacks.localhost.crt"),keyPath:Wh(Eh(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Fh=uT;T$();var a0=null,d2="rpx-root-ca.crt",g2="rpx-root-ca.key";function $F($){return{caCertPath:S$($,d2),caKeyPath:S$($,g2)}}async function l2($,w){try{let[A,J]=await Promise.all([B$.readFile($.caCertPath,"utf8"),B$.readFile($.caKeyPath,"utf8")]);if(!A.includes("-----BEGIN CERTIFICATE-----")||!J.includes("PRIVATE KEY-----"))return z("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:A,privateKey:J}}catch(A){return z("ssl",`No existing Root CA at ${$.caCertPath} (${A.code||A}), will create one`,w),null}}function oW($){let w=new Set;w.add($);let A=$.split(".");if(A.length>=2)w.add(`*.${A.slice(1).join(".")}`);return Array.from(w)}function wF($){let A=gJ($).replace(/\*/g,"wildcard"),J=S$(S1(),".stacks","ssl"),U=J;if(typeof $?.https==="object")return U=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:J,{caCertPath:$.https.caCertPath||S$(U,`${A}.ca.crt`),certPath:$.https.certPath||S$(U,`${A}.crt`),keyPath:$.https.keyPath||S$(U,`${A}.key`)};return{caCertPath:S$(U,`${A}.ca.crt`),certPath:S$(U,`${A}.crt`),keyPath:S$(U,`${A}.key`)}}function eW($){let w=new Set;if(Uw($))$.proxies.forEach((A)=>{let J=A.to||"rpx.localhost";oW(J).forEach((U)=>w.add(U))});else if(C1($)){let A=$.to||"rpx.localhost";oW(A).forEach((J)=>w.add(J))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function A1($){if(a0&&!$.forceRegenerate){z("ssl","Using cached SSL configuration",$.verbose);return}t2();let w=Uw($)?$.proxies.map((W)=>W.to):[$.to];z("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let A=V1($,$.verbose),J=A.basePath||S$(S1(),".stacks","ssl");await B$.mkdir(J,{recursive:!0});let U=$F(J),Y=await l2(U,$.verbose),h=!1;if(!Y){if($.verbose)N.info("Generating Root CA certificate (one-time)...");Y=await hh(A);try{await Promise.all([B$.writeFile(U.caCertPath,Y.certificate),B$.writeFile(U.caKeyPath,Y.privateKey,{mode:384})]),h=!0,z("ssl",`Persisted Root CA at ${U.caCertPath}`,$.verbose)}catch(W){throw z("ssl",`Error saving Root CA files: ${W}`,$.verbose),Error(`Failed to save Root CA files: ${W}`)}}else z("ssl",`Reusing existing Root CA from ${U.caCertPath}`,$.verbose);if($.verbose)N.info(`Generating host certificate for: ${w.join(", ")}`);let Z=await fh({...A,rootCA:{certificate:Y.certificate,privateKey:Y.privateKey}});try{await Promise.all([B$.writeFile(A.certPath,Z.certificate),B$.writeFile(A.keyPath,Z.privateKey),B$.writeFile(A.caCertPath,Y.certificate)]),z("ssl","Certificate files saved successfully",$.verbose)}catch(W){throw z("ssl",`Error saving certificate files: ${W}`,$.verbose),Error(`Failed to save certificate files: ${W}`)}if(h?!1:await JF(U.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(z("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)N.success("Root CA is already trusted in system trust store");if(a0={key:Z.privateKey,cert:Z.certificate,ca:Y.certificate},$.verbose)N.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)N.info("Adding certificate to system trust store (may require sudo permission)...");let E=!1;if(r0.platform==="darwin")try{if(rh(`security add-trusted-cert -d -r trustRoot -p ssl -p basic -k /Library/Keychains/System.keychain "${U.caCertPath}"`),$.verbose)N.success("Successfully added Root CA to system trust store");E=!0;let W=S$(J,"trust-rpx-cert.sh"),F=`#!/bin/bash
|
|
212
|
+
`}function Bf(){return mw.randomBytes(20)}function pW($=2048){let{privateKey:w,publicKey:A}=mw.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:A}}function dH($){let w=$.export({type:"spki",format:"der"});return mw.createHash("sha1").update(w).digest()}function rW($){let w={serialNumber:$.serialNumber||Bf(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:dH($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let A=nH(w),J=vH(A,$.signingKey);return{certificate:mH(J,"CERTIFICATE"),certificateDer:J}}function aW($){return $.export({type:"pkcs8",format:"pem"})}function gH($){return mw.createPrivateKey($)}function lH($){let w=new mw.X509Certificate($),A=w.publicKey,J=[],U=w.subject.split(`
|
|
213
|
+
`);for(let Y of U){let[f,...Z]=Y.split("="),E=Z.join("=");if(f&&E)J.push({shortName:f.trim(),value:E.trim()})}return{publicKey:A,subject:J}}async function jf($={}){I("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||E0.DEFAULT_KEY_SIZE;I("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:J}=pW(w),U=[{shortName:"C",value:$.countryName||A$.countryName},{shortName:"ST",value:$.stateName||A$.stateName},{shortName:"L",value:$.localityName||A$.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:Y,notAfter:f}=Ff({validityYears:$.validityYears||E0.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:Z}=rW({serialNumber:Bf(),notBefore:Y,notAfter:f,subject:U,publicKey:J,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:Z,privateKey:aW(A),notBefore:Y,notAfter:f}}async function zf($){if(I("ca","Generating new certificate",$.verbose),I("ca",`Options: ${HJ($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=lH($.rootCA.certificate),A=gH($.rootCA.privateKey);I("ca",`Generating ${E0.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let J=E0.DEFAULT_KEY_SIZE,{privateKey:U,publicKey:Y}=pW(J),f=$.commonName||mW($),Z=$.certificateAttributes||[{shortName:"C",value:$.countryName||A$.countryName},{shortName:"ST",value:$.stateName||A$.stateName},{shortName:"L",value:$.localityName||A$.localityName},{shortName:"O",value:$.organizationName||A$.organizationName},{shortName:"CN",value:f}],{notBefore:E,notAfter:W}=Ff({validityDays:$.validityDays||E0.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),h=dW($),F=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},j=$.extKeyUsage||{serverAuth:!0},{certificate:B}=rW({serialNumber:Bf(),notBefore:E,notAfter:W,subject:Z,issuer:w,publicKey:Y,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:F,extendedKeyUsage:j,subjectAltName:h});return{certificate:B,privateKey:aW(U),notBefore:E,notAfter:W}}function sW($,w){I(L.STORAGE,`Storing certificate and private key with options: ${HJ(w)}`,w?.verbose);let{certPath:A,keyPath:J}=hf({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});I(L.STORAGE,`Certificate path: ${A}`,w?.verbose),I(L.STORAGE,`Private key path: ${J}`,w?.verbose);let U=eY.dirname(A);if(!_0.existsSync(U))I(L.STORAGE,`Creating certificate directory: ${U}`,w?.verbose),_0.mkdirSync(U,{recursive:!0});I(L.STORAGE,"Writing certificate file",w?.verbose),_0.writeFileSync(A,$.certificate);let Y=eY.dirname(J);if(!_0.existsSync(Y))I(L.STORAGE,`Creating private key directory: ${Y}`,w?.verbose),_0.mkdirSync(Y,{recursive:!0});return I(L.STORAGE,"Writing private key file",w?.verbose),_0.writeFileSync(J,$.privateKey),I(L.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function oW($,w){I(L.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=hf({basePath:w?.basePath,caCertPath:w?.caCertPath});I(L.STORAGE,`CA certificate path: ${A}`,w?.verbose);let J=eY.dirname(A);if(!_0.existsSync(J))I(L.STORAGE,`Creating CA certificate directory: ${J}`,w?.verbose),_0.mkdirSync(J,{recursive:!0});return I(L.STORAGE,"Writing CA certificate file",w?.verbose),_0.writeFileSync(A,$),I(L.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function tH($,w){if(FJ.platform()!=="darwin")return!1;try{let A=JW(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return I(L.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(JW("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return I(L.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return I(L.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return I(L.TRUST,`Error checking certificate trust: ${A}`,w),!1}}var pH={platform:"darwin",async addCertificate($,w){if(await tH($,w?.verbose)){I(L.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),uw.success("Certificate is already trusted in system keychain");return}I(L.TRUST,"Adding certificate to macOS keychain",w?.verbose),await g0(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let J=A||A$.commonName;I(L.TRUST,`Removing certificate ${J} from macOS keychain`,w?.verbose);try{await g0(`sudo security delete-certificate -c "${J}" /Library/Keychains/System.keychain`),I(L.TRUST,`Removed certificate ${J} from macOS keychain`,w?.verbose)}catch(U){throw I(L.TRUST,`Error removing certificate: ${U}`,w?.verbose),U}}},rH={platform:"win32",async addCertificate($,w){I(L.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await g0(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let J=A||A$.commonName;I(L.TRUST,`Removing certificate ${J} from Windows certificate store`,w?.verbose);try{await g0(`certutil -delstore -enterprise Root "${J}"`),I(L.TRUST,`Removed certificate ${J} from Windows certificate store`,w?.verbose)}catch(U){throw I(L.TRUST,`Error removing certificate: ${U}`,w?.verbose),U}}},aH={platform:"linux",async addCertificate($,w){I(L.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=FJ.homedir(),J=E0.LINUX_CERT_DB_FILENAME,U=E0.LINUX_TRUST_ARGS;I(L.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let Y=sY(A,J);if(Y.length===0){uw.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let f of Y){I(L.TRUST,`Processing certificate database in ${f}`,w?.verbose);try{I(L.TRUST,`Attempting to delete existing cert for ${A$.commonName}`,w?.verbose),await g0(`certutil -d sql:${f} -D -n ${A$.commonName}`)}catch(Z){I(L.TRUST,`Warning: Error deleting existing cert: ${Z}`,w?.verbose),console.warn(`Error deleting existing cert: ${Z}`)}I(L.TRUST,`Adding new certificate to ${f}`,w?.verbose),await g0(`certutil -d sql:${f} -A -t ${U} -n ${A$.commonName} -i ${$}`),uw.info(`Cert added to ${f}`)}},async removeCertificate($,w,A){let J=A||A$.commonName;I(L.TRUST,`Removing certificate ${J} from Linux certificate store`,w?.verbose);let U=FJ.homedir(),Y=E0.LINUX_CERT_DB_FILENAME;I(L.TRUST,`Searching for certificate databases in ${U}`,w?.verbose);let f=sY(U,Y);if(f.length===0){uw.warn("No certificate databases found. Cannot remove certificate.");return}for(let Z of f){I(L.TRUST,`Processing certificate database in ${Z}`,w?.verbose);try{await g0(`certutil -d sql:${Z} -D -n "${J}"`),uw.info(`Cert removed from ${Z}`)}catch(E){I(L.TRUST,`Error removing cert from ${Z}: ${E}`,w?.verbose),console.warn(`Error removing cert from ${Z}: ${E}`)}}}},sH={darwin:pH,win32:rH,linux:aH};async function Tf($,w,A){I(L.TRUST,`Adding certificate to system trust store with options: ${HJ(A)}`,A?.verbose),I(L.TRUST,"Storing certificate and private key",A?.verbose);let J=sW($,A);I(L.TRUST,"Storing CA certificate",A?.verbose);let U=oW(w,A),Y=FJ.platform();I(L.TRUST,`Detected platform: ${Y}`,A?.verbose);let f=sH[Y];if(!f){let Z=`Unsupported platform: ${Y}`;throw I(L.TRUST,`Error: ${Z}`,A?.verbose),Error(Z)}return await f.addCertificate(U,A),I(L.TRUST,"Certificate successfully added to system trust store",A?.verbose),J}import{homedir as Hf}from"node:os";import{join as Gf,resolve as BK}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",oH={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Gf(Hf(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Gf(Hf(),".stacks","ssl","stacks.localhost.crt"),keyPath:Gf(Hf(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var qf=oH;import{execSync as aJ}from"node:child_process";import{homedir as J7}from"node:os";import{join as U7}from"node:path";import{execSync as eH}from"node:child_process";function eW($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function GJ($){try{let w=eH(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return eW(w)}catch{return null}}B$();var w1="-d -r trustRoot -p ssl -p basic",A1="/Library/Keychains/System.keychain",f8="rpx.localhost";function sJ(){return U7(J7(),"Library/Keychains/login.keychain-db")}function E8(){return[A1,sJ()]}function WF($,w=f8){let A=aJ(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),J=[];for(let U of A.split(`
|
|
214
|
+
`)){let Y=U.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(Y)J.push(Y[1].toUpperCase())}return J}function Z8($){if(process.platform!=="darwin")return;let w=GJ($.caPath);if(!w)return;let A=$.commonName??f8,J=$.keychains??E8();for(let U of J)for(let Y of WF(U,A)){if(Y===w)continue;try{if(U.startsWith("/Library"))V1(`security delete-certificate -Z ${Y} "${U}"`);else aJ(`security delete-certificate -Z ${Y} "${U}"`,{stdio:"ignore"});z("ssl",`Removed stale Root CA ${Y} from ${U}`,$.verbose)}catch{}}}function W8($,w,A){if(process.platform!=="darwin")return oJ($,A);try{let U=aJ(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return z("ssl",`verify-cert ${w}: ${U?"trusted":"not trusted"}`,A?.verbose),U}catch{return!1}}function oJ($,w){let A=GJ($);if(!A)return!1;for(let J of E8())try{let U=aJ(`security find-certificate -a -Z "${J}" 2>/dev/null || true`,{encoding:"utf8"});for(let Y of U.split(`
|
|
215
|
+
`))if(Y.toUpperCase().includes("SHA-256")){if(Y.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===A)return z("ssl",`Root CA fingerprint found in ${J}`,w?.verbose),!0}}catch{}return!1}B$();var a0=null,f7="rpx-root-ca.crt",E7="rpx-root-ca.key";function BF($){return{caCertPath:S$($,f7),caKeyPath:S$($,E7)}}async function Z7($,w){try{let[A,J]=await Promise.all([j$.readFile($.caCertPath,"utf8"),j$.readFile($.caKeyPath,"utf8")]);if(!A.includes("-----BEGIN CERTIFICATE-----")||!J.includes("PRIVATE KEY-----"))return z("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:A,privateKey:J}}catch(A){return z("ssl",`No existing Root CA at ${$.caCertPath} (${A.code||A}), will create one`,w),null}}function hF($){let w=new Set;w.add($);let A=$.split(".");if(A.length>=2)w.add(`*.${A.slice(1).join(".")}`);return Array.from(w)}function jF($){let A=pJ($).replace(/\*/g,"wildcard"),J=S$(eJ(),".stacks","ssl"),U=J;if(typeof $?.https==="object")return U=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:J,{caCertPath:$.https.caCertPath||S$(U,`${A}.ca.crt`),certPath:$.https.certPath||S$(U,`${A}.crt`),keyPath:$.https.keyPath||S$(U,`${A}.key`)};return{caCertPath:S$(U,`${A}.ca.crt`),certPath:S$(U,`${A}.crt`),keyPath:S$(U,`${A}.key`)}}function FF($){let w=new Set;if(Uw($))$.proxies.forEach((A)=>{let J=A.to||"rpx.localhost";hF(J).forEach((U)=>w.add(U))});else if(O1($)){let A=$.to||"rpx.localhost";hF(A).forEach((J)=>w.add(J))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function U1($){if(a0&&!$.forceRegenerate){z("ssl","Using cached SSL configuration",$.verbose);return}W7();let w=Uw($)?$.proxies.map((h)=>h.to):[$.to];z("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let A=D1($,$.verbose),J=A.basePath||S$(eJ(),".stacks","ssl");await j$.mkdir(J,{recursive:!0});let U=BF(J),Y=await Z7(U,$.verbose),f=!1;if(!Y){if($.verbose)N.info("Generating Root CA certificate (one-time)...");Y=await jf(A);try{await Promise.all([j$.writeFile(U.caCertPath,Y.certificate),j$.writeFile(U.caKeyPath,Y.privateKey,{mode:384})]),f=!0,z("ssl",`Persisted Root CA at ${U.caCertPath}`,$.verbose)}catch(h){throw z("ssl",`Error saving Root CA files: ${h}`,$.verbose),Error(`Failed to save Root CA files: ${h}`)}}else z("ssl",`Reusing existing Root CA from ${U.caCertPath}`,$.verbose);if($.verbose)N.info(`Generating host certificate for: ${w.join(", ")}`);let Z=await zf({...A,rootCA:{certificate:Y.certificate,privateKey:Y.privateKey}});try{await Promise.all([j$.writeFile(A.certPath,Z.certificate),j$.writeFile(A.keyPath,Z.privateKey),j$.writeFile(A.caCertPath,Y.certificate)]),z("ssl","Certificate files saved successfully",$.verbose)}catch(h){throw z("ssl",`Error saving certificate files: ${h}`,$.verbose),Error(`Failed to save certificate files: ${h}`)}if(f?!1:await TF(U.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(z("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)N.success("Root CA is already trusted in system trust store");if(a0={key:Z.privateKey,cert:Z.certificate,ca:Y.certificate},$.verbose)N.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)N.info("Adding certificate to system trust store (may require sudo permission)...");let W=!1;if(r0.platform==="darwin")try{Z8({caPath:U.caCertPath,verbose:$.verbose});let h=sJ();try{J1(`security add-trusted-cert ${w1} -k "${h}" "${U.caCertPath}"`,{stdio:"ignore"})}catch{}if(V1(`security add-trusted-cert ${w1} -k ${A1} "${U.caCertPath}"`),$.verbose)N.success("Successfully added Root CA to system trust store");W=!0;let F=S$(J,"trust-rpx-cert.sh"),j=`#!/bin/bash
|
|
214
216
|
echo "Trusting RPX Root CA"
|
|
215
|
-
sudo security add-trusted-cert
|
|
217
|
+
sudo security add-trusted-cert ${w1} -k ${A1} "${U.caCertPath}"
|
|
216
218
|
echo "Root CA trusted! Please restart your browser."
|
|
217
219
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
218
|
-
`;await
|
|
220
|
+
`;await j$.writeFile(F,j,{mode:493})}catch(h){if($.verbose)N.warn(`Could not add Root CA to trust store automatically: ${h}`);let F=S$(J,"trust-rpx-cert.sh"),j=`#!/bin/bash
|
|
219
221
|
echo "Trusting RPX Root CA"
|
|
220
|
-
sudo security add-trusted-cert
|
|
222
|
+
sudo security add-trusted-cert ${w1} -k ${A1} "${U.caCertPath}"
|
|
221
223
|
echo "Root CA trusted! Please restart your browser."
|
|
222
224
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
223
|
-
`;if(await
|
|
225
|
+
`;if(await j$.writeFile(F,j,{mode:493}),$.verbose)N.info(`Created a trust helper script at: ${F}`),N.info(`If you're still having certificate issues, run: sh ${F}`)}else if(r0.platform==="linux")try{let{exec:h}=await import("node:child_process"),F="/usr/local/share/ca-certificates/rpx",j=`
|
|
224
226
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
225
227
|
cp "${U.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
226
228
|
update-ca-certificates
|
|
227
229
|
echo "RPX Root CA installed. Please restart your browser."
|
|
228
|
-
`,B=S$(
|
|
230
|
+
`,B=S$(h8.tmpdir(),`rpx-trust-${Date.now()}.sh`);await j$.writeFile(B,j,{mode:493}),await new Promise((H)=>{h(`sudo bash "${B}"`,(T)=>{if(T){if($.verbose)N.warn(`Could not trust certificates: ${T}`);H(!1)}else{if($.verbose)N.success("Successfully added certificates to system trust store");H(!0)}})}),await j$.unlink(B).catch(()=>{}),W=!0}catch(h){if($.verbose)N.warn(`Failed to trust certificates: ${h}`)}else if(r0.platform==="win32")try{let h=`
|
|
229
231
|
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${U.caCertPath.replace(/\//g,"\\")}")
|
|
230
232
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
231
233
|
$store.Open("ReadWrite")
|
|
232
234
|
$store.Add($cert)
|
|
233
235
|
$store.Close()
|
|
234
236
|
Write-Host "Root CA trusted successfully!"
|
|
235
|
-
`,F=S$(eh.tmpdir(),"rpx-trust.ps1");if(await B$.writeFile(F,W),Yw(`powershell -ExecutionPolicy Bypass -File "${F}"`),$.verbose)N.success("Successfully added certificate to Windows trust store");E=!0}catch(W){if($.verbose)N.warn(`Could not trust certificate: ${W}`)}else try{await Zh(Z,Y.certificate,A),E=!0}catch(W){if($.verbose)N.warn(`Could not add certificate to trust store: ${W}`)}if(a0={key:Z.privateKey,cert:Z.certificate,ca:Y.certificate},$.verbose)N.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!E&&$.verbose)N.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),N.warn("This will bypass the warning and you should only need to do it once")}function t2(){a0=null}async function c0($){if(!$)return null;if(a0)return a0;let w=V1($);try{let[A,J,U]=await Promise.all([B$.access(w.keyPath).then(()=>!0).catch(()=>!1),B$.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?B$.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!A||!J)return z("ssl",`Certificate files don't exist: key=${A}, cert=${J}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let Y="regenerateUntrustedCerts"in $,h=$.regenerateUntrustedCerts,Z=Y?h!==!1:!0;z("ssl",`Trust check: hasFlag=${Y}, flagValue=${h}, shouldCheckTrust=${Z}`,$.verbose);let f=w.basePath||S$(S1(),".stacks","ssl"),E=$F(f);if(!(Z?await JF(E.caCertPath,$):!0))return z("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[F,j,B]=await Promise.all([B$.readFile(w.keyPath,"utf8"),B$.readFile(w.certPath,"utf8"),U&&w.caCertPath?B$.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(B&&!B.includes("-----BEGIN CERTIFICATE-----"))return z("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(Uw($))try{let{X509Certificate:T}=await import("node:crypto"),q=new T(j).subjectAltName||"",R=$.proxies.map((K)=>K.to).filter((K)=>!q.includes(`DNS:${K}`));if(R.length>0)return z("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,$.verbose),null}catch(T){z("ssl",`Could not verify cert SANs: ${T}`,$.verbose)}return z("ssl","Successfully loaded existing certificates",$.verbose),a0={key:F,cert:j,ca:B},a0}catch(A){return z("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function V1($,w){let A=gJ($);z("ssl",`Primary domain: ${A}`,w);let J=wF($),U=S$(S1(),".stacks","ssl");if(typeof $.https==="object"){let Y=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:U,h={domain:A,hostCertCN:A,basePath:Y,caCertPath:$.https.caCertPath||J.caCertPath,certPath:$.https.certPath||J.certPath,keyPath:$.https.keyPath||J.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||A,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(eW($)).map((Z)=>({type:2,value:Z}))};if(ah($.https.rootCA))h.rootCA=$.https.rootCA;return h}return{domain:A,hostCertCN:A,basePath:U,...J,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:A,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:w||!1,subjectAltNames:Array.from(eW($)).map((Y)=>({type:2,value:Y}))}}async function AF($,w){let A=wF({to:$,verbose:w}),J=[A.caCertPath,A.certPath,A.keyPath];z("certificates","Attempting to clean up relating certificates",w),await Promise.all(J.map((U)=>oh(U,w)))}async function JF($,w){try{if(z("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),r0.platform==="darwin")try{let A=Yw(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim(),J=(h)=>h.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase(),U=J(A);if(!U)return z("ssl","Could not extract certificate fingerprint",w?.verbose),!1;let Y=["/Library/Keychains/System.keychain",S$(S1(),"Library/Keychains/login.keychain-db")];for(let h of Y)try{let Z=Yw(`security find-certificate -a -Z "${h}" 2>/dev/null || true`).toString();for(let f of Z.split(`
|
|
236
|
-
`))if(f.toUpperCase().includes("SHA-256")&&J(f)===U)return z("ssl",`Certificate fingerprint found in ${h}`,w?.verbose),!0}catch{}return z("ssl","Certificate fingerprint not found in system keychains",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust: ${A}`,w?.verbose),!1}else if(r0.platform==="win32")try{let J=Yw(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!J)return z("ssl","Could not extract certificate subject",w?.verbose),!1;let U=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${J}*' } | Select-Object Subject"`;if(Yw(U).toString().includes(J))return z("ssl","Certificate found in trusted root store",w?.verbose),!0;return z("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Windows: ${A}`,w?.verbose),!1}else if(r0.platform==="linux")try{let J=Yw(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"",U=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let Y of U)try{if(Yw(`find ${Y} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${J}"`).toString().includes(J))return z("ssl",`Certificate fingerprint found in ${Y}`,w?.verbose),!0}catch{}return z("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Linux: ${A}`,w?.verbose),!1}return z("ssl",`Platform ${r0.platform} not supported for certificate trust check`,w?.verbose),!1}catch(A){return z("ssl",`Error checking if certificate is trusted: ${A}`,w?.verbose),!1}}T$();T$();function D1($,w){return async(A)=>{let J=new URL(A.url),Y=(A.headers.get("host")||"").split(":")[0],h=$(Y);if(!h)return z("request",`No route found for host: ${Y}`,w),new Response(`No proxy configured for ${Y}`,{status:404});let Z=h.sourceHost,f=J.pathname,E=sh(J.pathname,h.pathRewrites);if(E)Z=E.targetHost,f=E.targetPath,z("request",`Path rewrite: ${J.pathname} → ${Z}${f}`,w);let W=`http://${Z}${f}${J.search}`;try{let F=new Headers(A.headers);if(F.set("host",Z),h.changeOrigin)F.set("origin",`http://${h.sourceHost}`);F.set("x-forwarded-for","127.0.0.1"),F.set("x-forwarded-proto","https"),F.set("x-forwarded-host",Y);let j=await fetch(W,{method:A.method,headers:F,body:A.body,redirect:"manual"});if(h.cleanUrls&&J.pathname.endsWith(".html")){let T=J.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:T}})}let B=new Headers(j.headers);return new Response(j.body,{status:j.status,statusText:j.statusText,headers:B})}catch(F){return z("request",`Proxy error for ${Y}: ${F}`,w),new Response(`Proxy Error: ${F}`,{status:502})}}}T$();import*as tJ from"node:fs";import*as P$ from"node:fs/promises";import{homedir as p2}from"node:os";import*as $8 from"node:path";import*as pJ from"node:process";var r2=/^[a-zA-Z0-9._-]+$/;function s0(){return $8.join(p2(),".stacks","rpx","registry.d")}function O1($){return typeof $==="string"&&$.length>0&&$.length<=128&&r2.test($)}function w8($,w){if(!O1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return $8.join($,`${w}.json`)}function F0($){if(!Number.isInteger($)||$<=0)return!1;try{return pJ.kill($,0),!0}catch(w){return w.code==="EPERM"}}function UF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0;return typeof w.id==="string"&&O1(w.id)&&typeof w.from==="string"&&w.from.length>0&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function a2($){await P$.mkdir($,{recursive:!0})}async function YF($,w=s0(),A){if(!UF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await a2(w);let J=w8(w,$.id),U=`${J}.tmp.${pJ.pid}.${Date.now()}`,Y=JSON.stringify($,null,2);try{await P$.writeFile(U,Y,{encoding:"utf8",mode:420}),await P$.rename(U,J),z("registry",`wrote entry ${$.id} → ${J}`,A)}catch(h){throw await P$.unlink(U).catch(()=>{}),h}}async function A8($,w=s0(),A){let J=w8(w,$);try{await P$.unlink(J),z("registry",`removed entry ${$}`,A)}catch(U){if(U.code!=="ENOENT")throw U}}async function s2($,w=s0(),A){let J=w8(w,$);try{let U=await P$.readFile(J,"utf8"),Y=JSON.parse(U);if(!UF(Y))return z("registry",`entry ${$} failed validation, removing`,A),await P$.unlink(J).catch(()=>{}),null;return Y}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await P$.unlink(J).catch(()=>{}),null;throw U}}async function hw($=s0(),w){let A;try{A=await P$.readdir($)}catch(U){if(U.code==="ENOENT")return[];throw U}let J=[];for(let U of A){if(!U.endsWith(".json"))continue;let Y=U.slice(0,-5);if(!O1(Y))continue;let h=await s2(Y,$,w);if(h)J.push(h)}return J}async function rJ($=s0(),w){let A=await hw($,w),J=0;for(let U of A){if(U.pid===void 0)continue;if(!F0(U.pid))z("registry",`GC: pid ${U.pid} for ${U.id} is dead, removing`,w),await A8(U.id,$,w).catch(()=>{}),J++}return J}function J8($,w={}){let A=w.dir??s0(),J=w.debounceMs??100,U=w.pollMs??Math.max(J*2,250),Y=w.verbose;tJ.mkdirSync(A,{recursive:!0});let h=null,Z=!1,f=null,E=!1,W=(q)=>{return JSON.stringify(q.map((G)=>({id:G.id,from:G.from,to:G.to,pid:G.pid,pathRewrites:G.pathRewrites,cleanUrls:G.cleanUrls,changeOrigin:G.changeOrigin})).sort((G,R)=>G.id.localeCompare(R.id)))},F=()=>{if(h=null,Z)return;hw(A,Y).then((q)=>{return f=W(q),$(q)}).catch((q)=>{z("registry",`watcher onChange failed: ${q}`,Y)})},j=()=>{if(Z)return;if(h)clearTimeout(h);h=setTimeout(F,J)},T=setInterval(()=>{if(Z||E)return;E=!0,hw(A,Y).then((q)=>{if(W(q)!==f)j()}).catch((q)=>{z("registry",`watcher poll failed: ${q}`,Y)}).finally(()=>{E=!1})},U),H=tJ.watch(A,{persistent:!0},(q,G)=>{if(G&&/\.tmp\.\d+\.\d+$/.test(G))return;j()});return H.on("error",(q)=>{z("registry",`watcher error: ${q}`,Y)}),j(),{close:()=>{if(Z=!0,h)clearTimeout(h);clearInterval(T),H.close()}}}T$();var e2=5000;function z0(){return B0.join(hF(),".stacks","rpx")}function Zw($=z0()){return B0.join($,"daemon.pid")}async function fw($=z0()){try{let w=await j0.readFile(Zw($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function fF($=z0()){let w=await fw($);return w!==null&&F0(w)}async function $7($=z0()){await j0.mkdir($,{recursive:!0});let w=Zw($);while(!0){try{let J=await j0.open(w,"wx");try{await J.write(`${G$.pid}
|
|
237
|
-
`)}finally{await J.close()}return w}catch(J){if(J.code!=="EEXIST")throw J}let A=await fw($);if(A!==null&&F0(A))throw Error(`rpx daemon already running (pid=${A})`);await j0.unlink(w).catch(()=>{})}}async function _1($=z0()){await j0.unlink(Zw($)).catch(()=>{})}function w7($){return{sourceHost:new URL($.from.startsWith("http")?$.from:`http://${$.from}`).host,cleanUrls:$.cleanUrls??!1,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites}}function A7($){return $.find((A)=>!/^api\./.test(A)&&!/^docs\./.test(A)&&!/^dashboard\./.test(A))??$[0]??"rpx.localhost"}async function J7($,w){let A=await hw(w,$.verbose),J=[...new Set(A.map((W)=>W.to))],U=A7(J),Y=[...new Set([U,...J,"rpx.localhost"])],h=B0.join(hF(),".stacks","ssl"),Z=B0.join(h,"rpx.localhost.crt"),f={https:typeof $.https==="object"?{...$.https,certPath:Z,keyPath:B0.join(h,"rpx.localhost.key"),commonName:U}:{certPath:Z,keyPath:B0.join(h,"rpx.localhost.key"),caCertPath:B0.join(h,"rpx.localhost.ca.crt"),commonName:U},verbose:$.verbose,regenerateUntrustedCerts:!0,...Y.length>1?{proxies:Y.map((W)=>({from:"localhost:1",to:W}))}:{to:U,from:"localhost:1"}},E=await c0(f);if(!E)z("daemon","no usable cert on disk, generating one",$.verbose),await A1(f),E=await c0(f);if(!E)throw Error("failed to bootstrap TLS for rpx daemon");return E}async function ZF($={}){let w=$.verbose??!1,A=$.rpxDir??z0(),J=$.registryDir??B0.join(A,"registry.d"),U=$.httpsPort??443,Y=$.httpPort??80,h=$.hostname??"0.0.0.0",Z=$.gcIntervalMs??e2,f=await $7(A),E=new Map,W=(M)=>E.get(M);function F(M){let V$=new Map;for(let c$ of M)V$.set(c$.to,w7(c$));E=V$,z("daemon",`routing table now covers ${V$.size} host(s): ${Array.from(V$.keys()).join(", ")||"<empty>"}`,w)}await rJ(J,w).catch((M)=>{z("daemon",`initial gc failed: ${M}`,w)}),F(await hw(J,w));let j=await J7($,J),B=Bun.serve({port:U,hostname:h,tls:{key:j.key,cert:j.cert,ca:j.ca,requestCert:!1,rejectUnauthorized:!1},fetch:D1(W,w),error(M){return z("daemon",`https server error: ${M}`,w),new Response(`Server Error: ${M.message}`,{status:500})}}),T=null;if(Y>0)T=Bun.serve({port:Y,hostname:h,fetch(M){let V$=new URL(M.url),c$=(M.headers.get("host")??V$.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${c$}${V$.pathname}${V$.search}`}})}});if(w)N.success(`rpx daemon listening on https://${h}:${U}${T?` (http→https on :${Y})`:""}`),N.info(`pid file: ${f}`),N.info(`registry: ${J}`);let H=J8((M)=>{F(M)},{dir:J,verbose:w}),q=setInterval(()=>{rJ(J,w).then((M)=>{if(M>0)z("daemon",`gc reaped ${M} stale entries`,w)}).catch((M)=>{z("daemon",`periodic gc failed: ${M}`,w)})},Z);if(typeof q.unref==="function")q.unref();let G=!1,R,K=new Promise((M)=>{R=M});async function L(){if(G)return K;if(G=!0,clearInterval(q),H.close(),B.stop(!1),T?.stop(!1),await _1(A),w)N.info("rpx daemon stopped");return R(),K}let C=(M)=>{z("daemon",`received ${M}, shutting down`,w),L().catch(()=>{})};return G$.once("SIGINT",C),G$.once("SIGTERM",C),{stop:L,done:K,httpsPort:typeof B.port==="number"?B.port:U,httpPort:T&&typeof T.port==="number"?T.port:Y,pidPath:f}}function U7(){let $=G$.execPath,w=B0.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&G$.argv[1])return[$,G$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function EF($={}){let w=$.rpxDir??z0(),A=$.verbose??!1,J=await fw(w);if(J!==null&&F0(J))return z("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await _1(w);await j0.mkdir(w,{recursive:!0});let U=$.spawnCommand??U7();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${U.join(" ")}`,A);let Y=o2(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??G$.cwd(),env:$.spawnEnv?{...G$.env,...$.spawnEnv}:G$.env});Y.unref();let h=null;Y.once("error",(W)=>{h=W});let Z=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,E=Date.now()+Z;while(Date.now()<E){if(h)throw h;let W=await fw(w);if(W!==null&&F0(W))return z("daemon",`daemon registered with pid=${W}`,A),{pid:W,spawned:!0};await new Promise((F)=>setTimeout(F,f))}if(h)throw h;throw Error(`rpx daemon failed to start within ${Z}ms (rpxDir=${w})`)}async function WF($={}){let w=$.rpxDir??z0(),A=$.verbose??!1,J=$.timeoutMs??5000,U=$.pollIntervalMs??50,Y=$.forceAfterTimeout??!0,h=await fw(w);if(h===null||!F0(h)){if(h!==null)await _1(w);return{stopped:!1,pid:h,forced:!1}}try{G$.kill(h,"SIGTERM")}catch(f){if(f.code==="ESRCH")return await _1(w),{stopped:!1,pid:h,forced:!1};throw f}let Z=Date.now()+J;while(Date.now()<Z){if(!F0(h))return z("daemon",`daemon pid=${h} stopped cleanly`,A),{stopped:!0,pid:h,forced:!1};await new Promise((f)=>setTimeout(f,U))}if(!Y)throw Error(`rpx daemon (pid=${h}) did not exit within ${J}ms`);z("daemon",`daemon pid=${h} did not exit, escalating to SIGKILL`,A);try{G$.kill(h,"SIGKILL")}catch(f){if(f.code!=="ESRCH")throw f}return await _1(w),{stopped:!0,pid:h,forced:!0}}import{spawn as Y7}from"node:child_process";import*as Ew from"node:process";T$();class FF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[J,...U]=w.command.split(" "),Y=w.cwd||Ew.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${J} ${U.join(" ")}`,A),z("start",` Working directory: ${Y}`,A),z("start",` Environment variables: ${w0(w.env)}`,A);let h=Y7(J,U,{cwd:Y,env:{...Ew.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:Y,process:h,env:w.env}),new Promise((Z,f)=>{if(h.on("error",(E)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${E}`,A),this.processes.delete($),f(E),Ew.emit("SIGINT")}),h.on("exit",(E)=>{if(!this.isShuttingDown&&E!==null&&E!==0)z("start",`Process ${$} exited with code ${E}`,A),this.processes.delete($),f(Error(`Process ${$} exited with code ${E}`)),Ew.emit("SIGINT")}),A)h.stdout?.on("data",(E)=>{z("process",`[${$}] ${E.toString().trim()}`,!0)}),h.stderr?.on("data",(E)=>{z("process",`[${$}] ERR: ${E.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&h.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),Z()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){z("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((J)=>{N.error(`Failed to stop process ${A}:`,J)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var aJ=new FF;T$();import*as b$ from"node:fs/promises";import{homedir as h7}from"node:os";import*as U8 from"node:path";import*as Y8 from"node:process";var f7=/^[a-zA-Z0-9._-]+$/;function Ww(){return U8.join(h7(),".stacks","rpx","registry.d")}function J1($){return typeof $==="string"&&$.length>0&&$.length<=128&&f7.test($)}function h8($,w){if(!J1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return U8.join($,`${w}.json`)}function BF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0;return typeof w.id==="string"&&J1(w.id)&&typeof w.from==="string"&&w.from.length>0&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function Z7($){await b$.mkdir($,{recursive:!0})}async function jF($,w=Ww(),A){if(!BF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await Z7(w);let J=h8(w,$.id),U=`${J}.tmp.${Y8.pid}.${Date.now()}`,Y=JSON.stringify($,null,2);try{await b$.writeFile(U,Y,{encoding:"utf8",mode:420}),await b$.rename(U,J),z("registry",`wrote entry ${$.id} → ${J}`,A)}catch(h){throw await b$.unlink(U).catch(()=>{}),h}}async function zF($,w=Ww(),A){let J=h8(w,$);try{await b$.unlink(J),z("registry",`removed entry ${$}`,A)}catch(U){if(U.code!=="ENOENT")throw U}}async function f8($,w=Ww(),A){let J=h8(w,$);try{let U=await b$.readFile(J,"utf8"),Y=JSON.parse(U);if(!BF(Y))return z("registry",`entry ${$} failed validation, removing`,A),await b$.unlink(J).catch(()=>{}),null;return Y}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await b$.unlink(J).catch(()=>{}),null;throw U}}async function HF($=Ww(),w){let A;try{A=await b$.readdir($)}catch(U){if(U.code==="ENOENT")return[];throw U}let J=[];for(let U of A){if(!U.endsWith(".json"))continue;let Y=U.slice(0,-5);if(!J1(Y))continue;let h=await f8(Y,$,w);if(h)J.push(h)}return J}import{execSync as O7}from"node:child_process";import*as Hw from"node:http";import*as VF from"node:http2";import*as DF from"node:net";import*as s from"node:process";var sJ=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,H0={bold:sJ(1,22),dim:sJ(2,22),green:sJ(32,39),cyan:sJ(36,39)};import*as RF from"node:fs";import*as NF from"node:path";import*as T0 from"node:process";import{spawn as E7}from"node:child_process";import*as Fw from"node:fs/promises";import{homedir as W7}from"node:os";import*as X1 from"node:path";import*as g$ from"node:process";T$();function oJ(){return X1.join(W7(),".stacks","rpx")}function GF($=oJ()){return X1.join($,"daemon.pid")}async function TF($=oJ()){try{let w=await Fw.readFile(GF($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function F7($=oJ()){await Fw.unlink(GF($)).catch(()=>{})}function B7(){let $=g$.execPath,w=X1.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&g$.argv[1])return[$,g$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function qF($={}){let w=$.rpxDir??oJ(),A=$.verbose??!1,J=await TF(w);if(J!==null&&F0(J))return z("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await F7(w);await Fw.mkdir(w,{recursive:!0});let U=$.spawnCommand??B7();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${U.join(" ")}`,A);let Y=E7(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??g$.cwd(),env:$.spawnEnv?{...g$.env,...$.spawnEnv}:g$.env});Y.unref();let h=null;Y.once("error",(W)=>{h=W});let Z=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,E=Date.now()+Z;while(Date.now()<E){if(h)throw h;let W=await TF(w);if(W!==null&&F0(W))return z("daemon",`daemon registered with pid=${W}`,A),{pid:W,spawned:!0};await new Promise((F)=>setTimeout(F,f))}if(h)throw h;throw Error(`rpx daemon failed to start within ${Z}ms (rpxDir=${w})`)}T$();function j7($){let w=$.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function Z8($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,J=new Set,U=$.proxies.map((j)=>{let B=j.id??j7(j.to);if(!O1(B))throw Error(`invalid registry id "${B}" derived from to="${j.to}"`);if(J.has(B))throw Error(`duplicate registry id "${B}" — set an explicit \`id\` on one of the proxies`);return J.add(B),{...j,id:B}}),Y=new Date().toISOString();for(let j of U)await YF({id:j.id,from:j.from,to:j.to,pid:$.persistent?void 0:T0.pid,cwd:T0.cwd(),createdAt:Y,cleanUrls:j.cleanUrls,changeOrigin:j.changeOrigin,pathRewrites:j.pathRewrites},A,w);let h=await qF({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let j of U)N.success(`https://${j.to} → ${j.from}`);if(N.info(`(via rpx daemon pid=${h.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let Z=!1,f=A??s0(),E=U.map((j)=>j.id),W=async()=>{if(Z)return;Z=!0;for(let j of E)await A8(j,A,w).catch((B)=>{z("runner",`removeEntry(${j}) failed: ${B}`,w)})},F=(j)=>{z("runner",`received ${j}, unregistering ${E.length} entries`,w),W().finally(()=>T0.exit(0))};T0.once("SIGINT",F),T0.once("SIGTERM",F),T0.once("exit",()=>{if(Z)return;for(let j of E)try{RF.unlinkSync(NF.join(f,`${j}.json`))}catch{}}),await new Promise(()=>{})}T$();import{exec as z7}from"node:child_process";import Bw from"node:fs";import KF from"node:os";import W8 from"node:path";import*as k1 from"node:process";import{promisify as H7}from"node:util";var eJ=H7(z7),A0=k1.platform==="win32"?W8.join(k1.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",E8=!1;async function $U($){if(k1.platform==="win32")throw Error("Administrator privileges required on Windows");let w=Jw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:U}=await eJ(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return E8=!0,U}if(E8)try{let{stdout:U}=await eJ(`sudo -n sh -c '${A}'`);return U}catch(U){z("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:J}=await eJ(`sudo sh -c '${A}'`);return E8=!0,J}catch(J){throw Error(`Failed to execute sudo command: ${J.message}`)}}async function Q1($,w){z("hosts",`Adding hosts: ${$.join(", ")}`,w),z("hosts",`Using hosts file at: ${A0}`,w);try{let A;try{A=await Bw.promises.readFile(A0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await $U(`cat "${A0}"`)}catch(h){throw console.log(" Could not read hosts file — skipping hosts setup"),z("hosts",`sudo read also failed: ${h}`,w),Error(`Cannot read hosts file: ${h}`)}}let J=$.filter((h)=>{let Z=`127.0.0.1 ${h}`,f=`::1 ${h}`;return!A.includes(Z)&&!A.includes(f)});if(J.length===0){z("hosts","All hosts already exist in hosts file",w);return}let U=J.map((h)=>`
|
|
237
|
+
`,F=S$(h8.tmpdir(),"rpx-trust.ps1");if(await j$.writeFile(F,h),J1(`powershell -ExecutionPolicy Bypass -File "${F}"`),$.verbose)N.success("Successfully added certificate to Windows trust store");W=!0}catch(h){if($.verbose)N.warn(`Could not trust certificate: ${h}`)}else try{await Tf(Z,Y.certificate,A),W=!0}catch(h){if($.verbose)N.warn(`Could not add certificate to trust store: ${h}`)}if(a0={key:Z.privateKey,cert:Z.certificate,ca:Y.certificate},$.verbose)N.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!W&&$.verbose)N.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),N.warn("This will bypass the warning and you should only need to do it once")}function W7(){a0=null}async function c0($){if(!$)return null;if(a0)return a0;let w=D1($);try{let[A,J,U]=await Promise.all([j$.access(w.keyPath).then(()=>!0).catch(()=>!1),j$.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?j$.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!A||!J)return z("ssl",`Certificate files don't exist: key=${A}, cert=${J}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let Y="regenerateUntrustedCerts"in $,f=$.regenerateUntrustedCerts,Z=Y?f!==!1:!0;z("ssl",`Trust check: hasFlag=${Y}, flagValue=${f}, shouldCheckTrust=${Z}`,$.verbose);let E=w.basePath||S$(eJ(),".stacks","ssl"),W=BF(E);if(!(Z?await TF(W.caCertPath,$):!0))return z("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[F,j,B]=await Promise.all([j$.readFile(w.keyPath,"utf8"),j$.readFile(w.certPath,"utf8"),U&&w.caCertPath?j$.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(B&&!B.includes("-----BEGIN CERTIFICATE-----"))return z("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(Uw($))try{let{X509Certificate:H}=await import("node:crypto"),q=new H(j).subjectAltName||"",R=$.proxies.map((K)=>K.to).filter((K)=>!q.includes(`DNS:${K}`));if(R.length>0)return z("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,$.verbose),null}catch(H){z("ssl",`Could not verify cert SANs: ${H}`,$.verbose)}return z("ssl","Successfully loaded existing certificates",$.verbose),a0={key:F,cert:j,ca:B},a0}catch(A){return z("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function D1($,w){let A=pJ($);z("ssl",`Primary domain: ${A}`,w);let J=jF($),U=S$(eJ(),".stacks","ssl");if(typeof $.https==="object"){let Y=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:U,f={domain:A,hostCertCN:A,basePath:Y,caCertPath:$.https.caCertPath||J.caCertPath,certPath:$.https.certPath||J.certPath,keyPath:$.https.keyPath||J.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||A,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(FF($)).map((Z)=>({type:2,value:Z}))};if(J8($.https.rootCA))f.rootCA=$.https.rootCA;return f}return{domain:A,hostCertCN:A,basePath:U,...J,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:A,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:w||!1,subjectAltNames:Array.from(FF($)).map((Y)=>({type:2,value:Y}))}}async function zF($,w){let A=jF({to:$,verbose:w}),J=[A.caCertPath,A.certPath,A.keyPath];z("certificates","Attempting to clean up relating certificates",w),await Promise.all(J.map((U)=>Y8(U,w)))}async function TF($,w){try{if(z("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),r0.platform==="darwin"){if(w?.serverName)return W8($,w.serverName,{verbose:w.verbose});return oJ($,{verbose:w.verbose})}else if(r0.platform==="win32")try{let J=J1(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!J)return z("ssl","Could not extract certificate subject",w?.verbose),!1;let U=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${J}*' } | Select-Object Subject"`;if(J1(U).toString().includes(J))return z("ssl","Certificate found in trusted root store",w?.verbose),!0;return z("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Windows: ${A}`,w?.verbose),!1}else if(r0.platform==="linux")try{let J=J1(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"",U=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let Y of U)try{if(J1(`find ${Y} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${J}"`).toString().includes(J))return z("ssl",`Certificate fingerprint found in ${Y}`,w?.verbose),!0}catch{}return z("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Linux: ${A}`,w?.verbose),!1}return z("ssl",`Platform ${r0.platform} not supported for certificate trust check`,w?.verbose),!1}catch(A){return z("ssl",`Error checking if certificate is trusted: ${A}`,w?.verbose),!1}}B$();B$();function _1($,w){return async(A)=>{let J=new URL(A.url),Y=(A.headers.get("host")||"").split(":")[0],f=$(Y);if(!f)return z("request",`No route found for host: ${Y}`,w),new Response(`No proxy configured for ${Y}`,{status:404});let Z=f.sourceHost,E=J.pathname,W=U8(J.pathname,f.pathRewrites);if(W)Z=W.targetHost,E=W.targetPath,z("request",`Path rewrite: ${J.pathname} → ${Z}${E}`,w);let h=`http://${Z}${E}${J.search}`;try{let F=new Headers(A.headers);if(F.set("host",Z),f.changeOrigin)F.set("origin",`http://${f.sourceHost}`);F.set("x-forwarded-for","127.0.0.1"),F.set("x-forwarded-proto","https"),F.set("x-forwarded-host",Y);let j=await fetch(h,{method:A.method,headers:F,body:A.body,redirect:"manual"});if(f.cleanUrls&&J.pathname.endsWith(".html")){let H=J.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:H}})}let B=new Headers(j.headers);return new Response(j.body,{status:j.status,statusText:j.statusText,headers:B})}catch(F){return z("request",`Proxy error for ${Y}: ${F}`,w),new Response(`Proxy Error: ${F}`,{status:502})}}}B$();import*as $U from"node:fs";import*as P$ from"node:fs/promises";import{homedir as h7}from"node:os";import*as F8 from"node:path";import*as wU from"node:process";var F7=/^[a-zA-Z0-9._-]+$/;function s0(){return F8.join(h7(),".stacks","rpx","registry.d")}function X1($){return typeof $==="string"&&$.length>0&&$.length<=128&&F7.test($)}function B8($,w){if(!X1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return F8.join($,`${w}.json`)}function F0($){if(!Number.isInteger($)||$<=0)return!1;try{return wU.kill($,0),!0}catch(w){return w.code==="EPERM"}}function HF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0;return typeof w.id==="string"&&X1(w.id)&&typeof w.from==="string"&&w.from.length>0&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function B7($){await P$.mkdir($,{recursive:!0})}async function GF($,w=s0(),A){if(!HF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await B7(w);let J=B8(w,$.id),U=`${J}.tmp.${wU.pid}.${Date.now()}`,Y=JSON.stringify($,null,2);try{await P$.writeFile(U,Y,{encoding:"utf8",mode:420}),await P$.rename(U,J),z("registry",`wrote entry ${$.id} → ${J}`,A)}catch(f){throw await P$.unlink(U).catch(()=>{}),f}}async function j8($,w=s0(),A){let J=B8(w,$);try{await P$.unlink(J),z("registry",`removed entry ${$}`,A)}catch(U){if(U.code!=="ENOENT")throw U}}async function j7($,w=s0(),A){let J=B8(w,$);try{let U=await P$.readFile(J,"utf8"),Y=JSON.parse(U);if(!HF(Y))return z("registry",`entry ${$} failed validation, removing`,A),await P$.unlink(J).catch(()=>{}),null;return Y}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await P$.unlink(J).catch(()=>{}),null;throw U}}async function Yw($=s0(),w){let A;try{A=await P$.readdir($)}catch(U){if(U.code==="ENOENT")return[];throw U}let J=[];for(let U of A){if(!U.endsWith(".json"))continue;let Y=U.slice(0,-5);if(!X1(Y))continue;let f=await j7(Y,$,w);if(f)J.push(f)}return J}async function AU($=s0(),w){let A=await Yw($,w),J=0;for(let U of A){if(U.pid===void 0)continue;if(!F0(U.pid))z("registry",`GC: pid ${U.pid} for ${U.id} is dead, removing`,w),await j8(U.id,$,w).catch(()=>{}),J++}return J}function z8($,w={}){let A=w.dir??s0(),J=w.debounceMs??100,U=w.pollMs??Math.max(J*2,250),Y=w.verbose;$U.mkdirSync(A,{recursive:!0});let f=null,Z=!1,E=null,W=!1,h=(q)=>{return JSON.stringify(q.map((G)=>({id:G.id,from:G.from,to:G.to,pid:G.pid,pathRewrites:G.pathRewrites,cleanUrls:G.cleanUrls,changeOrigin:G.changeOrigin})).sort((G,R)=>G.id.localeCompare(R.id)))},F=()=>{if(f=null,Z)return;Yw(A,Y).then((q)=>{return E=h(q),$(q)}).catch((q)=>{z("registry",`watcher onChange failed: ${q}`,Y)})},j=()=>{if(Z)return;if(f)clearTimeout(f);f=setTimeout(F,J)},H=setInterval(()=>{if(Z||W)return;W=!0,Yw(A,Y).then((q)=>{if(h(q)!==E)j()}).catch((q)=>{z("registry",`watcher poll failed: ${q}`,Y)}).finally(()=>{W=!1})},U),T=$U.watch(A,{persistent:!0},(q,G)=>{if(G&&/\.tmp\.\d+\.\d+$/.test(G))return;j()});return T.on("error",(q)=>{z("registry",`watcher error: ${q}`,Y)}),j(),{close:()=>{if(Z=!0,f)clearTimeout(f);clearInterval(H),T.close()}}}B$();var T7=5000;function z0(){return B0.join(qF(),".stacks","rpx")}function Ew($=z0()){return B0.join($,"daemon.pid")}async function fw($=z0()){try{let w=await j0.readFile(Ew($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function RF($=z0()){let w=await fw($);return w!==null&&F0(w)}async function H7($=z0()){await j0.mkdir($,{recursive:!0});let w=Ew($);while(!0){try{let J=await j0.open(w,"wx");try{await J.write(`${G$.pid}
|
|
238
|
+
`)}finally{await J.close()}return w}catch(J){if(J.code!=="EEXIST")throw J}let A=await fw($);if(A!==null&&F0(A))throw Error(`rpx daemon already running (pid=${A})`);await j0.unlink(w).catch(()=>{})}}async function k1($=z0()){await j0.unlink(Ew($)).catch(()=>{})}function G7($){return{sourceHost:new URL($.from.startsWith("http")?$.from:`http://${$.from}`).host,cleanUrls:$.cleanUrls??!1,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites}}function q7($){return $.find((A)=>!/^api\./.test(A)&&!/^docs\./.test(A)&&!/^dashboard\./.test(A))??$[0]??"rpx.localhost"}async function R7($,w){let A=await Yw(w,$.verbose),J=[...new Set(A.map((h)=>h.to))],U=q7(J),Y=[...new Set([U,...J,"rpx.localhost"])],f=B0.join(qF(),".stacks","ssl"),Z=B0.join(f,"rpx.localhost.crt"),E={https:typeof $.https==="object"?{...$.https,certPath:Z,keyPath:B0.join(f,"rpx.localhost.key"),commonName:U}:{certPath:Z,keyPath:B0.join(f,"rpx.localhost.key"),caCertPath:B0.join(f,"rpx.localhost.ca.crt"),commonName:U},verbose:$.verbose,regenerateUntrustedCerts:!0,...Y.length>1?{proxies:Y.map((h)=>({from:"localhost:1",to:h}))}:{to:U,from:"localhost:1"}},W=await c0(E);if(!W)z("daemon","no usable cert on disk, generating one",$.verbose),await U1(E),W=await c0(E);if(!W)throw Error("failed to bootstrap TLS for rpx daemon");return W}async function NF($={}){let w=$.verbose??!1,A=$.rpxDir??z0(),J=$.registryDir??B0.join(A,"registry.d"),U=$.httpsPort??443,Y=$.httpPort??80,f=$.hostname??"0.0.0.0",Z=$.gcIntervalMs??T7,E=await H7(A),W=new Map,h=(M)=>W.get(M);function F(M){let V$=new Map;for(let c$ of M)V$.set(c$.to,G7(c$));W=V$,z("daemon",`routing table now covers ${V$.size} host(s): ${Array.from(V$.keys()).join(", ")||"<empty>"}`,w)}await AU(J,w).catch((M)=>{z("daemon",`initial gc failed: ${M}`,w)}),F(await Yw(J,w));let j=await R7($,J),B=Bun.serve({port:U,hostname:f,tls:{key:j.key,cert:j.cert,ca:j.ca,requestCert:!1,rejectUnauthorized:!1},fetch:_1(h,w),error(M){return z("daemon",`https server error: ${M}`,w),new Response(`Server Error: ${M.message}`,{status:500})}}),H=null;if(Y>0)H=Bun.serve({port:Y,hostname:f,fetch(M){let V$=new URL(M.url),c$=(M.headers.get("host")??V$.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${c$}${V$.pathname}${V$.search}`}})}});if(w)N.success(`rpx daemon listening on https://${f}:${U}${H?` (http→https on :${Y})`:""}`),N.info(`pid file: ${E}`),N.info(`registry: ${J}`);let T=z8((M)=>{F(M)},{dir:J,verbose:w}),q=setInterval(()=>{AU(J,w).then((M)=>{if(M>0)z("daemon",`gc reaped ${M} stale entries`,w)}).catch((M)=>{z("daemon",`periodic gc failed: ${M}`,w)})},Z);if(typeof q.unref==="function")q.unref();let G=!1,R,K=new Promise((M)=>{R=M});async function y(){if(G)return K;if(G=!0,clearInterval(q),T.close(),B.stop(!1),H?.stop(!1),await k1(A),w)N.info("rpx daemon stopped");return R(),K}let C=(M)=>{z("daemon",`received ${M}, shutting down`,w),y().catch(()=>{})};return G$.once("SIGINT",C),G$.once("SIGTERM",C),{stop:y,done:K,httpsPort:typeof B.port==="number"?B.port:U,httpPort:H&&typeof H.port==="number"?H.port:Y,pidPath:E}}function N7(){let $=G$.execPath,w=B0.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&G$.argv[1])return[$,G$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function KF($={}){let w=$.rpxDir??z0(),A=$.verbose??!1,J=await fw(w);if(J!==null&&F0(J))return z("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await k1(w);await j0.mkdir(w,{recursive:!0});let U=$.spawnCommand??N7();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${U.join(" ")}`,A);let Y=z7(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??G$.cwd(),env:$.spawnEnv?{...G$.env,...$.spawnEnv}:G$.env});Y.unref();let f=null;Y.once("error",(h)=>{f=h});let Z=$.startupTimeoutMs??5000,E=$.pollIntervalMs??50,W=Date.now()+Z;while(Date.now()<W){if(f)throw f;let h=await fw(w);if(h!==null&&F0(h))return z("daemon",`daemon registered with pid=${h}`,A),{pid:h,spawned:!0};await new Promise((F)=>setTimeout(F,E))}if(f)throw f;throw Error(`rpx daemon failed to start within ${Z}ms (rpxDir=${w})`)}async function MF($={}){let w=$.rpxDir??z0(),A=$.verbose??!1,J=$.timeoutMs??5000,U=$.pollIntervalMs??50,Y=$.forceAfterTimeout??!0,f=await fw(w);if(f===null||!F0(f)){if(f!==null)await k1(w);return{stopped:!1,pid:f,forced:!1}}try{G$.kill(f,"SIGTERM")}catch(E){if(E.code==="ESRCH")return await k1(w),{stopped:!1,pid:f,forced:!1};throw E}let Z=Date.now()+J;while(Date.now()<Z){if(!F0(f))return z("daemon",`daemon pid=${f} stopped cleanly`,A),{stopped:!0,pid:f,forced:!1};await new Promise((E)=>setTimeout(E,U))}if(!Y)throw Error(`rpx daemon (pid=${f}) did not exit within ${J}ms`);z("daemon",`daemon pid=${f} did not exit, escalating to SIGKILL`,A);try{G$.kill(f,"SIGKILL")}catch(E){if(E.code!=="ESRCH")throw E}return await k1(w),{stopped:!0,pid:f,forced:!0}}import{spawn as K7}from"node:child_process";import*as Zw from"node:process";B$();class IF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[J,...U]=w.command.split(" "),Y=w.cwd||Zw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${J} ${U.join(" ")}`,A),z("start",` Working directory: ${Y}`,A),z("start",` Environment variables: ${w0(w.env)}`,A);let f=K7(J,U,{cwd:Y,env:{...Zw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:Y,process:f,env:w.env}),new Promise((Z,E)=>{if(f.on("error",(W)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${W}`,A),this.processes.delete($),E(W),Zw.emit("SIGINT")}),f.on("exit",(W)=>{if(!this.isShuttingDown&&W!==null&&W!==0)z("start",`Process ${$} exited with code ${W}`,A),this.processes.delete($),E(Error(`Process ${$} exited with code ${W}`)),Zw.emit("SIGINT")}),A)f.stdout?.on("data",(W)=>{z("process",`[${$}] ${W.toString().trim()}`,!0)}),f.stderr?.on("data",(W)=>{z("process",`[${$}] ERR: ${W.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&f.killed)this.processes.delete($),E(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),Z()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){z("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((J)=>{N.error(`Failed to stop process ${A}:`,J)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var JU=new IF;B$();import*as b$ from"node:fs/promises";import{homedir as M7}from"node:os";import*as T8 from"node:path";import*as H8 from"node:process";var I7=/^[a-zA-Z0-9._-]+$/;function Ww(){return T8.join(M7(),".stacks","rpx","registry.d")}function Y1($){return typeof $==="string"&&$.length>0&&$.length<=128&&I7.test($)}function G8($,w){if(!Y1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return T8.join($,`${w}.json`)}function LF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0;return typeof w.id==="string"&&Y1(w.id)&&typeof w.from==="string"&&w.from.length>0&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function L7($){await b$.mkdir($,{recursive:!0})}async function yF($,w=Ww(),A){if(!LF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await L7(w);let J=G8(w,$.id),U=`${J}.tmp.${H8.pid}.${Date.now()}`,Y=JSON.stringify($,null,2);try{await b$.writeFile(U,Y,{encoding:"utf8",mode:420}),await b$.rename(U,J),z("registry",`wrote entry ${$.id} → ${J}`,A)}catch(f){throw await b$.unlink(U).catch(()=>{}),f}}async function CF($,w=Ww(),A){let J=G8(w,$);try{await b$.unlink(J),z("registry",`removed entry ${$}`,A)}catch(U){if(U.code!=="ENOENT")throw U}}async function q8($,w=Ww(),A){let J=G8(w,$);try{let U=await b$.readFile(J,"utf8"),Y=JSON.parse(U);if(!LF(Y))return z("registry",`entry ${$} failed validation, removing`,A),await b$.unlink(J).catch(()=>{}),null;return Y}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await b$.unlink(J).catch(()=>{}),null;throw U}}async function SF($=Ww(),w){let A;try{A=await b$.readdir($)}catch(U){if(U.code==="ENOENT")return[];throw U}let J=[];for(let U of A){if(!U.endsWith(".json"))continue;let Y=U.slice(0,-5);if(!Y1(Y))continue;let f=await q8(Y,$,w);if(f)J.push(f)}return J}import{execSync as l7}from"node:child_process";import*as zw from"node:http";import*as uF from"node:http2";import*as nF from"node:net";import*as s from"node:process";var UU=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,T0={bold:UU(1,22),dim:UU(2,22),green:UU(32,39),cyan:UU(36,39)};import*as _F from"node:fs";import*as XF from"node:path";import*as H0 from"node:process";import{spawn as y7}from"node:child_process";import*as hw from"node:fs/promises";import{homedir as C7}from"node:os";import*as Q1 from"node:path";import*as g$ from"node:process";B$();function YU(){return Q1.join(C7(),".stacks","rpx")}function OF($=YU()){return Q1.join($,"daemon.pid")}async function VF($=YU()){try{let w=await hw.readFile(OF($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function S7($=YU()){await hw.unlink(OF($)).catch(()=>{})}function V7(){let $=g$.execPath,w=Q1.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&g$.argv[1])return[$,g$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function DF($={}){let w=$.rpxDir??YU(),A=$.verbose??!1,J=await VF(w);if(J!==null&&F0(J))return z("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await S7(w);await hw.mkdir(w,{recursive:!0});let U=$.spawnCommand??V7();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${U.join(" ")}`,A);let Y=y7(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??g$.cwd(),env:$.spawnEnv?{...g$.env,...$.spawnEnv}:g$.env});Y.unref();let f=null;Y.once("error",(h)=>{f=h});let Z=$.startupTimeoutMs??5000,E=$.pollIntervalMs??50,W=Date.now()+Z;while(Date.now()<W){if(f)throw f;let h=await VF(w);if(h!==null&&F0(h))return z("daemon",`daemon registered with pid=${h}`,A),{pid:h,spawned:!0};await new Promise((F)=>setTimeout(F,E))}if(f)throw f;throw Error(`rpx daemon failed to start within ${Z}ms (rpxDir=${w})`)}B$();function O7($){let w=$.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function R8($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,J=new Set,U=$.proxies.map((j)=>{let B=j.id??O7(j.to);if(!X1(B))throw Error(`invalid registry id "${B}" derived from to="${j.to}"`);if(J.has(B))throw Error(`duplicate registry id "${B}" — set an explicit \`id\` on one of the proxies`);return J.add(B),{...j,id:B}}),Y=new Date().toISOString();for(let j of U)await GF({id:j.id,from:j.from,to:j.to,pid:$.persistent?void 0:H0.pid,cwd:H0.cwd(),createdAt:Y,cleanUrls:j.cleanUrls,changeOrigin:j.changeOrigin,pathRewrites:j.pathRewrites},A,w);let f=await DF({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let j of U)N.success(`https://${j.to} → ${j.from}`);if(N.info(`(via rpx daemon pid=${f.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let Z=!1,E=A??s0(),W=U.map((j)=>j.id),h=async()=>{if(Z)return;Z=!0;for(let j of W)await j8(j,A,w).catch((B)=>{z("runner",`removeEntry(${j}) failed: ${B}`,w)})},F=(j)=>{z("runner",`received ${j}, unregistering ${W.length} entries`,w),h().finally(()=>H0.exit(0))};H0.once("SIGINT",F),H0.once("SIGTERM",F),H0.once("exit",()=>{if(Z)return;for(let j of W)try{_F.unlinkSync(XF.join(E,`${j}.json`))}catch{}}),await new Promise(()=>{})}B$();import{exec as D7}from"node:child_process";import Fw from"node:fs";import kF from"node:os";import K8 from"node:path";import*as x1 from"node:process";import{promisify as _7}from"node:util";var fU=_7(D7),A0=x1.platform==="win32"?K8.join(x1.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",N8=!1;async function EU($){if(x1.platform==="win32")throw Error("Administrator privileges required on Windows");let w=Jw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:U}=await fU(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return N8=!0,U}if(N8)try{let{stdout:U}=await fU(`sudo -n sh -c '${A}'`);return U}catch(U){z("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:J}=await fU(`sudo sh -c '${A}'`);return N8=!0,J}catch(J){throw Error(`Failed to execute sudo command: ${J.message}`)}}async function P1($,w){z("hosts",`Adding hosts: ${$.join(", ")}`,w),z("hosts",`Using hosts file at: ${A0}`,w);try{let A;try{A=await Fw.promises.readFile(A0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await EU(`cat "${A0}"`)}catch(f){throw console.log(" Could not read hosts file — skipping hosts setup"),z("hosts",`sudo read also failed: ${f}`,w),Error(`Cannot read hosts file: ${f}`)}}let J=$.filter((f)=>{let Z=`127.0.0.1 ${f}`,E=`::1 ${f}`;return!A.includes(Z)&&!A.includes(E)});if(J.length===0){z("hosts","All hosts already exist in hosts file",w);return}let U=J.map((f)=>`
|
|
238
239
|
# Added by rpx
|
|
239
|
-
127.0.0.1 ${
|
|
240
|
-
::1 ${
|
|
241
|
-
`),Y=
|
|
242
|
-
`),U=!1,Y=J.filter((
|
|
240
|
+
127.0.0.1 ${f}
|
|
241
|
+
::1 ${f}`).join(`
|
|
242
|
+
`),Y=K8.join(kF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Fw.promises.writeFile(Y,A+U,"utf8"),await EU(`cat "${Y}" | tee "${A0}" > /dev/null`),console.log(` Hosts updated: ${J.join(", ")}`)}catch(f){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),J.forEach((Z)=>{console.log(` 127.0.0.1 ${Z}`),console.log(` ::1 ${Z}`)}),console.log(` Or run: sudo nano ${A0}`)}finally{try{await Fw.promises.unlink(Y)}catch{}}}catch(A){z("hosts",`Failed to manage hosts file: ${A.message}`,w)}}async function QF($,w){z("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let A;try{A=await Fw.promises.readFile(A0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await EU(`cat "${A0}"`)}catch(E){throw z("hosts",`sudo read also failed: ${E}`,w),Error(`Cannot read hosts file: ${E}`)}}let J=A.split(`
|
|
243
|
+
`),U=!1,Y=J.filter((E)=>{if($.some((h)=>E.includes(` ${h}`)&&(E.includes("127.0.0.1")||E.includes("::1"))))return U=!0,!1;if(E.trim()==="# Added by rpx")return U=!0,!1;return!0});if(!U){z("hosts","No matching hosts found to remove",w);return}while(Y[Y.length-1]?.trim()==="")Y.pop();let f=`${Y.join(`
|
|
243
244
|
`)}
|
|
244
|
-
`,Z=W8.join(KF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Bw.promises.writeFile(Z,h,"utf8"),await $U(`cat "${Z}" | tee "${A0}" > /dev/null`),z("hosts","Hosts removed successfully",w)}catch(f){z("hosts","Could not clean up hosts file automatically",w)}finally{try{await Bw.promises.unlink(Z)}catch(f){z("hosts",`Failed to remove temporary file: ${f}`,w)}}}catch(A){z("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function x1($,w){z("hosts",`Checking hosts: ${$}`,w);let A;try{A=await Bw.promises.readFile(A0,"utf-8")}catch(J){z("hosts",`Error reading hosts file: ${J}`,w);try{let U=Jw(),Y;if(U)Y=`echo '${U}' | sudo -S cat "${A0}" 2>/dev/null`;else Y=`sudo -n cat "${A0}" 2>/dev/null || cat "${A0}" 2>/dev/null || echo ""`;let{stdout:h}=await eJ(Y);A=h}catch(U){return z("hosts",`Cannot read hosts file, assuming entries don't exist: ${U}`,w),$.map(()=>!1)}}return $.map((J)=>{let U=`127.0.0.1 ${J}`,Y=`::1 ${J}`;return A.includes(U)||A.includes(Y)})}T$();import*as wU from"node:net";function jw($,w,A){return z("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((J)=>{let U=wU.createServer(),Y=setTimeout(()=>{z("port",`Checking port ${$} timed out, assuming it's in use`,A),U.close(),J(!0)},3000);U.once("error",(h)=>{if(clearTimeout(Y),h.code==="EADDRINUSE")z("port",`Port ${$} is in use`,A),J(!0);else z("port",`Error checking port ${$}: ${h.message}`,A),J(!0)}),U.once("listening",()=>{clearTimeout(Y),z("port",`Port ${$} is available`,A),U.close(),J(!1)});try{U.listen($,w)}catch(h){clearTimeout(Y),z("port",`Exception checking port ${$}: ${h}`,A),J(!0)}})}async function T7($,w,A,J=50){z("port",`Finding available port starting from ${$} (max attempts: ${J})`,A);let U=$,Y=0;while(Y<J){if(Y++,!await jw(U,w,A))return z("port",`Found available port: ${U} after ${Y} attempts`,A),U;z("port",`Port ${U} is in use, trying ${U+1} (attempt ${Y}/${J})`,A),U++}throw Error(`Unable to find available port after ${J} attempts starting from ${$}`)}function IF($,w,A=5000,J){return z("port",`Testing connection to ${w}:${$}`,J),new Promise((U)=>{let Y=wU.connect({host:w,port:$,timeout:A});Y.once("connect",()=>{z("port",`Successfully connected to ${w}:${$}`,J),Y.end(),U(!0)}),Y.once("timeout",()=>{z("port",`Connection to ${w}:${$} timed out`,J),Y.destroy(),U(!1)}),Y.once("error",(h)=>{z("port",`Failed to connect to ${w}:${$}: ${h.message}`,J),Y.destroy(),U(!1)})})}class AU{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,A=50){this.hostname=$,this.verbose=w,this.maxRetries=A}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await jw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await IF($,this.hostname,3000,this.verbose))return z("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let A=await T7($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await IF(A,this.hostname,3000,this.verbose))if(A<$+this.maxRetries)return this.findNextAvailablePort(A+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(A),A}releasePort($){z("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var yI=new AU;import{spawn as G7}from"node:child_process";import*as zw from"node:process";T$();class JU{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[J,...U]=w.command.split(" "),Y=w.cwd||zw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${J} ${U.join(" ")}`,A),z("start",` Working directory: ${Y}`,A),z("start",` Environment variables: ${w0(w.env)}`,A);let h=G7(J,U,{cwd:Y,env:{...zw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:Y,process:h,env:w.env}),new Promise((Z,f)=>{if(h.on("error",(E)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${E}`,A),this.processes.delete($),f(E),zw.emit("SIGINT")}),h.on("exit",(E)=>{if(!this.isShuttingDown&&E!==null&&E!==0)z("start",`Process ${$} exited with code ${E}`,A),this.processes.delete($),f(Error(`Process ${$} exited with code ${E}`)),zw.emit("SIGINT")}),A)h.stdout?.on("data",(E)=>{z("process",`[${$}] ${E.toString().trim()}`,!0)}),h.stderr?.on("data",(E)=>{z("process",`[${$}] ERR: ${E.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&h.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),Z()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){z("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((J)=>{N.error(`Failed to stop process ${A}:`,J)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var DI=new JU;T$();var EU=new JU,_7="0.12.0",X7=new AU("0.0.0.0"),P1=new Set,F8=!1,ZU=null,B8=null;async function WU($){if(F8)return z("cleanup","Cleanup already in progress, skipping",$?.verbose),B8||Promise.resolve();F8=!0,z("cleanup","Starting cleanup process",$?.verbose),B8=new Promise((w)=>{ZU=w});try{await EU.stopAll($?.verbose),N.info("Shutting down proxy servers...");let w=[],A=Array.from(P1).map((J)=>new Promise((U)=>{J.close(()=>{z("cleanup","Server closed successfully",$?.verbose),U()})}));if(w.push(...A),$?.hosts&&$.domains?.length){z("cleanup","Cleaning up hosts file entries",$?.verbose),z("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let J=$.domains.filter((U)=>{if(U==="test.local")return!0;return U!=="localhost"&&!U.startsWith("localhost.")&&U!=="127.0.0.1"});if(z("cleanup",`Filtered domains for cleanup: ${JSON.stringify(J)}`,$?.verbose),J.length>0)N.info("Cleaning up hosts file entries..."),w.push(MF(J,$?.verbose).then(()=>{z("cleanup",`Removed hosts entries for ${J.join(", ")}`,$?.verbose)}).catch((U)=>{z("cleanup",`Failed to remove hosts entries: ${U}`,$?.verbose),N.warn(`Failed to clean up hosts file entries for ${J.join(", ")}:`,U)}))}if($?.certs&&$.domains?.length){z("cleanup","Cleaning up SSL certificates",$?.verbose),N.info("Cleaning up SSL certificates...");let J=$.domains.map(async(U)=>{try{await AF(U,$?.verbose),z("cleanup",`Removed certificates for ${U}`,$?.verbose)}catch(Y){z("cleanup",`Failed to remove certificates for ${U}: ${Y}`,$?.verbose),N.warn(`Failed to clean up certificates for ${U}:`,Y)}});w.push(...J)}await Promise.allSettled(w),z("cleanup","All cleanup tasks completed successfully",$?.verbose),N.success("All cleanup tasks completed successfully")}catch(w){z("cleanup",`Error during cleanup: ${w}`,$?.verbose),N.error("Error during cleanup:",w)}finally{if(ZU)ZU();ZU=null,F8=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(s.env.NODE_ENV!=="test"&&s.env.BUN_ENV!=="test"&&!w)s.exit(0)}return B8}var j8=!1;function z8($){if(j8){z("signal",`Received second ${$} signal, forcing exit`,!0),s.exit(1);return}j8=!0,z("signal",`Received ${$} signal, initiating cleanup`,!0),WU().catch((w)=>{z("signal",`Cleanup failed after ${$}: ${w}`,!0),s.exit(1)}).finally(()=>{j8=!1})}s.once("SIGINT",()=>z8("SIGINT"));s.once("SIGTERM",()=>z8("SIGTERM"));s.on("uncaughtException",($)=>{z("process",`Uncaught exception: ${$}`,!0),N.error("Uncaught exception:",$),z8("uncaughtException")});async function b1($,w,A,J=5){z("connection",`Testing connection to ${$}:${w} (retries left: ${J})`,A);let U=15000,Y=Date.now();if(s.env.RPX_BYPASS_CONNECTION_TEST==="true"){z("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let h=()=>new Promise((Z,f)=>{let E=DF.connect({host:$,port:w,timeout:3000});E.once("connect",()=>{z("connection",`Successfully connected to ${$}:${w}`,A),E.end(),Z()}),E.once("timeout",()=>{z("connection",`Connection to ${$}:${w} timed out`,A),E.destroy(),f(Error("Connection timed out"))}),E.once("error",(W)=>{z("connection",`Failed to connect to ${$}:${w}: ${W}`,A),E.destroy(),f(W)})});try{await h()}catch(Z){if(Date.now()-Y>U){z("connection",`Connection test timed out after ${U}ms, but continuing anyway`,A),N.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(Z.code==="ECONNREFUSED"&&J>0)return z("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${J} retries left)`,A),await new Promise((E)=>setTimeout(E,2000)),b1($,w,A,J-1);if(J>0)try{z("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((E,W)=>{let F=Hw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(j)=>{z("connection",`Received HTTP response with status: ${j.statusCode}`,A),E()});F.on("error",(j)=>W(j)),F.on("timeout",()=>{F.destroy(),W(Error("HTTP request timed out"))}),F.end()}),z("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(E){return z("connection",`HTTP request to ${$}:${w} failed: ${E}`,A),z("connection",`Retrying socket connection in 2 seconds... (${J} retries left)`,A),await new Promise((W)=>setTimeout(W,2000)),b1($,w,A,J-1)}let f=`Failed to connect to ${$}:${w} after ${5-J} attempts: ${Z.message}`;z("connection",`${f}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),N.warn(f),N.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function OF($){z("server",`Starting server with options: ${w0($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),J=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),U=[A.hostname];if(!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){z("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await x1(U,$.verbose))[0]){N.info(`Adding ${A.hostname} to hosts file...`),N.info("This may require sudo/administrator privileges");try{await Q1(U,$.verbose)}catch(Z){if(N.error("Failed to add hosts entry:",Z.message),N.warn("You can manually add this entry to your hosts file:"),N.warn(`127.0.0.1 ${A.hostname}`),N.warn(`::1 ${A.hostname}`),s.platform==="win32")N.warn("On Windows:"),N.warn("1. Run notepad as administrator"),N.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else N.warn("On Unix systems:"),N.warn("sudo nano /etc/hosts")}}else z("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(h){N.error("Failed to check hosts file:",h.message)}}try{await b1(w.hostname,J,$.verbose)}catch(h){z("server",`Connection test failed: ${h}`,$.verbose),N.error(h.message),N.warn("Continuing with proxy setup despite connection test failure..."),N.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let Y=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=V1({...$,to:A.hostname});if(Y=await c0({...$,to:A.hostname,https:$.https}),!Y){if(z("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await A1({...$,from:w.toString(),to:A.hostname,https:$.https}),Y=await c0({...$,to:A.hostname,https:$.https}),!Y)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(h){throw z("server",`SSL setup failed: ${h}`,$.verbose),h}z("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await Q7({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:J,sourceUrl:{hostname:w.hostname,host:w.host},ssl:Y})}async function k7($,w,A,J,U,Y,h,Z,f,E,W){z("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${E}`,f);function F(H){let q={};for(let[G,R]of Object.entries(H))if(!G.startsWith(":"))q[G]=R;return q}let j=(H,q)=>{z("request",`Incoming request: ${H.method} ${H.url}`,f);let G=H.url||"/",R=H.method||"GET";if(H instanceof VF.Http2ServerRequest){let M=H.headers;R=M[":method"]||R,G=M[":path"]||G}if(E){if(!G.match(/\.[a-z0-9]+$/i))if(G.endsWith("/"))G=`${G}index.html`;else G=`${G}.html`}let K=F(H.headers);if(W)K.host=`${Y.hostname}:${A}`,z("request",`Changed origin: setting host header to ${K.host}`,f);let L={hostname:Y.hostname,port:A,path:G,method:R,headers:K};z("request",`Proxy request options: ${w0(L)}`,f);let C=Hw.request(L,(M)=>{if(z("response",`Proxy response received with status ${M.statusCode}`,f),E&&M.statusCode===404){let c$=[];if(G.endsWith(".html"))c$.push(G.slice(0,-5));else if(!G.match(/\.[a-z0-9]+$/i))c$.push(`${G}.html`);if(!G.endsWith("/"))c$.push(`${G}/index.html`);if(c$.length>0){z("cleanUrls",`Trying alternative paths: ${c$.join(", ")}`,f);let U1=(i1)=>{if(i1.length===0){q.writeHead(M.statusCode||404,M.headers),M.pipe(q);return}let H8=i1[0],PF={...L,path:H8},T8=Hw.request(PF,(c1)=>{if(c1.statusCode===200)z("cleanUrls",`Found matching path: ${H8}`,f),q.writeHead(c1.statusCode,c1.headers),c1.pipe(q);else U1(i1.slice(1))});T8.on("error",()=>U1(i1.slice(1))),T8.end()};U1(c$);return}}let V$={...M.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};q.writeHead(M.statusCode||500,V$),M.pipe(q)});C.on("error",(M)=>{z("request",`Proxy request failed: ${M}`,f),N.error("Proxy request failed:",M),q.writeHead(502),q.end(`Proxy Error: ${M.message}`)}),H.pipe(C)};if(z("server",`Creating server with SSL config: ${!!h}`,f),h)return new Promise((H,q)=>{try{let G=Bun.serve({port:J,hostname:U,tls:{key:h.key,cert:h.cert,ca:h.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let K=new URL(R.url);z("request",`Bun.serve received: ${R.method} ${K.pathname}`,f);let L=`http://${Y.host}`,C=new URL(K.pathname+K.search,L);try{let M=new Headers(R.headers);if(M.set("host",Y.host),W)M.set("origin",L);M.set("x-forwarded-for","127.0.0.1"),M.set("x-forwarded-proto","https"),M.set("x-forwarded-host",w);let V$=await fetch(C.toString(),{method:R.method,headers:M,body:R.body,redirect:"manual"}),c$=new Headers(V$.headers);if(E&&K.pathname.endsWith(".html")){let U1=K.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:U1}})}return new Response(V$.body,{status:V$.status,statusText:V$.statusText,headers:c$})}catch(M){return z("request",`Proxy error: ${M}`,f),new Response(`Proxy Error: ${M}`,{status:502})}},error(R){return z("server",`Bun.serve error: ${R}`,f),new Response(`Server Error: ${R.message}`,{status:500})}});P1.add(G),SF({from:$,to:w,vitePluginUsage:Z,listenPort:J,ssl:!0,cleanUrls:E,verbose:f}),H()}catch(G){q(G)}});let B=Hw.createServer(j);function T(H){return P1.add(H),new Promise((q,G)=>{H.listen(J,U,()=>{z("server",`Server listening on port ${J}`,f),SF({from:$,to:w,vitePluginUsage:Z,listenPort:J,ssl:!!h,cleanUrls:E,verbose:f}),q()}),H.on("error",(R)=>{z("server",`Server error: ${R}`,f),G(R)})})}return T(B)}async function Q7($){z("setup",`Setting up reverse proxy: ${w0($)}`,$.verbose);let{from:w,to:A,fromPort:J,sourceUrl:U,ssl:Y,verbose:h,cleanup:Z,vitePluginUsage:f,changeOrigin:E,cleanUrls:W}=$,F=80,j=443,B="0.0.0.0",T=$.portManager||X7;try{if(A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await x1([A],h))[0]){N.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await Q1([A],h),N.success(`Added ${A} to your hosts file.`)}catch(K){N.error(`Failed to add ${A} to your hosts file: ${K}`),N.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(s.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await x1([A],h))[0]){z("hosts",`${A} not found in hosts file, adding...`,h);try{await Q1([A],h)}catch(K){z("hosts",`Failed to add ${A} to hosts file: ${K}`,h)}}}if(Y&&!T.usedPorts.has(F)){if(!await jw(F,B,h))z("setup","Starting HTTP redirect server",h),_F(h),T.usedPorts.add(F);else if(z("setup","Port 80 is in use, skipping HTTP redirect",h),h)N.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let H=Y?j:F,q=await jw(H,B,h),G;if(q){if(z("setup",`Port ${H} is already in use`,h),h)N.warn(`Port ${H} is already in use. This may be another instance of rpx or another service.`);if(H===443){if(G=await T.getNextAvailablePort(3443,!0),z("setup",`Using port ${G} instead of ${H}`,h),h)N.info(`Using port ${G} instead. Access your site at https://${A}:${G}`)}else if(G=await T.getNextAvailablePort(H+1000,!0),z("setup",`Using port ${G} instead of ${H}`,h),h)N.info(`Using port ${G} instead. Access your site at http://${A}:${G}`)}else G=H,T.usedPorts.add(G),z("setup",`Using standard ${H===443?"HTTPS":"HTTP"} port ${H} for ${A}`,h);await k7(w,A,J,G,B,U,Y,f,h,W,E)}catch(H){z("setup",`Setup failed: ${H}`,h),N.error(`Failed to setup reverse proxy: ${H.message}`),WU({domains:[A],hosts:typeof Z==="boolean"?Z:Z?.hosts,certs:typeof Z==="boolean"?Z:Z?.certs,verbose:h,vitePluginUsage:f})}}function _F($){z("redirect","Starting HTTP redirect server",$);let w=Hw.createServer((A,J)=>{let U=A.headers.host||"";z("redirect",`Redirecting request from ${U}${A.url} to HTTPS`,$),J.writeHead(301,{Location:`https://${U}${A.url}`}),J.end()}).listen(80);P1.add(w),z("redirect","HTTP redirect server started",$)}function XF($){let w={...Fh,...$};if(z("proxy",`Starting proxy with options: ${w0(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){N.error("viaDaemon mode requires both `from` and `to`");return}Z8({proxies:[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((f)=>{N.error(`Failed to register with rpx daemon: ${f.message}`),s.exit(1)});return}let A=w.to||"",J=A.split(".").pop()?.toLowerCase()||"",U=s.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),Y=["dev","app","page","new","day","foo"],h=["test","localhost","local","example","invalid"];if(U&&Y.includes(J)&&w?.verbose)N.warn(`The .${J} TLD may not work reliably for local development`),N.info(` Google owns .${J} with HSTS preloading, which can bypass local DNS`),N.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(U)Promise.resolve().then(() => (fU(),hU)).then(({startDnsServer:f,setupResolver:E})=>{f([A],w.verbose).then((W)=>{if(W)E(w.verbose,[A]).then(()=>{if(w.verbose)if(h.includes(J))N.success(`DNS server started for .${J} domains`);else N.success(`DNS server started for .${J} domains (hosts file entry also added)`)});else z("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((f)=>{z("dns",`Failed to start DNS server: ${f}`,w.verbose)});let Z={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:V1(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};z("proxy",`Server options: ${w0(Z)}`,w.verbose),OF(Z).catch((f)=>{z("proxy",`Failed to start proxy: ${f}`,w.verbose),N.error(`Failed to start proxy: ${f.message}`),WU({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function x7($){return $?.verbose||!1}async function kF($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let A=x7(w);if(z("config",`Starting with config: ${w0(w,2)}`,A),z("config",`Is multi-proxy? ${"proxies"in w}`,A),w.viaDaemon){let T="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({id:H.id,from:H.from,to:H.to,cleanUrls:H.cleanUrls??w.cleanUrls,changeOrigin:H.changeOrigin??w.changeOrigin,pathRewrites:H.pathRewrites})):[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await Z8({proxies:T,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){z("servers",`Found ${w.proxies.length} proxies in config`,A);for(let B of w.proxies)if(B.start){let T=`${B.from}-${B.to}`;try{z("watch",`Starting command for ${T} with command: ${B.start.command}`,A),N.info(`Starting command for ${T}...`),await EU.startProcess(T,B.start,A);let H=new URL(B.from.startsWith("http")?B.from:`http://${B.from}`),q=H.hostname||"localhost",G=Number(H.port)||80;try{await b1(q,G,A),z("watch",`Dev server is ready at ${q}:${G}`,A)}catch(R){z("watch",`Connection check failed, but continuing with proxy setup: ${R}`,A),N.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(H){throw z("watch",`Failed to start command for ${T}: ${H}`,A),Error(`Failed to start command for ${T}: ${H}`)}}else z("watch",`No start command for proxy ${B.from} -> ${B.to}`,A)}else if("start"in w&&w.start){z("watch","Found start command in single proxy config",A);let B=`${w.from}-${w.to}`;try{if(w.start)z("watch",`Starting command: ${w.start.command}`,A),await EU.startProcess(B,w.start,A);let T=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),H=T.hostname||"localhost",q=Number(T.port)||80;try{await b1(H,q,A),z("watch",`Dev server is ready at ${H}:${q}`,A)}catch(G){z("watch",`Connection check failed, but continuing with proxy setup: ${G}`,A),N.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(T){throw z("watch",`Failed to run start command: ${T}`,A),Error(`Failed to run start command: ${T}`)}}else z("watch","No start command found in config",A);let J="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(s.platform!=="win32"&&(w.https||w.cleanup?.hosts!==!1)){if(!Jw())try{z("sudo","Pre-acquiring sudo credentials for privileged operations",A),O7("sudo -v",{stdio:"inherit"})}catch{z("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let B=await c0(w);if(!B){if(z("ssl",`No valid or trusted certificates found for ${J}, generating new ones`,w.verbose),await A1(w),B=await c0(w),!B)throw Error(`Failed to load SSL certificates after generation for ${J}`)}else z("ssl",`Using existing and trusted certificates for ${J}`,w.verbose);w._cachedSSLConfig=B}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((B)=>({...B,https:w.https,cleanup:w.cleanup,cleanUrls:B.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:B.changeOrigin??w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig}],Y=U.map((B)=>B.to||"rpx.localhost"),h=w._cachedSSLConfig,Z=Y.filter((B)=>B&&!B.includes("localhost")&&!B.includes("127.0.0.1")),f=["dev","app","page","new","day","foo"],E=["test","localhost","local","example","invalid"],W=[...new Set(Z.map((B)=>B.split(".").pop()?.toLowerCase()))],F=W.filter((B)=>!!B&&f.includes(B));if(F.length>0&&A)N.warn(`The following TLDs may not work reliably for local development: ${F.map((B)=>`.${B}`).join(", ")}`),N.info(" These TLDs have HSTS preloading which can bypass local DNS"),N.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(s.platform==="darwin"&&Z.length>0){let{startDnsServer:B,setupResolver:T}=await Promise.resolve().then(() => (fU(),hU));if(await B(Z,A)){if(await T(A,Z),A)if(W.every((G)=>!!G&&E.includes(G)))N.success(`DNS server started for ${W.map((G)=>`.${G}`).join(", ")} domains`);else N.success(`DNS server started for ${W.map((G)=>`.${G}`).join(", ")} domains (hosts file entries also added)`)}else z("dns","Could not start DNS server - custom domains may not resolve",A)}let j=async()=>{z("cleanup","Starting cleanup handler",w.verbose);try{let{stopDnsServer:B,removeResolver:T}=await Promise.resolve().then(() => (fU(),hU));B(w.verbose),await T(w.verbose)}catch(B){z("cleanup",`Error stopping DNS server: ${B}`,w.verbose)}try{await EU.stopAll(w.verbose)}catch(B){z("cleanup",`Error stopping processes: ${B}`,w.verbose)}await WU({domains:Y,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};if(s.on("SIGINT",j),s.on("SIGTERM",j),s.on("uncaughtException",(B)=>{z("process",`Uncaught exception: ${B}`,!0),console.error("Uncaught exception:",B),j()}),h&&U.length>1){z("proxies",`Creating shared HTTPS server for ${U.length} domains`,A);let B=new Map;for(let G of U){let R=G.to||"rpx.localhost",K=new URL(G.from?.startsWith("http")?G.from:`http://${G.from}`);if(B.set(R,{sourceHost:K.host,cleanUrls:G.cleanUrls||!1,changeOrigin:G.changeOrigin||!1,pathRewrites:G.pathRewrites}),z("proxies",`Route: ${R} → ${K.host}`,A),!R.includes("localhost")&&!R.includes("127.0.0.1"))try{if(!(await x1([R],A))[0])await Q1([R],A)}catch{z("hosts",`Could not add hosts entry for ${R}`,A)}}if(!await jw(80,"0.0.0.0",A))_F(A);let H=443;if(await jw(H,"0.0.0.0",A)){if(z("proxies",`Port ${H} is already in use, cannot start shared proxy`,A),A)N.warn(`Port ${H} is in use. Shared HTTPS proxy cannot start.`);return}try{let G=Bun.serve({port:H,hostname:"0.0.0.0",tls:{key:h.key,cert:h.cert,ca:h.ca,requestCert:!1,rejectUnauthorized:!1},fetch:D1((R)=>B.get(R),A),error(R){return z("server",`Shared proxy server error: ${R}`,A),new Response(`Server Error: ${R.message}`,{status:500})}});P1.add(G),z("proxies",`Shared HTTPS proxy listening on port ${H} for ${B.size} domains`,A)}catch(G){z("proxies",`Failed to start shared proxy: ${G}`,A),console.error("Failed to start shared HTTPS proxy:",G),j()}}else for(let B of U)try{let T=B.to||"rpx.localhost";z("proxy",`Starting proxy for ${T} with SSL config: ${!!h}`,B.verbose),await OF({from:B.from||"localhost:5173",to:T,cleanUrls:B.cleanUrls||!1,https:B.https||!1,cleanup:B.cleanup||!1,vitePluginUsage:B.vitePluginUsage||!1,verbose:B.verbose||!1,_cachedSSLConfig:h,changeOrigin:B.changeOrigin||!1})}catch(T){z("proxies",`Failed to start proxy for ${B.to}: ${T}`,B.verbose),console.error(`Failed to start proxy for ${B.to}:`,T),j()}}function SF($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${H0.green(H0.bold("rpx"))} ${H0.green(`v${_7}`)}`),console.log(` ${H0.green("➜")} ${H0.dim($?.from??"")} ${H0.dim("➜")} ${H0.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${H0.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${H0.green("➜")} Clean URLs enabled`)}ph();var rI=new Aw("rpx",{showTags:!1});function QF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}var t$=new NU("rpx"),xF="0.12.0";t$.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").action(async($)=>{if(!$?.from||!$.to)return kF(Dw);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let A={command:$.startCommand};if($.startCwd)A.cwd=$.startCwd;if($.startEnv)try{A.env=JSON.parse($.startEnv)}catch(J){console.error("Failed to parse start-env JSON:",J),l$.exit(1)}w.start=A}return XF(w)});t$.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=QF(Dw)?Dw.proxies.find((J)=>J.to===$||`${J.from}-${J.to}`===$):Dw.to===$?Dw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),l$.exit(1);try{await aJ.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(J){console.error(`Failed to start dev server for ${$}:`,J),l$.exit(1)}});t$.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await aJ.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),l$.exit(1)}});t$.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await aJ.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),l$.exit(1)}});t$.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--verbose","Enable verbose logging").action(async($)=>{try{await(await ZF({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,verbose:$.verbose??!0})).done,l$.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),l$.exit(1)}});t$.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,A=await WF({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!A.stopped&&A.pid===null){console.log("rpx daemon is not running");return}if(!A.stopped){console.log(`rpx daemon pid=${A.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${A.pid} stopped${A.forced?" (SIGKILL)":""}`)});t$.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??z0(),A=await fw(w),J=await fF(w),U=$.registryDir,Y=await HF(U).catch(()=>[]);if($.json){console.log(JSON.stringify({running:J,pid:A,pidFile:Zw(w),rpxDir:w,registryDir:U??Ww(),entries:Y},null,2));return}if(!J){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Zw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Zw(w)}`);if(console.log(`registry: ${U??Ww()}`),Y.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${Y.length}):`);for(let h of Y){let Z=h.pid!==void 0?`, pid=${h.pid}`:"";console.log(` https://${h.to} \u2192 ${h.from} (id=${h.id}${Z})`)}});t$.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),l$.exit(1);if(!J1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),l$.exit(1);try{await jF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),l$.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await EF({rpxDir:$.rpxDir,verbose:$.verbose}),A=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${A} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),l$.exit(1)}});t$.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async($,w)=>{if(!J1($))console.error(`invalid id: ${JSON.stringify($)}`),l$.exit(1);let A=await f8($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await zF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});t$.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(xF)});t$.version(xF);t$.help();t$.run();
|
|
245
|
+
`,Z=K8.join(kF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Fw.promises.writeFile(Z,f,"utf8"),await EU(`cat "${Z}" | tee "${A0}" > /dev/null`),z("hosts","Hosts removed successfully",w)}catch(E){z("hosts","Could not clean up hosts file automatically",w)}finally{try{await Fw.promises.unlink(Z)}catch(E){z("hosts",`Failed to remove temporary file: ${E}`,w)}}}catch(A){z("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function b1($,w){z("hosts",`Checking hosts: ${$}`,w);let A;try{A=await Fw.promises.readFile(A0,"utf-8")}catch(J){z("hosts",`Error reading hosts file: ${J}`,w);try{let U=Jw(),Y;if(U)Y=`echo '${U}' | sudo -S cat "${A0}" 2>/dev/null`;else Y=`sudo -n cat "${A0}" 2>/dev/null || cat "${A0}" 2>/dev/null || echo ""`;let{stdout:f}=await fU(Y);A=f}catch(U){return z("hosts",`Cannot read hosts file, assuming entries don't exist: ${U}`,w),$.map(()=>!1)}}return $.map((J)=>{let U=`127.0.0.1 ${J}`,Y=`::1 ${J}`;return A.includes(U)||A.includes(Y)})}B$();import*as ZU from"node:net";function Bw($,w,A){return z("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((J)=>{let U=ZU.createServer(),Y=setTimeout(()=>{z("port",`Checking port ${$} timed out, assuming it's in use`,A),U.close(),J(!0)},3000);U.once("error",(f)=>{if(clearTimeout(Y),f.code==="EADDRINUSE")z("port",`Port ${$} is in use`,A),J(!0);else z("port",`Error checking port ${$}: ${f.message}`,A),J(!0)}),U.once("listening",()=>{clearTimeout(Y),z("port",`Port ${$} is available`,A),U.close(),J(!1)});try{U.listen($,w)}catch(f){clearTimeout(Y),z("port",`Exception checking port ${$}: ${f}`,A),J(!0)}})}async function X7($,w,A,J=50){z("port",`Finding available port starting from ${$} (max attempts: ${J})`,A);let U=$,Y=0;while(Y<J){if(Y++,!await Bw(U,w,A))return z("port",`Found available port: ${U} after ${Y} attempts`,A),U;z("port",`Port ${U} is in use, trying ${U+1} (attempt ${Y}/${J})`,A),U++}throw Error(`Unable to find available port after ${J} attempts starting from ${$}`)}function xF($,w,A=5000,J){return z("port",`Testing connection to ${w}:${$}`,J),new Promise((U)=>{let Y=ZU.connect({host:w,port:$,timeout:A});Y.once("connect",()=>{z("port",`Successfully connected to ${w}:${$}`,J),Y.end(),U(!0)}),Y.once("timeout",()=>{z("port",`Connection to ${w}:${$} timed out`,J),Y.destroy(),U(!1)}),Y.once("error",(f)=>{z("port",`Failed to connect to ${w}:${$}: ${f.message}`,J),Y.destroy(),U(!1)})})}class WU{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,A=50){this.hostname=$,this.verbose=w,this.maxRetries=A}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Bw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await xF($,this.hostname,3000,this.verbose))return z("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let A=await X7($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await xF(A,this.hostname,3000,this.verbose))if(A<$+this.maxRetries)return this.findNextAvailablePort(A+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(A),A}releasePort($){z("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var wL=new WU;import{spawn as k7}from"node:child_process";import*as jw from"node:process";B$();class hU{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[J,...U]=w.command.split(" "),Y=w.cwd||jw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${J} ${U.join(" ")}`,A),z("start",` Working directory: ${Y}`,A),z("start",` Environment variables: ${w0(w.env)}`,A);let f=k7(J,U,{cwd:Y,env:{...jw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:Y,process:f,env:w.env}),new Promise((Z,E)=>{if(f.on("error",(W)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${W}`,A),this.processes.delete($),E(W),jw.emit("SIGINT")}),f.on("exit",(W)=>{if(!this.isShuttingDown&&W!==null&&W!==0)z("start",`Process ${$} exited with code ${W}`,A),this.processes.delete($),E(Error(`Process ${$} exited with code ${W}`)),jw.emit("SIGINT")}),A)f.stdout?.on("data",(W)=>{z("process",`[${$}] ${W.toString().trim()}`,!0)}),f.stderr?.on("data",(W)=>{z("process",`[${$}] ERR: ${W.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&f.killed)this.processes.delete($),E(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),Z()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){z("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((J)=>{N.error(`Failed to stop process ${A}:`,J)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var fL=new hU;B$();var HU=new hU,t7="0.12.0",p7=new WU("0.0.0.0"),i1=new Set,M8=!1,TU=null,I8=null;async function GU($){if(M8)return z("cleanup","Cleanup already in progress, skipping",$?.verbose),I8||Promise.resolve();M8=!0,z("cleanup","Starting cleanup process",$?.verbose),I8=new Promise((w)=>{TU=w});try{await HU.stopAll($?.verbose),N.info("Shutting down proxy servers...");let w=[],A=Array.from(i1).map((J)=>new Promise((U)=>{J.close(()=>{z("cleanup","Server closed successfully",$?.verbose),U()})}));if(w.push(...A),$?.hosts&&$.domains?.length){z("cleanup","Cleaning up hosts file entries",$?.verbose),z("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let J=$.domains.filter((U)=>{if(U==="test.local")return!0;return U!=="localhost"&&!U.startsWith("localhost.")&&U!=="127.0.0.1"});if(z("cleanup",`Filtered domains for cleanup: ${JSON.stringify(J)}`,$?.verbose),J.length>0)N.info("Cleaning up hosts file entries..."),w.push(QF(J,$?.verbose).then(()=>{z("cleanup",`Removed hosts entries for ${J.join(", ")}`,$?.verbose)}).catch((U)=>{z("cleanup",`Failed to remove hosts entries: ${U}`,$?.verbose),N.warn(`Failed to clean up hosts file entries for ${J.join(", ")}:`,U)}))}if($?.certs&&$.domains?.length){z("cleanup","Cleaning up SSL certificates",$?.verbose),N.info("Cleaning up SSL certificates...");let J=$.domains.map(async(U)=>{try{await zF(U,$?.verbose),z("cleanup",`Removed certificates for ${U}`,$?.verbose)}catch(Y){z("cleanup",`Failed to remove certificates for ${U}: ${Y}`,$?.verbose),N.warn(`Failed to clean up certificates for ${U}:`,Y)}});w.push(...J)}await Promise.allSettled(w),z("cleanup","All cleanup tasks completed successfully",$?.verbose),N.success("All cleanup tasks completed successfully")}catch(w){z("cleanup",`Error during cleanup: ${w}`,$?.verbose),N.error("Error during cleanup:",w)}finally{if(TU)TU();TU=null,M8=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(s.env.NODE_ENV!=="test"&&s.env.BUN_ENV!=="test"&&!w)s.exit(0)}return I8}var L8=!1;function y8($){if(L8){z("signal",`Received second ${$} signal, forcing exit`,!0),s.exit(1);return}L8=!0,z("signal",`Received ${$} signal, initiating cleanup`,!0),GU().catch((w)=>{z("signal",`Cleanup failed after ${$}: ${w}`,!0),s.exit(1)}).finally(()=>{L8=!1})}s.once("SIGINT",()=>y8("SIGINT"));s.once("SIGTERM",()=>y8("SIGTERM"));s.on("uncaughtException",($)=>{z("process",`Uncaught exception: ${$}`,!0),N.error("Uncaught exception:",$),y8("uncaughtException")});async function c1($,w,A,J=5){z("connection",`Testing connection to ${$}:${w} (retries left: ${J})`,A);let U=15000,Y=Date.now();if(s.env.RPX_BYPASS_CONNECTION_TEST==="true"){z("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let f=()=>new Promise((Z,E)=>{let W=nF.connect({host:$,port:w,timeout:3000});W.once("connect",()=>{z("connection",`Successfully connected to ${$}:${w}`,A),W.end(),Z()}),W.once("timeout",()=>{z("connection",`Connection to ${$}:${w} timed out`,A),W.destroy(),E(Error("Connection timed out"))}),W.once("error",(h)=>{z("connection",`Failed to connect to ${$}:${w}: ${h}`,A),W.destroy(),E(h)})});try{await f()}catch(Z){if(Date.now()-Y>U){z("connection",`Connection test timed out after ${U}ms, but continuing anyway`,A),N.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(Z.code==="ECONNREFUSED"&&J>0)return z("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${J} retries left)`,A),await new Promise((W)=>setTimeout(W,2000)),c1($,w,A,J-1);if(J>0)try{z("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((W,h)=>{let F=zw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(j)=>{z("connection",`Received HTTP response with status: ${j.statusCode}`,A),W()});F.on("error",(j)=>h(j)),F.on("timeout",()=>{F.destroy(),h(Error("HTTP request timed out"))}),F.end()}),z("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(W){return z("connection",`HTTP request to ${$}:${w} failed: ${W}`,A),z("connection",`Retrying socket connection in 2 seconds... (${J} retries left)`,A),await new Promise((h)=>setTimeout(h,2000)),c1($,w,A,J-1)}let E=`Failed to connect to ${$}:${w} after ${5-J} attempts: ${Z.message}`;z("connection",`${E}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),N.warn(E),N.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function vF($){z("server",`Starting server with options: ${w0($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),J=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),U=[A.hostname];if(!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){z("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await b1(U,$.verbose))[0]){N.info(`Adding ${A.hostname} to hosts file...`),N.info("This may require sudo/administrator privileges");try{await P1(U,$.verbose)}catch(Z){if(N.error("Failed to add hosts entry:",Z.message),N.warn("You can manually add this entry to your hosts file:"),N.warn(`127.0.0.1 ${A.hostname}`),N.warn(`::1 ${A.hostname}`),s.platform==="win32")N.warn("On Windows:"),N.warn("1. Run notepad as administrator"),N.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else N.warn("On Unix systems:"),N.warn("sudo nano /etc/hosts")}}else z("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(f){N.error("Failed to check hosts file:",f.message)}}try{await c1(w.hostname,J,$.verbose)}catch(f){z("server",`Connection test failed: ${f}`,$.verbose),N.error(f.message),N.warn("Continuing with proxy setup despite connection test failure..."),N.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let Y=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=D1({...$,to:A.hostname});if(Y=await c0({...$,to:A.hostname,https:$.https}),!Y){if(z("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await U1({...$,from:w.toString(),to:A.hostname,https:$.https}),Y=await c0({...$,to:A.hostname,https:$.https}),!Y)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(f){throw z("server",`SSL setup failed: ${f}`,$.verbose),f}z("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await a7({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:J,sourceUrl:{hostname:w.hostname,host:w.host},ssl:Y})}async function r7($,w,A,J,U,Y,f,Z,E,W,h){z("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${W}`,E);function F(T){let q={};for(let[G,R]of Object.entries(T))if(!G.startsWith(":"))q[G]=R;return q}let j=(T,q)=>{z("request",`Incoming request: ${T.method} ${T.url}`,E);let G=T.url||"/",R=T.method||"GET";if(T instanceof uF.Http2ServerRequest){let M=T.headers;R=M[":method"]||R,G=M[":path"]||G}if(W){if(!G.match(/\.[a-z0-9]+$/i))if(G.endsWith("/"))G=`${G}index.html`;else G=`${G}.html`}let K=F(T.headers);if(h)K.host=`${Y.hostname}:${A}`,z("request",`Changed origin: setting host header to ${K.host}`,E);let y={hostname:Y.hostname,port:A,path:G,method:R,headers:K};z("request",`Proxy request options: ${w0(y)}`,E);let C=zw.request(y,(M)=>{if(z("response",`Proxy response received with status ${M.statusCode}`,E),W&&M.statusCode===404){let c$=[];if(G.endsWith(".html"))c$.push(G.slice(0,-5));else if(!G.match(/\.[a-z0-9]+$/i))c$.push(`${G}.html`);if(!G.endsWith("/"))c$.push(`${G}/index.html`);if(c$.length>0){z("cleanUrls",`Trying alternative paths: ${c$.join(", ")}`,E);let f1=(u1)=>{if(u1.length===0){q.writeHead(M.statusCode||404,M.headers),M.pipe(q);return}let C8=u1[0],pF={...y,path:C8},S8=zw.request(pF,(n1)=>{if(n1.statusCode===200)z("cleanUrls",`Found matching path: ${C8}`,E),q.writeHead(n1.statusCode,n1.headers),n1.pipe(q);else f1(u1.slice(1))});S8.on("error",()=>f1(u1.slice(1))),S8.end()};f1(c$);return}}let V$={...M.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};q.writeHead(M.statusCode||500,V$),M.pipe(q)});C.on("error",(M)=>{z("request",`Proxy request failed: ${M}`,E),N.error("Proxy request failed:",M),q.writeHead(502),q.end(`Proxy Error: ${M.message}`)}),T.pipe(C)};if(z("server",`Creating server with SSL config: ${!!f}`,E),f)return new Promise((T,q)=>{try{let G=Bun.serve({port:J,hostname:U,tls:{key:f.key,cert:f.cert,ca:f.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let K=new URL(R.url);z("request",`Bun.serve received: ${R.method} ${K.pathname}`,E);let y=`http://${Y.host}`,C=new URL(K.pathname+K.search,y);try{let M=new Headers(R.headers);if(M.set("host",Y.host),h)M.set("origin",y);M.set("x-forwarded-for","127.0.0.1"),M.set("x-forwarded-proto","https"),M.set("x-forwarded-host",w);let V$=await fetch(C.toString(),{method:R.method,headers:M,body:R.body,redirect:"manual"}),c$=new Headers(V$.headers);if(W&&K.pathname.endsWith(".html")){let f1=K.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:f1}})}return new Response(V$.body,{status:V$.status,statusText:V$.statusText,headers:c$})}catch(M){return z("request",`Proxy error: ${M}`,E),new Response(`Proxy Error: ${M}`,{status:502})}},error(R){return z("server",`Bun.serve error: ${R}`,E),new Response(`Server Error: ${R.message}`,{status:500})}});i1.add(G),cF({from:$,to:w,vitePluginUsage:Z,listenPort:J,ssl:!0,cleanUrls:W,verbose:E}),T()}catch(G){q(G)}});let B=zw.createServer(j);function H(T){return i1.add(T),new Promise((q,G)=>{T.listen(J,U,()=>{z("server",`Server listening on port ${J}`,E),cF({from:$,to:w,vitePluginUsage:Z,listenPort:J,ssl:!!f,cleanUrls:W,verbose:E}),q()}),T.on("error",(R)=>{z("server",`Server error: ${R}`,E),G(R)})})}return H(B)}async function a7($){z("setup",`Setting up reverse proxy: ${w0($)}`,$.verbose);let{from:w,to:A,fromPort:J,sourceUrl:U,ssl:Y,verbose:f,cleanup:Z,vitePluginUsage:E,changeOrigin:W,cleanUrls:h}=$,F=80,j=443,B="0.0.0.0",H=$.portManager||p7;try{if(A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await b1([A],f))[0]){N.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await P1([A],f),N.success(`Added ${A} to your hosts file.`)}catch(K){N.error(`Failed to add ${A} to your hosts file: ${K}`),N.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(s.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await b1([A],f))[0]){z("hosts",`${A} not found in hosts file, adding...`,f);try{await P1([A],f)}catch(K){z("hosts",`Failed to add ${A} to hosts file: ${K}`,f)}}}if(Y&&!H.usedPorts.has(F)){if(!await Bw(F,B,f))z("setup","Starting HTTP redirect server",f),mF(f),H.usedPorts.add(F);else if(z("setup","Port 80 is in use, skipping HTTP redirect",f),f)N.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let T=Y?j:F,q=await Bw(T,B,f),G;if(q){if(z("setup",`Port ${T} is already in use`,f),f)N.warn(`Port ${T} is already in use. This may be another instance of rpx or another service.`);if(T===443){if(G=await H.getNextAvailablePort(3443,!0),z("setup",`Using port ${G} instead of ${T}`,f),f)N.info(`Using port ${G} instead. Access your site at https://${A}:${G}`)}else if(G=await H.getNextAvailablePort(T+1000,!0),z("setup",`Using port ${G} instead of ${T}`,f),f)N.info(`Using port ${G} instead. Access your site at http://${A}:${G}`)}else G=T,H.usedPorts.add(G),z("setup",`Using standard ${T===443?"HTTPS":"HTTP"} port ${T} for ${A}`,f);await r7(w,A,J,G,B,U,Y,E,f,h,W)}catch(T){z("setup",`Setup failed: ${T}`,f),N.error(`Failed to setup reverse proxy: ${T.message}`),GU({domains:[A],hosts:typeof Z==="boolean"?Z:Z?.hosts,certs:typeof Z==="boolean"?Z:Z?.certs,verbose:f,vitePluginUsage:E})}}function mF($){z("redirect","Starting HTTP redirect server",$);let w=zw.createServer((A,J)=>{let U=A.headers.host||"";z("redirect",`Redirecting request from ${U}${A.url} to HTTPS`,$),J.writeHead(301,{Location:`https://${U}${A.url}`}),J.end()}).listen(80);i1.add(w),z("redirect","HTTP redirect server started",$)}function dF($){let w={...qf,...$};if(z("proxy",`Starting proxy with options: ${w0(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){N.error("viaDaemon mode requires both `from` and `to`");return}R8({proxies:[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((E)=>{N.error(`Failed to register with rpx daemon: ${E.message}`),s.exit(1)});return}let A=w.to||"",J=A.split(".").pop()?.toLowerCase()||"",U=s.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),Y=["dev","app","page","new","day","foo"],f=["test","localhost","local","example","invalid"];if(U&&Y.includes(J)&&w?.verbose)N.warn(`The .${J} TLD may not work reliably for local development`),N.info(` Google owns .${J} with HSTS preloading, which can bypass local DNS`),N.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(U)Promise.resolve().then(() => (zU(),jU)).then(({startDnsServer:E,setupResolver:W})=>{E([A],w.verbose).then((h)=>{if(h)W(w.verbose,[A]).then(()=>{if(w.verbose)if(f.includes(J))N.success(`DNS server started for .${J} domains`);else N.success(`DNS server started for .${J} domains (hosts file entry also added)`)});else z("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((E)=>{z("dns",`Failed to start DNS server: ${E}`,w.verbose)});let Z={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:D1(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};z("proxy",`Server options: ${w0(Z)}`,w.verbose),vF(Z).catch((E)=>{z("proxy",`Failed to start proxy: ${E}`,w.verbose),N.error(`Failed to start proxy: ${E.message}`),GU({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function s7($){return $?.verbose||!1}async function gF($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let A=s7(w);if(z("config",`Starting with config: ${w0(w,2)}`,A),z("config",`Is multi-proxy? ${"proxies"in w}`,A),w.viaDaemon){let H="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((T)=>({id:T.id,from:T.from,to:T.to,cleanUrls:T.cleanUrls??w.cleanUrls,changeOrigin:T.changeOrigin??w.changeOrigin,pathRewrites:T.pathRewrites})):[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await R8({proxies:H,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){z("servers",`Found ${w.proxies.length} proxies in config`,A);for(let B of w.proxies)if(B.start){let H=`${B.from}-${B.to}`;try{z("watch",`Starting command for ${H} with command: ${B.start.command}`,A),N.info(`Starting command for ${H}...`),await HU.startProcess(H,B.start,A);let T=new URL(B.from.startsWith("http")?B.from:`http://${B.from}`),q=T.hostname||"localhost",G=Number(T.port)||80;try{await c1(q,G,A),z("watch",`Dev server is ready at ${q}:${G}`,A)}catch(R){z("watch",`Connection check failed, but continuing with proxy setup: ${R}`,A),N.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(T){throw z("watch",`Failed to start command for ${H}: ${T}`,A),Error(`Failed to start command for ${H}: ${T}`)}}else z("watch",`No start command for proxy ${B.from} -> ${B.to}`,A)}else if("start"in w&&w.start){z("watch","Found start command in single proxy config",A);let B=`${w.from}-${w.to}`;try{if(w.start)z("watch",`Starting command: ${w.start.command}`,A),await HU.startProcess(B,w.start,A);let H=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),T=H.hostname||"localhost",q=Number(H.port)||80;try{await c1(T,q,A),z("watch",`Dev server is ready at ${T}:${q}`,A)}catch(G){z("watch",`Connection check failed, but continuing with proxy setup: ${G}`,A),N.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(H){throw z("watch",`Failed to run start command: ${H}`,A),Error(`Failed to run start command: ${H}`)}}else z("watch","No start command found in config",A);let J="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(s.platform!=="win32"&&(w.https||w.cleanup?.hosts!==!1)){if(!Jw())try{z("sudo","Pre-acquiring sudo credentials for privileged operations",A),l7("sudo -v",{stdio:"inherit"})}catch{z("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let B=await c0(w);if(!B){if(z("ssl",`No valid or trusted certificates found for ${J}, generating new ones`,w.verbose),await U1(w),B=await c0(w),!B)throw Error(`Failed to load SSL certificates after generation for ${J}`)}else z("ssl",`Using existing and trusted certificates for ${J}`,w.verbose);w._cachedSSLConfig=B}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((B)=>({...B,https:w.https,cleanup:w.cleanup,cleanUrls:B.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:B.changeOrigin??w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig}],Y=U.map((B)=>B.to||"rpx.localhost"),f=w._cachedSSLConfig,Z=Y.filter((B)=>B&&!B.includes("localhost")&&!B.includes("127.0.0.1")),E=["dev","app","page","new","day","foo"],W=["test","localhost","local","example","invalid"],h=[...new Set(Z.map((B)=>B.split(".").pop()?.toLowerCase()))],F=h.filter((B)=>!!B&&E.includes(B));if(F.length>0&&A)N.warn(`The following TLDs may not work reliably for local development: ${F.map((B)=>`.${B}`).join(", ")}`),N.info(" These TLDs have HSTS preloading which can bypass local DNS"),N.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(s.platform==="darwin"&&Z.length>0){let{startDnsServer:B,setupResolver:H}=await Promise.resolve().then(() => (zU(),jU));if(await B(Z,A)){if(await H(A,Z),A)if(h.every((G)=>!!G&&W.includes(G)))N.success(`DNS server started for ${h.map((G)=>`.${G}`).join(", ")} domains`);else N.success(`DNS server started for ${h.map((G)=>`.${G}`).join(", ")} domains (hosts file entries also added)`)}else z("dns","Could not start DNS server - custom domains may not resolve",A)}let j=async()=>{z("cleanup","Starting cleanup handler",w.verbose);try{let{stopDnsServer:B,removeResolver:H}=await Promise.resolve().then(() => (zU(),jU));B(w.verbose),await H(w.verbose)}catch(B){z("cleanup",`Error stopping DNS server: ${B}`,w.verbose)}try{await HU.stopAll(w.verbose)}catch(B){z("cleanup",`Error stopping processes: ${B}`,w.verbose)}await GU({domains:Y,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};if(s.on("SIGINT",j),s.on("SIGTERM",j),s.on("uncaughtException",(B)=>{z("process",`Uncaught exception: ${B}`,!0),console.error("Uncaught exception:",B),j()}),f&&U.length>1){z("proxies",`Creating shared HTTPS server for ${U.length} domains`,A);let B=new Map;for(let G of U){let R=G.to||"rpx.localhost",K=new URL(G.from?.startsWith("http")?G.from:`http://${G.from}`);if(B.set(R,{sourceHost:K.host,cleanUrls:G.cleanUrls||!1,changeOrigin:G.changeOrigin||!1,pathRewrites:G.pathRewrites}),z("proxies",`Route: ${R} → ${K.host}`,A),!R.includes("localhost")&&!R.includes("127.0.0.1"))try{if(!(await b1([R],A))[0])await P1([R],A)}catch{z("hosts",`Could not add hosts entry for ${R}`,A)}}if(!await Bw(80,"0.0.0.0",A))mF(A);let T=443;if(await Bw(T,"0.0.0.0",A)){if(z("proxies",`Port ${T} is already in use, cannot start shared proxy`,A),A)N.warn(`Port ${T} is in use. Shared HTTPS proxy cannot start.`);return}try{let G=Bun.serve({port:T,hostname:"0.0.0.0",tls:{key:f.key,cert:f.cert,ca:f.ca,requestCert:!1,rejectUnauthorized:!1},fetch:_1((R)=>B.get(R),A),error(R){return z("server",`Shared proxy server error: ${R}`,A),new Response(`Server Error: ${R.message}`,{status:500})}});i1.add(G),z("proxies",`Shared HTTPS proxy listening on port ${T} for ${B.size} domains`,A)}catch(G){z("proxies",`Failed to start shared proxy: ${G}`,A),console.error("Failed to start shared HTTPS proxy:",G),j()}}else for(let B of U)try{let H=B.to||"rpx.localhost";z("proxy",`Starting proxy for ${H} with SSL config: ${!!f}`,B.verbose),await vF({from:B.from||"localhost:5173",to:H,cleanUrls:B.cleanUrls||!1,https:B.https||!1,cleanup:B.cleanup||!1,vitePluginUsage:B.vitePluginUsage||!1,verbose:B.verbose||!1,_cachedSSLConfig:f,changeOrigin:B.changeOrigin||!1})}catch(H){z("proxies",`Failed to start proxy for ${B.to}: ${H}`,B.verbose),console.error(`Failed to start proxy for ${B.to}:`,H),j()}}function cF($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${T0.green(T0.bold("rpx"))} ${T0.green(`v${t7}`)}`),console.log(` ${T0.green("➜")} ${T0.dim($?.from??"")} ${T0.dim("➜")} ${T0.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${T0.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${T0.green("➜")} Clean URLs enabled`)}A8();var CL=new Aw("rpx",{showTags:!1});function lF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}var t$=new SU("rpx"),tF="0.12.0";t$.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").action(async($)=>{if(!$?.from||!$.to)return gF(Vw);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let A={command:$.startCommand};if($.startCwd)A.cwd=$.startCwd;if($.startEnv)try{A.env=JSON.parse($.startEnv)}catch(J){console.error("Failed to parse start-env JSON:",J),l$.exit(1)}w.start=A}return dF(w)});t$.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=lF(Vw)?Vw.proxies.find((J)=>J.to===$||`${J.from}-${J.to}`===$):Vw.to===$?Vw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),l$.exit(1);try{await JU.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(J){console.error(`Failed to start dev server for ${$}:`,J),l$.exit(1)}});t$.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await JU.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),l$.exit(1)}});t$.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await JU.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),l$.exit(1)}});t$.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--verbose","Enable verbose logging").action(async($)=>{try{await(await NF({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,verbose:$.verbose??!0})).done,l$.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),l$.exit(1)}});t$.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,A=await MF({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!A.stopped&&A.pid===null){console.log("rpx daemon is not running");return}if(!A.stopped){console.log(`rpx daemon pid=${A.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${A.pid} stopped${A.forced?" (SIGKILL)":""}`)});t$.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??z0(),A=await fw(w),J=await RF(w),U=$.registryDir,Y=await SF(U).catch(()=>[]);if($.json){console.log(JSON.stringify({running:J,pid:A,pidFile:Ew(w),rpxDir:w,registryDir:U??Ww(),entries:Y},null,2));return}if(!J){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Ew(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Ew(w)}`);if(console.log(`registry: ${U??Ww()}`),Y.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${Y.length}):`);for(let f of Y){let Z=f.pid!==void 0?`, pid=${f.pid}`:"";console.log(` https://${f.to} \u2192 ${f.from} (id=${f.id}${Z})`)}});t$.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),l$.exit(1);if(!Y1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),l$.exit(1);try{await yF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),l$.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await KF({rpxDir:$.rpxDir,verbose:$.verbose}),A=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${A} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),l$.exit(1)}});t$.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async($,w)=>{if(!Y1($))console.error(`invalid id: ${JSON.stringify($)}`),l$.exit(1);let A=await q8($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await CF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});t$.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(tF)});t$.version(tF);t$.help();t$.run();
|