@stacksjs/rpx 0.11.17 → 0.11.18
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 +121 -120
- package/dist/{chunk-fndafyac.js → chunk-9njrhbd4.js} +1 -1
- package/dist/{chunk-zx2ghrc1.js → chunk-s4tdtq37.js} +53 -53
- package/dist/index.js +7 -7
- package/dist/types.d.ts +2 -0
- package/package.json +1 -1
- package/src/start.ts +8 -1
- package/src/types.ts +8 -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 dF}from"node:module";var nF=Object.defineProperty;var vF=($)=>$;function mF($,w){this[$]=vF.bind(null,w)}var dJ=($,w)=>{for(var A in w)nF($,A,{get:w[A],enumerable:!0,configurable:!0,set:mF.bind(w,A)})};var E$=($,w)=>()=>($&&(w=$($=0)),w);var u=dF(import.meta.url);import{existsSync as UW,statSync as JW}from"fs";import{existsSync as rz,mkdirSync as Nh,readdirSync as yh,readFileSync as az,writeFileSync as Mh}from"fs";import{homedir as xw}from"os";import{dirname as Sh,resolve as $0}from"path";import UY from"process";import{existsSync as WW,statSync as BW}from"fs";import{existsSync as PX,mkdirSync as sz,readdirSync as oz,writeFileSync as ez}from"fs";import{homedir as Pw}from"os";import{dirname as EW,resolve as x$}from"path";import Rw from"process";import{join as $2,relative as w2,resolve as jW}from"path";import tA from"process";import{existsSync as pW,mkdirSync as Ph,readdirSync as ih,writeFileSync as bh}from"fs";import{homedir as KX}from"os";import{dirname as nh,resolve as Z$}from"path";import x1 from"process";import{join as A2,relative as Y2,resolve as TW}from"path";import pA from"process";import{existsSync as rW,mkdirSync as gh,readdirSync as th,writeFileSync as ph}from"fs";import{dirname as ah,resolve as rA}from"path";import iX from"process";import{Buffer as $w}from"buffer";import{createCipheriv as f2,createDecipheriv as X2,randomBytes as RX}from"crypto";import{closeSync as hX,createReadStream as FW,createWriteStream as U2,existsSync as qX,fsyncSync as zW,openSync as GW,writeFileSync as J2}from"fs";import{access as W2,constants as HW,mkdir as B2,readdir as LA,rename as KW,stat as iw,unlink as OA,writeFile as NX}from"fs/promises";import{join as bw}from"path";import I$ from"process";import{pipeline as E2}from"stream/promises";import{createGzip as RW}from"zlib";import cw from"process";import Q0 from"process";import{Buffer as L0}from"buffer";import{createCipheriv as j2,createDecipheriv as T2,randomBytes as yX}from"crypto";import{closeSync as MX,createReadStream as hW,createWriteStream as F2,existsSync as VA,fsyncSync as qW,openSync as NW,writeFileSync as z2}from"fs";import{access as G2,constants as yW,mkdir as H2,readdir as QA,rename as MW,stat as uw,unlink as _A,writeFile as IX}from"fs/promises";import{isAbsolute as K2,join as nw,resolve as R2}from"path";import V from"process";import{pipeline as h2}from"stream/promises";import{createGzip as IW}from"zlib";import vw from"process";import _0 from"process";import DA from"process";import{existsSync as kA}from"fs";import{resolve as CX}from"path";import{existsSync as q2}from"fs";import{existsSync as N2,readdirSync as y2}from"fs";import{extname as SX,resolve as CW}from"path";import M2 from"process";import{join as I2,relative as C2,resolve as SW}from"path";import aA from"process";import{Buffer as O0}from"buffer";import{createCipheriv as S2,createDecipheriv as L2,randomBytes as LX}from"crypto";import{closeSync as OX,createReadStream as LW,createWriteStream as O2,existsSync as ZA,fsyncSync as OW,openSync as VW,writeFileSync as V2}from"fs";import{access as Q2,constants as QW,mkdir as _2,readdir as xA,rename as _W,stat as mw,unlink as PA,writeFile as VX}from"fs/promises";import{isAbsolute as D2,join as dw,resolve as k2}from"path";import Q from"process";import{pipeline as Z2}from"stream/promises";import{createGzip as DW}from"zlib";import lw from"process";import D0 from"process";import bA from"process";import{existsSync as cA}from"fs";import{resolve as xX}from"path";import{existsSync as $H}from"fs";class gW{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],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!UW($))return!0;return JW($).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,Y){try{let f=UW(A)?JW(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}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((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.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 Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class tW{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function i2($,w){this[$]=P2.bind(null,w)}class rX{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],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!WW($))return!0;return BW($).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,Y){try{let f=WW(A)?BW(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}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((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.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 Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class aX{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function u2($,w={}){let Y=Object.keys(w).sort().map((f)=>`${f}:${w[f]}`).join("|");return Y?`${$}:${Y}`:$}function n2($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function v2($){return $.getStats().size*2}function sX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&s(w[0])&&"id"in w[0]&&w[0].id===3&&s(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(s(w)&&s($)&&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(s($)&&"arr"in $&&Array.isArray($.arr)&&s(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&s(w[0])&&s($[0])){let Y=[...w];for(let f of $)if(s(f)&&"name"in f){if(!Y.find((U)=>s(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(s(f)&&"path"in f){if(!Y.find((U)=>s(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>sA(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!s(w)||!s($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(s(f)&&s(A[Y]))A[Y]=sX(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&s(f[0])&&s(A[Y][0])){let X=[...f];for(let U of A[Y])if(s(U)&&"name"in U){if(!X.find((J)=>s(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(s(U)&&"path"in U){if(!X.find((J)=>s(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>sA(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function sA($,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(!sA($[A],w[A]))return!1;return!0}if(s($)&&s(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!sA($[f],w[f]))return!1}return!0}return!1}function s($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function m2($,w){if(!rW($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return sX(w,Y)}catch{return null}}catch{return null}}async function d2({name:$="",cwd:w,defaultConfig:A}){let Y=w||iX.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=rA(Y,`${U}${W}`),B=await m2(J,A);if(B!==null)return B}try{let U=rA(Y,"package.json");if(rW(U)){let J=(await import(U))[$];if(J&&typeof J==="object"&&!Array.isArray(J))try{return sX(A,J)}catch{}}}catch{}return A}function l2($,w={}){let A=pA.cwd();while(A.includes("storage"))A=TW(A,"..");let Y=TW(A,$||"");if(w?.relative)return Y2(pA.cwd(),Y);return Y}async function g2(){try{let $=await d2({name:"clarity",defaultConfig:vA,cwd:pA.cwd(),endpoint:"",headers:{}});return{...vA,...$}}catch{return vA}}function Y$(){if(Q0.env.NODE_ENV==="test"||Q0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function t2(){if(Q0.env.NODE_ENV==="test"||Q0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Q0<"u"){let $=Q0.type;if($==="renderer"||$==="worker")return!1;return!!(Q0.versions&&(Q0.versions.node||Q0.versions.bun))}return!1}class sW{async format($){let w=await t2(),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}}}class oA{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={...cX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new sW,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??I$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...mA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...mA};return{...mA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:cX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==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 f,X=0,U=3,W=1000;while(X<U)try{try{try{await W2(this.config.logDirectory,HW.F_OK|HW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await B2(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:$w.from($);try{if(!qX(this.currentLogFile))await NX(this.currentLogFile,"",{mode:420});if(f=GW(this.currentLogFile,"a",420),J2(f,J,{flag:"a"}),zW(f),f!==void 0)hX(f),f=void 0;if((await iw(this.currentLogFile)).size===0){if(await NX(this.currentLogFile,J,{flag:"w",mode:420}),(await iw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{hX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 bw(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 bw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return bw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(Y$())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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return RX(16).toString("hex")}generateKey(){return RX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=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=RX(16),Y=f2("aes-256-gcm",w,A),f=$w.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:$w.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=RW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w($w.from($w.concat(f)))),Y.on("error",A),Y.write($),Y.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;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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await LA(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await iw(A).catch(()=>null))try{if(await KW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await OA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await NX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await iw(A).catch(()=>null))await KW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await LA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await OA(bw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=FW($),Y=U2(w),f=RW();await E2(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}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()})),qX(this.currentLogFile))try{let $=GW(this.currentLogFile,"r+");zW($),hX($)}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 LA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await OA(bw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=I$.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${g.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!Y$()){let B=JB[$],E=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:g.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:g.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
5
|
-
`);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
4
|
+
import{createRequire as lF}from"node:module";var vF=Object.defineProperty;var mF=($)=>$;function dF($,w){this[$]=mF.bind(null,w)}var lJ=($,w)=>{for(var A in w)vF($,A,{get:w[A],enumerable:!0,configurable:!0,set:dF.bind(w,A)})};var E0=($,w)=>()=>($&&(w=$($=0)),w);var n=lF(import.meta.url);import{existsSync as JW,statSync as WW}from"fs";import{existsSync as a9,mkdirSync as IN,readdirSync as CN,readFileSync as s9,writeFileSync as SN}from"fs";import{homedir as Pw}from"os";import{dirname as ON,resolve as A$}from"path";import UY from"process";import{existsSync as BW,statSync as EW}from"fs";import{existsSync as iX,mkdirSync as o9,readdirSync as e9,writeFileSync as $z}from"fs";import{homedir as iw}from"os";import{dirname as jW,resolve as x0}from"path";import qw from"process";import{join as wz,relative as Az,resolve as TW}from"path";import tA from"process";import{existsSync as rW,mkdirSync as cN,readdirSync as uN,writeFileSync as nN}from"fs";import{homedir as RX}from"os";import{dirname as dN,resolve as Z0}from"path";import x1 from"process";import{join as Yz,relative as fz,resolve as FW}from"path";import pA from"process";import{existsSync as aW,mkdirSync as rN,readdirSync as aN,writeFileSync as sN}from"fs";import{dirname as eN,resolve as rA}from"path";import bX from"process";import{Buffer as Aw}from"buffer";import{createCipheriv as Xz,createDecipheriv as Uz,randomBytes as NX}from"crypto";import{closeSync as qX,createReadStream as zW,createWriteStream as Jz,existsSync as hX,fsyncSync as GW,openSync as HW,writeFileSync as Wz}from"fs";import{access as Bz,constants as KW,mkdir as Ez,readdir as LA,rename as RW,stat as bw,unlink as VA,writeFile as yX}from"fs/promises";import{join as cw}from"path";import I0 from"process";import{pipeline as jz}from"stream/promises";import{createGzip as NW}from"zlib";import uw from"process";import D$ from"process";import{Buffer as O$}from"buffer";import{createCipheriv as Tz,createDecipheriv as Fz,randomBytes as MX}from"crypto";import{closeSync as IX,createReadStream as qW,createWriteStream as zz,existsSync as OA,fsyncSync as hW,openSync as yW,writeFileSync as Gz}from"fs";import{access as Hz,constants as MW,mkdir as Kz,readdir as _A,rename as IW,stat as nw,unlink as QA,writeFile as CX}from"fs/promises";import{isAbsolute as Rz,join as vw,resolve as Nz}from"path";import _ from"process";import{pipeline as qz}from"stream/promises";import{createGzip as CW}from"zlib";import mw from"process";import k$ from"process";import DA from"process";import{existsSync as kA}from"fs";import{resolve as SX}from"path";import{existsSync as hz}from"fs";import{existsSync as yz,readdirSync as Mz}from"fs";import{extname as LX,resolve as SW}from"path";import Iz from"process";import{join as Cz,relative as Sz,resolve as LW}from"path";import aA from"process";import{Buffer as _$}from"buffer";import{createCipheriv as Lz,createDecipheriv as Vz,randomBytes as VX}from"crypto";import{closeSync as OX,createReadStream as VW,createWriteStream as Oz,existsSync as ZA,fsyncSync as OW,openSync as _W,writeFileSync as _z}from"fs";import{access as Qz,constants as QW,mkdir as Dz,readdir as xA,rename as DW,stat as dw,unlink as PA,writeFile as _X}from"fs/promises";import{isAbsolute as kz,join as lw,resolve as Zz}from"path";import Q from"process";import{pipeline as xz}from"stream/promises";import{createGzip as kW}from"zlib";import gw from"process";import Z$ from"process";import bA from"process";import{existsSync as cA}from"fs";import{resolve as PX}from"path";import{existsSync as wG}from"fs";class tW{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],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!JW($))return!0;return WW($).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,Y){try{let f=JW(A)?WW(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}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((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.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 Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class pW{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function bz($,w){this[$]=iz.bind(null,w)}class aX{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],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!BW($))return!0;return EW($).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,Y){try{let f=BW(A)?EW(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}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((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.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 Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class sX{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function nz($,w={}){let Y=Object.keys(w).sort().map((f)=>`${f}:${w[f]}`).join("|");return Y?`${$}:${Y}`:$}function vz($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function mz($){return $.getStats().size*2}function oX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&o(w[0])&&"id"in w[0]&&w[0].id===3&&o(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(o(w)&&o($)&&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(o($)&&"arr"in $&&Array.isArray($.arr)&&o(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&o(w[0])&&o($[0])){let Y=[...w];for(let f of $)if(o(f)&&"name"in f){if(!Y.find((U)=>o(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(o(f)&&"path"in f){if(!Y.find((U)=>o(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>sA(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!o(w)||!o($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(o(f)&&o(A[Y]))A[Y]=oX(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&o(f[0])&&o(A[Y][0])){let X=[...f];for(let U of A[Y])if(o(U)&&"name"in U){if(!X.find((J)=>o(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(o(U)&&"path"in U){if(!X.find((J)=>o(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>sA(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function sA($,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(!sA($[A],w[A]))return!1;return!0}if(o($)&&o(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!sA($[f],w[f]))return!1}return!0}return!1}function o($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function dz($,w){if(!aW($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return oX(w,Y)}catch{return null}}catch{return null}}async function lz({name:$="",cwd:w,defaultConfig:A}){let Y=w||bX.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=rA(Y,`${U}${W}`),B=await dz(J,A);if(B!==null)return B}try{let U=rA(Y,"package.json");if(aW(U)){let J=(await import(U))[$];if(J&&typeof J==="object"&&!Array.isArray(J))try{return oX(A,J)}catch{}}}catch{}return A}function gz($,w={}){let A=pA.cwd();while(A.includes("storage"))A=FW(A,"..");let Y=FW(A,$||"");if(w?.relative)return fz(pA.cwd(),Y);return Y}async function tz(){try{let $=await lz({name:"clarity",defaultConfig:vA,cwd:pA.cwd(),endpoint:"",headers:{}});return{...vA,...$}}catch{return vA}}function Y0(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function pz(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D$<"u"){let $=D$.type;if($==="renderer"||$==="worker")return!1;return!!(D$.versions&&(D$.versions.node||D$.versions.bun))}return!1}class oW{async format($){let w=await pz(),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}}}class oA{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={...uX},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??I0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...mA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...mA};return{...mA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:uX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==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 f,X=0,U=3,W=1000;while(X<U)try{try{try{await Bz(this.config.logDirectory,KW.F_OK|KW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await Ez(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Aw.from($);try{if(!hX(this.currentLogFile))await yX(this.currentLogFile,"",{mode:420});if(f=HW(this.currentLogFile,"a",420),Wz(f,J,{flag:"a"}),GW(f),f!==void 0)qX(f),f=void 0;if((await bw(this.currentLogFile)).size===0){if(await yX(this.currentLogFile,J,{flag:"w",mode:420}),(await bw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{qX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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(Y0())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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return NX(16).toString("hex")}generateKey(){return NX(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=NX(16),Y=Xz("aes-256-gcm",w,A),f=Aw.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:Aw.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=NW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(Aw.from(Aw.concat(f)))),Y.on("error",A),Y.write($),Y.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(Y0())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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await LA(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await bw(A).catch(()=>null))try{if(await RW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await VA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await yX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await bw(A).catch(()=>null))await RW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await LA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await VA(cw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=zW($),Y=Jz(w),f=NW();await jz(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}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()})),hX(this.currentLogFile))try{let $=HW(this.currentLogFile,"r+");GW($),qX($)}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(!Y0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await LA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await VA(cw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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?t.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=I0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${t.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!Y0()){let B=WB[$],E=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:t.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:t.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
5
|
+
`);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:t.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!Y0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let J=`${X} ${this.environment}.${$.toUpperCase()}: ${U}
|
|
6
6
|
`;if(W)J+=`${W}
|
|
7
|
-
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time($){let w=performance.now();if(this.fancy&&!
|
|
8
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
9
|
-
`),U=Math.max(...X.map((E)=>E.length))+2,W=`┌${"─".repeat(U)}┐`,J=`└${"─".repeat(U)}┘`,B=X.map((E)=>{let j=" ".repeat(U-E.length-2);return`│ ${E}${j} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:
|
|
10
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt($){if(
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||
|
|
12
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Y$()||!I$.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 LA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=bw(this.config.logDirectory,Y);if($.before)try{if((await iw(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}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 Y of A)try{await OA(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function nA($,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 Y=[...w];for(let f of $)if(n(f)&&"name"in f){if(!Y.find((U)=>n(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(n(f)&&"path"in f){if(!Y.find((U)=>n(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>eA(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!n(w)||!n($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(n(f)&&n(A[Y]))A[Y]=nA(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&n(f[0])&&n(A[Y][0])){let X=[...f];for(let U of A[Y])if(n(U)&&"name"in U){if(!X.find((J)=>n(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(n(U)&&"path"in U){if(!X.find((J)=>n(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>eA(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function oX($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:nA($,w);if(Array.isArray($))return A==="replace"?w:nA($,w);if(!n(w)||!n($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=nA(U,X);else if(n(X)&&n(U))Y[f]=oX(U,X,A);else Y[f]=X}return Y}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(n($)&&n(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!eA($[f],w[f]))return!1}return!0}return!1}function n($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function iA($,w,A="replace"){if(!pW($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return oX(w,f,A)}catch{return null}}catch{return null}}function p2($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((G)=>G.toUpperCase()).join("_")}`;if(A)S$.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let G=x1.env[F]||x1.env[H];if(G!==void 0){if(A)S$.info(`Using environment variable ${G?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(G);else if(typeof E==="boolean")J[B]=G.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(G);if(Array.isArray(K))J[B]=K;else J[B]=G.split(",").map((R)=>R.trim())}catch{J[B]=G.split(",").map((K)=>K.trim())}else J[B]=G}}}return J}return X(f)}async function r2({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?p2($,f,X):f,B=A||x1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)S$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],G=Array.from(new Set([B,Z$(B,"config"),Z$(B,".config"),Y?Z$(B,Y):void 0].filter(Boolean)));for(let K of G){if(X)S$.info(`Searching for configuration in: ${K}`);let h=[Z$(B,"config"),Z$(B,".config")].concat(Y?[Z$(B,Y)]:[]).includes(K)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let N of h)for(let M of E){let C=Z$(K,`${N}${M}`),y=await iA(C,J,W);if(y!==null){if(X)S$.success(`Configuration loaded from: ${C}`);return y}}}if($){let K=Z$(KX(),".config",$),R=["config",`${$}.config`];if(w)R.push(`${w}.config`);if(X)S$.info(`Checking user config directory: ${K}`);for(let h of R)for(let N of E){let M=Z$(K,`${h}${N}`),C=await iA(M,J,W);if(C!==null){if(X)S$.success(`Configuration loaded from user config directory: ${M}`);return C}}}if($){let K=Z$(KX(),".config"),R=[`.${$}.config`];if(w)R.push(`.${w}.config`);if(X)S$.info(`Checking user config directory for dotfile configs: ${K}`);for(let h of R)for(let N of E){let M=Z$(K,`${h}${N}`),C=await iA(M,J,W);if(C!==null){if(X)S$.success(`Configuration loaded from user config directory dotfile: ${M}`);return C}}}if($){let K=KX(),R=[`.${$}.config`,`.${$}`];if(w)R.push(`.${w}.config`),R.push(`.${w}`);if(X)S$.info(`Checking user home directory for dotfile configs: ${K}`);for(let h of R)for(let N of E){let M=Z$(K,`${h}${N}`),C=await iA(M,J,W);if(C!==null){if(X)S$.success(`Configuration loaded from user home directory: ${M}`);return C}}}try{let K=Z$(B,"package.json");if(pW(K)){let R=await import(K),h=R[$];if(!h&&w){if(h=R[w],h&&X)S$.success(`Using alias "${w}" configuration from package.json`)}if(h&&typeof h==="object"&&!Array.isArray(h))try{if(X)S$.success(`Configuration loaded from package.json: ${h===R[$]?$:w}`);return oX(J,h,W)}catch(N){if(X)S$.warn("Failed to merge package.json config:",N)}}}catch(K){if(X)S$.warn("Failed to load package.json:",K)}if(X)S$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function a2($,w={}){let A=tA.cwd();while(A.includes("storage"))A=jW(A,"..");let Y=jW(A,$||"");if(w?.relative)return w2(tA.cwd(),Y);return Y}async function s2(){try{let $=await r2({name:"clarity",alias:"logging",defaultConfig:dA,cwd:tA.cwd()});return{...dA,...$||{}}}catch{return dA}}function j$(){if(_0.env.NODE_ENV==="test"||_0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function o2(){if(_0.env.NODE_ENV==="test"||_0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof _0<"u"){let $=_0.type;if($==="renderer"||$==="worker")return!1;return!!(_0.versions&&(_0.versions.node||_0.versions.bun))}return!1}class oW{async format($){let w=await o2(),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:vw.pid,hostname:w(),environment:vw.env.NODE_ENV||"development",platform:vw.platform,version:vw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:vw.env.NODE_ENV||vw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $Y{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={...uX},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??V.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...lA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...lA};return{...lA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:uX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==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 f,X=0,U=3,W=1000;while(X<U)try{try{try{await G2(this.config.logDirectory,yW.F_OK|yW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await H2(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:L0.from($);try{if(!VA(this.currentLogFile))await IX(this.currentLogFile,"",{mode:420});if(f=NW(this.currentLogFile,"a",420),z2(f,J,{flag:"a"}),qW(f),f!==void 0)MX(f),f=void 0;if((await uw(this.currentLogFile)).size===0){if(await IX(this.currentLogFile,J,{flag:"w",mode:420}),(await uw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{MX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 nw(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 nw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return nw(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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return yX(16).toString("hex")}generateKey(){return yX(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=yX(16),Y=j2("aes-256-gcm",w,A),f=L0.isBuffer($)?$:L0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=L0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=IW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(L0.from(L0.concat(f)))),Y.on("error",A),Y.write($),Y.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 uw(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await QA(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await uw(A).catch(()=>null))try{if(await MW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await _A(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await IX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await uw(A).catch(()=>null))await MW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await QA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await _A(nw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=hW($),Y=F2(w),f=IW();await h2(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),VA(this.currentLogFile))try{let $=NW(this.currentLogFile,"r+");qW($),MX($)}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 QA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await _A(nw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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||j$())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:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=V.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${k.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=k.underline(k.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>k.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>k.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>k.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>k.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>k.strikethrough(Y)),w}supportsHyperlinks(){if(j$())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(K2(w)||w.startsWith("./")||w.startsWith("../"))w=R2(w);else return null;return VA(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":WB[$],T=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:k.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:k.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
13
|
-
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
7
|
+
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time($){let w=performance.now();if(this.fancy&&!Y0()){let A=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:t.blue("◐"),tag:A,message:`${t.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
8
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!Y0()){let E=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:t.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!Y0())console.error(B.trim());await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=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 oA(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(Y0())throw Error("createReadStream is not supported in browser environments");if(!hX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return zW(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 Y=Aw.isBuffer($)?$:Aw.from($,"base64"),f=Y.slice(0,16),X=Y.slice(-16),U=Y.slice(16,-16),W=Uz("aes-256-gcm",A,f);return W.setAuthTag(X),Aw.concat([W.update(U),W.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Y0()}isServerMode(){return!Y0()}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),Y=this.formatFileTimestamp(w);if(this.fancy&&!Y0()){let X=$.split(`
|
|
9
|
+
`),U=Math.max(...X.map((E)=>E.length))+2,W=`┌${"─".repeat(U)}┐`,J=`└${"─".repeat(U)}┘`,B=X.map((E)=>{let j=" ".repeat(U-E.length-2);return`│ ${E}${j} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:t.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:t.cyan(W)})),B.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:A,message:t.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:t.cyan(J),showTimestamp:!1}))}else if(!Y0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let f=`${Y} ${this.environment}.INFO: [BOX] ${$}
|
|
10
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt($){if(Y0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${t.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();I0.stdin.removeListener("data",A);try{if(typeof I0.stdin.setRawMode==="function")I0.stdin.setRawMode(!1)}catch{}I0.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof I0.stdin.setRawMode==="function")I0.stdin.setRawMode(!0)}catch{}I0.stdin.resume(),I0.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,W=0;if(A=$.replace(U,(J,B)=>{if(B==="%")return"%";if(W>=w.length)return J;let E=w[W++];switch(B){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 J}}),W<w.length)A+=` ${w.slice(W).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!Y0()){let U=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",W=t.blue("◐");console.error(`${W} ${U} ${t.cyan(A)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
11
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||Y0()||$<=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:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Y0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),W!==void 0)this.activeProgressBar.message=W;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Y0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Y0())return;I0.stdout.write(`${"\r".padEnd(I0.stdout.columns||80)}\r`),this.log(W,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||Y0()||!I0.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=t.green("━".repeat(Y)),U=t.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=w||A===100?t.green("✓"):t.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${t.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=I0.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,I0.stdout.write($.lastRenderedLine),w)I0.stdout.write(`
|
|
12
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Y0()||!I0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(Y0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await LA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=cw(this.config.logDirectory,Y);if($.before)try{if((await bw(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}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 Y of A)try{await VA(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function nA($,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 Y=[...w];for(let f of $)if(v(f)&&"name"in f){if(!Y.find((U)=>v(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(v(f)&&"path"in f){if(!Y.find((U)=>v(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>eA(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!v(w)||!v($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(v(f)&&v(A[Y]))A[Y]=nA(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&v(f[0])&&v(A[Y][0])){let X=[...f];for(let U of A[Y])if(v(U)&&"name"in U){if(!X.find((J)=>v(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(v(U)&&"path"in U){if(!X.find((J)=>v(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>eA(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function eX($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:nA($,w);if(Array.isArray($))return A==="replace"?w:nA($,w);if(!v(w)||!v($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=nA(U,X);else if(v(X)&&v(U))Y[f]=eX(U,X,A);else Y[f]=X}return Y}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(v($)&&v(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!eA($[f],w[f]))return!1}return!0}return!1}function v($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function iA($,w,A="replace"){if(!rW($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return eX(w,f,A)}catch{return null}}catch{return null}}function rz($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((G)=>G.toUpperCase()).join("_")}`;if(A)S0.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let G=x1.env[F]||x1.env[H];if(G!==void 0){if(A)S0.info(`Using environment variable ${G?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(G);else if(typeof E==="boolean")J[B]=G.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(G);if(Array.isArray(K))J[B]=K;else J[B]=G.split(",").map((R)=>R.trim())}catch{J[B]=G.split(",").map((K)=>K.trim())}else J[B]=G}}}return J}return X(f)}async function az({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?rz($,f,X):f,B=A||x1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)S0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],G=Array.from(new Set([B,Z0(B,"config"),Z0(B,".config"),Y?Z0(B,Y):void 0].filter(Boolean)));for(let K of G){if(X)S0.info(`Searching for configuration in: ${K}`);let N=[Z0(B,"config"),Z0(B,".config")].concat(Y?[Z0(B,Y)]:[]).includes(K)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let h of N)for(let y of E){let I=Z0(K,`${h}${y}`),S=await iA(I,J,W);if(S!==null){if(X)S0.success(`Configuration loaded from: ${I}`);return S}}}if($){let K=Z0(RX(),".config",$),R=["config",`${$}.config`];if(w)R.push(`${w}.config`);if(X)S0.info(`Checking user config directory: ${K}`);for(let N of R)for(let h of E){let y=Z0(K,`${N}${h}`),I=await iA(y,J,W);if(I!==null){if(X)S0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let K=Z0(RX(),".config"),R=[`.${$}.config`];if(w)R.push(`.${w}.config`);if(X)S0.info(`Checking user config directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=Z0(K,`${N}${h}`),I=await iA(y,J,W);if(I!==null){if(X)S0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let K=RX(),R=[`.${$}.config`,`.${$}`];if(w)R.push(`.${w}.config`),R.push(`.${w}`);if(X)S0.info(`Checking user home directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=Z0(K,`${N}${h}`),I=await iA(y,J,W);if(I!==null){if(X)S0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let K=Z0(B,"package.json");if(rW(K)){let R=await import(K),N=R[$];if(!N&&w){if(N=R[w],N&&X)S0.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(X)S0.success(`Configuration loaded from package.json: ${N===R[$]?$:w}`);return eX(J,N,W)}catch(h){if(X)S0.warn("Failed to merge package.json config:",h)}}}catch(K){if(X)S0.warn("Failed to load package.json:",K)}if(X)S0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function sz($,w={}){let A=tA.cwd();while(A.includes("storage"))A=TW(A,"..");let Y=TW(A,$||"");if(w?.relative)return Az(tA.cwd(),Y);return Y}async function oz(){try{let $=await az({name:"clarity",alias:"logging",defaultConfig:dA,cwd:tA.cwd()});return{...dA,...$||{}}}catch{return dA}}function j0(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ez(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof k$<"u"){let $=k$.type;if($==="renderer"||$==="worker")return!1;return!!(k$.versions&&(k$.versions.node||k$.versions.bun))}return!1}class eW{async format($){let w=await ez(),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 $Y{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={...nX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new eW,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??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...lA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...lA};return{...lA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:nX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!j0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await Hz(this.config.logDirectory,MW.F_OK|MW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await Kz(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:O$.from($);try{if(!OA(this.currentLogFile))await CX(this.currentLogFile,"",{mode:420});if(f=yW(this.currentLogFile,"a",420),Gz(f,J,{flag:"a"}),hW(f),f!==void 0)IX(f),f=void 0;if((await nw(this.currentLogFile)).size===0){if(await CX(this.currentLogFile,J,{flag:"w",mode:420}),(await nw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{IX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 vw(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 vw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return vw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(j0())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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return MX(16).toString("hex")}generateKey(){return MX(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=MX(16),Y=Tz("aes-256-gcm",w,A),f=O$.isBuffer($)?$:O$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=O$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=CW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(O$.from(O$.concat(f)))),Y.on("error",A),Y.write($),Y.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(j0())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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await _A(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await nw(A).catch(()=>null))try{if(await IW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await QA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await CX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await nw(A).catch(()=>null))await IW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await _A(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await QA(vw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=qW($),Y=zz(w),f=CW();await qz(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),OA(this.currentLogFile))try{let $=yW(this.currentLogFile,"r+");hW($),IX($)}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(!j0()&&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 QA(vw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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()?Z.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||j0())return!1;let $=typeof _.env.NO_COLOR<"u",w=_.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=_.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${Z.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=Z.underline(Z.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>Z.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>Z.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>Z.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>Z.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>Z.strikethrough(Y)),w}supportsHyperlinks(){if(j0())return!1;let $=_.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=_.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(Rz(w)||w.startsWith("./")||w.startsWith("../"))w=Nz(w);else return null;return OA(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":BB[$],T=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:Z.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:Z.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
13
|
+
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:Z.gray(` ${G}`),level:$,showTimestamp:!1}))}break}}else if(!j0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
14
14
|
`;if(W)E+=`${W}
|
|
15
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
16
|
-
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
17
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?
|
|
18
|
-
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:
|
|
19
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
21
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
15
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!j0()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!j0()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,J="info")=>{if(!j0()&&_.stdout.isTTY)_.stdout.write(`
|
|
16
|
+
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!j0()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":Z.blue("◐"),tag:A,message:`${Z.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
17
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":Z.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!j0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=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 $Y(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(j0())throw Error("createReadStream is not supported in browser environments");if(!OA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return qW(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 Y=O$.isBuffer($)?$:O$.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=Fz("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=O$.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return j0()}isServerMode(){return!j0()}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),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
18
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:Z.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:Z.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:Z.cyan(E),showTimestamp:!1}))}else if(!j0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
19
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(j0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${Z.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();_.stdin.removeListener("data",A);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.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 J=/%([sdijfo%])/g,B=0;if(A=$.replace(J,(E,j)=>{if(j==="%")return"%";if(B>=w.length)return E;let T=w[B++];switch(j){case"s":return String(T);case"d":case"i":return Number(T).toString();case"j":case"o":return JSON.stringify(T,null,2);default:return E}}),B<w.length)A+=` ${w.slice(B).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${Z.blue("◐")} `;console.error(`${B}${J} ${Z.cyan(Y)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
20
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=Z.green("━".repeat(Y)),U=Z.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?Z.green("✓"):Z.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${Z.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=_.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,_.stdout.write($.lastRenderedLine),w)_.stdout.write(`
|
|
21
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||j0()||!_.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(j0()){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 Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=vw(this.config.logDirectory,Y);if($.before)try{if((await nw(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}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 Y of A)try{await QA(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function $B($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:f=()=>!0,fallback:X}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(J){if(U=J instanceof Error?J:Error(String(J)),W===A||!f(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(X!==void 0)return X;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function wB($){return $ instanceof p0}function $2($){return $ instanceof wY}function w2($){if(wB($))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 JY{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:Y,useCamelCase:f=!0,useBackwardCompatibility:X=!0,customParsers:U={},verbose:W=!1,trackPerformance:J=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix($),j={...w};return this.processObject(j,[],E,{useCamelCase:f,useBackwardCompatibility:X,customParsers:U,verbose:W,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return b1.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=U.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),J=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,U,A,Y);else{let E=DA.env[J]||(B?DA.env[B]:void 0);if(E!==void 0){if(Y.verbose){let j=DA.env[J]?J:B}try{$[f]=this.parseEnvironmentValue(E,typeof X,J,Y.customParsers,Y.configName)}catch(j){if(j instanceof AY)throw j;throw Yw.envVar(J,E,typeof X,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,f){for(let[X,U]of Object.entries(Y))try{return U($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw Yw.envVar(A,$,`${w} (via ${X.name} parser)`,f)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,f]of Object.entries(DA.env))if(Y.startsWith(A)&&f!==void 0)w[Y]=f;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(f){Y.push(`Cannot parse value "${w}" as ${A}: ${f}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:f="text"}=A,X=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],X,U),f){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=`${A}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,U,A,Y);else Y.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${U.join(".")}`,example:this.generateExample(X)})}}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 Y of $)A+=`${Y.key}
|
|
24
24
|
`,A+=` Type: ${Y.type}
|
|
@@ -30,25 +30,25 @@ import{createRequire as dF}from"node:module";var nF=Object.defineProperty;var vF
|
|
|
30
30
|
`;A+=`| Variable | Type | Description | Example |
|
|
31
31
|
`,A+=`|----------|------|-------------|----------|
|
|
32
32
|
`;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
33
|
-
`;return A}}function wG($,w){let A=XB("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function wB($,w,A={}){return AB($,w,A,new WeakMap)}function AB($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return YB($,w,f,Y);if(!w0(w)||!w0($))return w;return XG($,w,A,Y)}function YB($,w,A,Y){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 AG($,w);case"smart":return YG($,w,Y);default:return w}return w}function AG($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>bX(f,Y)))A.push(Y);return A}function YG($,w,A){if(w.length===0)return $;if($.length===0)return w;if(w0(w[0])&&w0($[0]))return fG($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function fG($,w,A){let Y=[...w];for(let f of $){if(!w0(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>w0(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function XG($,w,A,Y){let f=w;if(w0(f)&&Y.has(f))return Y.get(f);let X={...$};if(w0(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(w0(W)&&w0(J))X[U]=AB(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=YB(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function eX($,w,A="replace"){return wB($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function bX($,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(!bX($[A],w[A]))return!1;return!0}if(w0($)&&w0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!bX($[f],w[f]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class WY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=gw.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!kA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new P1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new P1($,Error("Configuration must export a valid object"),"unknown");let K={config:eX(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)gw.setWithFileCheck("file",K,$,X);return K}catch(B){throw B instanceof Error?ww.configLoad($,B):ww.configLoad($,Error(String(B)))}};if(U)return b1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(CX(w,`${X}${U}`));return f}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 eW(async()=>{return kA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!kA($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=CX($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=CX($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}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(!kA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}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(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class $8{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await b1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!q2(w))throw new i1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new i1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.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)Y.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($))Y.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)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.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($))Y.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 f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}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:EB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class w8{fileLoader=new WY;envProcessor=new JY;validator=new $8;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)F0.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw F0.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||Rw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(x$(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw ww.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?Z1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)F0.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)F0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?Z1($,A,f):A,W=[x$(Pw(),".config",$),x$(Pw(),".config"),Pw()];for(let J of W){if(f)F0.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)F0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?Z1($,Y,X):Y;try{let J=x$(A,"package.json");if(!PX(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)F0.success(`Configuration loaded from package.json: ${j}`);return{config:eX(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)F0.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){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,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw ww.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return gw.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);gw.set(f,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,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(x$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[x$(Pw(),".config",$),x$(Pw(),".config"),Pw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function kW($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function UG($){return k0.loadConfig({...$,__strictErrorHandling:!0})}async function fB($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await k0.loadConfig($);else Y=await k0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)F0.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await k0.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function JG($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await k0.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"&&kW(A)))return(await k0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await k0.loadConfig({...$,cwd:$.cwd||Rw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&kW(w)))return(await k0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function WG($,w,A="replace"){let Y=new WY;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Z1($,w,A=!1){let Y=new JY,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=Rw.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function BG($){let w=x$(Rw.cwd(),$.configDir),A=x$(Rw.cwd(),$.generatedDir),Y=x$(A,"config-types.ts");if(!PX(EW(Y)))sz(EW(Y),{recursive:!0,mode:511});let f=PX(w)?oz(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${bG}
|
|
33
|
+
`;return A}}function A2($,w){let A=UB("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function AB($,w,A={}){return YB($,w,A,new WeakMap)}function YB($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return fB($,w,f,Y);if(!Y$(w)||!Y$($))return w;return U2($,w,A,Y)}function fB($,w,A,Y){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 Y2($,w);case"smart":return f2($,w,Y);default:return w}return w}function Y2($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>cX(f,Y)))A.push(Y);return A}function f2($,w,A){if(w.length===0)return $;if($.length===0)return w;if(Y$(w[0])&&Y$($[0]))return X2($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function X2($,w,A){let Y=[...w];for(let f of $){if(!Y$(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>Y$(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function U2($,w,A,Y){let f=w;if(Y$(f)&&Y.has(f))return Y.get(f);let X={...$};if(Y$(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(Y$(W)&&Y$(J))X[U]=YB(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=fB(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function $U($,w,A="replace"){return AB($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function cX($,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(!cX($[A],w[A]))return!1;return!0}if(Y$($)&&Y$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!cX($[f],w[f]))return!1}return!0}return!1}function Y$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class WY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=tw.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!kA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new P1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new P1($,Error("Configuration must export a valid object"),"unknown");let K={config:$U(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)tw.setWithFileCheck("file",K,$,X);return K}catch(B){throw B instanceof Error?Yw.configLoad($,B):Yw.configLoad($,Error(String(B)))}};if(U)return b1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(SX(w,`${X}${U}`));return f}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 $B(async()=>{return kA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!kA($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=SX($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=SX($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}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(!kA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}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(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class wU{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await b1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!hz(w))throw new i1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new i1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.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)Y.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($))Y.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)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.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($))Y.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 f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}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:jB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class AU{fileLoader=new WY;envProcessor=new JY;validator=new wU;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)G$.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw G$.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||qw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(x0(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw Yw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?Z1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)G$.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)G$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?Z1($,A,f):A,W=[x0(iw(),".config",$),x0(iw(),".config"),iw()];for(let J of W){if(f)G$.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)G$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?Z1($,Y,X):Y;try{let J=x0(A,"package.json");if(!iX(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)G$.success(`Configuration loaded from package.json: ${j}`);return{config:$U(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)G$.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){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,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw Yw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return tw.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);tw.set(f,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([$,x0($,"config"),x0($,".config"),w?x0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(x0(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[x0(iw(),".config",$),x0(iw(),".config"),iw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function ZW($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function J2($){return x$.loadConfig({...$,__strictErrorHandling:!0})}async function XB($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await x$.loadConfig($);else Y=await x$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)G$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await x$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function W2($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await x$.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"&&ZW(A)))return(await x$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await x$.loadConfig({...$,cwd:$.cwd||qw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&ZW(w)))return(await x$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function B2($,w,A="replace"){let Y=new WY;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Z1($,w,A=!1){let Y=new JY,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=qw.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function E2($){let w=x0(qw.cwd(),$.configDir),A=x0(qw.cwd(),$.generatedDir),Y=x0(A,"config-types.ts");if(!iX(jW(Y)))o9(jW(Y),{recursive:!0,mode:511});let f=iX(w)?e9(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${c2}
|
|
34
34
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
35
|
-
|
|
36
|
-
${f.map((B)=>{let E=
|
|
35
|
+
`;$z(Y,X,{mode:438})}function j2($){let w=null,A=null,Y=()=>{if(!A)A=XB($).then((X)=>{return w=X,X},(X)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)G$.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return U});return A},f="defaultConfig"in $?$.defaultConfig:{};return w=f,Y(),new Proxy({},{get(X,U){if(w)return w[U];let W=f[U];return Y(),W},has(X,U){return U in(w||f)},ownKeys(){return Object.keys(w||f)},getOwnPropertyDescriptor(X,U){return Object.getOwnPropertyDescriptor(w||f,U)},set(X,U,W){if(!w)w={...f};return w[U]=W,!0}})}function T2($){let w=SW(Iz.cwd(),$?.configDir||"./config");function A(){if(!yz(w))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=Mz(w).filter((J)=>f.has(LX(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),W=new Map;for(let{base:J,file:B}of U){let E=LX(B).toLowerCase(),j=W.get(J);if(!j){W.set(J,B);continue}let T=LX(j).toLowerCase();if(X.indexOf(E)<X.indexOf(T))W.set(J,B)}return Array.from(W.entries()).map(([J,B])=>({base:J,file:B})).sort((J,B)=>J.base.localeCompare(B.base))}function Y(){let f=A(),X=f.map((B)=>B.base),U=X.length?X.map((B)=>`'${B}'`).join(" | "):"string",W=f.length?`{
|
|
36
|
+
${f.map((B)=>{let E=SW(w,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${E}').default`}).join(`,
|
|
37
37
|
`)}
|
|
38
38
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
39
39
|
export type ConfigByName = ${W}
|
|
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(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function uG($,w={}){let A=aA.cwd();while(A.includes("storage"))A=SW(A,"..");let Y=SW(A,$||"");if(w?.relative)return C2(aA.cwd(),Y);return Y}function F$(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vG(){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 zB{async format($){let w=await vG(),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:lw.pid,hostname:w(),environment:lw.env.NODE_ENV||"development",platform:lw.platform,version:lw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:lw.env.NODE_ENV||lw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class BY{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={...YY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new zB,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},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...ZX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...ZX};return{...ZX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:YY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==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 f,X=0,U=3,W=1000;while(X<U)try{try{try{await Q2(this.config.logDirectory,QW.F_OK|QW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await _2(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:O0.from($);try{if(!ZA(this.currentLogFile))await VX(this.currentLogFile,"",{mode:420});if(f=VW(this.currentLogFile,"a",420),V2(f,J,{flag:"a"}),OW(f),f!==void 0)OX(f),f=void 0;if((await mw(this.currentLogFile)).size===0){if(await VX(this.currentLogFile,J,{flag:"w",mode:420}),(await mw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{OX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 dw(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 dw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return dw(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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return LX(16).toString("hex")}generateKey(){return LX(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=LX(16),Y=S2("aes-256-gcm",w,A),f=O0.isBuffer($)?$:O0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=O0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=DW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(O0.from(O0.concat(f)))),Y.on("error",A),Y.write($),Y.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 mw(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await xA(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await mw(A).catch(()=>null))try{if(await _W(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await PA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await VX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await mw(A).catch(()=>null))await _W(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await xA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await PA(dw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=LW($),Y=O2(w),f=DW();await Z2(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),ZA(this.currentLogFile))try{let $=VW(this.currentLogFile,"r+");OW($),OX($)}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 xA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await PA(dw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F$())return!1;let $=typeof Q.env.NO_COLOR<"u",w=Q.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof Q.stderr<"u"&&Q.stderr.isTTY||typeof Q.stdout<"u"&&Q.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=Q.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${i.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=i.underline(i.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>i.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>i.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>i.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>i.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>i.strikethrough(Y)),w}supportsHyperlinks(){if(F$())return!1;let $=Q.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=Q.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(D2(w)||w.startsWith("./")||w.startsWith("../"))w=k2(w);else return null;return ZA(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":tG[$],T=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:i.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:i.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
43
|
-
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
42
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function n2($,w={}){let A=aA.cwd();while(A.includes("storage"))A=LW(A,"..");let Y=LW(A,$||"");if(w?.relative)return Sz(aA.cwd(),Y);return Y}function F0(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function m2(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z$<"u"){let $=Z$.type;if($==="renderer"||$==="worker")return!1;return!!(Z$.versions&&(Z$.versions.node||Z$.versions.bun))}return!1}class GB{async format($){let w=await m2(),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:gw.pid,hostname:w(),environment:gw.env.NODE_ENV||"development",platform:gw.platform,version:gw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:gw.env.NODE_ENV||gw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class BY{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={...YY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new GB,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},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...xX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...xX};return{...xX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:YY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await Qz(this.config.logDirectory,QW.F_OK|QW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await Dz(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:_$.from($);try{if(!ZA(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if(f=_W(this.currentLogFile,"a",420),_z(f,J,{flag:"a"}),OW(f),f!==void 0)OX(f),f=void 0;if((await dw(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await dw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{OX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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(F0())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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return VX(16).toString("hex")}generateKey(){return VX(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=VX(16),Y=Lz("aes-256-gcm",w,A),f=_$.isBuffer($)?$:_$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=_$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=kW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(_$.from(_$.concat(f)))),Y.on("error",A),Y.write($),Y.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(F0())return;if(!this.shouldWriteToFile())return;let $=await dw(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await xA(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await dw(A).catch(()=>null))try{if(await DW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await PA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await dw(A).catch(()=>null))await DW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await xA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await PA(lw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=VW($),Y=Oz(w),f=kW();await xz(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),ZA(this.currentLogFile))try{let $=_W(this.currentLogFile,"r+");OW($),OX($)}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(!F0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await xA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await PA(lw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F0())return!1;let $=typeof Q.env.NO_COLOR<"u",w=Q.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof Q.stderr<"u"&&Q.stderr.isTTY||typeof Q.stdout<"u"&&Q.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=Q.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${b.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=b.underline(b.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>b.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>b.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>b.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>b.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>b.strikethrough(Y)),w}supportsHyperlinks(){if(F0())return!1;let $=Q.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=Q.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(kz(w)||w.startsWith("./")||w.startsWith("../"))w=Zz(w);else return null;return ZA(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":p2[$],T=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:b.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:b.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
43
|
+
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:b.gray(` ${G}`),level:$,showTimestamp:!1}))}break}}else if(!F0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
44
44
|
`;if(W)E+=`${W}
|
|
45
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
46
|
-
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
47
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?
|
|
48
|
-
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:
|
|
49
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!Q.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=
|
|
51
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
45
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!F0()&&Q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!F0()&&Q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,J="info")=>{if(!F0()&&Q.stdout.isTTY)Q.stdout.write(`
|
|
46
|
+
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!F0()&&Q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":b.blue("◐"),tag:A,message:`${b.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
47
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":b.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!F0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=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 BY(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(F0())throw Error("createReadStream is not supported in browser environments");if(!ZA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return VW(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 Y=_$.isBuffer($)?$:_$.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=Vz("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=_$.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F0()}isServerMode(){return!F0()}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),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
48
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:b.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:b.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:b.cyan(E),showTimestamp:!1}))}else if(!F0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
49
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(F0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${b.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.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(f==="y"||f==="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 J=/%([sdijfo%])/g,B=0;if(A=$.replace(J,(E,j)=>{if(j==="%")return"%";if(B>=w.length)return E;let T=w[B++];switch(j){case"s":return String(T);case"d":case"i":return Number(T).toString();case"j":case"o":return JSON.stringify(T,null,2);default:return E}}),B<w.length)A+=` ${w.slice(B).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${b.blue("◐")} `;console.error(`${B}${J} ${b.cyan(Y)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
50
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!Q.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=b.green("━".repeat(Y)),U=b.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?b.green("✓"):b.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=Q.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,Q.stdout.write($.lastRenderedLine),w)Q.stdout.write(`
|
|
51
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F0()||!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(F0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await xA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=lw(this.config.logDirectory,Y);if($.before)try{if((await dw(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}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 Y of A)try{await PA(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function r2($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:f=()=>!0,fallback:X}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(J){if(U=J instanceof Error?J:Error(String(J)),W===A||!f(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(X!==void 0)return X;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class fU{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:Y,useCamelCase:f=!0,useBackwardCompatibility:X=!0,customParsers:U={},verbose:W=!1,trackPerformance:J=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix($),j={...w};return this.processObject(j,[],E,{useCamelCase:f,useBackwardCompatibility:X,customParsers:U,verbose:W,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return rX.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=U.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),J=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,U,A,Y);else{let E=bA.env[J]||(B?bA.env[B]:void 0);if(E!==void 0){if(Y.verbose){let j=bA.env[J]?J:B}try{$[f]=this.parseEnvironmentValue(E,typeof X,J,Y.customParsers,Y.configName)}catch(j){if(j instanceof YU)throw j;throw pw.envVar(J,E,typeof X,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,f){for(let[X,U]of Object.entries(Y))try{return U($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw pw.envVar(A,$,`${w} (via ${X.name} parser)`,f)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,f]of Object.entries(bA.env))if(Y.startsWith(A)&&f!==void 0)w[Y]=f;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(f){Y.push(`Cannot parse value "${w}" as ${A}: ${f}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:f="text"}=A,X=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],X,U),f){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=`${A}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,U,A,Y);else Y.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${U.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
52
52
|
|
|
53
53
|
`;for(let Y of $)A+=`${Y.key}
|
|
54
54
|
`,A+=` Type: ${Y.type}
|
|
@@ -60,28 +60,28 @@ export type ConfigOf = Config
|
|
|
60
60
|
`;A+=`| Variable | Type | Description | Example |
|
|
61
61
|
`,A+=`|----------|------|-------------|----------|
|
|
62
62
|
`;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
63
|
-
`;return A}}function rG($,w,A={}){return yB($,w,A,new WeakMap)}function yB($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return MB($,w,f,Y);if(!A0(w)||!A0($))return w;return eG($,w,A,Y)}function MB($,w,A,Y){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 aG($,w);case"smart":return sG($,w,Y);default:return w}return w}function aG($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>tX(f,Y)))A.push(Y);return A}function sG($,w,A){if(w.length===0)return $;if($.length===0)return w;if(A0(w[0])&&A0($[0]))return oG($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function oG($,w,A){let Y=[...w];for(let f of $){if(!A0(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>A0(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function eG($,w,A,Y){let f=w;if(A0(f)&&Y.has(f))return Y.get(f);let X={...$};if(A0(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(A0(W)&&A0(J))X[U]=yB(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=MB(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function IB($,w,A="replace"){return rG($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function tX($,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(!tX($[A],w[A]))return!1;return!0}if(A0($)&&A0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!tX($[f],w[f]))return!1}return!0}return!1}function A0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class CB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=gA.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!cA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new fY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new fY($,Error("Configuration must export a valid object"),"unknown");let K={config:IB(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)gA.setWithFileCheck("file",K,$,X);return K}catch(B){throw B instanceof Error?tw.configLoad($,B):tw.configLoad($,Error(String(B)))}};if(U)return pX.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(xX(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of Y){if(!X)continue;if(A.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)A.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let f=new Set;return A.filter((X)=>{if(!X||f.has(X))return!1;return f.add(X),!0})}checkFileAccess($){return pG(async()=>{return cA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!cA($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=xX($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=xX($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}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(!cA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}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(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class SB{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await pX.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!$H(w))throw new XY(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new XY(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.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)Y.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($))Y.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)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.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($))Y.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 f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}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:wH},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function AH($){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 LB{fileLoader=new CB;envProcessor=new Y8;validator=new SB;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)V0.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let J=Date.now()-w;throw V0.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||UY.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push($0(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw tw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${AH(f)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?uA($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)V0.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)V0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?uA($,A,f):A,W=[$0(xw(),".config",$),$0(xw(),".config"),xw()];for(let J of W){if(f)V0.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)V0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?uA($,Y,X):Y;try{let J=$0(A,"package.json");if(!rz(J))return null;let B={};try{B=JSON.parse(az(J,"utf8"))}catch(T){if(X)V0.warn("Failed to parse package.json:",[T instanceof Error?T:Error(String(T))]);return null}let E=B[$],j=$;if(!E&&w){let T=Array.isArray(w)?w:[w];for(let F of T){if(!F)continue;if(B[F]){E=B[F],j=F;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)V0.success(`Configuration loaded from package.json: ${j}`);return{config:IB(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)V0.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:uA($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw tw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return gA.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);gA.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}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([$,$0($,"config"),$0($,".config"),w?$0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push($0(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[$0(xw(),".config",$),$0(xw(),".config"),xw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function uA($,w,A=!1){let Y=new Y8,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=UY.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}var gA,pX,x2,P2=($)=>$,b2=($,w)=>{for(var A in w)x2($,A,{get:w[A],enumerable:!0,configurable:!0,set:i2.bind(w,A)})},c2=($,w)=>()=>($&&(w=$($=0)),w),aW,XB,gw,b1,UB,TG,FG,ZW,vA,cX,C$,g,zG,xW,GG,PW,HG,KG,QX,RG,iW,bW,_X,hG,qG,NG,yG,mA,JB,MG,S$,IG,CG,cW,dA,uX,T$,k,SG,uW,LG,nW,OG,VG,DX,QG,vW,mW,_G,kX,DG,kG,ZG,xG,PG,lA,WB,iG,bG="0.15.6",p$,wY,P1,nX,vX,AY,mX,dX,i1,lX,gX,ww,BB,EB,F0,k0,jB,TB,cG,nG,FB,YY,iq,N$,i,bq,mG,cq,dG,uq,nq,dW,vq,lG,gG,mq,lW,dq,lq,gq,tq,pq,ZX,tG,rq,z0,GB,fY,HB,KB,A8,RB,hB,XY,qB,NB,tw,wH,V0,$N,wN,AN;var f8=E$(()=>{gA=new gW,pX=new tW,x2=Object.defineProperty;aW={};b2(aW,{withErrorRecovery:()=>eW,tryLoadConfig:()=>WG,loadConfigWithResult:()=>UG,loadConfig:()=>fB,isRetryableError:()=>$G,isConfigNotFoundError:()=>e2,isBunfigError:()=>$B,globalPerformanceMonitor:()=>b1,globalCache:()=>gw,getEnvOrDefault:()=>wG,generateConfigTypes:()=>BG,defaultGeneratedDir:()=>TB,defaultConfigDir:()=>jB,deepMergeWithArrayStrategy:()=>eX,deepMerge:()=>wB,createLibraryConfig:()=>EG,config:()=>JG,bunfigPlugin:()=>jG,applyEnvVarsToConfig:()=>Z1,TypeGenerationError:()=>dX,SchemaValidationError:()=>i1,PluginError:()=>gX,PerformanceMonitor:()=>aX,FileSystemError:()=>mX,ErrorFactory:()=>ww,EnvVarError:()=>AY,EnvProcessor:()=>JY,ConfigValidator:()=>$8,ConfigValidationError:()=>nX,ConfigNotFoundError:()=>wY,ConfigMergeError:()=>vX,ConfigLoader:()=>w8,ConfigLoadError:()=>P1,ConfigFileLoader:()=>WY,ConfigCache:()=>rX,CacheUtils:()=>UB,BunfigError:()=>p$,BrowserConfigError:()=>lX,ArrayMergeStrategies:()=>BB});cG=c2(async()=>{XB=import.meta.require,gw=new rX,b1=new aX,UB={createKey:u2,isEquivalent:n2,estimateMemoryUsage:v2},TG=rA(iX.cwd(),"config"),FG=rA(iX.cwd(),"src/generated"),ZW=pA.env.CLARITY_LOG_DIR||A2(l2(),"logs"),vA={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},cX=await g2(),C$={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=C$,zG=C$.red,xW=C$.green,GG=C$.yellow,PW=C$.blue,HG=C$.magenta,KG=C$.cyan,QX=C$.white,RG=C$.gray,iW=C$.bgRed,bW=C$.bgYellow,_X=C$.bold,hG=C$.dim,qG=C$.italic,NG=C$.underline,yG=C$.reset,mA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},JB={debug:"\uD83D\uDD0D",info:PW("ℹ"),success:xW("✓"),warning:bW(QX(_X(" WARN "))),error:iW(QX(_X(" ERROR ")))},MG=new oA("stacks"),S$=new oA("bunfig",{showTags:!0}),IG=Z$(x1.cwd(),"config"),CG=Z$(x1.cwd(),"src/generated"),cW=tA.env.CLARITY_LOG_DIR||$2(a2(),"logs"),dA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:cW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},uX=await s2(),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"},k=T$,SG=T$.red,uW=T$.green,LG=T$.yellow,nW=T$.blue,OG=T$.magenta,VG=T$.cyan,DX=T$.white,QG=T$.gray,vW=T$.bgRed,mW=T$.bgYellow,_G=T$.bgGray,kX=T$.bold,DG=T$.dim,kG=T$.italic,ZG=T$.underline,xG=T$.strikethrough,PG=T$.reset,lA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},WB={debug:"\uD83D\uDD0D",info:nW("ℹ"),success:uW("✓"),warning:mW(DX(kX(" WARN "))),error:vW(DX(kX(" ERROR ")))},iG=new $Y("stacks"),p$=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,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},wY=class extends p${code="CONFIG_NOT_FOUND";constructor(w,A,Y){let f=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${f} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},P1=class extends p${code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},nX=class extends p${code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},vX=class extends p${code="CONFIG_MERGE_ERROR";constructor(w,A,Y,f){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:f,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},AY=class extends p${code="ENV_VAR_ERROR";constructor(w,A,Y,f){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:f})}},mX=class extends p${code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},dX=class extends p${code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},i1=class extends p${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},lX=class extends p${code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,f){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:f})}},gX=class extends p${code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},ww={configNotFound($,w,A){return new wY($,w,A)},configLoad($,w,A){return new P1($,w,A)},configValidation($,w,A){return new nX($,w,A)},configMerge($,w,A,Y){return new vX($,w,A,Y)},envVar($,w,A,Y){return new AY($,w,A,Y)},fileSystem($,w,A){return new mX($,w,A)},typeGeneration($,w,A){return new dX($,w,A)},schemaValidation($,w,A){return new i1($,w,A)},browserConfig($,w,A,Y){return new lX($,w,A,Y)},plugin($,w,A){return new gX($,w,A)}},BB={replace:"replace",concat:"concat",smart:"smart"},EB=/^https?:\/\//,F0=new $Y("bunfig",{showTags:!0}),k0=new w8,jB=x$(Rw.cwd(),"config"),TB=x$(Rw.cwd(),"src/generated")});nG=aA.env.CLARITY_LOG_DIR||I2(uG(),"logs"),FB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:nG,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},YY={...FB},iq=(async()=>{try{let{loadConfig:$}=await cG().then(()=>aW),w=await $({name:"clarity",alias:"logging",defaultConfig:FB,cwd:aA.cwd()});if(w)Object.assign(YY,w)}catch{}return YY})();N$={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"},i=N$,bq=N$.red,mG=N$.green,cq=N$.yellow,dG=N$.blue,uq=N$.magenta,nq=N$.cyan,dW=N$.white,vq=N$.gray,lG=N$.bgRed,gG=N$.bgYellow,mq=N$.bgGray,lW=N$.bold,dq=N$.dim,lq=N$.italic,gq=N$.underline,tq=N$.strikethrough,pq=N$.reset,ZX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},tG={debug:"\uD83D\uDD0D",info:dG("ℹ"),success:mG("✓"),warning:gG(dW(lW(" WARN "))),error:lG(dW(lW(" ERROR ")))};rq=new BY("stacks");z0=class z0 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}${$}`}};GB=class GB extends z0{code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],f="";if(Y.length===1)f=` or alias "${Y[0]}"`;else if(Y.length>1)f=` or aliases ${Y.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${f} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};fY=class fY extends z0{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}};HB=class HB extends z0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};KB=class KB extends z0{code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};A8=class A8 extends z0{code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};RB=class RB extends z0{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}};hB=class hB extends z0{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}};XY=class XY extends z0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};qB=class qB extends z0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};NB=class NB extends z0{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}};tw={configNotFound($,w,A){return new GB($,w,A)},configLoad($,w,A){return new fY($,w,A)},configValidation($,w,A){return new HB($,w,A)},configMerge($,w,A,Y){return new KB($,w,A,Y)},envVar($,w,A,Y){return new A8($,w,A,Y)},fileSystem($,w,A){return new RB($,w,A)},typeGeneration($,w,A){return new hB($,w,A)},schemaValidation($,w,A){return new XY($,w,A)},browserConfig($,w,A,Y){return new qB($,w,A,Y)},plugin($,w,A){return new NB($,w,A)}};wH=/^https?:\/\//;V0=new BY("bunfig",{showTags:!0});$N=new LB;wN=$0(UY.cwd(),"config"),AN=$0(UY.cwd(),"src/generated")});var q;var Aw=E$(()=>{q={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{createRequire as XH}from"node:module";import{Resolver as J8}from"node:dns/promises";import{createHash as JH,sign as WH}from"node:crypto";import{createHash as BH}from"node:crypto";import{sign as EH}from"node:crypto";import{generateKeyPairSync as ZE,X509Certificate as hH}from"node:crypto";import W8 from"node:os";import B8 from"node:path";import{existsSync as VB,statSync as QB}from"fs";import{existsSync as NH,mkdirSync as qN,readdirSync as NN,readFileSync as yH,writeFileSync as yN}from"fs";import{homedir as rw}from"os";import{dirname as CN,resolve as f0}from"path";import rY from"process";import{existsSync as _B,statSync as DB}from"fs";import{existsSync as k8,mkdirSync as MH,readdirSync as IH,writeFileSync as CH}from"fs";import{homedir as aw}from"os";import{dirname as kB,resolve as i$}from"path";import qw from"process";import{join as SH,relative as LH,resolve as ZB}from"path";import DY from"process";import{existsSync as xE,mkdirSync as xN,readdirSync as PN,writeFileSync as iN}from"fs";import{homedir as E8}from"os";import{dirname as uN,resolve as P$}from"path";import m1 from"process";import{join as OH,relative as VH,resolve as xB}from"path";import kY from"process";import{existsSync as PE,mkdirSync as lN,readdirSync as gN,writeFileSync as tN}from"fs";import{dirname as rN,resolve as ZY}from"path";import Z8 from"process";import{Buffer as Yw}from"buffer";import{createCipheriv as QH,createDecipheriv as _H,randomBytes as j8}from"crypto";import{closeSync as T8,createReadStream as PB,createWriteStream as DH,existsSync as F8,fsyncSync as iB,openSync as bB,writeFileSync as kH}from"fs";import{access as ZH,constants as cB,mkdir as xH,readdir as EY,rename as uB,stat as sw,unlink as jY,writeFile as z8}from"fs/promises";import{join as ow}from"path";import L$ from"process";import{pipeline as PH}from"stream/promises";import{createGzip as nB}from"zlib";import ew from"process";import i0 from"process";import{Buffer as Z0}from"buffer";import{createCipheriv as iH,createDecipheriv as bH,randomBytes as G8}from"crypto";import{closeSync as H8,createReadStream as vB,createWriteStream as cH,existsSync as TY,fsyncSync as mB,openSync as dB,writeFileSync as uH}from"fs";import{access as nH,constants as lB,mkdir as vH,readdir as FY,rename as gB,stat as $1,unlink as zY,writeFile as K8}from"fs/promises";import{isAbsolute as mH,join as w1,resolve as dH}from"path";import v from"process";import{pipeline as lH}from"stream/promises";import{createGzip as tB}from"zlib";import A1 from"process";import b0 from"process";import GY from"process";import{existsSync as HY}from"fs";import{resolve as R8}from"path";import{existsSync as gH}from"fs";import{existsSync as tH,readdirSync as pH}from"fs";import{extname as h8,resolve as pB}from"path";import rH from"process";import{join as aH,relative as sH,resolve as rB}from"path";import xY from"process";import{Buffer as x0}from"buffer";import{createCipheriv as oH,createDecipheriv as eH,randomBytes as q8}from"crypto";import{closeSync as N8,createReadStream as aB,createWriteStream as $9,existsSync as KY,fsyncSync as sB,openSync as oB,writeFileSync as w9}from"fs";import{access as A9,constants as eB,mkdir as Y9,readdir as RY,rename as $E,stat as Y1,unlink as hY,writeFile as y8}from"fs/promises";import{isAbsolute as f9,join as f1,resolve as X9}from"path";import m from"process";import{pipeline as U9}from"stream/promises";import{createGzip as wE}from"zlib";import X1 from"process";import c0 from"process";import qY from"process";import{existsSync as NY}from"fs";import{resolve as M8}from"path";import{existsSync as J9}from"fs";import{exec as V5}from"node:child_process";import GE from"node:fs";import Q5 from"node:os";import G0 from"node:path";import Rj from"node:process";import{promisify as _5}from"node:util";import B1 from"node:crypto";import u0 from"node:fs";import t8 from"node:path";import{execSync as qE}from"node:child_process";import tY from"node:os";async function NE($,w,A={}){let Y=A.timeoutMs??120000,f=A.intervalMs??3000,X=$.split(".").slice(-2).join("."),U;try{let B=new J8,E=await B.resolveNs(X),j=(await Promise.all(E.map((T)=>B.resolve4(T).catch(()=>[])))).flat();if(j.length>0)U=new J8,U.setServers(j)}catch{}let W=Date.now()+Y,J=U??new J8;for(;;){try{if((await J.resolveTxt($)).some((B)=>B.join("")===w))return!0}catch{}if(Date.now()>=W)return!1;await new Promise((B)=>setTimeout(B,f))}}class v1{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(v1.PATH_PREFIX);if(w===-1)return;let A=$.slice(w+v1.PATH_PREFIX.length);return this.get(A)}}function IY($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function V8($){return Buffer.from($,"base64url")}function yE($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function ME($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return JH("sha256").update(w).digest("base64url")}function IE($){let{protectedHeader:w,payload:A,privateKey:Y}=$,f=IY(JSON.stringify(w)),X=A===""?"":IY(JSON.stringify(A)),U=`${f}.${X}`,W=WH("sha256",Buffer.from(U),{key:Y,dsaEncoding:"ieee-p1363"});return{protected:f,payload:X,signature:IY(W)}}class _Y{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=yE($.accountPublicKey),this.thumbprint=ME(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:A,useJwk:Y}=$,f={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(Y)f.jwk=this.jwk;else f.kid=this.requireKid();let X=IE({protectedHeader:f,payload:A,privateKey:this.accountKey}),U=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(X)}),W=U.headers.get("replay-nonce");if(W)this.nonce=W;let J=U.headers.get("content-type")??"",B;if(J.includes("application/pem-certificate-chain")||J.startsWith("text/"))B=await U.text();else{let E=await U.text();B=E?JSON.parse(E):{}}if(U.status>=400){let E=B??{};throw new QY(`ACME request to ${w} failed (HTTP ${U.status}): ${E.type??""} ${E.detail??""}`.trim(),E,U.status)}return{status:U.status,headers:U.headers,body:B,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),A={termsOfServiceAgreed:!0};if($.email)A.contact=[`mailto:${$.email}`];let Y=await this.signedPost({url:w.newAccount,payload:A,useJwk:!0});if(!Y.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=Y.location,this.accountKid}async newOrder($){let w=await this.directory(),A={identifiers:$.map((f)=>({type:"dns",value:f}))},Y=await this.signedPost({url:w.newOrder,payload:A});if(!Y.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:Y.body,orderUrl:Y.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return BH("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,f=Date.now()+A;while(Date.now()<f){let X=await this.getAuthorization($);if(X.status==="valid")return;if(X.status==="invalid"){let U=X.challenges.find((W)=>W.status==="invalid");throw new QY(`Authorization for ${X.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await OB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,f=Date.now()+A;while(Date.now()<f){let X=await this.getOrder($);if(X.status==="valid"){if(!X.certificate)throw Error("ACME order is valid but has no certificate URL");return X.certificate}if(X.status==="invalid")throw Error(`ACME order ${$} became invalid`);await OB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let A=$.challenges.find((Y)=>Y.type===w);if(!A)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return A}}function LE($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],A=w[0];if(!A)return{certPem:`${$.trim()}
|
|
63
|
+
`;return A}}function a2($,w,A={}){return MB($,w,A,new WeakMap)}function MB($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return IB($,w,f,Y);if(!f$(w)||!f$($))return w;return $G($,w,A,Y)}function IB($,w,A,Y){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 s2($,w);case"smart":return o2($,w,Y);default:return w}return w}function s2($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>pX(f,Y)))A.push(Y);return A}function o2($,w,A){if(w.length===0)return $;if($.length===0)return w;if(f$(w[0])&&f$($[0]))return e2($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function e2($,w,A){let Y=[...w];for(let f of $){if(!f$(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>f$(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function $G($,w,A,Y){let f=w;if(f$(f)&&Y.has(f))return Y.get(f);let X={...$};if(f$(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(f$(W)&&f$(J))X[U]=MB(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=IB(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function CB($,w,A="replace"){return a2($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function pX($,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(!pX($[A],w[A]))return!1;return!0}if(f$($)&&f$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!pX($[f],w[f]))return!1}return!0}return!1}function f$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class SB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=gA.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!cA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new fY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new fY($,Error("Configuration must export a valid object"),"unknown");let K={config:CB(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)gA.setWithFileCheck("file",K,$,X);return K}catch(B){throw B instanceof Error?pw.configLoad($,B):pw.configLoad($,Error(String(B)))}};if(U)return rX.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(PX(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of Y){if(!X)continue;if(A.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)A.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let f=new Set;return A.filter((X)=>{if(!X||f.has(X))return!1;return f.add(X),!0})}checkFileAccess($){return r2(async()=>{return cA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!cA($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=PX($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=PX($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}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(!cA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}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(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class LB{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await rX.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!wG(w))throw new XY(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new XY(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.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)Y.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($))Y.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)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.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($))Y.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 f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}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:AG},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function YG($){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 VB{fileLoader=new SB;envProcessor=new fU;validator=new LB;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)Q$.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let J=Date.now()-w;throw Q$.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||UY.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(A$(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw pw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${YG(f)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?uA($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)Q$.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)Q$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?uA($,A,f):A,W=[A$(Pw(),".config",$),A$(Pw(),".config"),Pw()];for(let J of W){if(f)Q$.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)Q$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?uA($,Y,X):Y;try{let J=A$(A,"package.json");if(!a9(J))return null;let B={};try{B=JSON.parse(s9(J,"utf8"))}catch(T){if(X)Q$.warn("Failed to parse package.json:",[T instanceof Error?T:Error(String(T))]);return null}let E=B[$],j=$;if(!E&&w){let T=Array.isArray(w)?w:[w];for(let F of T){if(!F)continue;if(B[F]){E=B[F],j=F;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)Q$.success(`Configuration loaded from package.json: ${j}`);return{config:CB(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)Q$.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:uA($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw pw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return gA.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);gA.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}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([$,A$($,"config"),A$($,".config"),w?A$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(A$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[A$(Pw(),".config",$),A$(Pw(),".config"),Pw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function uA($,w,A=!1){let Y=new fU,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=UY.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}var gA,rX,Pz,iz=($)=>$,cz=($,w)=>{for(var A in w)Pz($,A,{get:w[A],enumerable:!0,configurable:!0,set:bz.bind(w,A)})},uz=($,w)=>()=>($&&(w=$($=0)),w),sW,UB,tw,b1,JB,F2,z2,xW,vA,uX,C0,t,G2,PW,H2,iW,K2,R2,QX,N2,bW,cW,DX,q2,h2,y2,M2,mA,WB,I2,S0,C2,S2,uW,dA,nX,T0,Z,L2,nW,V2,vW,O2,_2,kX,Q2,mW,dW,D2,ZX,k2,Z2,x2,P2,i2,lA,BB,b2,c2="0.15.6",p0,wY,P1,vX,mX,AY,dX,lX,i1,gX,tX,Yw,EB,jB,G$,x$,TB,FB,u2,v2,zB,YY,uq,h0,b,nq,d2,vq,l2,mq,dq,lW,lq,g2,t2,gq,gW,tq,pq,rq,aq,sq,xX,p2,oq,H$,HB,fY,KB,RB,YU,NB,qB,XY,hB,yB,pw,AG,Q$,Yh,fh,Xh;var XU=E0(()=>{gA=new tW,rX=new pW,Pz=Object.defineProperty;sW={};cz(sW,{withErrorRecovery:()=>$B,tryLoadConfig:()=>B2,loadConfigWithResult:()=>J2,loadConfig:()=>XB,isRetryableError:()=>w2,isConfigNotFoundError:()=>$2,isBunfigError:()=>wB,globalPerformanceMonitor:()=>b1,globalCache:()=>tw,getEnvOrDefault:()=>A2,generateConfigTypes:()=>E2,defaultGeneratedDir:()=>FB,defaultConfigDir:()=>TB,deepMergeWithArrayStrategy:()=>$U,deepMerge:()=>AB,createLibraryConfig:()=>j2,config:()=>W2,bunfigPlugin:()=>T2,applyEnvVarsToConfig:()=>Z1,TypeGenerationError:()=>lX,SchemaValidationError:()=>i1,PluginError:()=>tX,PerformanceMonitor:()=>sX,FileSystemError:()=>dX,ErrorFactory:()=>Yw,EnvVarError:()=>AY,EnvProcessor:()=>JY,ConfigValidator:()=>wU,ConfigValidationError:()=>vX,ConfigNotFoundError:()=>wY,ConfigMergeError:()=>mX,ConfigLoader:()=>AU,ConfigLoadError:()=>P1,ConfigFileLoader:()=>WY,ConfigCache:()=>aX,CacheUtils:()=>JB,BunfigError:()=>p0,BrowserConfigError:()=>gX,ArrayMergeStrategies:()=>EB});u2=uz(async()=>{UB=import.meta.require,tw=new aX,b1=new sX,JB={createKey:nz,isEquivalent:vz,estimateMemoryUsage:mz},F2=rA(bX.cwd(),"config"),z2=rA(bX.cwd(),"src/generated"),xW=pA.env.CLARITY_LOG_DIR||Yz(gz(),"logs"),vA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},uX=await tz(),C0={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"},t=C0,G2=C0.red,PW=C0.green,H2=C0.yellow,iW=C0.blue,K2=C0.magenta,R2=C0.cyan,QX=C0.white,N2=C0.gray,bW=C0.bgRed,cW=C0.bgYellow,DX=C0.bold,q2=C0.dim,h2=C0.italic,y2=C0.underline,M2=C0.reset,mA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},WB={debug:"\uD83D\uDD0D",info:iW("ℹ"),success:PW("✓"),warning:cW(QX(DX(" WARN "))),error:bW(QX(DX(" ERROR ")))},I2=new oA("stacks"),S0=new oA("bunfig",{showTags:!0}),C2=Z0(x1.cwd(),"config"),S2=Z0(x1.cwd(),"src/generated"),uW=tA.env.CLARITY_LOG_DIR||wz(sz(),"logs"),dA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},nX=await oz(),T0={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"},Z=T0,L2=T0.red,nW=T0.green,V2=T0.yellow,vW=T0.blue,O2=T0.magenta,_2=T0.cyan,kX=T0.white,Q2=T0.gray,mW=T0.bgRed,dW=T0.bgYellow,D2=T0.bgGray,ZX=T0.bold,k2=T0.dim,Z2=T0.italic,x2=T0.underline,P2=T0.strikethrough,i2=T0.reset,lA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},BB={debug:"\uD83D\uDD0D",info:vW("ℹ"),success:nW("✓"),warning:dW(kX(ZX(" WARN "))),error:mW(kX(ZX(" ERROR ")))},b2=new $Y("stacks"),p0=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,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},wY=class extends p0{code="CONFIG_NOT_FOUND";constructor(w,A,Y){let f=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${f} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},P1=class extends p0{code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},vX=class extends p0{code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},mX=class extends p0{code="CONFIG_MERGE_ERROR";constructor(w,A,Y,f){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:f,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},AY=class extends p0{code="ENV_VAR_ERROR";constructor(w,A,Y,f){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:f})}},dX=class extends p0{code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},lX=class extends p0{code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},i1=class extends p0{code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},gX=class extends p0{code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,f){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:f})}},tX=class extends p0{code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Yw={configNotFound($,w,A){return new wY($,w,A)},configLoad($,w,A){return new P1($,w,A)},configValidation($,w,A){return new vX($,w,A)},configMerge($,w,A,Y){return new mX($,w,A,Y)},envVar($,w,A,Y){return new AY($,w,A,Y)},fileSystem($,w,A){return new dX($,w,A)},typeGeneration($,w,A){return new lX($,w,A)},schemaValidation($,w,A){return new i1($,w,A)},browserConfig($,w,A,Y){return new gX($,w,A,Y)},plugin($,w,A){return new tX($,w,A)}},EB={replace:"replace",concat:"concat",smart:"smart"},jB=/^https?:\/\//,G$=new $Y("bunfig",{showTags:!0}),x$=new AU,TB=x0(qw.cwd(),"config"),FB=x0(qw.cwd(),"src/generated")});v2=aA.env.CLARITY_LOG_DIR||Cz(n2(),"logs"),zB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:v2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},YY={...zB},uq=(async()=>{try{let{loadConfig:$}=await u2().then(()=>sW),w=await $({name:"clarity",alias:"logging",defaultConfig:zB,cwd:aA.cwd()});if(w)Object.assign(YY,w)}catch{}return YY})();h0={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"},b=h0,nq=h0.red,d2=h0.green,vq=h0.yellow,l2=h0.blue,mq=h0.magenta,dq=h0.cyan,lW=h0.white,lq=h0.gray,g2=h0.bgRed,t2=h0.bgYellow,gq=h0.bgGray,gW=h0.bold,tq=h0.dim,pq=h0.italic,rq=h0.underline,aq=h0.strikethrough,sq=h0.reset,xX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},p2={debug:"\uD83D\uDD0D",info:l2("ℹ"),success:d2("✓"),warning:t2(lW(gW(" WARN "))),error:g2(lW(gW(" ERROR ")))};oq=new BY("stacks");H$=class H$ 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}${$}`}};HB=class HB extends H${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],f="";if(Y.length===1)f=` or alias "${Y[0]}"`;else if(Y.length>1)f=` or aliases ${Y.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${f} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};fY=class fY extends H${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}};KB=class KB extends H${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};RB=class RB extends H${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};YU=class YU extends H${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};NB=class NB extends H${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}};qB=class qB extends H${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}};XY=class XY extends H${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};hB=class hB extends H${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};yB=class yB extends H${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}};pw={configNotFound($,w,A){return new HB($,w,A)},configLoad($,w,A){return new fY($,w,A)},configValidation($,w,A){return new KB($,w,A)},configMerge($,w,A,Y){return new RB($,w,A,Y)},envVar($,w,A,Y){return new YU($,w,A,Y)},fileSystem($,w,A){return new NB($,w,A)},typeGeneration($,w,A){return new qB($,w,A)},schemaValidation($,w,A){return new XY($,w,A)},browserConfig($,w,A,Y){return new hB($,w,A,Y)},plugin($,w,A){return new yB($,w,A)}};AG=/^https?:\/\//;Q$=new BY("bunfig",{showTags:!0});Yh=new VB;fh=A$(UY.cwd(),"config"),Xh=A$(UY.cwd(),"src/generated")});var q;var fw=E0(()=>{q={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{createRequire as UG}from"node:module";import{Resolver as WU}from"node:dns/promises";import{createHash as WG,sign as BG}from"node:crypto";import{createHash as EG}from"node:crypto";import{sign as jG}from"node:crypto";import{generateKeyPairSync as xE,X509Certificate as qG}from"node:crypto";import BU from"node:os";import EU from"node:path";import{existsSync as _B,statSync as QB}from"fs";import{existsSync as yG,mkdirSync as Mh,readdirSync as Ih,readFileSync as MG,writeFileSync as Ch}from"fs";import{homedir as aw}from"os";import{dirname as Vh,resolve as U$}from"path";import rY from"process";import{existsSync as DB,statSync as kB}from"fs";import{existsSync as ZU,mkdirSync as IG,readdirSync as CG,writeFileSync as SG}from"fs";import{homedir as sw}from"os";import{dirname as ZB,resolve as i0}from"path";import yw from"process";import{join as LG,relative as VG,resolve as xB}from"path";import DY from"process";import{existsSync as PE,mkdirSync as bh,readdirSync as ch,writeFileSync as uh}from"fs";import{homedir as jU}from"os";import{dirname as mh,resolve as P0}from"path";import m1 from"process";import{join as OG,relative as _G,resolve as PB}from"path";import kY from"process";import{existsSync as iE,mkdirSync as ph,readdirSync as rh,writeFileSync as ah}from"fs";import{dirname as oh,resolve as ZY}from"path";import xU from"process";import{Buffer as Xw}from"buffer";import{createCipheriv as QG,createDecipheriv as DG,randomBytes as TU}from"crypto";import{closeSync as FU,createReadStream as iB,createWriteStream as kG,existsSync as zU,fsyncSync as bB,openSync as cB,writeFileSync as ZG}from"fs";import{access as xG,constants as uB,mkdir as PG,readdir as EY,rename as nB,stat as ow,unlink as jY,writeFile as GU}from"fs/promises";import{join as ew}from"path";import L0 from"process";import{pipeline as iG}from"stream/promises";import{createGzip as vB}from"zlib";import $1 from"process";import c$ from"process";import{Buffer as P$}from"buffer";import{createCipheriv as bG,createDecipheriv as cG,randomBytes as HU}from"crypto";import{closeSync as KU,createReadStream as mB,createWriteStream as uG,existsSync as TY,fsyncSync as dB,openSync as lB,writeFileSync as nG}from"fs";import{access as vG,constants as gB,mkdir as mG,readdir as FY,rename as tB,stat as w1,unlink as zY,writeFile as RU}from"fs/promises";import{isAbsolute as dG,join as A1,resolve as lG}from"path";import m from"process";import{pipeline as gG}from"stream/promises";import{createGzip as pB}from"zlib";import Y1 from"process";import u$ from"process";import GY from"process";import{existsSync as HY}from"fs";import{resolve as NU}from"path";import{existsSync as tG}from"fs";import{existsSync as pG,readdirSync as rG}from"fs";import{extname as qU,resolve as rB}from"path";import aG from"process";import{join as sG,relative as oG,resolve as aB}from"path";import xY from"process";import{Buffer as i$}from"buffer";import{createCipheriv as eG,createDecipheriv as $H,randomBytes as hU}from"crypto";import{closeSync as yU,createReadStream as sB,createWriteStream as wH,existsSync as KY,fsyncSync as oB,openSync as eB,writeFileSync as AH}from"fs";import{access as YH,constants as $E,mkdir as fH,readdir as RY,rename as wE,stat as f1,unlink as NY,writeFile as MU}from"fs/promises";import{isAbsolute as XH,join as X1,resolve as UH}from"path";import d from"process";import{pipeline as JH}from"stream/promises";import{createGzip as AE}from"zlib";import U1 from"process";import n$ from"process";import qY from"process";import{existsSync as hY}from"fs";import{resolve as IU}from"path";import{existsSync as WH}from"fs";import{exec as _5}from"node:child_process";import HE from"node:fs";import Q5 from"node:os";import K$ from"node:path";import Nj from"node:process";import{promisify as D5}from"node:util";import E1 from"node:crypto";import v$ from"node:fs";import pU from"node:path";import{execSync as hE}from"node:child_process";import tY from"node:os";async function yE($,w,A={}){let Y=A.timeoutMs??120000,f=A.intervalMs??3000,X=$.split(".").slice(-2).join("."),U;try{let B=new WU,E=await B.resolveNs(X),j=(await Promise.all(E.map((T)=>B.resolve4(T).catch(()=>[])))).flat();if(j.length>0)U=new WU,U.setServers(j)}catch{}let W=Date.now()+Y,J=U??new WU;for(;;){try{if((await J.resolveTxt($)).some((B)=>B.join("")===w))return!0}catch{}if(Date.now()>=W)return!1;await new Promise((B)=>setTimeout(B,f))}}class v1{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(v1.PATH_PREFIX);if(w===-1)return;let A=$.slice(w+v1.PATH_PREFIX.length);return this.get(A)}}function IY($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function _U($){return Buffer.from($,"base64url")}function ME($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function IE($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return WG("sha256").update(w).digest("base64url")}function CE($){let{protectedHeader:w,payload:A,privateKey:Y}=$,f=IY(JSON.stringify(w)),X=A===""?"":IY(JSON.stringify(A)),U=`${f}.${X}`,W=BG("sha256",Buffer.from(U),{key:Y,dsaEncoding:"ieee-p1363"});return{protected:f,payload:X,signature:IY(W)}}class QY{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=ME($.accountPublicKey),this.thumbprint=IE(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:A,useJwk:Y}=$,f={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(Y)f.jwk=this.jwk;else f.kid=this.requireKid();let X=CE({protectedHeader:f,payload:A,privateKey:this.accountKey}),U=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(X)}),W=U.headers.get("replay-nonce");if(W)this.nonce=W;let J=U.headers.get("content-type")??"",B;if(J.includes("application/pem-certificate-chain")||J.startsWith("text/"))B=await U.text();else{let E=await U.text();B=E?JSON.parse(E):{}}if(U.status>=400){let E=B??{};throw new _Y(`ACME request to ${w} failed (HTTP ${U.status}): ${E.type??""} ${E.detail??""}`.trim(),E,U.status)}return{status:U.status,headers:U.headers,body:B,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),A={termsOfServiceAgreed:!0};if($.email)A.contact=[`mailto:${$.email}`];let Y=await this.signedPost({url:w.newAccount,payload:A,useJwk:!0});if(!Y.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=Y.location,this.accountKid}async newOrder($){let w=await this.directory(),A={identifiers:$.map((f)=>({type:"dns",value:f}))},Y=await this.signedPost({url:w.newOrder,payload:A});if(!Y.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:Y.body,orderUrl:Y.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return EG("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,f=Date.now()+A;while(Date.now()<f){let X=await this.getAuthorization($);if(X.status==="valid")return;if(X.status==="invalid"){let U=X.challenges.find((W)=>W.status==="invalid");throw new _Y(`Authorization for ${X.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await OB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,f=Date.now()+A;while(Date.now()<f){let X=await this.getOrder($);if(X.status==="valid"){if(!X.certificate)throw Error("ACME order is valid but has no certificate URL");return X.certificate}if(X.status==="invalid")throw Error(`ACME order ${$} became invalid`);await OB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let A=$.challenges.find((Y)=>Y.type===w);if(!A)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return A}}function VE($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],A=w[0];if(!A)return{certPem:`${$.trim()}
|
|
64
64
|
`,chainPem:""};let Y=`${A.trim()}
|
|
65
65
|
`,f=w.slice(1).map((X)=>X.trim()).join(`
|
|
66
66
|
`);return{certPem:Y,chainPem:f?`${f}
|
|
67
|
-
`:""}}function OE($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function OB($){return new Promise((w)=>setTimeout(w,$))}function jH($){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 Uw($,w){return Buffer.concat([Buffer.from([$]),jH(w.length),w])}function VE($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let A=[],Y=$;while(Y>0)A.unshift(Y&255),Y>>=8;if(A[0]&128)A.unshift(0);w=Buffer.from(A)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return Uw(2,w)}function hw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let A=[40*w[0]+w[1]];for(let Y=2;Y<w.length;Y++){let f=w[Y],X=[f&127];f=Math.floor(f/128);while(f>0)X.unshift(f&127|128),f=Math.floor(f/128);A.push(...X)}return Uw(6,Buffer.from(A))}function Y0(...$){return Uw(48,Buffer.concat($))}function Q8(...$){return Uw(49,Buffer.concat($))}function _8($){return Uw(3,Buffer.concat([Buffer.from([0]),$]))}function QE($){return Uw(4,$)}function _E($){return Uw(12,Buffer.from($,"utf8"))}function D8($,w,A){let Y=128|(A?32:0)|$;return Uw(Y,w)}function RH($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let A=V8(w.x),Y=V8(w.y);if(A.length!==32||Y.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${A.length} y=${Y.length}`);return Buffer.concat([Buffer.from([4]),A,Y])}function DE($){let{domains:w,publicKey:A,privateKey:Y}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let f=Y0(Q8(Y0(hw(GH),_E(w[0])))),X=Y0(Y0(hw(TH),hw(FH)),_8(RH(A))),U=w.map((G)=>D8(2,Buffer.from(G,"ascii"),!1)),W=Y0(...U),J=Y0(hw(KH),QE(W)),B=Y0(J),E=Y0(hw(HH),Q8(B)),j=D8(0,E,!0),T=Y0(VE(0),f,X,j),F=EH("sha256",T,Y),H=Y0(hw(zH));return Y0(T,H,_8(F))}function kE($){return DE($).toString("base64url")}function qH($){if($){let{createPrivateKey:f,createPublicKey:X}=UH("node:crypto"),U=f($),W=X(U);return{privateKey:U,publicKey:W,pem:$}}let{privateKey:w,publicKey:A}=ZE("ec",{namedCurve:"P-256"}),Y=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:A,pem:Y}}async function p8($){let{domains:w,method:A}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(A==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((j)=>j.startsWith("*."))&&A!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let Y=$.directoryUrl??($.staging===!1?SE:CE),f=qH($.accountKeyPem),X=new _Y({directoryUrl:Y,accountKey:f.privateKey,accountPublicKey:f.publicKey});await X.newAccount({email:$.email});let{order:U,orderUrl:W}=await X.newOrder(w),J=$.http01Store??pY,B=[],E=[];try{for(let C of U.authorizations){let y=await X.getAuthorization(C);if(y.status==="valid")continue;let O=_Y.selectChallenge(y,A);if(A==="dns-01"){let B$=OE(y.identifier.value),A$=X.dns01TxtValue(O.token);await $.dnsProvider.setTxt(B$,A$),B.push({name:B$,value:A$}),await NE(B$,A$,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else J.add(O.token,X.keyAuthorization(O.token)),E.push(O.token);await X.notifyChallengeReady(O.url),await X.pollAuthorization(C,{timeoutMs:$.timeoutMs})}let{privateKey:j,publicKey:T}=ZE("ec",{namedCurve:"P-256"}),F=kE({domains:w,publicKey:T,privateKey:j});await X.finalizeOrder(U.finalize,F);let H=await X.pollOrder(W,{timeoutMs:$.timeoutMs}),G=await X.downloadCertificate(H),{certPem:K,chainPem:R}=LE(G),h=R?`${K}${R}`:K,N=j.export({format:"pem",type:"pkcs8"}).toString(),M=new Date(new hH(K).validTo);return{certPem:K,keyPem:N,chainPem:R,fullChainPem:h,accountKeyPem:f.pem,notAfter:M}}finally{for(let{name:j,value:T}of B)await $.dnsProvider?.removeTxt(j,T).catch(()=>{});for(let j of E)J.remove(j)}}class iE{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],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!VB($))return!0;return QB($).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,Y){try{let f=VB(A)?QB(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}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((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.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 Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class bE{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function E9($,w){this[$]=B9.bind(null,w)}class a8{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],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!_B($))return!0;return DB($).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,Y){try{let f=_B(A)?DB(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}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((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.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 Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class s8{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function F9($,w={}){let A=Object.keys(w).sort().map((Y)=>`${Y}:${w[Y]}`).join("|");return A?`${$}:${A}`:$}function z9($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function G9($){return $.getStats().size*2}function o8($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&o(w[0])&&"id"in w[0]&&w[0].id===3&&o(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(o(w)&&o($)&&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(o($)&&"arr"in $&&Array.isArray($.arr)&&o(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&o(w[0])&&o($[0])){let Y=[...w];for(let f of $)if(o(f)&&"name"in f){if(!Y.find((X)=>o(X)&&("name"in X)&&X.name===f.name))Y.push(f)}else if(o(f)&&"path"in f){if(!Y.find((X)=>o(X)&&("path"in X)&&X.path===f.path))Y.push(f)}else if(!Y.some((X)=>iY(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!o(w)||!o($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(o(f)&&o(A[Y]))A[Y]=o8(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&o(f[0])&&o(A[Y][0])){let X=[...f];for(let U of A[Y])if(o(U)&&"name"in U){if(!X.find((W)=>o(W)&&("name"in W)&&W.name===U.name))X.push(U)}else if(o(U)&&"path"in U){if(!X.find((W)=>o(W)&&("path"in W)&&W.path===U.path))X.push(U)}else if(!X.some((W)=>iY(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function iY($,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(!iY($[A],w[A]))return!1;return!0}if(o($)&&o(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!iY($[f],w[f]))return!1}return!0}return!1}function o($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function H9($,w){if(!PE($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return o8(w,Y)}catch{return null}}catch{return null}}async function K9({name:$="",cwd:w,defaultConfig:A}){let Y=w||Z8.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=ZY(Y,`${U}${W}`),B=await H9(J,A);if(B!==null)return B}try{let U=ZY(Y,"package.json");if(PE(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return o8(A,W)}catch{}}}catch{}return A}function R9($,w={}){let A=kY.cwd();while(A.includes("storage"))A=xB(A,"..");let Y=xB(A,$||"");if(w?.relative)return VH(kY.cwd(),Y);return Y}async function h9(){try{let $=await K9({name:"clarity",defaultConfig:SY,cwd:kY.cwd(),endpoint:"",headers:{}});return{...SY,...$}}catch{return SY}}function f$(){if(i0.env.NODE_ENV==="test"||i0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function q9(){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 uE{async format($){let w=await q9(),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 bY{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={...P8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new uE,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},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...LY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...LY};return{...LY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:P8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==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 Y,f=0,X=3,U=1000;while(f<X)try{try{try{await ZH(this.config.logDirectory,cB.F_OK|cB.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await xH(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Yw.from($);try{if(!F8(this.currentLogFile))await z8(this.currentLogFile,"",{mode:420});if(Y=bB(this.currentLogFile,"a",420),kH(Y,W,{flag:"a"}),iB(Y),Y!==void 0)T8(Y),Y=void 0;if((await sw(this.currentLogFile)).size===0){if(await z8(this.currentLogFile,W,{flag:"w",mode:420}),(await sw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{T8(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 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(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((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return j8(16).toString("hex")}generateKey(){return j8(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=j8(16),Y=QH("aes-256-gcm",w,A),f=Yw.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:Yw.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=nB(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(Yw.from(Yw.concat(f)))),Y.on("error",A),Y.write($),Y.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;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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await EY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await sw(A).catch(()=>null))try{if(await uB(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await jY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await z8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await sw(A).catch(()=>null))await uB(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await EY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await jY(ow(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=PB($),Y=DH(w),f=nB();await PH(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}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()})),F8(this.currentLogFile))try{let $=bB(this.currentLogFile,"r+");iB($),T8($)}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 EY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await jY(ow(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?t.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=L$.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${t.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!f$()){let B=aE[$],E=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:t.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:t.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
68
|
-
`);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
67
|
+
`:""}}function OE($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function OB($){return new Promise((w)=>setTimeout(w,$))}function TG($){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 Ww($,w){return Buffer.concat([Buffer.from([$]),TG(w.length),w])}function _E($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let A=[],Y=$;while(Y>0)A.unshift(Y&255),Y>>=8;if(A[0]&128)A.unshift(0);w=Buffer.from(A)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return Ww(2,w)}function hw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let A=[40*w[0]+w[1]];for(let Y=2;Y<w.length;Y++){let f=w[Y],X=[f&127];f=Math.floor(f/128);while(f>0)X.unshift(f&127|128),f=Math.floor(f/128);A.push(...X)}return Ww(6,Buffer.from(A))}function X$(...$){return Ww(48,Buffer.concat($))}function QU(...$){return Ww(49,Buffer.concat($))}function DU($){return Ww(3,Buffer.concat([Buffer.from([0]),$]))}function QE($){return Ww(4,$)}function DE($){return Ww(12,Buffer.from($,"utf8"))}function kU($,w,A){let Y=128|(A?32:0)|$;return Ww(Y,w)}function NG($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let A=_U(w.x),Y=_U(w.y);if(A.length!==32||Y.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${A.length} y=${Y.length}`);return Buffer.concat([Buffer.from([4]),A,Y])}function kE($){let{domains:w,publicKey:A,privateKey:Y}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let f=X$(QU(X$(hw(HG),DE(w[0])))),X=X$(X$(hw(FG),hw(zG)),DU(NG(A))),U=w.map((G)=>kU(2,Buffer.from(G,"ascii"),!1)),W=X$(...U),J=X$(hw(RG),QE(W)),B=X$(J),E=X$(hw(KG),QU(B)),j=kU(0,E,!0),T=X$(_E(0),f,X,j),F=jG("sha256",T,Y),H=X$(hw(GG));return X$(T,H,DU(F))}function ZE($){return kE($).toString("base64url")}function hG($){if($){let{createPrivateKey:f,createPublicKey:X}=JG("node:crypto"),U=f($),W=X(U);return{privateKey:U,publicKey:W,pem:$}}let{privateKey:w,publicKey:A}=xE("ec",{namedCurve:"P-256"}),Y=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:A,pem:Y}}async function rU($){let{domains:w,method:A}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(A==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((j)=>j.startsWith("*."))&&A!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let Y=$.directoryUrl??($.staging===!1?LE:SE),f=hG($.accountKeyPem),X=new QY({directoryUrl:Y,accountKey:f.privateKey,accountPublicKey:f.publicKey});await X.newAccount({email:$.email});let{order:U,orderUrl:W}=await X.newOrder(w),J=$.http01Store??pY,B=[],E=[];try{for(let I of U.authorizations){let S=await X.getAuthorization(I);if(S.status==="valid")continue;let B0=QY.selectChallenge(S,A);if(A==="dns-01"){let V=OE(S.identifier.value),O=X.dns01TxtValue(B0.token);await $.dnsProvider.setTxt(V,O),B.push({name:V,value:O}),await yE(V,O,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else J.add(B0.token,X.keyAuthorization(B0.token)),E.push(B0.token);await X.notifyChallengeReady(B0.url),await X.pollAuthorization(I,{timeoutMs:$.timeoutMs})}let{privateKey:j,publicKey:T}=xE("ec",{namedCurve:"P-256"}),F=ZE({domains:w,publicKey:T,privateKey:j});await X.finalizeOrder(U.finalize,F);let H=await X.pollOrder(W,{timeoutMs:$.timeoutMs}),G=await X.downloadCertificate(H),{certPem:K,chainPem:R}=VE(G),N=R?`${K}${R}`:K,h=j.export({format:"pem",type:"pkcs8"}).toString(),y=new Date(new qG(K).validTo);return{certPem:K,keyPem:h,chainPem:R,fullChainPem:N,accountKeyPem:f.pem,notAfter:y}}finally{for(let{name:j,value:T}of B)await $.dnsProvider?.removeTxt(j,T).catch(()=>{});for(let j of E)J.remove(j)}}class bE{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],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!_B($))return!0;return QB($).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,Y){try{let f=_B(A)?QB(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}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((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.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 Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class cE{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function jH($,w){this[$]=EH.bind(null,w)}class sU{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],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!DB($))return!0;return kB($).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,Y){try{let f=DB(A)?kB(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}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((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.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 Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class oU{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function zH($,w={}){let A=Object.keys(w).sort().map((Y)=>`${Y}:${w[Y]}`).join("|");return A?`${$}:${A}`:$}function GH($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function HH($){return $.getStats().size*2}function eU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&e(w[0])&&"id"in w[0]&&w[0].id===3&&e(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(e(w)&&e($)&&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(e($)&&"arr"in $&&Array.isArray($.arr)&&e(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&e(w[0])&&e($[0])){let Y=[...w];for(let f of $)if(e(f)&&"name"in f){if(!Y.find((X)=>e(X)&&("name"in X)&&X.name===f.name))Y.push(f)}else if(e(f)&&"path"in f){if(!Y.find((X)=>e(X)&&("path"in X)&&X.path===f.path))Y.push(f)}else if(!Y.some((X)=>iY(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!e(w)||!e($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(e(f)&&e(A[Y]))A[Y]=eU(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&e(f[0])&&e(A[Y][0])){let X=[...f];for(let U of A[Y])if(e(U)&&"name"in U){if(!X.find((W)=>e(W)&&("name"in W)&&W.name===U.name))X.push(U)}else if(e(U)&&"path"in U){if(!X.find((W)=>e(W)&&("path"in W)&&W.path===U.path))X.push(U)}else if(!X.some((W)=>iY(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function iY($,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(!iY($[A],w[A]))return!1;return!0}if(e($)&&e(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!iY($[f],w[f]))return!1}return!0}return!1}function e($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function KH($,w){if(!iE($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return eU(w,Y)}catch{return null}}catch{return null}}async function RH({name:$="",cwd:w,defaultConfig:A}){let Y=w||xU.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=ZY(Y,`${U}${W}`),B=await KH(J,A);if(B!==null)return B}try{let U=ZY(Y,"package.json");if(iE(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return eU(A,W)}catch{}}}catch{}return A}function NH($,w={}){let A=kY.cwd();while(A.includes("storage"))A=PB(A,"..");let Y=PB(A,$||"");if(w?.relative)return _G(kY.cwd(),Y);return Y}async function qH(){try{let $=await RH({name:"clarity",defaultConfig:SY,cwd:kY.cwd(),endpoint:"",headers:{}});return{...SY,...$}}catch{return SY}}function f0(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hH(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c$<"u"){let $=c$.type;if($==="renderer"||$==="worker")return!1;return!!(c$.versions&&(c$.versions.node||c$.versions.bun))}return!1}class nE{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:$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 bY{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={...iU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new nE,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??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...LY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...LY};return{...LY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:iU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==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 Y,f=0,X=3,U=1000;while(f<X)try{try{try{await xG(this.config.logDirectory,uB.F_OK|uB.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await PG(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Xw.from($);try{if(!zU(this.currentLogFile))await GU(this.currentLogFile,"",{mode:420});if(Y=cB(this.currentLogFile,"a",420),ZG(Y,W,{flag:"a"}),bB(Y),Y!==void 0)FU(Y),Y=void 0;if((await ow(this.currentLogFile)).size===0){if(await GU(this.currentLogFile,W,{flag:"w",mode:420}),(await ow(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{FU(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 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(f0())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((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return TU(16).toString("hex")}generateKey(){return TU(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=TU(16),Y=QG("aes-256-gcm",w,A),f=Xw.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:Xw.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=vB(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(Xw.from(Xw.concat(f)))),Y.on("error",A),Y.write($),Y.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(f0())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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await EY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await ow(A).catch(()=>null))try{if(await nB(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await jY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await GU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await ow(A).catch(()=>null))await nB(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await EY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await jY(ew(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=iB($),Y=kG(w),f=vB();await iG(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}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()})),zU(this.currentLogFile))try{let $=cB(this.currentLogFile,"r+");bB($),FU($)}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(!f0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await EY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await jY(ew(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?p.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=L0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${p.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!f0()){let B=sE[$],E=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:p.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:p.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
68
|
+
`);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:p.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!f0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let J=`${X} ${this.environment}.${$.toUpperCase()}: ${U}
|
|
69
69
|
`;if(W)J+=`${W}
|
|
70
|
-
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time($){let w=performance.now();if(this.fancy&&!
|
|
71
|
-
`,J=J.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
72
|
-
`),U=Math.max(...X.map((E)=>E.length))+2,W=`┌${"─".repeat(U)}┐`,J=`└${"─".repeat(U)}┘`,B=X.map((E)=>{let j=" ".repeat(U-E.length-2);return`│ ${E}${j} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:
|
|
73
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt($){if(
|
|
74
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress($,w=""){if(!this.enabled||!this.fancy||
|
|
75
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||f$()||!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(f$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await EY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let f=ow(this.config.logDirectory,Y);if($.before)try{if((await sw(f)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${f}:`,X);continue}A.push(f)}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 Y of A)try{await jY(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function CY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&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(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let Y=[...w];for(let f of $)if(d(f)&&"name"in f){if(!Y.find((X)=>d(X)&&("name"in X)&&X.name===f.name))Y.push(f)}else if(d(f)&&"path"in f){if(!Y.find((X)=>d(X)&&("path"in X)&&X.path===f.path))Y.push(f)}else if(!Y.some((X)=>cY(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!d(w)||!d($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(d(f)&&d(A[Y]))A[Y]=CY(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&d(f[0])&&d(A[Y][0])){let X=[...f];for(let U of A[Y])if(d(U)&&"name"in U){if(!X.find((W)=>d(W)&&("name"in W)&&W.name===U.name))X.push(U)}else if(d(U)&&"path"in U){if(!X.find((W)=>d(W)&&("path"in W)&&W.path===U.path))X.push(U)}else if(!X.some((W)=>cY(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function e8($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:CY($,w);if(Array.isArray($))return A==="replace"?w:CY($,w);if(!d(w)||!d($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=CY(U,X);else if(d(X)&&d(U))Y[f]=e8(U,X,A);else Y[f]=X}return Y}function cY($,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(!cY($[A],w[A]))return!1;return!0}if(d($)&&d(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!cY($[f],w[f]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function yY($,w,A="replace"){if(!xE($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return e8(w,f,A)}catch{return null}}catch{return null}}function N9($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((G)=>G.toUpperCase()).join("_")}`;if(A)V$.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let G=m1.env[F]||m1.env[H];if(G!==void 0){if(A)V$.info(`Using environment variable ${G?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(G);else if(typeof E==="boolean")J[B]=G.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(G);if(Array.isArray(K))J[B]=K;else J[B]=G.split(",").map((R)=>R.trim())}catch{J[B]=G.split(",").map((K)=>K.trim())}else J[B]=G}}}return J}return X(f)}async function y9({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?N9($,f,X):f,B=A||m1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)V$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],G=Array.from(new Set([B,P$(B,"config"),P$(B,".config"),Y?P$(B,Y):void 0].filter(Boolean)));for(let K of G){if(X)V$.info(`Searching for configuration in: ${K}`);let R=[P$(B,"config"),P$(B,".config")].concat(Y?[P$(B,Y)]:[]).includes(K)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let h of R)for(let N of E){let M=P$(K,`${h}${N}`),C=await yY(M,J,W);if(C!==null){if(X)V$.success(`Configuration loaded from: ${M}`);return C}}}if($){let K=P$(E8(),".config",$),R=["config",`${$}.config`];if(w)R.push(`${w}.config`);if(X)V$.info(`Checking user config directory: ${K}`);for(let h of R)for(let N of E){let M=P$(K,`${h}${N}`),C=await yY(M,J,W);if(C!==null){if(X)V$.success(`Configuration loaded from user config directory: ${M}`);return C}}}if($){let K=P$(E8(),".config"),R=[`.${$}.config`];if(w)R.push(`.${w}.config`);if(X)V$.info(`Checking user config directory for dotfile configs: ${K}`);for(let h of R)for(let N of E){let M=P$(K,`${h}${N}`),C=await yY(M,J,W);if(C!==null){if(X)V$.success(`Configuration loaded from user config directory dotfile: ${M}`);return C}}}if($){let K=E8(),R=[`.${$}.config`,`.${$}`];if(w)R.push(`.${w}.config`),R.push(`.${w}`);if(X)V$.info(`Checking user home directory for dotfile configs: ${K}`);for(let h of R)for(let N of E){let M=P$(K,`${h}${N}`),C=await yY(M,J,W);if(C!==null){if(X)V$.success(`Configuration loaded from user home directory: ${M}`);return C}}}try{let K=P$(B,"package.json");if(xE(K)){let R=await import(K),h=R[$];if(!h&&w){if(h=R[w],h&&X)V$.success(`Using alias "${w}" configuration from package.json`)}if(h&&typeof h==="object"&&!Array.isArray(h))try{if(X)V$.success(`Configuration loaded from package.json: ${h===R[$]?$:w}`);return e8(J,h,W)}catch(N){if(X)V$.warn("Failed to merge package.json config:",N)}}}catch(K){if(X)V$.warn("Failed to load package.json:",K)}if(X)V$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function M9($,w={}){let A=DY.cwd();while(A.includes("storage"))A=ZB(A,"..");let Y=ZB(A,$||"");if(w?.relative)return LH(DY.cwd(),Y);return Y}async function I9(){try{let $=await y9({name:"clarity",alias:"logging",defaultConfig:OY,cwd:DY.cwd()});return{...OY,...$||{}}}catch{return OY}}function z$(){if(b0.env.NODE_ENV==="test"||b0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function C9(){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 nE{async format($){let w=await C9(),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:A1.pid,hostname:w(),environment:A1.env.NODE_ENV||"development",platform:A1.platform,version:A1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:A1.env.NODE_ENV||A1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class uY{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={...i8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new nE,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},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...VY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...VY};return{...VY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:i8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==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 Y,f=0,X=3,U=1000;while(f<X)try{try{try{await nH(this.config.logDirectory,lB.F_OK|lB.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await vH(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Z0.from($);try{if(!TY(this.currentLogFile))await K8(this.currentLogFile,"",{mode:420});if(Y=dB(this.currentLogFile,"a",420),uH(Y,W,{flag:"a"}),mB(Y),Y!==void 0)H8(Y),Y=void 0;if((await $1(this.currentLogFile)).size===0){if(await K8(this.currentLogFile,W,{flag:"w",mode:420}),(await $1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{H8(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 w1(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 w1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return w1(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((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return G8(16).toString("hex")}generateKey(){return G8(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=G8(16),Y=iH("aes-256-gcm",w,A),f=Z0.isBuffer($)?$:Z0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=Z0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=tB(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(Z0.from(Z0.concat(f)))),Y.on("error",A),Y.write($),Y.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 $1(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await FY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await $1(A).catch(()=>null))try{if(await gB(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await zY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await K8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await $1(A).catch(()=>null))await gB(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await FY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await zY(w1(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=vB($),Y=cH(w),f=tB();await lH(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),TY(this.currentLogFile))try{let $=dB(this.currentLogFile,"r+");mB($),H8($)}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 FY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await zY(w1(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()?Z.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||z$())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:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=v.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${Z.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=Z.underline(Z.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>Z.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>Z.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>Z.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>Z.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>Z.strikethrough(Y)),w}supportsHyperlinks(){if(z$())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(mH(w)||w.startsWith("./")||w.startsWith("../"))w=dH(w);else return null;return TY(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":sE[$],T=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:Z.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:Z.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
76
|
-
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
70
|
+
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time($){let w=performance.now();if(this.fancy&&!f0()){let A=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:p.blue("◐"),tag:A,message:`${p.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),J=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)J+=` ${JSON.stringify(A)}`;if(J+=`
|
|
71
|
+
`,J=J.replace(this.ANSI_PATTERN,""),this.fancy&&!f0()){let B=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:p.green("✓"),tag:B,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!f0())console.error(J.trim());await this.writeToFile(J)}}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 bY(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(f0())throw Error("createReadStream is not supported in browser environments");if(!zU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return iB(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 Y=Xw.isBuffer($)?$:Xw.from($,"base64"),f=Y.slice(0,16),X=Y.slice(-16),U=Y.slice(16,-16),W=DG("aes-256-gcm",A,f);return W.setAuthTag(X),Xw.concat([W.update(U),W.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return f0()}isServerMode(){return!f0()}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),Y=this.formatFileTimestamp(w);if(this.fancy&&!f0()){let X=$.split(`
|
|
72
|
+
`),U=Math.max(...X.map((E)=>E.length))+2,W=`┌${"─".repeat(U)}┐`,J=`└${"─".repeat(U)}┘`,B=X.map((E)=>{let j=" ".repeat(U-E.length-2);return`│ ${E}${j} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:p.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:p.cyan(W)})),B.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:A,message:p.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:p.cyan(J),showTimestamp:!1}))}else if(!f0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let f=`${Y} ${this.environment}.INFO: [BOX] ${$}
|
|
73
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt($){if(f0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${p.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();L0.stdin.removeListener("data",A);try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!1)}catch{}L0.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!0)}catch{}L0.stdin.resume(),L0.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,X=0;if(A=$.replace(f,(U,W)=>{if(W==="%")return"%";if(X>=w.length)return U;let J=w[X++];switch(W){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 U}}),X<w.length)A+=` ${w.slice(X).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!f0()){let f=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",X=p.blue("◐");console.error(`${X} ${f} ${p.cyan(A)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
74
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress($,w=""){if(!this.enabled||!this.fancy||f0()||$<=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:(Y,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||f0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,Y)),f!==void 0)this.activeProgressBar.message=f;let X=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,X)},finish:(Y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||f0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Y!==void 0)this.activeProgressBar.message=Y;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Y,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||f0())return;L0.stdout.write(`${"\r".padEnd(L0.stdout.columns||80)}\r`),this.log(f,Y),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||f0()||!L0.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=p.green("━".repeat(Y)),U=p.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=w||A===100?p.green("✓"):p.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${p.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=L0.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,L0.stdout.write($.lastRenderedLine),w)L0.stdout.write(`
|
|
75
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||f0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(f0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await EY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let f=ew(this.config.logDirectory,Y);if($.before)try{if((await ow(f)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${f}:`,X);continue}A.push(f)}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 Y of A)try{await jY(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function CY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&l(w[0])&&"id"in w[0]&&w[0].id===3&&l(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(l(w)&&l($)&&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(l($)&&"arr"in $&&Array.isArray($.arr)&&l(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&l(w[0])&&l($[0])){let Y=[...w];for(let f of $)if(l(f)&&"name"in f){if(!Y.find((X)=>l(X)&&("name"in X)&&X.name===f.name))Y.push(f)}else if(l(f)&&"path"in f){if(!Y.find((X)=>l(X)&&("path"in X)&&X.path===f.path))Y.push(f)}else if(!Y.some((X)=>cY(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!l(w)||!l($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(l(f)&&l(A[Y]))A[Y]=CY(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&l(f[0])&&l(A[Y][0])){let X=[...f];for(let U of A[Y])if(l(U)&&"name"in U){if(!X.find((W)=>l(W)&&("name"in W)&&W.name===U.name))X.push(U)}else if(l(U)&&"path"in U){if(!X.find((W)=>l(W)&&("path"in W)&&W.path===U.path))X.push(U)}else if(!X.some((W)=>cY(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function $8($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:CY($,w);if(Array.isArray($))return A==="replace"?w:CY($,w);if(!l(w)||!l($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=CY(U,X);else if(l(X)&&l(U))Y[f]=$8(U,X,A);else Y[f]=X}return Y}function cY($,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(!cY($[A],w[A]))return!1;return!0}if(l($)&&l(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!cY($[f],w[f]))return!1}return!0}return!1}function l($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function yY($,w,A="replace"){if(!PE($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return $8(w,f,A)}catch{return null}}catch{return null}}function yH($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((G)=>G.toUpperCase()).join("_")}`;if(A)O0.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let G=m1.env[F]||m1.env[H];if(G!==void 0){if(A)O0.info(`Using environment variable ${G?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(G);else if(typeof E==="boolean")J[B]=G.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(G);if(Array.isArray(K))J[B]=K;else J[B]=G.split(",").map((R)=>R.trim())}catch{J[B]=G.split(",").map((K)=>K.trim())}else J[B]=G}}}return J}return X(f)}async function MH({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?yH($,f,X):f,B=A||m1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)O0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],G=Array.from(new Set([B,P0(B,"config"),P0(B,".config"),Y?P0(B,Y):void 0].filter(Boolean)));for(let K of G){if(X)O0.info(`Searching for configuration in: ${K}`);let R=[P0(B,"config"),P0(B,".config")].concat(Y?[P0(B,Y)]:[]).includes(K)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let N of R)for(let h of E){let y=P0(K,`${N}${h}`),I=await yY(y,J,W);if(I!==null){if(X)O0.success(`Configuration loaded from: ${y}`);return I}}}if($){let K=P0(jU(),".config",$),R=["config",`${$}.config`];if(w)R.push(`${w}.config`);if(X)O0.info(`Checking user config directory: ${K}`);for(let N of R)for(let h of E){let y=P0(K,`${N}${h}`),I=await yY(y,J,W);if(I!==null){if(X)O0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let K=P0(jU(),".config"),R=[`.${$}.config`];if(w)R.push(`.${w}.config`);if(X)O0.info(`Checking user config directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=P0(K,`${N}${h}`),I=await yY(y,J,W);if(I!==null){if(X)O0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let K=jU(),R=[`.${$}.config`,`.${$}`];if(w)R.push(`.${w}.config`),R.push(`.${w}`);if(X)O0.info(`Checking user home directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=P0(K,`${N}${h}`),I=await yY(y,J,W);if(I!==null){if(X)O0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let K=P0(B,"package.json");if(PE(K)){let R=await import(K),N=R[$];if(!N&&w){if(N=R[w],N&&X)O0.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(X)O0.success(`Configuration loaded from package.json: ${N===R[$]?$:w}`);return $8(J,N,W)}catch(h){if(X)O0.warn("Failed to merge package.json config:",h)}}}catch(K){if(X)O0.warn("Failed to load package.json:",K)}if(X)O0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function IH($,w={}){let A=DY.cwd();while(A.includes("storage"))A=xB(A,"..");let Y=xB(A,$||"");if(w?.relative)return VG(DY.cwd(),Y);return Y}async function CH(){try{let $=await MH({name:"clarity",alias:"logging",defaultConfig:VY,cwd:DY.cwd()});return{...VY,...$||{}}}catch{return VY}}function z0(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function SH(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof u$<"u"){let $=u$.type;if($==="renderer"||$==="worker")return!1;return!!(u$.versions&&(u$.versions.node||u$.versions.bun))}return!1}class vE{async format($){let w=await SH(),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:Y1.pid,hostname:w(),environment:Y1.env.NODE_ENV||"development",platform:Y1.platform,version:Y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Y1.env.NODE_ENV||Y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class uY{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={...bU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new vE,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??m.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...OY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...OY};return{...OY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:bU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!z0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let Y,f=0,X=3,U=1000;while(f<X)try{try{try{await vG(this.config.logDirectory,gB.F_OK|gB.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await mG(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P$.from($);try{if(!TY(this.currentLogFile))await RU(this.currentLogFile,"",{mode:420});if(Y=lB(this.currentLogFile,"a",420),nG(Y,W,{flag:"a"}),dB(Y),Y!==void 0)KU(Y),Y=void 0;if((await w1(this.currentLogFile)).size===0){if(await RU(this.currentLogFile,W,{flag:"w",mode:420}),(await w1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{KU(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 A1(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 A1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return A1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(z0())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((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return HU(16).toString("hex")}generateKey(){return HU(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=HU(16),Y=bG("aes-256-gcm",w,A),f=P$.isBuffer($)?$:P$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=P$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=pB(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(P$.from(P$.concat(f)))),Y.on("error",A),Y.write($),Y.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(z0())return;if(!this.shouldWriteToFile())return;let $=await w1(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await FY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await w1(A).catch(()=>null))try{if(await tB(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await zY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await RU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await w1(A).catch(()=>null))await tB(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await FY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await zY(A1(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=mB($),Y=uG(w),f=pB();await gG(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),TY(this.currentLogFile))try{let $=lB(this.currentLogFile,"r+");dB($),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(!z0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await FY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await zY(A1(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||z0())return!1;let $=typeof m.env.NO_COLOR<"u",w=m.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof m.stderr<"u"&&m.stderr.isTTY||typeof m.stdout<"u"&&m.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=m.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${x.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=x.underline(x.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>x.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>x.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>x.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>x.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>x.strikethrough(Y)),w}supportsHyperlinks(){if(z0())return!1;let $=m.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=m.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(dG(w)||w.startsWith("./")||w.startsWith("../"))w=lG(w);else return null;return TY(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":oE[$],T=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:x.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:x.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
76
|
+
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:x.gray(` ${G}`),level:$,showTimestamp:!1}))}break}}else if(!z0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
77
77
|
`;if(W)E+=`${W}
|
|
78
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(f,X)=>{},finish:(f)=>{},interrupt:(f,X)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
79
|
-
`);if(this[X==="warning"?"warn":X](f),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
80
|
-
`,J=J.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?
|
|
81
|
-
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:
|
|
82
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
83
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
84
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
78
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(f,X)=>{},finish:(f)=>{},interrupt:(f,X)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!z0()&&m.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,X)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),X!==void 0)this.activeProgressBar.message=X;if(this.shouldStyleConsole()&&!z0()&&m.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,X="info")=>{if(!z0()&&m.stdout.isTTY)m.stdout.write(`
|
|
79
|
+
`);if(this[X==="warning"?"warn":X](f),this.activeProgressBar&&this.shouldStyleConsole()&&!z0()&&m.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)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":x.blue("◐"),tag:A,message:`${x.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),J=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)J+=` ${JSON.stringify(A)}`;if(J+=`
|
|
80
|
+
`,J=J.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":x.green("✓"),tag:B,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!z0())console.error(J.trim());if(this.shouldWriteToFile())await this.writeToFile(J)}}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 uY(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(z0())throw Error("createReadStream is not supported in browser environments");if(!TY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return mB(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 Y=P$.isBuffer($)?$:P$.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=cG("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=P$.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return z0()}isServerMode(){return!z0()}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),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
81
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:x.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:x.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:x.cyan(E),showTimestamp:!1}))}else if(!z0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
82
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(z0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${x.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();m.stdin.removeListener("data",A);try{if(typeof m.stdin.setRawMode==="function")m.stdin.setRawMode(!1)}catch{}m.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof m.stdin.setRawMode==="function")m.stdin.setRawMode(!0)}catch{}m.stdin.resume(),m.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,W=0;if(A=$.replace(U,(J,B)=>{if(B==="%")return"%";if(W>=w.length)return J;let E=w[W++];switch(B){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 J}}),W<w.length)A+=` ${w.slice(W).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${x.blue("◐")} `;console.error(`${W}${U} ${x.cyan(Y)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
83
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!m.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=x.green("━".repeat(Y)),U=x.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?x.green("✓"):x.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=m.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,m.stdout.write($.lastRenderedLine),w)m.stdout.write(`
|
|
84
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||z0()||!m.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(z0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await FY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let f=A1(this.config.logDirectory,Y);if($.before)try{if((await w1(f)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${f}:`,X);continue}A.push(f)}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 Y of A)try{await zY(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function mE($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:f=()=>!0,fallback:X}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(J){if(U=J instanceof Error?J:Error(String(J)),W===A||!f(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(X!==void 0)return X;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function dE($){return $ instanceof r0}function LH($){return $ instanceof nY}function VH($){if(dE($))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 aY{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:Y,useCamelCase:f=!0,useBackwardCompatibility:X=!0,customParsers:U={},verbose:W=!1,trackPerformance:J=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix($),j={...w};return this.processObject(j,[],E,{useCamelCase:f,useBackwardCompatibility:X,customParsers:U,verbose:W,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return t1.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=U.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),J=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,U,A,Y);else{let E=GY.env[J]||(B?GY.env[B]:void 0);if(E!==void 0){if(Y.verbose){let j=GY.env[J]?J:B}try{$[f]=this.parseEnvironmentValue(E,typeof X,J,Y.customParsers,Y.configName)}catch(j){if(j instanceof vY)throw j;throw Jw.envVar(J,E,typeof X,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,f){for(let[X,U]of Object.entries(Y))try{return U($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw Jw.envVar(A,$,`${w} (via ${X.name} parser)`,f)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,f]of Object.entries(GY.env))if(Y.startsWith(A)&&f!==void 0)w[Y]=f;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(f){Y.push(`Cannot parse value "${w}" as ${A}: ${f}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:f="text"}=A,X=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],X,U),f){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=`${A}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,U,A,Y);else Y.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${U.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
85
85
|
|
|
86
86
|
`;for(let Y of $)A+=`${Y.key}
|
|
87
87
|
`,A+=` Type: ${Y.type}
|
|
@@ -93,25 +93,25 @@ export type ConfigOf = Config
|
|
|
93
93
|
`;A+=`| Variable | Type | Description | Example |
|
|
94
94
|
`,A+=`|----------|------|-------------|----------|
|
|
95
95
|
`;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
96
|
-
`;return A}}function O9($,w){let A=pE("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function dE($,w,A={}){return lE($,w,A,new WeakMap)}function lE($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return gE($,w,f,Y);if(!X0(w)||!X0($))return w;return D9($,w,A,Y)}function gE($,w,A,Y){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 V9($,w);case"smart":return Q9($,w,Y);default:return w}return w}function V9($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>x8(f,Y)))A.push(Y);return A}function Q9($,w,A){if(w.length===0)return $;if($.length===0)return w;if(X0(w[0])&&X0($[0]))return _9($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function _9($,w,A){let Y=[...w];for(let f of $){if(!X0(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((J)=>X0(J)&&(W in J)&&J[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function D9($,w,A,Y){let f=w;if(X0(f)&&Y.has(f))return Y.get(f);let X={...$};if(X0(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(X0(W)&&X0(J))X[U]=lE(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=gE(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function $U($,w,A="replace"){return dE($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function x8($,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(!x8($[A],w[A]))return!1;return!0}if(X0($)&&X0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!x8($[f],w[f]))return!1}return!0}return!1}function X0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class sY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=J1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!HY($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new d1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new d1($,Error("Configuration must export a valid object"),"unknown");let H={config:$U(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)J1.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?Xw.configLoad($,B):Xw.configLoad($,Error(String(B)))}};if(U)return t1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(R8(w,`${X}${U}`));return f}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 vE(async()=>{return HY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!HY($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=R8($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=R8($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}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(!HY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}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(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class wU{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await t1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!gH(w))throw new l1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new l1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.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)Y.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($))Y.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)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.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($))Y.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 f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}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:eE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class AU{fileLoader=new sY;envProcessor=new aY;validator=new wU;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)H0.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw H0.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||qw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(i$(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw Xw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?u1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)H0.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)H0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?u1($,A,f):A,W=[i$(aw(),".config",$),i$(aw(),".config"),aw()];for(let J of W){if(f)H0.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)H0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?u1($,Y,X):Y;try{let J=i$(A,"package.json");if(!k8(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)H0.success(`Configuration loaded from package.json: ${j}`);return{config:$U(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)H0.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:u1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw Xw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return J1.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);J1.set(f,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([$,i$($,"config"),i$($,".config"),w?i$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(i$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[i$(aw(),".config",$),i$(aw(),".config"),aw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function AE($){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 k9($){return n0.loadConfig({...$,__strictErrorHandling:!0})}async function tE($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await n0.loadConfig($);else Y=await n0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)H0.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let U=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await n0.applyEnvironmentVariables(U.name||"",w,!0,U.verbose||!1))?.config??w;return w}}async function Z9($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await n0.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"&&AE(A)))return(await n0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await n0.loadConfig({...$,cwd:$.cwd||qw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&AE(w)))return(await n0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function x9($,w,A="replace"){let Y=new sY;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function u1($,w,A=!1){let Y=new aY,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=qw.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function P9($){let w=i$(qw.cwd(),$.configDir),A=i$(qw.cwd(),$.generatedDir),Y=i$(A,"config-types.ts");if(!k8(kB(Y)))MH(kB(Y),{recursive:!0,mode:511});let f=k8(w)?IH(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${j5}
|
|
96
|
+
`;return A}}function OH($,w){let A=rE("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function lE($,w,A={}){return gE($,w,A,new WeakMap)}function gE($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return tE($,w,f,Y);if(!J$(w)||!J$($))return w;return kH($,w,A,Y)}function tE($,w,A,Y){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 _H($,w);case"smart":return QH($,w,Y);default:return w}return w}function _H($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>PU(f,Y)))A.push(Y);return A}function QH($,w,A){if(w.length===0)return $;if($.length===0)return w;if(J$(w[0])&&J$($[0]))return DH($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function DH($,w,A){let Y=[...w];for(let f of $){if(!J$(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((J)=>J$(J)&&(W in J)&&J[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function kH($,w,A,Y){let f=w;if(J$(f)&&Y.has(f))return Y.get(f);let X={...$};if(J$(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(J$(W)&&J$(J))X[U]=gE(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=tE(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function w8($,w,A="replace"){return lE($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function PU($,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(!PU($[A],w[A]))return!1;return!0}if(J$($)&&J$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!PU($[f],w[f]))return!1}return!0}return!1}function J$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class sY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=W1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!HY($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new d1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new d1($,Error("Configuration must export a valid object"),"unknown");let H={config:w8(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)W1.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?Jw.configLoad($,B):Jw.configLoad($,Error(String(B)))}};if(U)return t1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(NU(w,`${X}${U}`));return f}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 mE(async()=>{return HY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!HY($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=NU($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=NU($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}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(!HY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}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(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class A8{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await t1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!tG(w))throw new l1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new l1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.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)Y.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($))Y.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)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.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($))Y.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 f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}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:$j},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Y8{fileLoader=new sY;envProcessor=new aY;validator=new A8;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)R$.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw R$.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||yw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(i0(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw Jw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?u1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)R$.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)R$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?u1($,A,f):A,W=[i0(sw(),".config",$),i0(sw(),".config"),sw()];for(let J of W){if(f)R$.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)R$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?u1($,Y,X):Y;try{let J=i0(A,"package.json");if(!ZU(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)R$.success(`Configuration loaded from package.json: ${j}`);return{config:w8(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)R$.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:u1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw Jw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return W1.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);W1.set(f,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([$,i0($,"config"),i0($,".config"),w?i0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(i0(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[i0(sw(),".config",$),i0(sw(),".config"),sw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function YE($){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 m$.loadConfig({...$,__strictErrorHandling:!0})}async function pE($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await m$.loadConfig($);else Y=await m$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)R$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let U=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await m$.applyEnvironmentVariables(U.name||"",w,!0,U.verbose||!1))?.config??w;return w}}async function xH($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await m$.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"&&YE(A)))return(await m$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await m$.loadConfig({...$,cwd:$.cwd||yw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&YE(w)))return(await m$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function PH($,w,A="replace"){let Y=new sY;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function u1($,w,A=!1){let Y=new aY,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=yw.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function iH($){let w=i0(yw.cwd(),$.configDir),A=i0(yw.cwd(),$.generatedDir),Y=i0(A,"config-types.ts");if(!ZU(ZB(Y)))IG(ZB(Y),{recursive:!0,mode:511});let f=ZU(w)?CG(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${T5}
|
|
97
97
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
98
|
-
`;
|
|
99
|
-
${f.map((J)=>{let B=
|
|
98
|
+
`;SG(Y,X,{mode:438})}function bH($){let w=null,A=null,Y=()=>{if(!A)A=pE($).then((X)=>{return w=X,X},(X)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)R$.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return U});return A},f="defaultConfig"in $?$.defaultConfig:{};return w=f,Y(),new Proxy({},{get(X,U){if(w)return w[U];let W=f[U];return Y(),W},has(X,U){return U in(w||f)},ownKeys(){return Object.keys(w||f)},getOwnPropertyDescriptor(X,U){return Object.getOwnPropertyDescriptor(w||f,U)},set(X,U,W){if(!w)w={...f};return w[U]=W,!0}})}function cH($){let w=rB(aG.cwd(),$?.configDir||"./config");function A(){if(!pG(w))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=rG(w).filter((J)=>f.has(qU(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),W=new Map;for(let{base:J,file:B}of U){let E=qU(B).toLowerCase(),j=W.get(J);if(!j){W.set(J,B);continue}let T=qU(j).toLowerCase();if(X.indexOf(E)<X.indexOf(T))W.set(J,B)}return Array.from(W.entries()).map(([J,B])=>({base:J,file:B})).sort((J,B)=>J.base.localeCompare(B.base))}function Y(){let f=A(),X=f.map((J)=>J.base),U=X.length?X.map((J)=>`'${J}'`).join(" | "):"string",W=f.length?`{
|
|
99
|
+
${f.map((J)=>{let B=rB(w,J.file).replace(/\\/g,"/");return` '${J.base}': typeof import('${B}').default`}).join(`,
|
|
100
100
|
`)}
|
|
101
101
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
102
102
|
export type ConfigByName = ${W}
|
|
103
103
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
104
104
|
export type ConfigOf = Config
|
|
105
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function F5($,w={}){let A=xY.cwd();while(A.includes("storage"))A=rB(A,"..");let Y=rB(A,$||"");if(w?.relative)return sH(xY.cwd(),Y);return Y}function H$(){if(c0.env.NODE_ENV==="test"||c0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function G5(){if(c0.env.NODE_ENV==="test"||c0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c0<"u"){let $=c0.type;if($==="renderer"||$==="worker")return!1;return!!(c0.versions&&(c0.versions.node||c0.versions.bun))}return!1}class Yj{async format($){let w=await G5(),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:X1.pid,hostname:w(),environment:X1.env.NODE_ENV||"development",platform:X1.platform,version:X1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:X1.env.NODE_ENV||X1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class oY{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 Yj,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??m.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...O8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...O8};return{...O8,...$.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(([,Y])=>Y!==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 Y,f=0,X=3,U=1000;while(f<X)try{try{try{await A9(this.config.logDirectory,eB.F_OK|eB.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await Y9(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:x0.from($);try{if(!KY(this.currentLogFile))await y8(this.currentLogFile,"",{mode:420});if(Y=oB(this.currentLogFile,"a",420),w9(Y,W,{flag:"a"}),sB(Y),Y!==void 0)N8(Y),Y=void 0;if((await Y1(this.currentLogFile)).size===0){if(await y8(this.currentLogFile,W,{flag:"w",mode:420}),(await Y1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{N8(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 f1(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 f1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return f1(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((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return q8(16).toString("hex")}generateKey(){return q8(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=q8(16),Y=oH("aes-256-gcm",w,A),f=x0.isBuffer($)?$:x0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=x0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=wE(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(x0.from(x0.concat(f)))),Y.on("error",A),Y.write($),Y.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 Y1(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await RY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await Y1(A).catch(()=>null))try{if(await $E(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await hY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await y8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await Y1(A).catch(()=>null))await $E(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await RY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await hY(f1(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=aB($),Y=$9(w),f=wE();await U9(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),KY(this.currentLogFile))try{let $=oB(this.currentLogFile,"r+");sB($),N8($)}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 RY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await hY(f1(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()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H$())return!1;let $=typeof m.env.NO_COLOR<"u",w=m.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof m.stderr<"u"&&m.stderr.isTTY||typeof m.stdout<"u"&&m.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=m.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${b.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=b.underline(b.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>b.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>b.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>b.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>b.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>b.strikethrough(Y)),w}supportsHyperlinks(){if(H$())return!1;let $=m.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=m.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(f9(w)||w.startsWith("./")||w.startsWith("../"))w=X9(w);else return null;return KY(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":q5[$],T=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:b.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:b.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
106
|
-
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
105
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function z5($,w={}){let A=xY.cwd();while(A.includes("storage"))A=aB(A,"..");let Y=aB(A,$||"");if(w?.relative)return oG(xY.cwd(),Y);return Y}function H0(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function H5(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n$<"u"){let $=n$.type;if($==="renderer"||$==="worker")return!1;return!!(n$.versions&&(n$.versions.node||n$.versions.bun))}return!1}class fj{async format($){let w=await H5(),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:U1.pid,hostname:w(),environment:U1.env.NODE_ENV||"development",platform:U1.platform,version:U1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:U1.env.NODE_ENV||U1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class oY{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 fj,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},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...OU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...OU};return{...OU,...$.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(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let Y,f=0,X=3,U=1000;while(f<X)try{try{try{await YH(this.config.logDirectory,$E.F_OK|$E.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await fH(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:i$.from($);try{if(!KY(this.currentLogFile))await MU(this.currentLogFile,"",{mode:420});if(Y=eB(this.currentLogFile,"a",420),AH(Y,W,{flag:"a"}),oB(Y),Y!==void 0)yU(Y),Y=void 0;if((await f1(this.currentLogFile)).size===0){if(await MU(this.currentLogFile,W,{flag:"w",mode:420}),(await f1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{yU(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return X1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return X1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return X1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(H0())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((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return hU(16).toString("hex")}generateKey(){return hU(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=hU(16),Y=eG("aes-256-gcm",w,A),f=i$.isBuffer($)?$:i$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=i$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=AE(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(i$.from(i$.concat(f)))),Y.on("error",A),Y.write($),Y.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(H0())return;if(!this.shouldWriteToFile())return;let $=await f1(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await RY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await f1(A).catch(()=>null))try{if(await wE(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await NY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await MU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await f1(A).catch(()=>null))await wE(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await RY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await NY(X1(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=sB($),Y=wH(w),f=AE();await JH(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),KY(this.currentLogFile))try{let $=eB(this.currentLogFile,"r+");oB($),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(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await RY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await NY(X1(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()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())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:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=d.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${c.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=c.underline(c.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>c.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>c.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>c.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>c.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>c.strikethrough(Y)),w}supportsHyperlinks(){if(H0())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(XH(w)||w.startsWith("./")||w.startsWith("../"))w=UH(w);else return null;return KY(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":h5[$],T=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:c.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:c.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
106
|
+
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:c.gray(` ${G}`),level:$,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
107
107
|
`;if(W)E+=`${W}
|
|
108
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(f,X)=>{},finish:(f)=>{},interrupt:(f,X)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
109
|
-
`);if(this[X==="warning"?"warn":X](f),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
110
|
-
`,J=J.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?
|
|
111
|
-
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:
|
|
112
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
113
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
114
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
108
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(f,X)=>{},finish:(f)=>{},interrupt:(f,X)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,X)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),X!==void 0)this.activeProgressBar.message=X;if(this.shouldStyleConsole()&&!H0()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,X="info")=>{if(!H0()&&d.stdout.isTTY)d.stdout.write(`
|
|
109
|
+
`);if(this[X==="warning"?"warn":X](f),this.activeProgressBar&&this.shouldStyleConsole()&&!H0()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":c.blue("◐"),tag:A,message:`${c.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),J=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)J+=` ${JSON.stringify(A)}`;if(J+=`
|
|
110
|
+
`,J=J.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":c.green("✓"),tag:B,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!H0())console.error(J.trim());if(this.shouldWriteToFile())await this.writeToFile(J)}}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 oY(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(H0())throw Error("createReadStream is not supported in browser environments");if(!KY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return sB(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 Y=i$.isBuffer($)?$:i$.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=$H("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=i$.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return H0()}isServerMode(){return!H0()}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),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
111
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:c.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:c.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:c.cyan(E),showTimestamp:!1}))}else if(!H0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
112
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(H0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${c.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.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(f==="y"||f==="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 U=/%([sdijfo%])/g,W=0;if(A=$.replace(U,(J,B)=>{if(B==="%")return"%";if(W>=w.length)return J;let E=w[W++];switch(B){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 J}}),W<w.length)A+=` ${w.slice(W).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${c.blue("◐")} `;console.error(`${W}${U} ${c.cyan(Y)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
113
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}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))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=c.green("━".repeat(Y)),U=c.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?c.green("✓"):c.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=d.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,d.stdout.write($.lastRenderedLine),w)d.stdout.write(`
|
|
114
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||H0()||!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(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await RY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let f=X1(this.config.logDirectory,Y);if($.before)try{if((await f1(f)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${f}:`,X);continue}A.push(f)}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 Y of A)try{await NY(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function y5($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:f=()=>!0,fallback:X}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(J){if(U=J instanceof Error?J:Error(String(J)),W===A||!f(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(X!==void 0)return X;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class X8{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:Y,useCamelCase:f=!0,useBackwardCompatibility:X=!0,customParsers:U={},verbose:W=!1,trackPerformance:J=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix($),j={...w};return this.processObject(j,[],E,{useCamelCase:f,useBackwardCompatibility:X,customParsers:U,verbose:W,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return aU.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=U.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),J=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,U,A,Y);else{let E=qY.env[J]||(B?qY.env[B]:void 0);if(E!==void 0){if(Y.verbose){let j=qY.env[J]?J:B}try{$[f]=this.parseEnvironmentValue(E,typeof X,J,Y.customParsers,Y.configName)}catch(j){if(j instanceof f8)throw j;throw B1.envVar(J,E,typeof X,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,f){for(let[X,U]of Object.entries(Y))try{return U($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw B1.envVar(A,$,`${w} (via ${X.name} parser)`,f)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,f]of Object.entries(qY.env))if(Y.startsWith(A)&&f!==void 0)w[Y]=f;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(f){Y.push(`Cannot parse value "${w}" as ${A}: ${f}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:f="text"}=A,X=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],X,U),f){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=`${A}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,U,A,Y);else Y.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${U.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
115
115
|
|
|
116
116
|
`;for(let Y of $)A+=`${Y.key}
|
|
117
117
|
`,A+=` Type: ${Y.type}
|
|
@@ -123,30 +123,30 @@ export type ConfigOf = Config
|
|
|
123
123
|
`;A+=`| Variable | Type | Description | Example |
|
|
124
124
|
`,A+=`|----------|------|-------------|----------|
|
|
125
125
|
`;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
126
|
-
`;return A}}function y5($,w,A={}){return jj($,w,A,new WeakMap)}function jj($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return Tj($,w,f,Y);if(!U0(w)||!U0($))return w;return S5($,w,A,Y)}function Tj($,w,A,Y){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 M5($,w);case"smart":return I5($,w,Y);default:return w}return w}function M5($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>d8(f,Y)))A.push(Y);return A}function I5($,w,A){if(w.length===0)return $;if($.length===0)return w;if(U0(w[0])&&U0($[0]))return C5($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function C5($,w,A){let Y=[...w];for(let f of $){if(!U0(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((J)=>U0(J)&&(W in J)&&J[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function S5($,w,A,Y){let f=w;if(U0(f)&&Y.has(f))return Y.get(f);let X={...$};if(U0(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(U0(W)&&U0(J))X[U]=jj(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=Tj(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function Fj($,w,A="replace"){return y5($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function d8($,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(!d8($[A],w[A]))return!1;return!0}if(U0($)&&U0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!d8($[f],w[f]))return!1}return!0}return!1}function U0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class zj{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=PY.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!NY($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new dY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new dY($,Error("Configuration must export a valid object"),"unknown");let H={config:Fj(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)PY.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?W1.configLoad($,B):W1.configLoad($,Error(String(B)))}};if(U)return r8.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(M8(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of Y){if(!X)continue;if(A.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)A.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let f=new Set;return A.filter((X)=>{if(!X||f.has(X))return!1;return f.add(X),!0})}checkFileAccess($){return N5(async()=>{return NY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!NY($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=M8($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=M8($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}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(!NY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}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(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class Gj{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await r8.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!J9(w))throw new lY(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new lY(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.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)Y.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($))Y.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)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.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($))Y.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 f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}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:L5},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function O5($){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 Hj{fileLoader=new zj;envProcessor=new fU;validator=new Gj;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)P0.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let J=Date.now()-w;throw P0.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||rY.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(f0(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw W1.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${O5(f)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?MY($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)P0.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)P0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?MY($,A,f):A,W=[f0(rw(),".config",$),f0(rw(),".config"),rw()];for(let J of W){if(f)P0.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)P0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?MY($,Y,X):Y;try{let J=f0(A,"package.json");if(!NH(J))return null;let B={};try{B=JSON.parse(yH(J,"utf8"))}catch(T){if(X)P0.warn("Failed to parse package.json:",[T instanceof Error?T:Error(String(T))]);return null}let E=B[$],j=$;if(!E&&w){let T=Array.isArray(w)?w:[w];for(let F of T){if(!F)continue;if(B[F]){E=B[F],j=F;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)P0.success(`Configuration loaded from package.json: ${j}`);return{config:Fj(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)P0.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:MY($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw W1.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return PY.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);PY.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}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([$,f0($,"config"),f0($,".config"),w?f0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(f0(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[f0(rw(),".config",$),f0(rw(),".config"),rw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function MY($,w,A=!1){let Y=new fU,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=rY.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function l8($,w){let A=[];function Y(f){let X;try{X=GE.readdirSync(f)}catch{return}for(let U of X){let W=G0.join(f,U);try{if(GE.statSync(W).isDirectory())Y(W);else if(U===w)A.push(f)}catch{continue}}}return Y($),A}function I($,w,A){if(A||W$.verbose)console.debug(`[tlsx:${$}] ${w}`)}function hj(){return Rj.env.SUDO_PASSWORD}function x5($){let w=$.toLowerCase();return k5.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function gY($){if(Array.isArray($))return $.map((A)=>gY(A));if(typeof $==="string")return Z5.test($)?HE:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(x5(A)){w[A]=HE;continue}w[A]=gY(Y)}return w}function eY($){return JSON.stringify(gY($))}function P5($){let w=hj();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let A=w.replace(/'/g,"'\\''"),Y=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${A}' | ${Y}`}async function fw($,w={}){let A=P5($);try{let{stdout:Y,stderr:f}=await D5(A,{cwd:w.cwd||Rj.cwd(),timeout:w.timeout||30000});return{stdout:Y.trim(),stderr:f.trim()}}catch(Y){let f=Error(`Failed to execute command: ${$}
|
|
127
|
-
Error: ${Y.message}`);throw f.stack=Y.stack,f}}function
|
|
126
|
+
`;return A}}function M5($,w,A={}){return Tj($,w,A,new WeakMap)}function Tj($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return Fj($,w,f,Y);if(!W$(w)||!W$($))return w;return L5($,w,A,Y)}function Fj($,w,A,Y){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 I5($,w);case"smart":return C5($,w,Y);default:return w}return w}function I5($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>lU(f,Y)))A.push(Y);return A}function C5($,w,A){if(w.length===0)return $;if($.length===0)return w;if(W$(w[0])&&W$($[0]))return S5($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function S5($,w,A){let Y=[...w];for(let f of $){if(!W$(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((J)=>W$(J)&&(W in J)&&J[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function L5($,w,A,Y){let f=w;if(W$(f)&&Y.has(f))return Y.get(f);let X={...$};if(W$(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(W$(W)&&W$(J))X[U]=Tj(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=Fj(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function zj($,w,A="replace"){return M5($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function lU($,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(!lU($[A],w[A]))return!1;return!0}if(W$($)&&W$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!lU($[f],w[f]))return!1}return!0}return!1}function W$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class Gj{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=PY.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!hY($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new dY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new dY($,Error("Configuration must export a valid object"),"unknown");let H={config:zj(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)PY.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?B1.configLoad($,B):B1.configLoad($,Error(String(B)))}};if(U)return aU.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(IU(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of Y){if(!X)continue;if(A.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)A.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let f=new Set;return A.filter((X)=>{if(!X||f.has(X))return!1;return f.add(X),!0})}checkFileAccess($){return y5(async()=>{return hY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!hY($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=IU($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=IU($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}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(!hY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}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(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class Hj{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await aU.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!WH(w))throw new lY(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new lY(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.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)Y.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($))Y.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)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.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($))Y.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 f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}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:V5},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function O5($){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 Kj{fileLoader=new Gj;envProcessor=new X8;validator=new Hj;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)b$.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let J=Date.now()-w;throw b$.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||rY.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(U$(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw B1.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${O5(f)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?MY($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)b$.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)b$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?MY($,A,f):A,W=[U$(aw(),".config",$),U$(aw(),".config"),aw()];for(let J of W){if(f)b$.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)b$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?MY($,Y,X):Y;try{let J=U$(A,"package.json");if(!yG(J))return null;let B={};try{B=JSON.parse(MG(J,"utf8"))}catch(T){if(X)b$.warn("Failed to parse package.json:",[T instanceof Error?T:Error(String(T))]);return null}let E=B[$],j=$;if(!E&&w){let T=Array.isArray(w)?w:[w];for(let F of T){if(!F)continue;if(B[F]){E=B[F],j=F;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)b$.success(`Configuration loaded from package.json: ${j}`);return{config:zj(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)b$.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:MY($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw B1.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return PY.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);PY.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}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([$,U$($,"config"),U$($,".config"),w?U$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(U$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[U$(aw(),".config",$),U$(aw(),".config"),aw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function MY($,w,A=!1){let Y=new X8,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=rY.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function gU($,w){let A=[];function Y(f){let X;try{X=HE.readdirSync(f)}catch{return}for(let U of X){let W=K$.join(f,U);try{if(HE.statSync(W).isDirectory())Y(W);else if(U===w)A.push(f)}catch{continue}}}return Y($),A}function M($,w,A){if(A||W0.verbose)console.debug(`[tlsx:${$}] ${w}`)}function qj(){return Nj.env.SUDO_PASSWORD}function P5($){let w=$.toLowerCase();return Z5.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function gY($){if(Array.isArray($))return $.map((A)=>gY(A));if(typeof $==="string")return x5.test($)?KE:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(P5(A)){w[A]=KE;continue}w[A]=gY(Y)}return w}function eY($){return JSON.stringify(gY($))}function i5($){let w=qj();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let A=w.replace(/'/g,"'\\''"),Y=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${A}' | ${Y}`}async function Uw($,w={}){let A=i5($);try{let{stdout:Y,stderr:f}=await k5(A,{cwd:w.cwd||Nj.cwd(),timeout:w.timeout||30000});return{stdout:Y.trim(),stderr:f.trim()}}catch(Y){let f=Error(`Failed to execute command: ${$}
|
|
127
|
+
Error: ${Y.message}`);throw f.stack=Y.stack,f}}function hj($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function U8($){let w=K$.join(Q5.homedir(),".stacks","ssl"),A=$.basePath&&$.basePath.trim()!==""?$.basePath:W0.basePath&&W0.basePath.trim()!==""?W0.basePath:w,Y=$.certPath?K$.isAbsolute($.certPath)?$.certPath:K$.join(A,$.certPath):K$.join(A,W0.certPath),f=$.keyPath?K$.isAbsolute($.keyPath)?$.keyPath:K$.join(A,$.keyPath):K$.join(A,W0.keyPath),X=$.caCertPath?K$.isAbsolute($.caCertPath)?$.caCertPath:K$.join(A,$.caCertPath):K$.join(A,W0.caCertPath);return{certPath:Y,keyPath:f,caCertPath:X,basePath:A}}function yj($){let w=[],A=new Set;if($.domain)A.add($.domain);if($.domains?.length)$.domains.forEach((Y)=>A.add(Y));for(let Y of A)w.push({type:2,value:Y});if($.altNameIPs?.length)for(let Y of $.altNameIPs)w.push({type:7,ip:Y});if($.altNameURIs?.length)for(let Y of $.altNameURIs)w.push({type:6,value:Y});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return M(C.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function J8($){let w=$.notBeforeDays??N$.DEFAULT_NOT_BEFORE_DAYS,A=$.validityDays??($.validityYears?$.validityYears*365:N$.DEFAULT_VALIDITY_DAYS);M(C.CERT,"Calculating certificate validity dates",$.verbose);let Y=new Date(Date.now()-86400*w*1000),f=new Date(Y.getTime()+A*24*60*60*1000);return Y.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),M(C.CERT,`Validity period: ${Y.toISOString()} to ${f.toISOString()}`,$.verbose),{notBefore:Y,notAfter:f}}function n1($){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 s0($,w){let A=n1(w.length);return Buffer.concat([Buffer.from([$]),A,w])}function g1($){let w=$.split(".").map(Number),A=[];A.push(40*w[0]+w[1]);for(let Y=2;Y<w.length;Y++){let f=w[Y],X=[];X.unshift(f&127),f>>=7;while(f>0)X.unshift(f&127|128),f>>=7;A.push(...X)}return s0(q$.OID,Buffer.from(A))}function tU($){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 s0(q$.INTEGER,w)}function Mj($,w=0){return s0(q$.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function Ij($){return s0(q$.OCTET_STRING,$)}function a0(...$){return s0(q$.SEQUENCE,Buffer.concat($))}function b5(...$){return s0(q$.SET,Buffer.concat($))}function c5($){return s0(q$.PRINTABLE_STRING,Buffer.from($,"ascii"))}function u5($){return s0(q$.UTF8_STRING,Buffer.from($,"utf8"))}function n5(){return Buffer.from([q$.NULL,0])}function RE($,w,A=!0){let Y=160|$|(A?0:0),f=n1(w.length);return Buffer.concat([Buffer.from([Y]),f,w])}function NE($){let w=$.getUTCFullYear();if(w>=2050){let A=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return s0(q$.GENERALIZED_TIME,Buffer.from(A,"ascii"))}else{let A=(w%100).toString().padStart(2,"0"),Y=($.getUTCMonth()+1).toString().padStart(2,"0"),f=$.getUTCDate().toString().padStart(2,"0"),X=$.getUTCHours().toString().padStart(2,"0"),U=$.getUTCMinutes().toString().padStart(2,"0"),W=$.getUTCSeconds().toString().padStart(2,"0"),J=`${A}${Y}${f}${X}${U}${W}Z`;return s0(q$.UTC_TIME,Buffer.from(J,"ascii"))}}function v5($,w){return a0(NE($),NE(w))}function qE($){let w=[];for(let A of $){let Y;switch(A.shortName){case"CN":Y=b0.COMMON_NAME;break;case"C":Y=b0.COUNTRY;break;case"L":Y=b0.LOCALITY;break;case"ST":Y=b0.STATE;break;case"O":Y=b0.ORGANIZATION;break;case"OU":Y=b0.ORGANIZATIONAL_UNIT;break;default:continue}let f=A.shortName==="C"?c5(A.value):u5(A.value),X=a0(g1(Y),f);w.push(b5(X))}return a0(...w)}function Cj($){return a0(g1($),n5())}function m5($){return $.export({type:"spki",format:"der"})}function d5($){if($.includes(":")){let w=$;if($.includes("::")){let f=$.split("::"),X=f[0]?f[0].split(":"):[],U=f[1]?f[1].split(":"):[],W=8-X.length-U.length,J=Array.from({length:W},()=>"0");w=[...X,...J,...U].join(":")}let A=w.split(":"),Y=Buffer.alloc(16);for(let f=0;f<8;f++){let X=Number.parseInt(A[f]||"0",16);Y.writeUInt16BE(X,f*2)}return Y}else{let w=$.split(".").map((A)=>Number.parseInt(A,10));return Buffer.from(w)}}function l5($){let w=[];for(let A of $)if(A.type===2&&A.value){let Y=n1(A.value.length);w.push(Buffer.concat([Buffer.from([130]),Y,Buffer.from(A.value,"ascii")]))}else if(A.type===7&&A.ip){let Y=d5(A.ip),f=n1(Y.length);w.push(Buffer.concat([Buffer.from([135]),f,Y]))}else if(A.type===6&&A.value){let Y=n1(A.value.length);w.push(Buffer.concat([Buffer.from([134]),Y,Buffer.from(A.value,"ascii")]))}return a0(...w)}function g5($,w){if($){if(w!==void 0)return a0(s0(1,Buffer.from([255])),tU(w));return a0(s0(1,Buffer.from([255])))}return a0()}function t5($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let A=0,Y=w;while(Y>0&&(Y&1)===0)A++,Y>>=1;if(w===0)A=7;return Mj(Buffer.from([w]),A)}function p5($){let w=[];if($.serverAuth)w.push(g1(b0.SERVER_AUTH));if($.clientAuth)w.push(g1(b0.CLIENT_AUTH));return a0(...w)}function c1($,w,A){let Y=[g1($)];if(w)Y.push(s0(1,Buffer.from([255])));return Y.push(Ij(A)),a0(...Y)}function r5($){let w=[];if(w.push(RE(0,tU(2))),w.push(tU($.serialNumber)),w.push(Cj(b0.SHA256_WITH_RSA)),w.push(qE($.issuer)),w.push(v5($.notBefore,$.notAfter)),w.push(qE($.subject)),w.push(m5($.publicKey)),$.extensions){let A=[];if($.extensions.basicConstraints)A.push(c1(b0.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,g5($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)A.push(c1(b0.KEY_USAGE,$.extensions.keyUsage.critical??!0,t5($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)A.push(c1(b0.EXTENDED_KEY_USAGE,!1,p5($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)A.push(c1(b0.SUBJECT_ALT_NAME,!1,l5($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)A.push(c1(b0.SUBJECT_KEY_IDENTIFIER,!1,Ij($.extensions.subjectKeyIdentifier)));if(A.length>0)w.push(RE(3,a0(...A)))}return a0(...w)}function a5($,w){let A=E1.createSign("SHA256");A.update($);let Y=A.sign(w);return a0($,Cj(b0.SHA256_WITH_RSA),Mj(Y))}function s5($,w){let A=$.toString("base64"),Y=[];for(let f=0;f<A.length;f+=64)Y.push(A.slice(f,f+64));return`-----BEGIN ${w}-----
|
|
128
128
|
${Y.join(`
|
|
129
129
|
`)}
|
|
130
130
|
-----END ${w}-----
|
|
131
|
-
`}function
|
|
132
|
-
`);for(let X of f){let[U,...W]=X.split("="),J=W.join("=");if(U&&J)Y.push({shortName:U.trim(),value:J.trim()})}return{publicKey:A,subject:Y}}async function WU($={}){I("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||K0.DEFAULT_KEY_SIZE;I("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:Y}=Cj(w),f=[{shortName:"C",value:$.countryName||W$.countryName},{shortName:"ST",value:$.stateName||W$.stateName},{shortName:"L",value:$.localityName||W$.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:X,notAfter:U}=UU({validityYears:$.validityYears||K0.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=Sj({serialNumber:JU(),notBefore:X,notAfter:U,subject:f,publicKey:Y,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:Lj(A),notBefore:X,notAfter:U}}async function BU($){if(I("ca","Generating new certificate",$.verbose),I("ca",`Options: ${eY($)}`,$.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}=e5($.rootCA.certificate),A=o5($.rootCA.privateKey);I("ca",`Generating ${K0.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let Y=K0.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:X}=Cj(Y),U=$.commonName||qj($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||W$.countryName},{shortName:"ST",value:$.stateName||W$.stateName},{shortName:"L",value:$.localityName||W$.localityName},{shortName:"O",value:$.organizationName||W$.organizationName},{shortName:"CN",value:U}],{notBefore:J,notAfter:B}=UU({validityDays:$.validityDays||K0.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),E=Nj($),j=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},T=$.extKeyUsage||{serverAuth:!0},{certificate:F}=Sj({serialNumber:JU(),notBefore:J,notAfter:B,subject:W,issuer:w,publicKey:X,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:j,extendedKeyUsage:T,subjectAltName:E});return{certificate:F,privateKey:Lj(f),notBefore:J,notAfter:B}}function Oj($,w){I(S.STORAGE,`Storing certificate and private key with options: ${eY(w)}`,w?.verbose);let{certPath:A,keyPath:Y}=XU({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});I(S.STORAGE,`Certificate path: ${A}`,w?.verbose),I(S.STORAGE,`Private key path: ${Y}`,w?.verbose);let f=t8.dirname(A);if(!u0.existsSync(f))I(S.STORAGE,`Creating certificate directory: ${f}`,w?.verbose),u0.mkdirSync(f,{recursive:!0});I(S.STORAGE,"Writing certificate file",w?.verbose),u0.writeFileSync(A,$.certificate);let X=t8.dirname(Y);if(!u0.existsSync(X))I(S.STORAGE,`Creating private key directory: ${X}`,w?.verbose),u0.mkdirSync(X,{recursive:!0});return I(S.STORAGE,"Writing private key file",w?.verbose),u0.writeFileSync(Y,$.privateKey),I(S.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function Vj($,w){I(S.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=XU({basePath:w?.basePath,caCertPath:w?.caCertPath});I(S.STORAGE,`CA certificate path: ${A}`,w?.verbose);let Y=t8.dirname(A);if(!u0.existsSync(Y))I(S.STORAGE,`Creating CA certificate directory: ${Y}`,w?.verbose),u0.mkdirSync(Y,{recursive:!0});return I(S.STORAGE,"Writing CA certificate file",w?.verbose),u0.writeFileSync(A,$),I(S.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function $K($,w){if(tY.platform()!=="darwin")return!1;try{let A=qE(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return I(S.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(qE("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return I(S.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return I(S.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return I(S.TRUST,`Error checking certificate trust: ${A}`,w),!1}}async function EU($,w,A){I(S.TRUST,`Adding certificate to system trust store with options: ${eY(A)}`,A?.verbose),I(S.TRUST,"Storing certificate and private key",A?.verbose);let Y=Oj($,A);I(S.TRUST,"Storing CA certificate",A?.verbose);let f=Vj(w,A),X=tY.platform();I(S.TRUST,`Detected platform: ${X}`,A?.verbose);let U=fK[X];if(!U){let W=`Unsupported platform: ${X}`;throw I(S.TRUST,`Error: ${W}`,A?.verbose),Error(W)}return await U.addCertificate(f,A),I(S.TRUST,"Certificate successfully added to system trust store",A?.verbose),Y}var UH,pY,CE="https://acme-staging-v02.api.letsencrypt.org/directory",SE="https://acme-v02.api.letsencrypt.org/directory",QY,TH="1.2.840.10045.2.1",FH="1.2.840.10045.3.1.7",zH="1.2.840.10045.4.3.2",GH="2.5.4.3",HH="1.2.840.113549.1.9.14",KH="2.5.29.17",PY,r8,W9,B9=($)=>$,j9=($,w)=>{for(var A in w)W9($,A,{get:w[A],enumerable:!0,configurable:!0,set:E9.bind(w,A)})},T9=($,w)=>()=>($&&(w=$($=0)),w),cE,pE,J1,t1,rE,c9,u9,YE,SY,P8,O$,t,n9,fE,v9,XE,m9,d9,I8,l9,UE,JE,C8,g9,t9,p9,r9,LY,aE,a9,V$,s9,o9,WE,OY,i8,G$,Z,e9,BE,$5,EE,w5,A5,S8,Y5,jE,TE,f5,L8,X5,U5,J5,W5,B5,VY,sE,E5,j5="0.15.6",r$,nY,d1,b8,c8,vY,u8,n8,l1,v8,m8,Xw,oE,eE,H0,n0,$j,wj,T5,z5,Aj,mY,uy,y$,b,ny,H5,vy,K5,my,dy,FE,ly,R5,h5,gy,zE,ty,py,ry,ay,sy,O8,q5,oy,h0,fj,dY,Xj,Uj,YU,Jj,Wj,lY,Bj,Ej,W1,L5,P0,ey,$M,wM,Kj,W$,K0,S,U1,D5,HE="[redacted]",k5,Z5,R0,b$,wK,AK,YK,fK;var Qj=E$(()=>{UH=XH(import.meta.url);pY=new v1;QY=class QY extends Error{problem;httpStatus;constructor($,w,A){super($);this.name="AcmeError",this.problem=w,this.httpStatus=A}};PY=new iE,r8=new bE,W9=Object.defineProperty;cE={};j9(cE,{withErrorRecovery:()=>vE,tryLoadConfig:()=>x9,loadConfigWithResult:()=>k9,loadConfig:()=>tE,isRetryableError:()=>L9,isConfigNotFoundError:()=>S9,isBunfigError:()=>mE,globalPerformanceMonitor:()=>t1,globalCache:()=>J1,getEnvOrDefault:()=>O9,generateConfigTypes:()=>P9,defaultGeneratedDir:()=>wj,defaultConfigDir:()=>$j,deepMergeWithArrayStrategy:()=>$U,deepMerge:()=>dE,createLibraryConfig:()=>i9,config:()=>Z9,bunfigPlugin:()=>b9,applyEnvVarsToConfig:()=>u1,TypeGenerationError:()=>n8,SchemaValidationError:()=>l1,PluginError:()=>m8,PerformanceMonitor:()=>s8,FileSystemError:()=>u8,ErrorFactory:()=>Xw,EnvVarError:()=>vY,EnvProcessor:()=>aY,ConfigValidator:()=>wU,ConfigValidationError:()=>b8,ConfigNotFoundError:()=>nY,ConfigMergeError:()=>c8,ConfigLoader:()=>AU,ConfigLoadError:()=>d1,ConfigFileLoader:()=>sY,ConfigCache:()=>a8,CacheUtils:()=>rE,BunfigError:()=>r$,BrowserConfigError:()=>v8,ArrayMergeStrategies:()=>oE});T5=T9(async()=>{pE=import.meta.require,J1=new a8,t1=new s8,rE={createKey:F9,isEquivalent:z9,estimateMemoryUsage:G9},c9=ZY(Z8.cwd(),"config"),u9=ZY(Z8.cwd(),"src/generated"),YE=kY.env.CLARITY_LOG_DIR||OH(R9(),"logs"),SY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:YE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},P8=await h9(),O$={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"},t=O$,n9=O$.red,fE=O$.green,v9=O$.yellow,XE=O$.blue,m9=O$.magenta,d9=O$.cyan,I8=O$.white,l9=O$.gray,UE=O$.bgRed,JE=O$.bgYellow,C8=O$.bold,g9=O$.dim,t9=O$.italic,p9=O$.underline,r9=O$.reset,LY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},aE={debug:"\uD83D\uDD0D",info:XE("ℹ"),success:fE("✓"),warning:JE(I8(C8(" WARN "))),error:UE(I8(C8(" ERROR ")))},a9=new bY("stacks"),V$=new bY("bunfig",{showTags:!0}),s9=P$(m1.cwd(),"config"),o9=P$(m1.cwd(),"src/generated"),WE=DY.env.CLARITY_LOG_DIR||SH(M9(),"logs"),OY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:WE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},i8=await I9(),G$={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"},Z=G$,e9=G$.red,BE=G$.green,$5=G$.yellow,EE=G$.blue,w5=G$.magenta,A5=G$.cyan,S8=G$.white,Y5=G$.gray,jE=G$.bgRed,TE=G$.bgYellow,f5=G$.bgGray,L8=G$.bold,X5=G$.dim,U5=G$.italic,J5=G$.underline,W5=G$.strikethrough,B5=G$.reset,VY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sE={debug:"\uD83D\uDD0D",info:EE("ℹ"),success:BE("✓"),warning:TE(S8(L8(" WARN "))),error:jE(S8(L8(" ERROR ")))},E5=new uY("stacks"),r$=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}${$}`}},nY=class extends r${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A?` or alias "${A}"`:"";super(`Configuration "${$}"${Y} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}},d1=class extends r${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}},b8=class extends r${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},c8=class extends r${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},vY=class extends r${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}},u8=class extends r${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}},n8=class extends r${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}},l1=class extends r${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},v8=class extends r${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}},m8=class extends r${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}},Xw={configNotFound($,w,A){return new nY($,w,A)},configLoad($,w,A){return new d1($,w,A)},configValidation($,w,A){return new b8($,w,A)},configMerge($,w,A,Y){return new c8($,w,A,Y)},envVar($,w,A,Y){return new vY($,w,A,Y)},fileSystem($,w,A){return new u8($,w,A)},typeGeneration($,w,A){return new n8($,w,A)},schemaValidation($,w,A){return new l1($,w,A)},browserConfig($,w,A,Y){return new v8($,w,A,Y)},plugin($,w,A){return new m8($,w,A)}},oE={replace:"replace",concat:"concat",smart:"smart"},eE=/^https?:\/\//,H0=new uY("bunfig",{showTags:!0}),n0=new AU,$j=i$(qw.cwd(),"config"),wj=i$(qw.cwd(),"src/generated")});z5=xY.env.CLARITY_LOG_DIR||aH(F5(),"logs"),Aj={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:z5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mY={...Aj},uy=(async()=>{try{let{loadConfig:$}=await T5().then(()=>cE),w=await $({name:"clarity",alias:"logging",defaultConfig:Aj,cwd:xY.cwd()});if(w)Object.assign(mY,w)}catch{}return mY})();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`,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"},b=y$,ny=y$.red,H5=y$.green,vy=y$.yellow,K5=y$.blue,my=y$.magenta,dy=y$.cyan,FE=y$.white,ly=y$.gray,R5=y$.bgRed,h5=y$.bgYellow,gy=y$.bgGray,zE=y$.bold,ty=y$.dim,py=y$.italic,ry=y$.underline,ay=y$.strikethrough,sy=y$.reset,O8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},q5={debug:"\uD83D\uDD0D",info:K5("ℹ"),success:H5("✓"),warning:h5(FE(zE(" WARN "))),error:R5(FE(zE(" ERROR ")))};oy=new oY("stacks");h0=class h0 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}${$}`}};fj=class fj extends h0{code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],f="";if(Y.length===1)f=` or alias "${Y[0]}"`;else if(Y.length>1)f=` or aliases ${Y.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${f} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};dY=class dY extends h0{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}};Xj=class Xj extends h0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};Uj=class Uj extends h0{code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};YU=class YU extends h0{code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};Jj=class Jj extends h0{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}};Wj=class Wj extends h0{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}};lY=class lY extends h0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};Bj=class Bj extends h0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};Ej=class Ej extends h0{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}};W1={configNotFound($,w,A){return new fj($,w,A)},configLoad($,w,A){return new dY($,w,A)},configValidation($,w,A){return new Xj($,w,A)},configMerge($,w,A,Y){return new Uj($,w,A,Y)},envVar($,w,A,Y){return new YU($,w,A,Y)},fileSystem($,w,A){return new Jj($,w,A)},typeGeneration($,w,A){return new Wj($,w,A)},schemaValidation($,w,A){return new lY($,w,A)},browserConfig($,w,A,Y){return new Bj($,w,A,Y)},plugin($,w,A){return new Ej($,w,A)}};L5=/^https?:\/\//;P0=new oY("bunfig",{showTags:!0});ey=new Hj;$M=f0(rY.cwd(),"config"),wM=f0(rY.cwd(),"src/generated"),Kj={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:B8.join(W8.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:B8.join(W8.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:B8.join(W8.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},W$=Kj,K0={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"},S={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},U1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};D5=_5(V5);k5=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Z5=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;R0={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},b$={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"};wK={platform:"darwin",async addCertificate($,w){if(await $K($,w?.verbose)){I(S.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),U1.success("Certificate is already trusted in system keychain");return}I(S.TRUST,"Adding certificate to macOS keychain",w?.verbose),await fw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let Y=A||W$.commonName;I(S.TRUST,`Removing certificate ${Y} from macOS keychain`,w?.verbose);try{await fw(`sudo security delete-certificate -c "${Y}" /Library/Keychains/System.keychain`),I(S.TRUST,`Removed certificate ${Y} from macOS keychain`,w?.verbose)}catch(f){throw I(S.TRUST,`Error removing certificate: ${f}`,w?.verbose),f}}},AK={platform:"win32",async addCertificate($,w){I(S.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await fw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let Y=A||W$.commonName;I(S.TRUST,`Removing certificate ${Y} from Windows certificate store`,w?.verbose);try{await fw(`certutil -delstore -enterprise Root "${Y}"`),I(S.TRUST,`Removed certificate ${Y} from Windows certificate store`,w?.verbose)}catch(f){throw I(S.TRUST,`Error removing certificate: ${f}`,w?.verbose),f}}},YK={platform:"linux",async addCertificate($,w){I(S.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=tY.homedir(),Y=K0.LINUX_CERT_DB_FILENAME,f=K0.LINUX_TRUST_ARGS;I(S.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let X=l8(A,Y);if(X.length===0){U1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of X){I(S.TRUST,`Processing certificate database in ${U}`,w?.verbose);try{I(S.TRUST,`Attempting to delete existing cert for ${W$.commonName}`,w?.verbose),await fw(`certutil -d sql:${U} -D -n ${W$.commonName}`)}catch(W){I(S.TRUST,`Warning: Error deleting existing cert: ${W}`,w?.verbose),console.warn(`Error deleting existing cert: ${W}`)}I(S.TRUST,`Adding new certificate to ${U}`,w?.verbose),await fw(`certutil -d sql:${U} -A -t ${f} -n ${W$.commonName} -i ${$}`),U1.info(`Cert added to ${U}`)}},async removeCertificate($,w,A){let Y=A||W$.commonName;I(S.TRUST,`Removing certificate ${Y} from Linux certificate store`,w?.verbose);let f=tY.homedir(),X=K0.LINUX_CERT_DB_FILENAME;I(S.TRUST,`Searching for certificate databases in ${f}`,w?.verbose);let U=l8(f,X);if(U.length===0){U1.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of U){I(S.TRUST,`Processing certificate database in ${W}`,w?.verbose);try{await fw(`certutil -d sql:${W} -D -n "${Y}"`),U1.info(`Cert removed from ${W}`)}catch(J){I(S.TRUST,`Error removing cert from ${W}: ${J}`,w?.verbose),console.warn(`Error removing cert from ${W}: ${J}`)}}}},fK={darwin:wK,win32:AK,linux:YK}});var jU=E$(()=>{Qj()});import{homedir as TU}from"node:os";import{join as FU,resolve as sM}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",XK,zU;var GU=E$(()=>{f8();XK={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:FU(TU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:FU(TU(),".stacks","ssl","stacks.localhost.crt"),keyPath:FU(TU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},zU=XK});import{execSync as UK}from"node:child_process";function _j($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function $f($){try{let w=UK(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return _j(w)}catch{return null}}var HU=()=>{};import{existsSync as Dj,statSync as kj}from"fs";import{existsSync as xU,mkdirSync as TK,readdirSync as FK,writeFileSync as zK}from"fs";import{homedir as E1}from"os";import{dirname as Zj,resolve as u$}from"path";import Nw from"process";import{join as GK,relative as HK,resolve as xj}from"path";import Kf from"process";import{existsSync as KT,mkdirSync as EI,readdirSync as jI,writeFileSync as TI}from"fs";import{homedir as KU}from"os";import{dirname as GI,resolve as c$}from"path";import r1 from"process";import{join as KK,relative as RK,resolve as Pj}from"path";import Rf from"process";import{existsSync as RT,mkdirSync as qI,readdirSync as NI,writeFileSync as yI}from"fs";import{dirname as II,resolve as hf}from"path";import PU from"process";import{Buffer as Jw}from"buffer";import{createCipheriv as hK,createDecipheriv as qK,randomBytes as RU}from"crypto";import{closeSync as hU,createReadStream as ij,createWriteStream as NK,existsSync as qU,fsyncSync as bj,openSync as cj,writeFileSync as yK}from"fs";import{access as MK,constants as uj,mkdir as IK,readdir as wf,rename as nj,stat as j1,unlink as Af,writeFile as NU}from"fs/promises";import{join as T1}from"path";import Q$ from"process";import{pipeline as CK}from"stream/promises";import{createGzip as vj}from"zlib";import F1 from"process";import d0 from"process";import{Buffer as v0}from"buffer";import{createCipheriv as SK,createDecipheriv as LK,randomBytes as yU}from"crypto";import{closeSync as MU,createReadStream as mj,createWriteStream as OK,existsSync as Yf,fsyncSync as dj,openSync as lj,writeFileSync as VK}from"fs";import{access as QK,constants as gj,mkdir as _K,readdir as ff,rename as tj,stat as z1,unlink as Xf,writeFile as IU}from"fs/promises";import{isAbsolute as DK,join as G1,resolve as kK}from"path";import _ from"process";import{pipeline as ZK}from"stream/promises";import{createGzip as pj}from"zlib";import H1 from"process";import l0 from"process";import Uf from"process";import{existsSync as Jf}from"fs";import{resolve as CU}from"path";import{existsSync as xK}from"fs";import{existsSync as PK,readdirSync as iK}from"fs";import{extname as SU,resolve as rj}from"path";import bK from"process";import{join as c6,relative as u6,resolve as JT}from"path";import Sf from"process";import{Buffer as m0}from"buffer";import{createCipheriv as m6,createDecipheriv as d6,randomBytes as _U}from"crypto";import{closeSync as DU,createReadStream as WT,createWriteStream as l6,existsSync as Bf,fsyncSync as BT,openSync as ET,writeFileSync as g6}from"fs";import{access as t6,constants as jT,mkdir as p6,readdir as Ef,rename as TT,stat as K1,unlink as jf,writeFile as kU}from"fs/promises";import{isAbsolute as r6,join as R1,resolve as a6}from"path";import D from"process";import{pipeline as s6}from"stream/promises";import{createGzip as FT}from"zlib";import h1 from"process";import g0 from"process";function BK($,w){this[$]=WK.bind(null,w)}class gU{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],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!Dj($))return!0;return kj($).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,Y){try{let f=Dj(A)?kj(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}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((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.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 Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class tU{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function cK($,w={}){let Y=Object.keys(w).sort().map((f)=>`${f}:${w[f]}`).join("|");return Y?`${$}:${Y}`:$}function uK($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function nK($){return $.getStats().size*2}function pU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&e(w[0])&&"id"in w[0]&&w[0].id===3&&e(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(e(w)&&e($)&&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(e($)&&"arr"in $&&Array.isArray($.arr)&&e(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&e(w[0])&&e($[0])){let Y=[...w];for(let f of $)if(e(f)&&"name"in f){if(!Y.find((U)=>e(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(e(f)&&"path"in f){if(!Y.find((U)=>e(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>qf(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!e(w)||!e($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(e(f)&&e(A[Y]))A[Y]=pU(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&e(f[0])&&e(A[Y][0])){let X=[...f];for(let U of A[Y])if(e(U)&&"name"in U){if(!X.find((J)=>e(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(e(U)&&"path"in U){if(!X.find((J)=>e(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>qf(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function qf($,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(!qf($[A],w[A]))return!1;return!0}if(e($)&&e(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!qf($[f],w[f]))return!1}return!0}return!1}function e($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function vK($,w){if(!RT($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return pU(w,Y)}catch{return null}}catch{return null}}async function mK({name:$="",cwd:w,defaultConfig:A}){let Y=w||PU.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=hf(Y,`${U}${W}`),B=await vK(J,A);if(B!==null)return B}try{let U=hf(Y,"package.json");if(RT(U)){let J=(await import(U))[$];if(J&&typeof J==="object"&&!Array.isArray(J))try{return pU(A,J)}catch{}}}catch{}return A}function dK($,w={}){let A=Rf.cwd();while(A.includes("storage"))A=Pj(A,"..");let Y=Pj(A,$||"");if(w?.relative)return RK(Rf.cwd(),Y);return Y}async function lK(){try{let $=await mK({name:"clarity",defaultConfig:Ff,cwd:Rf.cwd(),endpoint:"",headers:{}});return{...Ff,...$}}catch{return Ff}}function X$(){if(d0.env.NODE_ENV==="test"||d0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gK(){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 hT{async format($){let w=await gK(),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:F1.pid,hostname:w(),environment:F1.env.NODE_ENV||"development",platform:F1.platform,version:F1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:F1.env.NODE_ENV||F1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Nf{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={...bU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new hT,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},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...zf,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...zf};return{...zf,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:bU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==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 f,X=0,U=3,W=1000;while(X<U)try{try{try{await MK(this.config.logDirectory,uj.F_OK|uj.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await IK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Jw.from($);try{if(!qU(this.currentLogFile))await NU(this.currentLogFile,"",{mode:420});if(f=cj(this.currentLogFile,"a",420),yK(f,J,{flag:"a"}),bj(f),f!==void 0)hU(f),f=void 0;if((await j1(this.currentLogFile)).size===0){if(await NU(this.currentLogFile,J,{flag:"w",mode:420}),(await j1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{hU(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 T1(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 T1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return T1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(X$())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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return RU(16).toString("hex")}generateKey(){return RU(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=RU(16),Y=hK("aes-256-gcm",w,A),f=Jw.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:Jw.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=vj(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(Jw.from(Jw.concat(f)))),Y.on("error",A),Y.write($),Y.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(X$())return;let $=await j1(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await wf(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await j1(A).catch(()=>null))try{if(await nj(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await Af(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await NU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await j1(A).catch(()=>null))await nj(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await wf(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await Af(T1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=ij($),Y=NK(w),f=vj();await CK(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}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()})),qU(this.currentLogFile))try{let $=cj(this.currentLogFile,"r+");bj($),hU($)}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(!X$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await wf(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await Af(T1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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?p.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=Q$.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${p.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!X$()){let B=VT[$],E=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:p.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:p.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
133
|
-
`);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
131
|
+
`}function W8(){return E1.randomBytes(20)}function Sj($=2048){let{privateKey:w,publicKey:A}=E1.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:A}}function o5($){let w=$.export({type:"spki",format:"der"});return E1.createHash("sha1").update(w).digest()}function Lj($){let w={serialNumber:$.serialNumber||W8(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:o5($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let A=r5(w),Y=a5(A,$.signingKey);return{certificate:s5(Y,"CERTIFICATE"),certificateDer:Y}}function Vj($){return $.export({type:"pkcs8",format:"pem"})}function e5($){return E1.createPrivateKey($)}function $K($){let w=new E1.X509Certificate($),A=w.publicKey,Y=[],f=w.subject.split(`
|
|
132
|
+
`);for(let X of f){let[U,...W]=X.split("="),J=W.join("=");if(U&&J)Y.push({shortName:U.trim(),value:J.trim()})}return{publicKey:A,subject:Y}}async function B8($={}){M("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||N$.DEFAULT_KEY_SIZE;M("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:Y}=Sj(w),f=[{shortName:"C",value:$.countryName||W0.countryName},{shortName:"ST",value:$.stateName||W0.stateName},{shortName:"L",value:$.localityName||W0.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:X,notAfter:U}=J8({validityYears:$.validityYears||N$.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=Lj({serialNumber:W8(),notBefore:X,notAfter:U,subject:f,publicKey:Y,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:Vj(A),notBefore:X,notAfter:U}}async function E8($){if(M("ca","Generating new certificate",$.verbose),M("ca",`Options: ${eY($)}`,$.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}=$K($.rootCA.certificate),A=e5($.rootCA.privateKey);M("ca",`Generating ${N$.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let Y=N$.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:X}=Sj(Y),U=$.commonName||hj($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||W0.countryName},{shortName:"ST",value:$.stateName||W0.stateName},{shortName:"L",value:$.localityName||W0.localityName},{shortName:"O",value:$.organizationName||W0.organizationName},{shortName:"CN",value:U}],{notBefore:J,notAfter:B}=J8({validityDays:$.validityDays||N$.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),E=yj($),j=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},T=$.extKeyUsage||{serverAuth:!0},{certificate:F}=Lj({serialNumber:W8(),notBefore:J,notAfter:B,subject:W,issuer:w,publicKey:X,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:j,extendedKeyUsage:T,subjectAltName:E});return{certificate:F,privateKey:Vj(f),notBefore:J,notAfter:B}}function Oj($,w){M(C.STORAGE,`Storing certificate and private key with options: ${eY(w)}`,w?.verbose);let{certPath:A,keyPath:Y}=U8({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});M(C.STORAGE,`Certificate path: ${A}`,w?.verbose),M(C.STORAGE,`Private key path: ${Y}`,w?.verbose);let f=pU.dirname(A);if(!v$.existsSync(f))M(C.STORAGE,`Creating certificate directory: ${f}`,w?.verbose),v$.mkdirSync(f,{recursive:!0});M(C.STORAGE,"Writing certificate file",w?.verbose),v$.writeFileSync(A,$.certificate);let X=pU.dirname(Y);if(!v$.existsSync(X))M(C.STORAGE,`Creating private key directory: ${X}`,w?.verbose),v$.mkdirSync(X,{recursive:!0});return M(C.STORAGE,"Writing private key file",w?.verbose),v$.writeFileSync(Y,$.privateKey),M(C.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function _j($,w){M(C.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=U8({basePath:w?.basePath,caCertPath:w?.caCertPath});M(C.STORAGE,`CA certificate path: ${A}`,w?.verbose);let Y=pU.dirname(A);if(!v$.existsSync(Y))M(C.STORAGE,`Creating CA certificate directory: ${Y}`,w?.verbose),v$.mkdirSync(Y,{recursive:!0});return M(C.STORAGE,"Writing CA certificate file",w?.verbose),v$.writeFileSync(A,$),M(C.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function wK($,w){if(tY.platform()!=="darwin")return!1;try{let A=hE(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return M(C.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(hE("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return M(C.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return M(C.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return M(C.TRUST,`Error checking certificate trust: ${A}`,w),!1}}async function j8($,w,A){M(C.TRUST,`Adding certificate to system trust store with options: ${eY(A)}`,A?.verbose),M(C.TRUST,"Storing certificate and private key",A?.verbose);let Y=Oj($,A);M(C.TRUST,"Storing CA certificate",A?.verbose);let f=_j(w,A),X=tY.platform();M(C.TRUST,`Detected platform: ${X}`,A?.verbose);let U=XK[X];if(!U){let W=`Unsupported platform: ${X}`;throw M(C.TRUST,`Error: ${W}`,A?.verbose),Error(W)}return await U.addCertificate(f,A),M(C.TRUST,"Certificate successfully added to system trust store",A?.verbose),Y}var JG,pY,SE="https://acme-staging-v02.api.letsencrypt.org/directory",LE="https://acme-v02.api.letsencrypt.org/directory",_Y,FG="1.2.840.10045.2.1",zG="1.2.840.10045.3.1.7",GG="1.2.840.10045.4.3.2",HG="2.5.4.3",KG="1.2.840.113549.1.9.14",RG="2.5.29.17",PY,aU,BH,EH=($)=>$,TH=($,w)=>{for(var A in w)BH($,A,{get:w[A],enumerable:!0,configurable:!0,set:jH.bind(w,A)})},FH=($,w)=>()=>($&&(w=$($=0)),w),uE,rE,W1,t1,aE,uH,nH,fE,SY,iU,V0,p,vH,XE,mH,UE,dH,lH,CU,gH,JE,WE,SU,tH,pH,rH,aH,LY,sE,sH,O0,oH,eH,BE,VY,bU,G0,x,$5,EE,w5,jE,A5,Y5,LU,f5,TE,FE,X5,VU,U5,J5,W5,B5,E5,OY,oE,j5,T5="0.15.6",r0,nY,d1,cU,uU,vY,nU,vU,l1,mU,dU,Jw,eE,$j,R$,m$,wj,Aj,F5,G5,Yj,mY,my,y0,c,dy,K5,ly,R5,gy,ty,zE,py,N5,q5,ry,GE,ay,sy,oy,ey,$M,OU,h5,wM,h$,Xj,dY,Uj,Jj,f8,Wj,Bj,lY,Ej,jj,B1,V5,b$,AM,YM,fM,Rj,W0,N$,C,J1,k5,KE="[redacted]",Z5,x5,q$,b0,AK,YK,fK,XK;var Qj=E0(()=>{JG=UG(import.meta.url);pY=new v1;_Y=class _Y extends Error{problem;httpStatus;constructor($,w,A){super($);this.name="AcmeError",this.problem=w,this.httpStatus=A}};PY=new bE,aU=new cE,BH=Object.defineProperty;uE={};TH(uE,{withErrorRecovery:()=>mE,tryLoadConfig:()=>PH,loadConfigWithResult:()=>ZH,loadConfig:()=>pE,isRetryableError:()=>VH,isConfigNotFoundError:()=>LH,isBunfigError:()=>dE,globalPerformanceMonitor:()=>t1,globalCache:()=>W1,getEnvOrDefault:()=>OH,generateConfigTypes:()=>iH,defaultGeneratedDir:()=>Aj,defaultConfigDir:()=>wj,deepMergeWithArrayStrategy:()=>w8,deepMerge:()=>lE,createLibraryConfig:()=>bH,config:()=>xH,bunfigPlugin:()=>cH,applyEnvVarsToConfig:()=>u1,TypeGenerationError:()=>vU,SchemaValidationError:()=>l1,PluginError:()=>dU,PerformanceMonitor:()=>oU,FileSystemError:()=>nU,ErrorFactory:()=>Jw,EnvVarError:()=>vY,EnvProcessor:()=>aY,ConfigValidator:()=>A8,ConfigValidationError:()=>cU,ConfigNotFoundError:()=>nY,ConfigMergeError:()=>uU,ConfigLoader:()=>Y8,ConfigLoadError:()=>d1,ConfigFileLoader:()=>sY,ConfigCache:()=>sU,CacheUtils:()=>aE,BunfigError:()=>r0,BrowserConfigError:()=>mU,ArrayMergeStrategies:()=>eE});F5=FH(async()=>{rE=import.meta.require,W1=new sU,t1=new oU,aE={createKey:zH,isEquivalent:GH,estimateMemoryUsage:HH},uH=ZY(xU.cwd(),"config"),nH=ZY(xU.cwd(),"src/generated"),fE=kY.env.CLARITY_LOG_DIR||OG(NH(),"logs"),SY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:fE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},iU=await qH(),V0={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"},p=V0,vH=V0.red,XE=V0.green,mH=V0.yellow,UE=V0.blue,dH=V0.magenta,lH=V0.cyan,CU=V0.white,gH=V0.gray,JE=V0.bgRed,WE=V0.bgYellow,SU=V0.bold,tH=V0.dim,pH=V0.italic,rH=V0.underline,aH=V0.reset,LY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sE={debug:"\uD83D\uDD0D",info:UE("ℹ"),success:XE("✓"),warning:WE(CU(SU(" WARN "))),error:JE(CU(SU(" ERROR ")))},sH=new bY("stacks"),O0=new bY("bunfig",{showTags:!0}),oH=P0(m1.cwd(),"config"),eH=P0(m1.cwd(),"src/generated"),BE=DY.env.CLARITY_LOG_DIR||LG(IH(),"logs"),VY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:BE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bU=await CH(),G0={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=G0,$5=G0.red,EE=G0.green,w5=G0.yellow,jE=G0.blue,A5=G0.magenta,Y5=G0.cyan,LU=G0.white,f5=G0.gray,TE=G0.bgRed,FE=G0.bgYellow,X5=G0.bgGray,VU=G0.bold,U5=G0.dim,J5=G0.italic,W5=G0.underline,B5=G0.strikethrough,E5=G0.reset,OY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oE={debug:"\uD83D\uDD0D",info:jE("ℹ"),success:EE("✓"),warning:FE(LU(VU(" WARN "))),error:TE(LU(VU(" ERROR ")))},j5=new uY("stacks"),r0=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}${$}`}},nY=class extends r0{code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A?` or alias "${A}"`:"";super(`Configuration "${$}"${Y} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}},d1=class extends r0{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}},cU=class extends r0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},uU=class extends r0{code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},vY=class extends r0{code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}},nU=class extends r0{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}},vU=class extends r0{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}},l1=class extends r0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},mU=class extends r0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}},dU=class extends r0{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}},Jw={configNotFound($,w,A){return new nY($,w,A)},configLoad($,w,A){return new d1($,w,A)},configValidation($,w,A){return new cU($,w,A)},configMerge($,w,A,Y){return new uU($,w,A,Y)},envVar($,w,A,Y){return new vY($,w,A,Y)},fileSystem($,w,A){return new nU($,w,A)},typeGeneration($,w,A){return new vU($,w,A)},schemaValidation($,w,A){return new l1($,w,A)},browserConfig($,w,A,Y){return new mU($,w,A,Y)},plugin($,w,A){return new dU($,w,A)}},eE={replace:"replace",concat:"concat",smart:"smart"},$j=/^https?:\/\//,R$=new uY("bunfig",{showTags:!0}),m$=new Y8,wj=i0(yw.cwd(),"config"),Aj=i0(yw.cwd(),"src/generated")});G5=xY.env.CLARITY_LOG_DIR||sG(z5(),"logs"),Yj={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:G5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mY={...Yj},my=(async()=>{try{let{loadConfig:$}=await F5().then(()=>uE),w=await $({name:"clarity",alias:"logging",defaultConfig:Yj,cwd:xY.cwd()});if(w)Object.assign(mY,w)}catch{}return mY})();y0={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"},c=y0,dy=y0.red,K5=y0.green,ly=y0.yellow,R5=y0.blue,gy=y0.magenta,ty=y0.cyan,zE=y0.white,py=y0.gray,N5=y0.bgRed,q5=y0.bgYellow,ry=y0.bgGray,GE=y0.bold,ay=y0.dim,sy=y0.italic,oy=y0.underline,ey=y0.strikethrough,$M=y0.reset,OU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},h5={debug:"\uD83D\uDD0D",info:R5("ℹ"),success:K5("✓"),warning:q5(zE(GE(" WARN "))),error:N5(zE(GE(" ERROR ")))};wM=new oY("stacks");h$=class h$ 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}${$}`}};Xj=class Xj extends h${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],f="";if(Y.length===1)f=` or alias "${Y[0]}"`;else if(Y.length>1)f=` or aliases ${Y.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${f} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};dY=class dY extends h${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}};Uj=class Uj extends h${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};Jj=class Jj extends h${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};f8=class f8 extends h${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};Wj=class Wj extends h${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}};Bj=class Bj extends h${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}};lY=class lY extends h${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};Ej=class Ej extends h${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};jj=class jj extends h${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}};B1={configNotFound($,w,A){return new Xj($,w,A)},configLoad($,w,A){return new dY($,w,A)},configValidation($,w,A){return new Uj($,w,A)},configMerge($,w,A,Y){return new Jj($,w,A,Y)},envVar($,w,A,Y){return new f8($,w,A,Y)},fileSystem($,w,A){return new Wj($,w,A)},typeGeneration($,w,A){return new Bj($,w,A)},schemaValidation($,w,A){return new lY($,w,A)},browserConfig($,w,A,Y){return new Ej($,w,A,Y)},plugin($,w,A){return new jj($,w,A)}};V5=/^https?:\/\//;b$=new oY("bunfig",{showTags:!0});AM=new Kj;YM=U$(rY.cwd(),"config"),fM=U$(rY.cwd(),"src/generated"),Rj={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:EU.join(BU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:EU.join(BU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:EU.join(BU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},W0=Rj,N$={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"},C={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},J1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};k5=D5(_5);Z5=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),x5=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;q$={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},b0={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"};AK={platform:"darwin",async addCertificate($,w){if(await wK($,w?.verbose)){M(C.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),J1.success("Certificate is already trusted in system keychain");return}M(C.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Uw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let Y=A||W0.commonName;M(C.TRUST,`Removing certificate ${Y} from macOS keychain`,w?.verbose);try{await Uw(`sudo security delete-certificate -c "${Y}" /Library/Keychains/System.keychain`),M(C.TRUST,`Removed certificate ${Y} from macOS keychain`,w?.verbose)}catch(f){throw M(C.TRUST,`Error removing certificate: ${f}`,w?.verbose),f}}},YK={platform:"win32",async addCertificate($,w){M(C.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Uw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let Y=A||W0.commonName;M(C.TRUST,`Removing certificate ${Y} from Windows certificate store`,w?.verbose);try{await Uw(`certutil -delstore -enterprise Root "${Y}"`),M(C.TRUST,`Removed certificate ${Y} from Windows certificate store`,w?.verbose)}catch(f){throw M(C.TRUST,`Error removing certificate: ${f}`,w?.verbose),f}}},fK={platform:"linux",async addCertificate($,w){M(C.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=tY.homedir(),Y=N$.LINUX_CERT_DB_FILENAME,f=N$.LINUX_TRUST_ARGS;M(C.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let X=gU(A,Y);if(X.length===0){J1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of X){M(C.TRUST,`Processing certificate database in ${U}`,w?.verbose);try{M(C.TRUST,`Attempting to delete existing cert for ${W0.commonName}`,w?.verbose),await Uw(`certutil -d sql:${U} -D -n ${W0.commonName}`)}catch(W){M(C.TRUST,`Warning: Error deleting existing cert: ${W}`,w?.verbose),console.warn(`Error deleting existing cert: ${W}`)}M(C.TRUST,`Adding new certificate to ${U}`,w?.verbose),await Uw(`certutil -d sql:${U} -A -t ${f} -n ${W0.commonName} -i ${$}`),J1.info(`Cert added to ${U}`)}},async removeCertificate($,w,A){let Y=A||W0.commonName;M(C.TRUST,`Removing certificate ${Y} from Linux certificate store`,w?.verbose);let f=tY.homedir(),X=N$.LINUX_CERT_DB_FILENAME;M(C.TRUST,`Searching for certificate databases in ${f}`,w?.verbose);let U=gU(f,X);if(U.length===0){J1.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of U){M(C.TRUST,`Processing certificate database in ${W}`,w?.verbose);try{await Uw(`certutil -d sql:${W} -D -n "${Y}"`),J1.info(`Cert removed from ${W}`)}catch(J){M(C.TRUST,`Error removing cert from ${W}: ${J}`,w?.verbose),console.warn(`Error removing cert from ${W}: ${J}`)}}}},XK={darwin:AK,win32:YK,linux:fK}});var T8=E0(()=>{Qj()});import{homedir as F8}from"node:os";import{join as z8,resolve as wI}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",UK,G8;var H8=E0(()=>{XU();UK={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:z8(F8(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:z8(F8(),".stacks","ssl","stacks.localhost.crt"),keyPath:z8(F8(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},G8=UK});import{execSync as JK}from"node:child_process";function Dj($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function $f($){try{let w=JK(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return Dj(w)}catch{return null}}var K8=()=>{};import{existsSync as kj,statSync as Zj}from"fs";import{existsSync as P8,mkdirSync as FK,readdirSync as zK,writeFileSync as GK}from"fs";import{homedir as j1}from"os";import{dirname as xj,resolve as u0}from"path";import Mw from"process";import{join as HK,relative as KK,resolve as Pj}from"path";import Kf from"process";import{existsSync as RT,mkdirSync as zI,readdirSync as GI,writeFileSync as HI}from"fs";import{homedir as R8}from"os";import{dirname as NI,resolve as c0}from"path";import r1 from"process";import{join as RK,relative as NK,resolve as ij}from"path";import Rf from"process";import{existsSync as NT,mkdirSync as II,readdirSync as CI,writeFileSync as SI}from"fs";import{dirname as VI,resolve as Nf}from"path";import i8 from"process";import{Buffer as Bw}from"buffer";import{createCipheriv as qK,createDecipheriv as hK,randomBytes as N8}from"crypto";import{closeSync as q8,createReadStream as bj,createWriteStream as yK,existsSync as h8,fsyncSync as cj,openSync as uj,writeFileSync as MK}from"fs";import{access as IK,constants as nj,mkdir as CK,readdir as wf,rename as vj,stat as T1,unlink as Af,writeFile as y8}from"fs/promises";import{join as F1}from"path";import _0 from"process";import{pipeline as SK}from"stream/promises";import{createGzip as mj}from"zlib";import z1 from"process";import g$ from"process";import{Buffer as d$}from"buffer";import{createCipheriv as LK,createDecipheriv as VK,randomBytes as M8}from"crypto";import{closeSync as I8,createReadStream as dj,createWriteStream as OK,existsSync as Yf,fsyncSync as lj,openSync as gj,writeFileSync as _K}from"fs";import{access as QK,constants as tj,mkdir as DK,readdir as ff,rename as pj,stat as G1,unlink as Xf,writeFile as C8}from"fs/promises";import{isAbsolute as kK,join as H1,resolve as ZK}from"path";import D from"process";import{pipeline as xK}from"stream/promises";import{createGzip as rj}from"zlib";import K1 from"process";import t$ from"process";import Uf from"process";import{existsSync as Jf}from"fs";import{resolve as S8}from"path";import{existsSync as PK}from"fs";import{existsSync as iK,readdirSync as bK}from"fs";import{extname as L8,resolve as aj}from"path";import cK from"process";import{join as u6,relative as n6,resolve as WT}from"path";import Sf from"process";import{Buffer as l$}from"buffer";import{createCipheriv as d6,createDecipheriv as l6,randomBytes as D8}from"crypto";import{closeSync as k8,createReadStream as BT,createWriteStream as g6,existsSync as Bf,fsyncSync as ET,openSync as jT,writeFileSync as t6}from"fs";import{access as p6,constants as TT,mkdir as r6,readdir as Ef,rename as FT,stat as R1,unlink as jf,writeFile as Z8}from"fs/promises";import{isAbsolute as a6,join as N1,resolve as s6}from"path";import k from"process";import{pipeline as o6}from"stream/promises";import{createGzip as zT}from"zlib";import q1 from"process";import p$ from"process";function EK($,w){this[$]=BK.bind(null,w)}class t8{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],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!kj($))return!0;return Zj($).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,Y){try{let f=kj(A)?Zj(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}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((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.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 Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class p8{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function uK($,w={}){let Y=Object.keys(w).sort().map((f)=>`${f}:${w[f]}`).join("|");return Y?`${$}:${Y}`:$}function nK($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function vK($){return $.getStats().size*2}function r8($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&$0(w[0])&&"id"in w[0]&&w[0].id===3&&$0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if($0(w)&&$0($)&&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($0($)&&"arr"in $&&Array.isArray($.arr)&&$0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&$0(w[0])&&$0($[0])){let Y=[...w];for(let f of $)if($0(f)&&"name"in f){if(!Y.find((U)=>$0(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if($0(f)&&"path"in f){if(!Y.find((U)=>$0(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>qf(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!$0(w)||!$0($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if($0(f)&&$0(A[Y]))A[Y]=r8(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&$0(f[0])&&$0(A[Y][0])){let X=[...f];for(let U of A[Y])if($0(U)&&"name"in U){if(!X.find((J)=>$0(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if($0(U)&&"path"in U){if(!X.find((J)=>$0(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>qf(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function qf($,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(!qf($[A],w[A]))return!1;return!0}if($0($)&&$0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!qf($[f],w[f]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function mK($,w){if(!NT($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return r8(w,Y)}catch{return null}}catch{return null}}async function dK({name:$="",cwd:w,defaultConfig:A}){let Y=w||i8.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=Nf(Y,`${U}${W}`),B=await mK(J,A);if(B!==null)return B}try{let U=Nf(Y,"package.json");if(NT(U)){let J=(await import(U))[$];if(J&&typeof J==="object"&&!Array.isArray(J))try{return r8(A,J)}catch{}}}catch{}return A}function lK($,w={}){let A=Rf.cwd();while(A.includes("storage"))A=ij(A,"..");let Y=ij(A,$||"");if(w?.relative)return NK(Rf.cwd(),Y);return Y}async function gK(){try{let $=await dK({name:"clarity",defaultConfig:Ff,cwd:Rf.cwd(),endpoint:"",headers:{}});return{...Ff,...$}}catch{return Ff}}function X0(){if(g$.env.NODE_ENV==="test"||g$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function tK(){if(g$.env.NODE_ENV==="test"||g$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof g$<"u"){let $=g$.type;if($==="renderer"||$==="worker")return!1;return!!(g$.versions&&(g$.versions.node||g$.versions.bun))}return!1}class qT{async format($){let w=await tK(),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:z1.pid,hostname:w(),environment:z1.env.NODE_ENV||"development",platform:z1.platform,version:z1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:z1.env.NODE_ENV||z1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class hf{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={...c8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new qT,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??_0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...zf,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...zf};return{...zf,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:c8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==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 f,X=0,U=3,W=1000;while(X<U)try{try{try{await IK(this.config.logDirectory,nj.F_OK|nj.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await CK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Bw.from($);try{if(!h8(this.currentLogFile))await y8(this.currentLogFile,"",{mode:420});if(f=uj(this.currentLogFile,"a",420),MK(f,J,{flag:"a"}),cj(f),f!==void 0)q8(f),f=void 0;if((await T1(this.currentLogFile)).size===0){if(await y8(this.currentLogFile,J,{flag:"w",mode:420}),(await T1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{q8(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 F1(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 F1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return F1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(X0())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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return N8(16).toString("hex")}generateKey(){return N8(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=N8(16),Y=qK("aes-256-gcm",w,A),f=Bw.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:Bw.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=mj(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(Bw.from(Bw.concat(f)))),Y.on("error",A),Y.write($),Y.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(X0())return;let $=await T1(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await wf(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await T1(A).catch(()=>null))try{if(await vj(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await Af(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await y8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await T1(A).catch(()=>null))await vj(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await wf(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await Af(F1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=bj($),Y=yK(w),f=mj();await SK(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}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()})),h8(this.currentLogFile))try{let $=uj(this.currentLogFile,"r+");cj($),q8($)}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(!X0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await wf(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await Af(F1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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?r.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=_0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${r.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!X0()){let B=_T[$],E=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:r.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:r.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
133
|
+
`);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:r.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!X0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let J=`${X} ${this.environment}.${$.toUpperCase()}: ${U}
|
|
134
134
|
`;if(W)J+=`${W}
|
|
135
|
-
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time($){let w=performance.now();if(this.fancy&&!
|
|
136
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
137
|
-
`),U=Math.max(...X.map((E)=>E.length))+2,W=`┌${"─".repeat(U)}┐`,J=`└${"─".repeat(U)}┘`,B=X.map((E)=>{let j=" ".repeat(U-E.length-2);return`│ ${E}${j} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:
|
|
138
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt($){if(
|
|
139
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||
|
|
140
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||X$()||!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(X$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await wf(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=T1(this.config.logDirectory,Y);if($.before)try{if((await j1(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}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 Y of A)try{await Af(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function Tf($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&l(w[0])&&"id"in w[0]&&w[0].id===3&&l(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(l(w)&&l($)&&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(l($)&&"arr"in $&&Array.isArray($.arr)&&l(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&l(w[0])&&l($[0])){let Y=[...w];for(let f of $)if(l(f)&&"name"in f){if(!Y.find((U)=>l(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(l(f)&&"path"in f){if(!Y.find((U)=>l(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>yf(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!l(w)||!l($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(l(f)&&l(A[Y]))A[Y]=Tf(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&l(f[0])&&l(A[Y][0])){let X=[...f];for(let U of A[Y])if(l(U)&&"name"in U){if(!X.find((J)=>l(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(l(U)&&"path"in U){if(!X.find((J)=>l(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>yf(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function rU($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:Tf($,w);if(Array.isArray($))return A==="replace"?w:Tf($,w);if(!l(w)||!l($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=Tf(U,X);else if(l(X)&&l(U))Y[f]=rU(U,X,A);else Y[f]=X}return Y}function yf($,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(!yf($[A],w[A]))return!1;return!0}if(l($)&&l(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!yf($[f],w[f]))return!1}return!0}return!1}function l($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function Wf($,w,A="replace"){if(!KT($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return rU(w,f,A)}catch{return null}}catch{return null}}function tK($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((G)=>G.toUpperCase()).join("_")}`;if(A)D$.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let G=r1.env[F]||r1.env[H];if(G!==void 0){if(A)D$.info(`Using environment variable ${G?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(G);else if(typeof E==="boolean")J[B]=G.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(G);if(Array.isArray(K))J[B]=K;else J[B]=G.split(",").map((R)=>R.trim())}catch{J[B]=G.split(",").map((K)=>K.trim())}else J[B]=G}}}return J}return X(f)}async function pK({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?tK($,f,X):f,B=A||r1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)D$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],G=Array.from(new Set([B,c$(B,"config"),c$(B,".config"),Y?c$(B,Y):void 0].filter(Boolean)));for(let K of G){if(X)D$.info(`Searching for configuration in: ${K}`);let h=[c$(B,"config"),c$(B,".config")].concat(Y?[c$(B,Y)]:[]).includes(K)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let N of h)for(let M of E){let C=c$(K,`${N}${M}`),y=await Wf(C,J,W);if(y!==null){if(X)D$.success(`Configuration loaded from: ${C}`);return y}}}if($){let K=c$(KU(),".config",$),R=["config",`${$}.config`];if(w)R.push(`${w}.config`);if(X)D$.info(`Checking user config directory: ${K}`);for(let h of R)for(let N of E){let M=c$(K,`${h}${N}`),C=await Wf(M,J,W);if(C!==null){if(X)D$.success(`Configuration loaded from user config directory: ${M}`);return C}}}if($){let K=c$(KU(),".config"),R=[`.${$}.config`];if(w)R.push(`.${w}.config`);if(X)D$.info(`Checking user config directory for dotfile configs: ${K}`);for(let h of R)for(let N of E){let M=c$(K,`${h}${N}`),C=await Wf(M,J,W);if(C!==null){if(X)D$.success(`Configuration loaded from user config directory dotfile: ${M}`);return C}}}if($){let K=KU(),R=[`.${$}.config`,`.${$}`];if(w)R.push(`.${w}.config`),R.push(`.${w}`);if(X)D$.info(`Checking user home directory for dotfile configs: ${K}`);for(let h of R)for(let N of E){let M=c$(K,`${h}${N}`),C=await Wf(M,J,W);if(C!==null){if(X)D$.success(`Configuration loaded from user home directory: ${M}`);return C}}}try{let K=c$(B,"package.json");if(KT(K)){let R=await import(K),h=R[$];if(!h&&w){if(h=R[w],h&&X)D$.success(`Using alias "${w}" configuration from package.json`)}if(h&&typeof h==="object"&&!Array.isArray(h))try{if(X)D$.success(`Configuration loaded from package.json: ${h===R[$]?$:w}`);return rU(J,h,W)}catch(N){if(X)D$.warn("Failed to merge package.json config:",N)}}}catch(K){if(X)D$.warn("Failed to load package.json:",K)}if(X)D$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function rK($,w={}){let A=Kf.cwd();while(A.includes("storage"))A=xj(A,"..");let Y=xj(A,$||"");if(w?.relative)return HK(Kf.cwd(),Y);return Y}async function aK(){try{let $=await pK({name:"clarity",alias:"logging",defaultConfig:Gf,cwd:Kf.cwd()});return{...Gf,...$||{}}}catch{return Gf}}function K$(){if(l0.env.NODE_ENV==="test"||l0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function sK(){if(l0.env.NODE_ENV==="test"||l0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof l0<"u"){let $=l0.type;if($==="renderer"||$==="worker")return!1;return!!(l0.versions&&(l0.versions.node||l0.versions.bun))}return!1}class qT{async format($){let w=await sK(),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:H1.pid,hostname:w(),environment:H1.env.NODE_ENV||"development",platform:H1.platform,version:H1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:H1.env.NODE_ENV||H1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mf{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={...cU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new qT,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??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...Hf,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Hf};return{...Hf,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:cU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!K$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await QK(this.config.logDirectory,gj.F_OK|gj.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await _K(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:v0.from($);try{if(!Yf(this.currentLogFile))await IU(this.currentLogFile,"",{mode:420});if(f=lj(this.currentLogFile,"a",420),VK(f,J,{flag:"a"}),dj(f),f!==void 0)MU(f),f=void 0;if((await z1(this.currentLogFile)).size===0){if(await IU(this.currentLogFile,J,{flag:"w",mode:420}),(await z1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{MU(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 G1(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 G1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return G1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(K$())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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return yU(16).toString("hex")}generateKey(){return yU(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=yU(16),Y=SK("aes-256-gcm",w,A),f=v0.isBuffer($)?$:v0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=v0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=pj(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(v0.from(v0.concat(f)))),Y.on("error",A),Y.write($),Y.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(K$())return;if(!this.shouldWriteToFile())return;let $=await z1(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await ff(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await z1(A).catch(()=>null))try{if(await tj(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await Xf(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await IU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await z1(A).catch(()=>null))await tj(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await ff(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await Xf(G1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=mj($),Y=OK(w),f=pj();await ZK(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),Yf(this.currentLogFile))try{let $=lj(this.currentLogFile,"r+");dj($),MU($)}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(!K$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await ff(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await Xf(G1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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||K$())return!1;let $=typeof _.env.NO_COLOR<"u",w=_.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=_.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${x.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=x.underline(x.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>x.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>x.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>x.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>x.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>x.strikethrough(Y)),w}supportsHyperlinks(){if(K$())return!1;let $=_.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=_.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(DK(w)||w.startsWith("./")||w.startsWith("../"))w=kK(w);else return null;return Yf(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":QT[$],T=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:x.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:x.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
141
|
-
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
135
|
+
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time($){let w=performance.now();if(this.fancy&&!X0()){let A=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:r.blue("◐"),tag:A,message:`${r.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
136
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!X0()){let E=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:r.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!X0())console.error(B.trim());await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=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 hf(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(X0())throw Error("createReadStream is not supported in browser environments");if(!h8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return bj(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 Y=Bw.isBuffer($)?$:Bw.from($,"base64"),f=Y.slice(0,16),X=Y.slice(-16),U=Y.slice(16,-16),W=hK("aes-256-gcm",A,f);return W.setAuthTag(X),Bw.concat([W.update(U),W.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return X0()}isServerMode(){return!X0()}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),Y=this.formatFileTimestamp(w);if(this.fancy&&!X0()){let X=$.split(`
|
|
137
|
+
`),U=Math.max(...X.map((E)=>E.length))+2,W=`┌${"─".repeat(U)}┐`,J=`└${"─".repeat(U)}┘`,B=X.map((E)=>{let j=" ".repeat(U-E.length-2);return`│ ${E}${j} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:r.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:r.cyan(W)})),B.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:A,message:r.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:r.cyan(J),showTimestamp:!1}))}else if(!X0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let f=`${Y} ${this.environment}.INFO: [BOX] ${$}
|
|
138
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt($){if(X0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${r.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();_0.stdin.removeListener("data",A);try{if(typeof _0.stdin.setRawMode==="function")_0.stdin.setRawMode(!1)}catch{}_0.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof _0.stdin.setRawMode==="function")_0.stdin.setRawMode(!0)}catch{}_0.stdin.resume(),_0.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,W=0;if(A=$.replace(U,(J,B)=>{if(B==="%")return"%";if(W>=w.length)return J;let E=w[W++];switch(B){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 J}}),W<w.length)A+=` ${w.slice(W).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!X0()){let U=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",W=r.blue("◐");console.error(`${W} ${U} ${r.cyan(A)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
139
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||X0()||$<=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:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),W!==void 0)this.activeProgressBar.message=W;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())return;_0.stdout.write(`${"\r".padEnd(_0.stdout.columns||80)}\r`),this.log(W,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||X0()||!_0.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=r.green("━".repeat(Y)),U=r.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=w||A===100?r.green("✓"):r.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${r.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=_0.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,_0.stdout.write($.lastRenderedLine),w)_0.stdout.write(`
|
|
140
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||X0()||!_0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(X0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await wf(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=F1(this.config.logDirectory,Y);if($.before)try{if((await T1(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}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 Y of A)try{await Af(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function Tf($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&g(w[0])&&"id"in w[0]&&w[0].id===3&&g(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(g(w)&&g($)&&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(g($)&&"arr"in $&&Array.isArray($.arr)&&g(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&g(w[0])&&g($[0])){let Y=[...w];for(let f of $)if(g(f)&&"name"in f){if(!Y.find((U)=>g(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(g(f)&&"path"in f){if(!Y.find((U)=>g(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>yf(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!g(w)||!g($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(g(f)&&g(A[Y]))A[Y]=Tf(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&g(f[0])&&g(A[Y][0])){let X=[...f];for(let U of A[Y])if(g(U)&&"name"in U){if(!X.find((J)=>g(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(g(U)&&"path"in U){if(!X.find((J)=>g(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>yf(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function a8($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:Tf($,w);if(Array.isArray($))return A==="replace"?w:Tf($,w);if(!g(w)||!g($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=Tf(U,X);else if(g(X)&&g(U))Y[f]=a8(U,X,A);else Y[f]=X}return Y}function yf($,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(!yf($[A],w[A]))return!1;return!0}if(g($)&&g(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!yf($[f],w[f]))return!1}return!0}return!1}function g($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function Wf($,w,A="replace"){if(!RT($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return a8(w,f,A)}catch{return null}}catch{return null}}function pK($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((G)=>G.toUpperCase()).join("_")}`;if(A)D0.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let G=r1.env[F]||r1.env[H];if(G!==void 0){if(A)D0.info(`Using environment variable ${G?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(G);else if(typeof E==="boolean")J[B]=G.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(G);if(Array.isArray(K))J[B]=K;else J[B]=G.split(",").map((R)=>R.trim())}catch{J[B]=G.split(",").map((K)=>K.trim())}else J[B]=G}}}return J}return X(f)}async function rK({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?pK($,f,X):f,B=A||r1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)D0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],G=Array.from(new Set([B,c0(B,"config"),c0(B,".config"),Y?c0(B,Y):void 0].filter(Boolean)));for(let K of G){if(X)D0.info(`Searching for configuration in: ${K}`);let N=[c0(B,"config"),c0(B,".config")].concat(Y?[c0(B,Y)]:[]).includes(K)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let h of N)for(let y of E){let I=c0(K,`${h}${y}`),S=await Wf(I,J,W);if(S!==null){if(X)D0.success(`Configuration loaded from: ${I}`);return S}}}if($){let K=c0(R8(),".config",$),R=["config",`${$}.config`];if(w)R.push(`${w}.config`);if(X)D0.info(`Checking user config directory: ${K}`);for(let N of R)for(let h of E){let y=c0(K,`${N}${h}`),I=await Wf(y,J,W);if(I!==null){if(X)D0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let K=c0(R8(),".config"),R=[`.${$}.config`];if(w)R.push(`.${w}.config`);if(X)D0.info(`Checking user config directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=c0(K,`${N}${h}`),I=await Wf(y,J,W);if(I!==null){if(X)D0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let K=R8(),R=[`.${$}.config`,`.${$}`];if(w)R.push(`.${w}.config`),R.push(`.${w}`);if(X)D0.info(`Checking user home directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=c0(K,`${N}${h}`),I=await Wf(y,J,W);if(I!==null){if(X)D0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let K=c0(B,"package.json");if(RT(K)){let R=await import(K),N=R[$];if(!N&&w){if(N=R[w],N&&X)D0.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(X)D0.success(`Configuration loaded from package.json: ${N===R[$]?$:w}`);return a8(J,N,W)}catch(h){if(X)D0.warn("Failed to merge package.json config:",h)}}}catch(K){if(X)D0.warn("Failed to load package.json:",K)}if(X)D0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function aK($,w={}){let A=Kf.cwd();while(A.includes("storage"))A=Pj(A,"..");let Y=Pj(A,$||"");if(w?.relative)return KK(Kf.cwd(),Y);return Y}async function sK(){try{let $=await rK({name:"clarity",alias:"logging",defaultConfig:Gf,cwd:Kf.cwd()});return{...Gf,...$||{}}}catch{return Gf}}function K0(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function oK(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t$<"u"){let $=t$.type;if($==="renderer"||$==="worker")return!1;return!!(t$.versions&&(t$.versions.node||t$.versions.bun))}return!1}class hT{async format($){let w=await oK(),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:K1.pid,hostname:w(),environment:K1.env.NODE_ENV||"development",platform:K1.platform,version:K1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:K1.env.NODE_ENV||K1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mf{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={...u8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new hT,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},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...Hf,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Hf};return{...Hf,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:u8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!K0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await QK(this.config.logDirectory,tj.F_OK|tj.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await DK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:d$.from($);try{if(!Yf(this.currentLogFile))await C8(this.currentLogFile,"",{mode:420});if(f=gj(this.currentLogFile,"a",420),_K(f,J,{flag:"a"}),lj(f),f!==void 0)I8(f),f=void 0;if((await G1(this.currentLogFile)).size===0){if(await C8(this.currentLogFile,J,{flag:"w",mode:420}),(await G1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{I8(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 H1(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 H1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return H1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(K0())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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return M8(16).toString("hex")}generateKey(){return M8(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=M8(16),Y=LK("aes-256-gcm",w,A),f=d$.isBuffer($)?$:d$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=d$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=rj(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(d$.from(d$.concat(f)))),Y.on("error",A),Y.write($),Y.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(K0())return;if(!this.shouldWriteToFile())return;let $=await G1(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await ff(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await G1(A).catch(()=>null))try{if(await pj(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await Xf(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await C8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await G1(A).catch(()=>null))await pj(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await ff(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await Xf(H1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=dj($),Y=OK(w),f=rj();await xK(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),Yf(this.currentLogFile))try{let $=gj(this.currentLogFile,"r+");lj($),I8($)}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(!K0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await ff(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await Xf(H1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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||K0())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:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=D.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${P.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=P.underline(P.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>P.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>P.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>P.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>P.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>P.strikethrough(Y)),w}supportsHyperlinks(){if(K0())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(kK(w)||w.startsWith("./")||w.startsWith("../"))w=ZK(w);else return null;return Yf(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":QT[$],T=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:P.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:P.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
141
|
+
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:P.gray(` ${G}`),level:$,showTimestamp:!1}))}break}}else if(!K0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
142
142
|
`;if(W)E+=`${W}
|
|
143
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
144
|
-
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
145
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?
|
|
146
|
-
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:
|
|
147
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
148
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
149
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
143
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!K0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!K0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,J="info")=>{if(!K0()&&D.stdout.isTTY)D.stdout.write(`
|
|
144
|
+
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!K0()&&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)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":P.blue("◐"),tag:A,message:`${P.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
145
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":P.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!K0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=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 Mf(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(K0())throw Error("createReadStream is not supported in browser environments");if(!Yf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return dj(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 Y=d$.isBuffer($)?$:d$.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=VK("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=d$.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return K0()}isServerMode(){return!K0()}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),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
146
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:P.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(E),showTimestamp:!1}))}else if(!K0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
147
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(K0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${P.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.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(f==="y"||f==="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 J=/%([sdijfo%])/g,B=0;if(A=$.replace(J,(E,j)=>{if(j==="%")return"%";if(B>=w.length)return E;let T=w[B++];switch(j){case"s":return String(T);case"d":case"i":return Number(T).toString();case"j":case"o":return JSON.stringify(T,null,2);default:return E}}),B<w.length)A+=` ${w.slice(B).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${P.blue("◐")} `;console.error(`${B}${J} ${P.cyan(Y)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
148
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}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))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=P.green("━".repeat(Y)),U=P.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?P.green("✓"):P.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=D.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,D.stdout.write($.lastRenderedLine),w)D.stdout.write(`
|
|
149
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||K0()||!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(K0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await ff(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=H1(this.config.logDirectory,Y);if($.before)try{if((await G1(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}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 Y of A)try{await Xf(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function yT($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:f=()=>!0,fallback:X}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(J){if(U=J instanceof Error?J:Error(String(J)),W===A||!f(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(X!==void 0)return X;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function MT($){return $ instanceof o0}function eK($){return $ instanceof If}function $6($){if(MT($))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 Vf{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:Y,useCamelCase:f=!0,useBackwardCompatibility:X=!0,customParsers:U={},verbose:W=!1,trackPerformance:J=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix($),j={...w};return this.processObject(j,[],E,{useCamelCase:f,useBackwardCompatibility:X,customParsers:U,verbose:W,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return o1.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=U.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),J=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,U,A,Y);else{let E=Uf.env[J]||(B?Uf.env[B]:void 0);if(E!==void 0){if(Y.verbose){let j=Uf.env[J]?J:B}try{$[f]=this.parseEnvironmentValue(E,typeof X,J,Y.customParsers,Y.configName)}catch(j){if(j instanceof Cf)throw j;throw Ew.envVar(J,E,typeof X,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,f){for(let[X,U]of Object.entries(Y))try{return U($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw Ew.envVar(A,$,`${w} (via ${X.name} parser)`,f)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,f]of Object.entries(Uf.env))if(Y.startsWith(A)&&f!==void 0)w[Y]=f;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(f){Y.push(`Cannot parse value "${w}" as ${A}: ${f}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:f="text"}=A,X=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],X,U),f){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=`${A}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,U,A,Y);else Y.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${U.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
150
150
|
|
|
151
151
|
`;for(let Y of $)A+=`${Y.key}
|
|
152
152
|
`,A+=` Type: ${Y.type}
|
|
@@ -158,97 +158,98 @@ ${Y.join(`
|
|
|
158
158
|
`;A+=`| Variable | Type | Description | Example |
|
|
159
159
|
`,A+=`|----------|------|-------------|----------|
|
|
160
160
|
`;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
161
|
-
`;return A}}function $6($,w){let A=LT("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function MT($,w,A={}){return IT($,w,A,new WeakMap)}function IT($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return CT($,w,f,Y);if(!J0(w)||!J0($))return w;return f6($,w,A,Y)}function CT($,w,A,Y){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 w6($,w);case"smart":return A6($,w,Y);default:return w}return w}function w6($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>iU(f,Y)))A.push(Y);return A}function A6($,w,A){if(w.length===0)return $;if($.length===0)return w;if(J0(w[0])&&J0($[0]))return Y6($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function Y6($,w,A){let Y=[...w];for(let f of $){if(!J0(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>J0(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function f6($,w,A,Y){let f=w;if(J0(f)&&Y.has(f))return Y.get(f);let X={...$};if(J0(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(J0(W)&&J0(J))X[U]=IT(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=CT(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function aU($,w,A="replace"){return MT($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function iU($,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(!iU($[A],w[A]))return!1;return!0}if(J0($)&&J0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!iU($[f],w[f]))return!1}return!0}return!1}function J0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class Vf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=q1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!Jf($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new a1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new a1($,Error("Configuration must export a valid object"),"unknown");let K={config:aU(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)q1.setWithFileCheck("file",K,$,X);return K}catch(B){throw B instanceof Error?Ww.configLoad($,B):Ww.configLoad($,Error(String(B)))}};if(U)return o1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(CU(w,`${X}${U}`));return f}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 NT(async()=>{return Jf($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!Jf($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=CU($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=CU($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}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(!Jf($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}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(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class sU{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await o1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!xK(w))throw new s1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new s1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.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)Y.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($))Y.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)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.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($))Y.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 f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}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:DT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class oU{fileLoader=new Vf;envProcessor=new Of;validator=new sU;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)q0.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw q0.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||Nw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(u$(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw Ww.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?p1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)q0.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)q0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?p1($,A,f):A,W=[u$(E1(),".config",$),u$(E1(),".config"),E1()];for(let J of W){if(f)q0.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)q0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?p1($,Y,X):Y;try{let J=u$(A,"package.json");if(!xU(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)q0.success(`Configuration loaded from package.json: ${j}`);return{config:aU(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)q0.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:p1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw Ww.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return q1.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);q1.set(f,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([$,u$($,"config"),u$($,".config"),w?u$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(u$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[u$(E1(),".config",$),u$(E1(),".config"),E1()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function aj($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function X6($){return t0.loadConfig({...$,__strictErrorHandling:!0})}async function ST($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await t0.loadConfig($);else Y=await t0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)q0.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await t0.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function U6($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await t0.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"&&aj(A)))return(await t0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await t0.loadConfig({...$,cwd:$.cwd||Nw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&aj(w)))return(await t0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function J6($,w,A="replace"){let Y=new Vf;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function p1($,w,A=!1){let Y=new Of,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=Nw.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function W6($){let w=u$(Nw.cwd(),$.configDir),A=u$(Nw.cwd(),$.generatedDir),Y=u$(A,"config-types.ts");if(!xU(Zj(Y)))TK(Zj(Y),{recursive:!0,mode:511});let f=xU(w)?FK(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${i6}
|
|
161
|
+
`;return A}}function w6($,w){let A=VT("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function IT($,w,A={}){return CT($,w,A,new WeakMap)}function CT($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return ST($,w,f,Y);if(!B$(w)||!B$($))return w;return X6($,w,A,Y)}function ST($,w,A,Y){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 A6($,w);case"smart":return Y6($,w,Y);default:return w}return w}function A6($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>b8(f,Y)))A.push(Y);return A}function Y6($,w,A){if(w.length===0)return $;if($.length===0)return w;if(B$(w[0])&&B$($[0]))return f6($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function f6($,w,A){let Y=[...w];for(let f of $){if(!B$(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>B$(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function X6($,w,A,Y){let f=w;if(B$(f)&&Y.has(f))return Y.get(f);let X={...$};if(B$(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(B$(W)&&B$(J))X[U]=CT(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=ST(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function s8($,w,A="replace"){return IT($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function b8($,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(!b8($[A],w[A]))return!1;return!0}if(B$($)&&B$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!b8($[f],w[f]))return!1}return!0}return!1}function B$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class Of{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=h1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!Jf($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new a1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new a1($,Error("Configuration must export a valid object"),"unknown");let K={config:s8(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)h1.setWithFileCheck("file",K,$,X);return K}catch(B){throw B instanceof Error?Ew.configLoad($,B):Ew.configLoad($,Error(String(B)))}};if(U)return o1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(S8(w,`${X}${U}`));return f}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 yT(async()=>{return Jf($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!Jf($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=S8($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=S8($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}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(!Jf($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}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(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class o8{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await o1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!PK(w))throw new s1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new s1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.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)Y.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($))Y.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)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.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($))Y.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 f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}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:kT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class e8{fileLoader=new Of;envProcessor=new Vf;validator=new o8;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)y$.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw y$.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||Mw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(u0(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw Ew.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?p1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)y$.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)y$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?p1($,A,f):A,W=[u0(j1(),".config",$),u0(j1(),".config"),j1()];for(let J of W){if(f)y$.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)y$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?p1($,Y,X):Y;try{let J=u0(A,"package.json");if(!P8(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)y$.success(`Configuration loaded from package.json: ${j}`);return{config:s8(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)y$.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:p1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw Ew.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return h1.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);h1.set(f,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([$,u0($,"config"),u0($,".config"),w?u0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(u0(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[u0(j1(),".config",$),u0(j1(),".config"),j1()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function sj($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function U6($){return r$.loadConfig({...$,__strictErrorHandling:!0})}async function LT($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await r$.loadConfig($);else Y=await r$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)y$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await r$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function J6($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await r$.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"&&sj(A)))return(await r$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await r$.loadConfig({...$,cwd:$.cwd||Mw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&sj(w)))return(await r$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function W6($,w,A="replace"){let Y=new Of;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function p1($,w,A=!1){let Y=new Vf,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=Mw.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function B6($){let w=u0(Mw.cwd(),$.configDir),A=u0(Mw.cwd(),$.generatedDir),Y=u0(A,"config-types.ts");if(!P8(xj(Y)))FK(xj(Y),{recursive:!0,mode:511});let f=P8(w)?zK(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${b6}
|
|
162
162
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
163
|
-
`;
|
|
164
|
-
${f.map((B)=>{let E=
|
|
163
|
+
`;GK(Y,X,{mode:438})}function E6($){let w=null,A=null,Y=()=>{if(!A)A=LT($).then((X)=>{return w=X,X},(X)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)y$.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return U});return A},f="defaultConfig"in $?$.defaultConfig:{};return w=f,Y(),new Proxy({},{get(X,U){if(w)return w[U];let W=f[U];return Y(),W},has(X,U){return U in(w||f)},ownKeys(){return Object.keys(w||f)},getOwnPropertyDescriptor(X,U){return Object.getOwnPropertyDescriptor(w||f,U)},set(X,U,W){if(!w)w={...f};return w[U]=W,!0}})}function j6($){let w=aj(cK.cwd(),$?.configDir||"./config");function A(){if(!iK(w))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=bK(w).filter((J)=>f.has(L8(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),W=new Map;for(let{base:J,file:B}of U){let E=L8(B).toLowerCase(),j=W.get(J);if(!j){W.set(J,B);continue}let T=L8(j).toLowerCase();if(X.indexOf(E)<X.indexOf(T))W.set(J,B)}return Array.from(W.entries()).map(([J,B])=>({base:J,file:B})).sort((J,B)=>J.base.localeCompare(B.base))}function Y(){let f=A(),X=f.map((B)=>B.base),U=X.length?X.map((B)=>`'${B}'`).join(" | "):"string",W=f.length?`{
|
|
164
|
+
${f.map((B)=>{let E=aj(w,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${E}').default`}).join(`,
|
|
165
165
|
`)}
|
|
166
166
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
167
167
|
export type ConfigByName = ${W}
|
|
168
168
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
169
169
|
export type ConfigOf = Config
|
|
170
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function n6($,w={}){let A=Sf.cwd();while(A.includes("storage"))A=JT(A,"..");let Y=JT(A,$||"");if(w?.relative)return u6(Sf.cwd(),Y);return Y}function h$(){if(g0.env.NODE_ENV==="test"||g0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function o6(){if(g0.env.NODE_ENV==="test"||g0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof g0<"u"){let $=g0.type;if($==="renderer"||$==="worker")return!1;return!!(g0.versions&&(g0.versions.node||g0.versions.bun))}return!1}class PT{async format($){let w=await o6(),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:h1.pid,hostname:w(),environment:h1.env.NODE_ENV||"development",platform:h1.platform,version:h1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:h1.env.NODE_ENV||h1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yw{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={...Lf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new PT,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},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...ZU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...ZU};return{...ZU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Lf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==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 A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await t6(this.config.logDirectory,jT.F_OK|jT.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await p6(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:m0.from($);try{if(!Bf(this.currentLogFile))await kU(this.currentLogFile,"",{mode:420});if(f=ET(this.currentLogFile,"a",420),g6(f,J,{flag:"a"}),BT(f),f!==void 0)DU(f),f=void 0;if((await K1(this.currentLogFile)).size===0){if(await kU(this.currentLogFile,J,{flag:"w",mode:420}),(await K1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{DU(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 R1(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 R1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return R1(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 w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return _U(16).toString("hex")}generateKey(){return _U(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=_U(16),Y=m6("aes-256-gcm",w,A),f=m0.isBuffer($)?$:m0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=m0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=FT(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(m0.from(m0.concat(f)))),Y.on("error",A),Y.write($),Y.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 K1(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ef(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await K1(A).catch(()=>null))try{if(await TT(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await jf(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await kU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await K1(A).catch(()=>null))await TT(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await Ef(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await jf(R1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=WT($),Y=l6(w),f=FT();await s6(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),Bf(this.currentLogFile))try{let $=ET(this.currentLogFile,"r+");BT($),DU($)}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 w=(await Ef(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await jf(R1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||h$())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:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=D.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${c.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=c.underline(c.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>c.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>c.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>c.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>c.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>c.strikethrough(Y)),w}supportsHyperlinks(){if(h$())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(r6(w)||w.startsWith("./")||w.startsWith("../"))w=a6(w);else return null;return Bf(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":Y7[$],T=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:c.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:c.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
171
|
-
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
170
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function v6($,w={}){let A=Sf.cwd();while(A.includes("storage"))A=WT(A,"..");let Y=WT(A,$||"");if(w?.relative)return n6(Sf.cwd(),Y);return Y}function N0(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function e6(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p$<"u"){let $=p$.type;if($==="renderer"||$==="worker")return!1;return!!(p$.versions&&(p$.versions.node||p$.versions.bun))}return!1}class iT{async format($){let w=await e6(),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:q1.pid,hostname:w(),environment:q1.env.NODE_ENV||"development",platform:q1.platform,version:q1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:q1.env.NODE_ENV||q1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Iw{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={...Lf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new iT,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},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,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{...x8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...x8};return{...x8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Lf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await p6(this.config.logDirectory,TT.F_OK|TT.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await r6(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:l$.from($);try{if(!Bf(this.currentLogFile))await Z8(this.currentLogFile,"",{mode:420});if(f=jT(this.currentLogFile,"a",420),t6(f,J,{flag:"a"}),ET(f),f!==void 0)k8(f),f=void 0;if((await R1(this.currentLogFile)).size===0){if(await Z8(this.currentLogFile,J,{flag:"w",mode:420}),(await R1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;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(f!==void 0)try{k8(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 N1(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 N1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return N1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(N0())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,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return D8(16).toString("hex")}generateKey(){return D8(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=D8(16),Y=d6("aes-256-gcm",w,A),f=l$.isBuffer($)?$:l$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=l$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=zT(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(l$.from(l$.concat(f)))),Y.on("error",A),Y.write($),Y.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(N0())return;if(!this.shouldWriteToFile())return;let $=await R1(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,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ef(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await R1(A).catch(()=>null))try{if(await FT(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await jf(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await Z8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await R1(A).catch(()=>null))await FT(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await Ef(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await jf(N1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=BT($),Y=g6(w),f=zT();await o6(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}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()})),Bf(this.currentLogFile))try{let $=jT(this.currentLogFile,"r+");ET($),k8($)}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(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await Ef(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await jf(N1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}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()?u.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let $=typeof k.env.NO_COLOR<"u",w=k.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=k.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${u.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=u.underline(u.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>u.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>u.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>u.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>u.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>u.strikethrough(Y)),w}supportsHyperlinks(){if(N0())return!1;let $=k.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=k.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(a6(w)||w.startsWith("./")||w.startsWith("../"))w=s6(w);else return null;return Bf(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 Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":f7[$],T=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:u.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:u.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
171
|
+
`);for(let G of H)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:u.gray(` ${G}`),level:$,showTimestamp:!1}))}break}}else if(!N0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
172
172
|
`;if(W)E+=`${W}
|
|
173
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
174
|
-
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
175
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?
|
|
176
|
-
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:
|
|
177
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
178
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
179
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||h$()||!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(h$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await Ef(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=R1(this.config.logDirectory,Y);if($.before)try{if((await K1(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}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 Y of A)try{await jf(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var JK,WK=($)=>$,EK=($,w)=>{for(var A in w)JK($,A,{get:w[A],enumerable:!0,configurable:!0,set:BK.bind(w,A)})},jK=($,w)=>()=>($&&(w=$($=0)),w),HT,LT,q1,o1,OT,j6,T6,sj,Ff,bU,_$,p,F6,oj,z6,ej,G6,H6,LU,K6,$T,wT,OU,R6,h6,q6,N6,zf,VT,y6,D$,M6,I6,AT,Gf,cU,R$,x,C6,YT,S6,fT,L6,O6,VU,V6,XT,UT,Q6,QU,_6,D6,k6,Z6,x6,Hf,QT,P6,i6="0.15.6",o$,If,a1,uU,nU,Cf,vU,mU,s1,dU,lU,Ww,_T,DT,q0,t0,kT,ZT,b6,v6,xT,Lf,wC,M$,c,TC,e6,FC,$7,zC,GC,zT,HC,w7,A7,KC,GT,RC,hC,qC,NC,yC,ZU,Y7,MC;var eU=E$(()=>{JK=Object.defineProperty;HT={};EK(HT,{withErrorRecovery:()=>NT,tryLoadConfig:()=>J6,loadConfigWithResult:()=>X6,loadConfig:()=>ST,isRetryableError:()=>eK,isConfigNotFoundError:()=>oK,isBunfigError:()=>yT,globalPerformanceMonitor:()=>o1,globalCache:()=>q1,getEnvOrDefault:()=>$6,generateConfigTypes:()=>W6,defaultGeneratedDir:()=>ZT,defaultConfigDir:()=>kT,deepMergeWithArrayStrategy:()=>aU,deepMerge:()=>MT,createLibraryConfig:()=>B6,config:()=>U6,bunfigPlugin:()=>E6,applyEnvVarsToConfig:()=>p1,TypeGenerationError:()=>mU,SchemaValidationError:()=>s1,PluginError:()=>lU,PerformanceMonitor:()=>tU,FileSystemError:()=>vU,ErrorFactory:()=>Ww,EnvVarError:()=>Cf,EnvProcessor:()=>Of,ConfigValidator:()=>sU,ConfigValidationError:()=>uU,ConfigNotFoundError:()=>If,ConfigMergeError:()=>nU,ConfigLoader:()=>oU,ConfigLoadError:()=>a1,ConfigFileLoader:()=>Vf,ConfigCache:()=>gU,CacheUtils:()=>OT,BunfigError:()=>o$,BrowserConfigError:()=>dU,ArrayMergeStrategies:()=>_T});b6=jK(async()=>{LT=import.meta.require,q1=new gU,o1=new tU,OT={createKey:cK,isEquivalent:uK,estimateMemoryUsage:nK},j6=hf(PU.cwd(),"config"),T6=hf(PU.cwd(),"src/generated"),sj=Rf.env.CLARITY_LOG_DIR||KK(dK(),"logs"),Ff={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:sj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},bU=await lK(),_$={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"},p=_$,F6=_$.red,oj=_$.green,z6=_$.yellow,ej=_$.blue,G6=_$.magenta,H6=_$.cyan,LU=_$.white,K6=_$.gray,$T=_$.bgRed,wT=_$.bgYellow,OU=_$.bold,R6=_$.dim,h6=_$.italic,q6=_$.underline,N6=_$.reset,zf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},VT={debug:"\uD83D\uDD0D",info:ej("ℹ"),success:oj("✓"),warning:wT(LU(OU(" WARN "))),error:$T(LU(OU(" ERROR ")))},y6=new Nf("stacks"),D$=new Nf("bunfig",{showTags:!0}),M6=c$(r1.cwd(),"config"),I6=c$(r1.cwd(),"src/generated"),AT=Kf.env.CLARITY_LOG_DIR||GK(rK(),"logs"),Gf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:AT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},cU=await aK(),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`,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=R$,C6=R$.red,YT=R$.green,S6=R$.yellow,fT=R$.blue,L6=R$.magenta,O6=R$.cyan,VU=R$.white,V6=R$.gray,XT=R$.bgRed,UT=R$.bgYellow,Q6=R$.bgGray,QU=R$.bold,_6=R$.dim,D6=R$.italic,k6=R$.underline,Z6=R$.strikethrough,x6=R$.reset,Hf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},QT={debug:"\uD83D\uDD0D",info:fT("ℹ"),success:YT("✓"),warning:UT(VU(QU(" WARN "))),error:XT(VU(QU(" ERROR ")))},P6=new Mf("stacks"),o$=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,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},If=class extends o${code="CONFIG_NOT_FOUND";constructor(w,A,Y){let f=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${f} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},a1=class extends o${code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},uU=class extends o${code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},nU=class extends o${code="CONFIG_MERGE_ERROR";constructor(w,A,Y,f){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:f,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Cf=class extends o${code="ENV_VAR_ERROR";constructor(w,A,Y,f){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:f})}},vU=class extends o${code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},mU=class extends o${code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},s1=class extends o${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},dU=class extends o${code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,f){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:f})}},lU=class extends o${code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Ww={configNotFound($,w,A){return new If($,w,A)},configLoad($,w,A){return new a1($,w,A)},configValidation($,w,A){return new uU($,w,A)},configMerge($,w,A,Y){return new nU($,w,A,Y)},envVar($,w,A,Y){return new Cf($,w,A,Y)},fileSystem($,w,A){return new vU($,w,A)},typeGeneration($,w,A){return new mU($,w,A)},schemaValidation($,w,A){return new s1($,w,A)},browserConfig($,w,A,Y){return new dU($,w,A,Y)},plugin($,w,A){return new lU($,w,A)}},_T={replace:"replace",concat:"concat",smart:"smart"},DT=/^https?:\/\//,q0=new Mf("bunfig",{showTags:!0}),t0=new oU,kT=u$(Nw.cwd(),"config"),ZT=u$(Nw.cwd(),"src/generated")});v6=Sf.env.CLARITY_LOG_DIR||c6(n6(),"logs"),xT={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:v6,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lf={...xT},wC=(async()=>{try{let{loadConfig:$}=await b6().then(()=>HT),w=await $({name:"clarity",alias:"logging",defaultConfig:xT,cwd:Sf.cwd()});if(w)Object.assign(Lf,w)}catch{}return Lf})();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`,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"},c=M$,TC=M$.red,e6=M$.green,FC=M$.yellow,$7=M$.blue,zC=M$.magenta,GC=M$.cyan,zT=M$.white,HC=M$.gray,w7=M$.bgRed,A7=M$.bgYellow,KC=M$.bgGray,GT=M$.bold,RC=M$.dim,hC=M$.italic,qC=M$.underline,NC=M$.strikethrough,yC=M$.reset,ZU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Y7={debug:"\uD83D\uDD0D",info:$7("ℹ"),success:e6("✓"),warning:A7(zT(GT(" WARN "))),error:w7(zT(GT(" ERROR ")))};MC=new yw("stacks")});var N1={};dJ(N1,{safeStringify:()=>W0,safeDeleteFile:()=>AJ,resolvePathRewrite:()=>wJ,redactSensitive:()=>Qf,isValidRootCA:()=>$J,isSingleProxyOptions:()=>$A,isSingleProxyConfig:()=>B7,isMultiProxyOptions:()=>Iw,isMultiProxyConfig:()=>uT,getSudoPassword:()=>Mw,getPrimaryDomain:()=>_f,extractHostname:()=>W7,execSudoSync:()=>e1,debugLog:()=>z});import{execSync as iT}from"node:child_process";import*as cT from"node:fs/promises";function Mw(){return process.env.SUDO_PASSWORD}function e1($){let w=Mw(),A=$.replace(/'/g,"'\\''");if(w)return iT(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return iT(`sudo -n sh -c '${A}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function z($,w,A){if(A)f7.debug(`[rpx:${$}] ${w}`)}function J7($){let w=$.toLowerCase();return X7.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function Qf($){if(Array.isArray($))return $.map((A)=>Qf(A));if(typeof $==="string")return U7.test($)?bT:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(J7(A)){w[A]=bT;continue}w[A]=Qf(Y)}return w}function W0($,w){return JSON.stringify(Qf($),null,w)}function W7($){if(Iw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if($A($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function $J($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function _f($){if(!$)return"stacks.localhost";if(Iw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if($A($))return $.to||"stacks.localhost";return"stacks.localhost"}function uT($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function Iw($){return"proxies"in $&&Array.isArray($.proxies)}function $A($){return"to"in $&&typeof $.to==="string"}function B7($){return!!($&&("to"in $)&&!("proxies"in $))}function wJ($,w){if(!w||w.length===0)return null;for(let A of w)if($===A.from||$.startsWith(`${A.from}/`)){let Y=A.to.startsWith("http")?new URL(A.to).host:A.to,f=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:Y,targetPath:f}}return null}async function AJ($,w){try{await cT.unlink($),z("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")z("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var f7,bT="[redacted]",X7,U7;var U$=E$(()=>{eU();f7=new yw("rpx",{showTags:!1});X7=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),U7=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as Df}from"node:child_process";import{homedir as E7}from"node:os";import{join as j7}from"node:path";function kf(){return j7(E7(),"Library/Keychains/login.keychain-db")}function fJ(){return[M1,kf()]}function nT($,w=YJ){let A=Df(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),Y=[];for(let f of A.split(`
|
|
180
|
-
`)){let X=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(X)Y.push(X[1].toUpperCase())}return Y}function
|
|
181
|
-
`))if(X.toUpperCase().includes("SHA-256")){if(X.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===A)return z("ssl",`Root CA fingerprint found in ${Y}`,w?.verbose),!0}}catch{}return!1}var
|
|
173
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!N0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!N0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,J="info")=>{if(!N0()&&k.stdout.isTTY)k.stdout.write(`
|
|
174
|
+
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!N0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":u.blue("◐"),tag:A,message:`${u.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
175
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":u.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!N0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=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 Iw(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(N0())throw Error("createReadStream is not supported in browser environments");if(!Bf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return BT(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 Y=l$.isBuffer($)?$:l$.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=l6("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=l$.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N0()}isServerMode(){return!N0()}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),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
176
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:u.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:u.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:u.cyan(E),showTimestamp:!1}))}else if(!N0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
177
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(N0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${u.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.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(f==="y"||f==="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 J=/%([sdijfo%])/g,B=0;if(A=$.replace(J,(E,j)=>{if(j==="%")return"%";if(B>=w.length)return E;let T=w[B++];switch(j){case"s":return String(T);case"d":case"i":return Number(T).toString();case"j":case"o":return JSON.stringify(T,null,2);default:return E}}),B<w.length)A+=` ${w.slice(B).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${B}${J} ${u.cyan(Y)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
178
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!k.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=u.green("━".repeat(Y)),U=u.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?u.green("✓"):u.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=k.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,k.stdout.write($.lastRenderedLine),w)k.stdout.write(`
|
|
179
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||N0()||!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(N0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await Ef(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=N1(this.config.logDirectory,Y);if($.before)try{if((await R1(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}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 Y of A)try{await jf(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var WK,BK=($)=>$,jK=($,w)=>{for(var A in w)WK($,A,{get:w[A],enumerable:!0,configurable:!0,set:EK.bind(w,A)})},TK=($,w)=>()=>($&&(w=$($=0)),w),KT,VT,h1,o1,OT,T6,F6,oj,Ff,c8,Q0,r,z6,ej,G6,$T,H6,K6,V8,R6,wT,AT,O8,N6,q6,h6,y6,zf,_T,M6,D0,I6,C6,YT,Gf,u8,R0,P,S6,fT,L6,XT,V6,O6,_8,_6,UT,JT,Q6,Q8,D6,k6,Z6,x6,P6,Hf,QT,i6,b6="0.15.6",o0,If,a1,n8,v8,Cf,m8,d8,s1,l8,g8,Ew,DT,kT,y$,r$,ZT,xT,c6,m6,PT,Lf,XC,M0,u,HC,$7,KC,w7,RC,NC,GT,qC,A7,Y7,hC,HT,yC,MC,IC,CC,SC,x8,f7,LC;var $J=E0(()=>{WK=Object.defineProperty;KT={};jK(KT,{withErrorRecovery:()=>yT,tryLoadConfig:()=>W6,loadConfigWithResult:()=>U6,loadConfig:()=>LT,isRetryableError:()=>$6,isConfigNotFoundError:()=>eK,isBunfigError:()=>MT,globalPerformanceMonitor:()=>o1,globalCache:()=>h1,getEnvOrDefault:()=>w6,generateConfigTypes:()=>B6,defaultGeneratedDir:()=>xT,defaultConfigDir:()=>ZT,deepMergeWithArrayStrategy:()=>s8,deepMerge:()=>IT,createLibraryConfig:()=>E6,config:()=>J6,bunfigPlugin:()=>j6,applyEnvVarsToConfig:()=>p1,TypeGenerationError:()=>d8,SchemaValidationError:()=>s1,PluginError:()=>g8,PerformanceMonitor:()=>p8,FileSystemError:()=>m8,ErrorFactory:()=>Ew,EnvVarError:()=>Cf,EnvProcessor:()=>Vf,ConfigValidator:()=>o8,ConfigValidationError:()=>n8,ConfigNotFoundError:()=>If,ConfigMergeError:()=>v8,ConfigLoader:()=>e8,ConfigLoadError:()=>a1,ConfigFileLoader:()=>Of,ConfigCache:()=>t8,CacheUtils:()=>OT,BunfigError:()=>o0,BrowserConfigError:()=>l8,ArrayMergeStrategies:()=>DT});c6=TK(async()=>{VT=import.meta.require,h1=new t8,o1=new p8,OT={createKey:uK,isEquivalent:nK,estimateMemoryUsage:vK},T6=Nf(i8.cwd(),"config"),F6=Nf(i8.cwd(),"src/generated"),oj=Rf.env.CLARITY_LOG_DIR||RK(lK(),"logs"),Ff={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:oj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},c8=await gK(),Q0={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"},r=Q0,z6=Q0.red,ej=Q0.green,G6=Q0.yellow,$T=Q0.blue,H6=Q0.magenta,K6=Q0.cyan,V8=Q0.white,R6=Q0.gray,wT=Q0.bgRed,AT=Q0.bgYellow,O8=Q0.bold,N6=Q0.dim,q6=Q0.italic,h6=Q0.underline,y6=Q0.reset,zf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_T={debug:"\uD83D\uDD0D",info:$T("ℹ"),success:ej("✓"),warning:AT(V8(O8(" WARN "))),error:wT(V8(O8(" ERROR ")))},M6=new hf("stacks"),D0=new hf("bunfig",{showTags:!0}),I6=c0(r1.cwd(),"config"),C6=c0(r1.cwd(),"src/generated"),YT=Kf.env.CLARITY_LOG_DIR||HK(aK(),"logs"),Gf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:YT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},u8=await sK(),R0={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=R0,S6=R0.red,fT=R0.green,L6=R0.yellow,XT=R0.blue,V6=R0.magenta,O6=R0.cyan,_8=R0.white,_6=R0.gray,UT=R0.bgRed,JT=R0.bgYellow,Q6=R0.bgGray,Q8=R0.bold,D6=R0.dim,k6=R0.italic,Z6=R0.underline,x6=R0.strikethrough,P6=R0.reset,Hf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},QT={debug:"\uD83D\uDD0D",info:XT("ℹ"),success:fT("✓"),warning:JT(_8(Q8(" WARN "))),error:UT(_8(Q8(" ERROR ")))},i6=new Mf("stacks"),o0=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,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},If=class extends o0{code="CONFIG_NOT_FOUND";constructor(w,A,Y){let f=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${f} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},a1=class extends o0{code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},n8=class extends o0{code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},v8=class extends o0{code="CONFIG_MERGE_ERROR";constructor(w,A,Y,f){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:f,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Cf=class extends o0{code="ENV_VAR_ERROR";constructor(w,A,Y,f){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:f})}},m8=class extends o0{code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},d8=class extends o0{code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},s1=class extends o0{code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},l8=class extends o0{code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,f){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:f})}},g8=class extends o0{code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Ew={configNotFound($,w,A){return new If($,w,A)},configLoad($,w,A){return new a1($,w,A)},configValidation($,w,A){return new n8($,w,A)},configMerge($,w,A,Y){return new v8($,w,A,Y)},envVar($,w,A,Y){return new Cf($,w,A,Y)},fileSystem($,w,A){return new m8($,w,A)},typeGeneration($,w,A){return new d8($,w,A)},schemaValidation($,w,A){return new s1($,w,A)},browserConfig($,w,A,Y){return new l8($,w,A,Y)},plugin($,w,A){return new g8($,w,A)}},DT={replace:"replace",concat:"concat",smart:"smart"},kT=/^https?:\/\//,y$=new Mf("bunfig",{showTags:!0}),r$=new e8,ZT=u0(Mw.cwd(),"config"),xT=u0(Mw.cwd(),"src/generated")});m6=Sf.env.CLARITY_LOG_DIR||u6(v6(),"logs"),PT={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:m6,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lf={...PT},XC=(async()=>{try{let{loadConfig:$}=await c6().then(()=>KT),w=await $({name:"clarity",alias:"logging",defaultConfig:PT,cwd:Sf.cwd()});if(w)Object.assign(Lf,w)}catch{}return Lf})();M0={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=M0,HC=M0.red,$7=M0.green,KC=M0.yellow,w7=M0.blue,RC=M0.magenta,NC=M0.cyan,GT=M0.white,qC=M0.gray,A7=M0.bgRed,Y7=M0.bgYellow,hC=M0.bgGray,HT=M0.bold,yC=M0.dim,MC=M0.italic,IC=M0.underline,CC=M0.strikethrough,SC=M0.reset,x8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},f7={debug:"\uD83D\uDD0D",info:w7("ℹ"),success:$7("✓"),warning:Y7(GT(HT(" WARN "))),error:A7(GT(HT(" ERROR ")))};LC=new Iw("stacks")});var y1={};lJ(y1,{safeStringify:()=>E$,safeDeleteFile:()=>YJ,resolvePathRewrite:()=>AJ,redactSensitive:()=>_f,isValidRootCA:()=>wJ,isSingleProxyOptions:()=>$A,isSingleProxyConfig:()=>E7,isMultiProxyOptions:()=>Sw,isMultiProxyConfig:()=>nT,getSudoPassword:()=>Cw,getPrimaryDomain:()=>Qf,extractHostname:()=>B7,execSudoSync:()=>e1,debugLog:()=>z});import{execSync as bT}from"node:child_process";import*as uT from"node:fs/promises";function Cw(){return process.env.SUDO_PASSWORD}function e1($){let w=Cw(),A=$.replace(/'/g,"'\\''");if(w)return bT(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return bT(`sudo -n sh -c '${A}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function z($,w,A){if(A)X7.debug(`[rpx:${$}] ${w}`)}function W7($){let w=$.toLowerCase();return U7.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function _f($){if(Array.isArray($))return $.map((A)=>_f(A));if(typeof $==="string")return J7.test($)?cT:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(W7(A)){w[A]=cT;continue}w[A]=_f(Y)}return w}function E$($,w){return JSON.stringify(_f($),null,w)}function B7($){if(Sw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if($A($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function wJ($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function Qf($){if(!$)return"stacks.localhost";if(Sw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if($A($))return $.to||"stacks.localhost";return"stacks.localhost"}function nT($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function Sw($){return"proxies"in $&&Array.isArray($.proxies)}function $A($){return"to"in $&&typeof $.to==="string"}function E7($){return!!($&&("to"in $)&&!("proxies"in $))}function AJ($,w){if(!w||w.length===0)return null;for(let A of w)if($===A.from||$.startsWith(`${A.from}/`)){let Y=A.to.startsWith("http")?new URL(A.to).host:A.to,f=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:Y,targetPath:f}}return null}async function YJ($,w){try{await uT.unlink($),z("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")z("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var X7,cT="[redacted]",U7,J7;var U0=E0(()=>{$J();X7=new Iw("rpx",{showTags:!1});U7=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),J7=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as Df}from"node:child_process";import{homedir as j7}from"node:os";import{join as T7}from"node:path";function kf(){return T7(j7(),"Library/Keychains/login.keychain-db")}function XJ(){return[I1,kf()]}function vT($,w=fJ){let A=Df(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),Y=[];for(let f of A.split(`
|
|
180
|
+
`)){let X=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(X)Y.push(X[1].toUpperCase())}return Y}function UJ($){if(process.platform!=="darwin")return;let w=$f($.caPath);if(!w)return;let A=$.commonName??fJ,Y=$.keychains??XJ();for(let f of Y)for(let X of vT(f,A)){if(X===w)continue;try{if(f.startsWith("/Library"))e1(`security delete-certificate -Z ${X} "${f}"`);else Df(`security delete-certificate -Z ${X} "${f}"`,{stdio:"ignore"});z("ssl",`Removed stale Root CA ${X} from ${f}`,$.verbose)}catch{}}}function JJ($,w,A){if(process.platform!=="darwin")return Zf($,A);try{let f=Df(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return z("ssl",`verify-cert ${w}: ${f?"trusted":"not trusted"}`,A?.verbose),f}catch{return!1}}function Zf($,w){let A=$f($);if(!A)return!1;for(let Y of XJ())try{let f=Df(`security find-certificate -a -Z "${Y}" 2>/dev/null || true`,{encoding:"utf8"});for(let X of f.split(`
|
|
181
|
+
`))if(X.toUpperCase().includes("SHA-256")){if(X.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===A)return z("ssl",`Root CA fingerprint found in ${Y}`,w?.verbose),!0}}catch{}return!1}var M1="-d -r trustRoot -p ssl -p basic",I1="/Library/Keychains/System.keychain",fJ="rpx.localhost";var WJ=E0(()=>{K8();U0()});import{execSync as C1}from"node:child_process";import q0 from"node:fs/promises";import*as BJ from"node:os";import{homedir as xf}from"node:os";import{join as k0}from"node:path";import*as jw from"node:process";function lT($){return{caCertPath:k0($,z7),caKeyPath:k0($,G7)}}async function H7($,w){try{let[A,Y]=await Promise.all([q0.readFile($.caCertPath,"utf8"),q0.readFile($.caKeyPath,"utf8")]);if(!A.includes("-----BEGIN CERTIFICATE-----")||!Y.includes("PRIVATE KEY-----"))return z("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:A,privateKey:Y}}catch(A){return z("ssl",`No existing Root CA at ${$.caCertPath} (${A.code||A}), will create one`,w),null}}function mT($){let w=new Set;w.add($);let A=$.split(".");if(A.length>=2)w.add(`*.${A.slice(1).join(".")}`);return Array.from(w)}function gT($){let A=Qf($).replace(/\*/g,"wildcard"),Y=k0(xf(),".stacks","ssl"),f=Y;if(typeof $?.https==="object")return f=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:Y,{caCertPath:$.https.caCertPath||k0(f,`${A}.ca.crt`),certPath:$.https.certPath||k0(f,`${A}.crt`),keyPath:$.https.keyPath||k0(f,`${A}.key`)};return{caCertPath:k0(f,`${A}.ca.crt`),certPath:k0(f,`${A}.crt`),keyPath:k0(f,`${A}.key`)}}function dT($){let w=new Set;if(Sw($))$.proxies.forEach((A)=>{let Y=A.to||"rpx.localhost";mT(Y).forEach((f)=>w.add(f))});else if($A($)){let A=$.to||"rpx.localhost";mT(A).forEach((Y)=>w.add(Y))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function S1($){if(Tw&&!$.forceRegenerate){z("ssl","Using cached SSL configuration",$.verbose);return}K7();let w=Sw($)?$.proxies.map((E)=>E.to):[$.to];z("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let A=wA($,$.verbose),Y=A.basePath||k0(xf(),".stacks","ssl");await q0.mkdir(Y,{recursive:!0});let f=lT(Y),X=await H7(f,$.verbose),U=!1;if(!X){if($.verbose)q.info("Generating Root CA certificate (one-time)...");X=await B8(A);try{await Promise.all([q0.writeFile(f.caCertPath,X.certificate),q0.writeFile(f.caKeyPath,X.privateKey,{mode:384})]),U=!0,z("ssl",`Persisted Root CA at ${f.caCertPath}`,$.verbose)}catch(E){throw z("ssl",`Error saving Root CA files: ${E}`,$.verbose),Error(`Failed to save Root CA files: ${E}`)}}else z("ssl",`Reusing existing Root CA from ${f.caCertPath}`,$.verbose);if($.verbose)q.info(`Generating host certificate for: ${w.join(", ")}`);let W=await E8({...A,rootCA:{certificate:X.certificate,privateKey:X.privateKey}});try{await Promise.all([q0.writeFile(A.certPath,W.certificate),q0.writeFile(A.keyPath,W.privateKey),q0.writeFile(A.caCertPath,X.certificate)]),z("ssl","Certificate files saved successfully",$.verbose)}catch(E){throw z("ssl",`Error saving certificate files: ${E}`,$.verbose),Error(`Failed to save certificate files: ${E}`)}if(U?!1:await pT(f.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(z("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)q.success("Root CA is already trusted in system trust store");if(Tw={key:W.privateKey,cert:W.certificate,ca:X.certificate},$.verbose)q.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)q.info("Adding certificate to system trust store (may require sudo permission)...");let B=!1;if(jw.platform==="darwin")try{UJ({caPath:f.caCertPath,verbose:$.verbose});let E=kf();try{C1(`security add-trusted-cert ${M1} -k "${E}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(e1(`security add-trusted-cert ${M1} -k ${I1} "${f.caCertPath}"`),$.verbose)q.success("Successfully added Root CA to system trust store");B=!0;let j=k0(Y,"trust-rpx-cert.sh"),T=`#!/bin/bash
|
|
182
182
|
echo "Trusting RPX Root CA"
|
|
183
|
-
sudo security add-trusted-cert ${
|
|
183
|
+
sudo security add-trusted-cert ${M1} -k ${I1} "${f.caCertPath}"
|
|
184
184
|
echo "Root CA trusted! Please restart your browser."
|
|
185
185
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
186
|
-
`;await
|
|
186
|
+
`;await q0.writeFile(j,T,{mode:493})}catch(E){if($.verbose)q.warn(`Could not add Root CA to trust store automatically: ${E}`);let j=k0(Y,"trust-rpx-cert.sh"),T=`#!/bin/bash
|
|
187
187
|
echo "Trusting RPX Root CA"
|
|
188
|
-
sudo security add-trusted-cert ${
|
|
188
|
+
sudo security add-trusted-cert ${M1} -k ${I1} "${f.caCertPath}"
|
|
189
189
|
echo "Root CA trusted! Please restart your browser."
|
|
190
190
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
191
|
-
`;if(await
|
|
191
|
+
`;if(await q0.writeFile(j,T,{mode:493}),$.verbose)q.info(`Created a trust helper script at: ${j}`),q.info(`If you're still having certificate issues, run: sh ${j}`)}else if(jw.platform==="linux")try{let{exec:E}=await import("node:child_process"),j="/usr/local/share/ca-certificates/rpx",T=`
|
|
192
192
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
193
193
|
cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
194
194
|
update-ca-certificates
|
|
195
195
|
echo "RPX Root CA installed. Please restart your browser."
|
|
196
|
-
`,F=
|
|
196
|
+
`,F=k0(BJ.tmpdir(),`rpx-trust-${Date.now()}.sh`);await q0.writeFile(F,T,{mode:493}),await new Promise((H)=>{E(`sudo bash "${F}"`,(G)=>{if(G){if($.verbose)q.warn(`Could not trust certificates: ${G}`);H(!1)}else{if($.verbose)q.success("Successfully added certificates to system trust store");H(!0)}})}),await q0.unlink(F).catch(()=>{}),B=!0}catch(E){if($.verbose)q.warn(`Failed to trust certificates: ${E}`)}else if(jw.platform==="win32")try{let E=`
|
|
197
197
|
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
|
|
198
198
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
199
199
|
$store.Open("ReadWrite")
|
|
200
200
|
$store.Add($cert)
|
|
201
201
|
$store.Close()
|
|
202
202
|
Write-Host "Root CA trusted successfully!"
|
|
203
|
-
`,j=k$(WJ.tmpdir(),"rpx-trust.ps1");if(await q$.writeFile(j,E),I1(`powershell -ExecutionPolicy Bypass -File "${j}"`),$.verbose)q.success("Successfully added certificate to Windows trust store");B=!0}catch(E){if($.verbose)q.warn(`Could not trust certificate: ${E}`)}else try{await EU(W,X.certificate,A),B=!0}catch(E){if($.verbose)q.warn(`Could not add certificate to trust store: ${E}`)}if(Ew={key:W.privateKey,cert:W.certificate,ca:X.certificate},$.verbose)q.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!B&&$.verbose)q.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),q.warn("This will bypass the warning and you should only need to do it once")}function H7(){Ew=null}async function p0($){if(!$)return null;if(Ew)return Ew;let w=wA($);try{let[A,Y,f]=await Promise.all([q$.access(w.keyPath).then(()=>!0).catch(()=>!1),q$.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?q$.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!A||!Y)return z("ssl",`Certificate files don't exist: key=${A}, cert=${Y}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let X="regenerateUntrustedCerts"in $,U=$.regenerateUntrustedCerts,W=X?U!==!1:!0;z("ssl",`Trust check: hasFlag=${X}, flagValue=${U}, shouldCheckTrust=${W}`,$.verbose);let J=w.basePath||k$(xf(),".stacks","ssl"),B=dT(J);if(!(W?await tT(B.caCertPath,$):!0))return z("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[j,T,F]=await Promise.all([q$.readFile(w.keyPath,"utf8"),q$.readFile(w.certPath,"utf8"),f&&w.caCertPath?q$.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return z("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(Iw($))try{let{X509Certificate:H}=await import("node:crypto"),K=new H(T).subjectAltName||"",h=$.proxies.map((N)=>N.to).filter((N)=>!K.includes(`DNS:${N}`));if(h.length>0)return z("ssl",`Certificate missing SANs for: ${h.join(", ")}, will regenerate`,$.verbose),null}catch(H){z("ssl",`Could not verify cert SANs: ${H}`,$.verbose)}return z("ssl","Successfully loaded existing certificates",$.verbose),Ew={key:j,cert:T,ca:F},Ew}catch(A){return z("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function wA($,w){let A=_f($);z("ssl",`Primary domain: ${A}`,w);let Y=lT($),f=k$(xf(),".stacks","ssl");if(typeof $.https==="object"){let X=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:f,U={domain:A,hostCertCN:A,basePath:X,caCertPath:$.https.caCertPath||Y.caCertPath,certPath:$.https.certPath||Y.certPath,keyPath:$.https.keyPath||Y.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(mT($)).map((W)=>({type:2,value:W}))};if($J($.https.rootCA))U.rootCA=$.https.rootCA;return U}return{domain:A,hostCertCN:A,basePath:f,...Y,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(mT($)).map((X)=>({type:2,value:X}))}}async function gT($,w){let A=lT({to:$,verbose:w}),Y=[A.caCertPath,A.certPath,A.keyPath];z("certificates","Attempting to clean up relating certificates",w),await Promise.all(Y.map((f)=>AJ(f,w)))}async function tT($,w){try{if(z("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),Bw.platform==="darwin"){if(w?.serverName)return UJ($,w.serverName,{verbose:w?.verbose});return Zf($,{verbose:w?.verbose})}else if(Bw.platform==="win32")try{let Y=I1(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!Y)return z("ssl","Could not extract certificate subject",w?.verbose),!1;let f=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(I1(f).toString().includes(Y))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(Bw.platform==="linux")try{let Y=I1(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"",f=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of f)try{if(I1(`find ${X} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${Y}"`).toString().includes(Y))return z("ssl",`Certificate fingerprint found in ${X}`,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 ${Bw.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}}var Ew=null,F7="rpx-root-ca.crt",z7="rpx-root-ca.key";var Pf=E$(()=>{jU();Aw();GU();JJ();U$();JJ();HU()});import*as B0 from"node:path";function AA($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function R7($){let w=B0.extname($).toLowerCase();return K7[w]??"application/octet-stream"}function h7($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let A=B0.posix.normalize(`/${w}`);if(A.includes(".."))return null;return A.replace(/^\/+/,"")}function q7($,w){let A=h7($);if(A===null)return null;let Y=B0.posix.extname(A);if(w.cleanUrls&&Y===".html"){let f=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:B0.join(w.dir,A),redirectTo:f||"/"}}if(A===""||$.endsWith("/"))return{filePath:B0.join(w.dir,A,"index.html")};if(Y!=="")return{filePath:B0.join(w.dir,A)};if(w.pathRewriteStyle==="flat")return{filePath:B0.join(w.dir,`${A}.html`)};return{filePath:B0.join(w.dir,A,"index.html")}}async function pT($,w){let A=q7($,w);if(!A)return new Response("Forbidden",{status:403});if(A.redirectTo)return new Response(null,{status:301,headers:{Location:A.redirectTo}});let Y=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",f=Bun.file(A.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":R7(A.filePath),"Cache-Control":Y}});if(w.spa){let X=B0.join(w.dir,"index.html"),U=Bun.file(X);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var K7;var YA=E$(()=>{K7={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".pdf":"application/pdf",".wasm":"application/wasm",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"}});function y7($){return($.headers.get("host")||"").split(":")[0]}function aT($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let A=$.slice(w.length);return A===""?"/":A}return $}function rT($,w,A){let Y=new URL($.url),f=w.sourceHost??"",U=w.stripBasePathPrefix??!1?aT(Y.pathname,w.basePath):Y.pathname,W=wJ(U,w.pathRewrites);if(W)f=W.targetHost,U=W.targetPath,z("request",`Path rewrite: ${Y.pathname} → ${f}${U}`,A);return{targetHost:f,targetPath:U,search:Y.search}}function fA($,w){return async(A,Y)=>{let f=new URL(A.url),X=y7(A),U=$(X,f.pathname);if(!U)return z("request",`No route found for host: ${X}`,w),new Response(`No proxy configured for ${X}`,{status:404});if(U.static){let T=U.stripBasePathPrefix??!0?aT(f.pathname,U.basePath):f.pathname;return pT(T,U.static)}if(A.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!Y||!U.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:j,targetPath:T,search:F}=rT(A,U,w),H=`ws://${j}${T}${F}`,G={};for(let[h,N]of A.headers)if(!N7.has(h.toLowerCase())&&h.toLowerCase()!=="host")G[h]=N;G.host=j,G["x-forwarded-for"]="127.0.0.1",G["x-forwarded-proto"]="https",G["x-forwarded-host"]=X;let K={targetUrl:H,forwardHeaders:G};if(Y.upgrade(A,{data:K})){z("ws",`upgraded ${X}${T} → ${H}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}if(!U.sourceHost)return new Response(`No upstream configured for ${X}`,{status:502});let{targetHost:W,targetPath:J,search:B}=rT(A,U,w),E=`http://${W}${J}${B}`;try{let j=new Headers(A.headers);if(j.set("host",W),U.changeOrigin)j.set("origin",`http://${U.sourceHost}`);j.set("x-forwarded-for","127.0.0.1"),j.set("x-forwarded-proto","https"),j.set("x-forwarded-host",X);let T=await fetch(E,{method:A.method,headers:j,body:A.body,redirect:"manual"});if(U.cleanUrls&&f.pathname.endsWith(".html")){let H=f.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:H}})}let F=new Headers(T.headers);return new Response(T.body,{status:T.status,statusText:T.statusText,headers:F})}catch(j){return z("request",`Proxy error for ${X}: ${j}`,w),new Response(`Proxy Error: ${j}`,{status:502})}}}function XA($){let w=new WeakMap;return{open(A){let{targetUrl:Y,forwardHeaders:f}=A.data,X;try{X=new WebSocket(Y,{headers:f})}catch(W){z("ws",`failed to open upstream ${Y}: ${W}`,$),A.close(1011,"upstream connect failed");return}X.binaryType="arraybuffer";let U={upstream:X,upstreamOpen:!1,pending:[]};w.set(A,U),X.addEventListener("open",()=>{U.upstreamOpen=!0;for(let W of U.pending)X.send(W);U.pending=[]}),X.addEventListener("message",(W)=>{A.send(W.data)}),X.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),X.addEventListener("error",()=>{z("ws",`upstream error for ${Y}`,$);try{A.close(1011,"upstream error")}catch{}})},message(A,Y){let f=w.get(A);if(!f)return;let X=typeof Y==="string"?Y:new Uint8Array(Y);if(f.upstreamOpen)f.upstream.send(X);else f.pending.push(X)},close(A,Y,f){let X=w.get(A);if(!X)return;w.delete(A);try{X.upstream.close(Y||1000,f||"")}catch{}}}}var N7;var bf=E$(()=>{YA();U$();N7=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});function UA($){return $.startsWith("*.")}function sT($,w){if(!UA(w))return!1;let A=w.slice(1);return $.length>A.length&&$.endsWith(A)}function S1($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function I7($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function JA($){let w=new Map;for(let Y of $){let f=S1(Y.path),X=w.get(Y.host);if(!X)X=new Map,w.set(Y.host,X);X.set(f,Y.route)}let A=new Map;for(let[Y,f]of w){let X=[];for(let[U,W]of f)X.push({path:U,route:W});X.sort((U,W)=>W.path.length-U.path.length),A.set(Y,X)}return A}function C7($,w){let A=$.get(w);if(A!==void 0)return A;let Y,f=-1;for(let[X,U]of $){if(!UA(X))continue;if(sT(w,X)){let W=X.length-1;if(W>f)f=W,Y=U}}return Y}function WA($,w,A){let Y=C7($,w);if(!Y)return;for(let f of Y)if(I7(A,f.path))return f.route;return}var cf=()=>{};import*as BA from"node:fs/promises";import*as BJ from"node:path";function S7($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function L7($,w,A,Y){try{let[f,X]=await Promise.all([BA.readFile(w,"utf8"),BA.readFile(A,"utf8")]);return{serverName:$,cert:f,key:X}}catch(f){return z("sni",`skipping ${$}: ${f.message}`,Y),null}}async function EJ($,w){let A=new Map;if($.certsDir){let f=[];try{f=await BA.readdir($.certsDir)}catch(X){z("sni",`certsDir read failed (${$.certsDir}): ${X.message}`,w)}for(let X of f){let U=S7(X);if(!U)continue;let W=X.slice(0,-4);A.set(U,{certPath:BJ.join($.certsDir,X),keyPath:BJ.join($.certsDir,`${W}.key`)})}}if($.domains)for(let[f,X]of Object.entries($.domains))A.set(f,X);let Y=[];for(let[f,X]of A){let U=await L7(f,X.certPath,X.keyPath,w);if(U)Y.push(U)}return Y}var jJ=E$(()=>{U$()});import*as jw from"node:fs/promises";import*as TJ from"node:path";function V7($,w){if(!w||w.length===0)return!1;return w.some((A)=>{let Y=A.startsWith(".")?A.slice(1):A;return $===Y||$.endsWith(`.${Y}`)})}function Q7($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class uf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??pY,this.issuer=$.issuer??p8,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??O7;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!Q7($))return!1;if(V7($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return z("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;let w=this.inFlight.get($);if(w)return w;let A=this.negativeCache.get($);if(A!==void 0&&Date.now()<A)return z("on-demand",`${$} negatively cached for ${A-Date.now()}ms`,this.verbose),!1;let Y=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,Y),Y}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return z("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),!1;try{z("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let A={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,A),this.negativeCache.delete($),z("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.negativeCache.set($,Date.now()+this.negativeCacheMs),z("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}async loadFromDisk($){let{certPath:w,keyPath:A}=this.pathsFor($);try{let[Y,f]=await Promise.all([jw.readFile(w,"utf8"),jw.readFile(A,"utf8")]),X={serverName:$,cert:Y,key:f};return this.certs.set($,X),z("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:TJ.join(this.certsDir,`${$}.crt`),keyPath:TJ.join(this.certsDir,`${$}.key`)}}async persist($,w,A){await jw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:Y,keyPath:f}=this.pathsFor($);await Promise.all([jw.writeFile(Y,w,"utf8"),jw.writeFile(f,A,{encoding:"utf8",mode:384})])}}var O7=60000;var FJ=E$(()=>{jU();U$()});import*as nf from"node:fs";import*as n$ from"node:fs/promises";import{homedir as _7}from"node:os";import*as zJ from"node:path";import*as vf from"node:process";function Tw(){return zJ.join(_7(),".stacks","rpx","registry.d")}function EA($){return typeof $==="string"&&$.length>0&&$.length<=128&&D7.test($)}function GJ($,w){if(!EA(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return zJ.join($,`${w}.json`)}function l$($){if(!Number.isInteger($)||$<=0)return!1;try{return vf.kill($,0),!0}catch(w){return w.code==="EPERM"}}function oT($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,f=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",X=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&EA(w.id)&&(Y||f)&&typeof w.to==="string"&&w.to.length>0&&X&&A&&typeof w.createdAt==="string"}async function k7($){await n$.mkdir($,{recursive:!0})}async function eT($,w=Tw(),A){if(!oT($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await k7(w);let Y=GJ(w,$.id),f=`${Y}.tmp.${vf.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await n$.writeFile(f,X,{encoding:"utf8",mode:420}),await n$.rename(f,Y),z("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await n$.unlink(f).catch(()=>{}),U}}async function HJ($,w=Tw(),A){let Y=GJ(w,$);try{await n$.unlink(Y),z("registry",`removed entry ${$}`,A)}catch(f){if(f.code!=="ENOENT")throw f}}async function Z7($,w=Tw(),A){let Y=GJ(w,$);try{let f=await n$.readFile(Y,"utf8"),X=JSON.parse(f);if(!oT(X))return z("registry",`entry ${$} failed validation, removing`,A),await n$.unlink(Y).catch(()=>{}),null;return X}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await n$.unlink(Y).catch(()=>{}),null;throw f}}async function Cw($=Tw(),w){let A;try{A=await n$.readdir($)}catch(f){if(f.code==="ENOENT")return[];throw f}let Y=[];for(let f of A){if(!f.endsWith(".json"))continue;let X=f.slice(0,-5);if(!EA(X))continue;let U=await Z7(X,$,w);if(U)Y.push(U)}return Y}async function mf($=Tw(),w){let A=await Cw($,w),Y=0;for(let f of A){if(f.pid===void 0)continue;if(!l$(f.pid))z("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,w),await HJ(f.id,$,w).catch(()=>{}),Y++}return Y}function KJ($,w={}){let A=w.dir??Tw(),Y=w.debounceMs??100,f=w.pollMs??Math.max(Y*2,250),X=w.verbose;nf.mkdirSync(A,{recursive:!0});let U=null,W=!1,J=null,B=!1,E=(K)=>{return JSON.stringify(K.map((R)=>({id:R.id,from:R.from,to:R.to,path:R.path,pid:R.pid,pathRewrites:R.pathRewrites,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,static:R.static})).sort((R,h)=>R.id.localeCompare(h.id)))},j=()=>{if(U=null,W)return;Cw(A,X).then((K)=>{return J=E(K),$(K)}).catch((K)=>{z("registry",`watcher onChange failed: ${K}`,X)})},T=()=>{if(W)return;if(U)clearTimeout(U);U=setTimeout(j,Y)},H=setInterval(()=>{if(W||B)return;B=!0,Cw(A,X).then((K)=>{if(E(K)!==J)T()}).catch((K)=>{z("registry",`watcher poll failed: ${K}`,X)}).finally(()=>{B=!1})},f),G=nf.watch(A,{persistent:!0},(K,R)=>{if(R&&/\.tmp\.\d+\.\d+$/.test(R))return;T()});return G.on("error",(K)=>{z("registry",`watcher error: ${K}`,X)}),T(),{close:()=>{if(W=!0,U)clearTimeout(U);clearInterval(H),G.close()}}}var D7;var jA=E$(()=>{U$();D7=/^[a-zA-Z0-9._-]+$/});import{spawn as x7}from"node:child_process";import*as Sw from"node:fs/promises";import{homedir as P7}from"node:os";import*as TA from"node:path";import*as v$ from"node:process";function r0(){return TA.join(P7(),".stacks","rpx")}function wF($=r0()){return TA.join($,"daemon.pid")}async function $F($=r0()){try{let w=await Sw.readFile(wF($),"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 i7($=r0()){await Sw.unlink(wF($)).catch(()=>{})}function b7(){let $=v$.execPath,w=TA.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&v$.argv[1])return[$,v$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function AF($={}){let w=$.rpxDir??r0(),A=$.verbose??!1;await Fw({rpxDir:w,verbose:A}).catch((E)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${E}`,A)});let Y=await $F(w);if(Y!==null&&l$(Y))return z("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await i7(w);await Sw.mkdir(w,{recursive:!0});let f=$.spawnCommand??b7();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${f.join(" ")}`,A);let X=x7(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??v$.cwd(),env:$.spawnEnv?{...v$.env,...$.spawnEnv}:v$.env});X.unref();let U=null;X.once("error",(E)=>{U=E});let W=$.startupTimeoutMs??5000,J=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let E=await $F(w);if(E!==null&&l$(E))return z("daemon",`daemon registered with pid=${E}`,A),{pid:E,spawned:!0};await new Promise((j)=>setTimeout(j,J))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var RJ=E$(()=>{Aw();Pf();bf();cf();jJ();FJ();YA();jA();L1();U$()});import*as zw from"node:fs/promises";import{homedir as c7}from"node:os";import*as hJ from"node:path";function fF(){return hJ.join(c7(),".stacks","rpx")}function qJ($=fF()){return hJ.join($,u7)}async function lf($=fF()){try{let w=await zw.readFile(qJ($),"utf8"),A=JSON.parse(w);if(A.version!==df||!Array.isArray(A.resolvers))return null;return{version:df,resolvers:A.resolvers.filter((Y)=>typeof Y==="string"),domains:Array.isArray(A.domains)?A.domains.filter((Y)=>typeof Y==="string"):[],ownerPid:typeof A.ownerPid==="number"?A.ownerPid:null,updatedAt:typeof A.updatedAt==="string"?A.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function XF($,w){await zw.mkdir($,{recursive:!0}),await zw.writeFile(qJ($),`${JSON.stringify(w,null,2)}
|
|
204
|
-
`,"utf8")}async function
|
|
203
|
+
`,j=k0(BJ.tmpdir(),"rpx-trust.ps1");if(await q0.writeFile(j,E),C1(`powershell -ExecutionPolicy Bypass -File "${j}"`),$.verbose)q.success("Successfully added certificate to Windows trust store");B=!0}catch(E){if($.verbose)q.warn(`Could not trust certificate: ${E}`)}else try{await j8(W,X.certificate,A),B=!0}catch(E){if($.verbose)q.warn(`Could not add certificate to trust store: ${E}`)}if(Tw={key:W.privateKey,cert:W.certificate,ca:X.certificate},$.verbose)q.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!B&&$.verbose)q.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),q.warn("This will bypass the warning and you should only need to do it once")}function K7(){Tw=null}async function a$($){if(!$)return null;if(Tw)return Tw;let w=wA($);try{let[A,Y,f]=await Promise.all([q0.access(w.keyPath).then(()=>!0).catch(()=>!1),q0.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?q0.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!A||!Y)return z("ssl",`Certificate files don't exist: key=${A}, cert=${Y}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let X="regenerateUntrustedCerts"in $,U=$.regenerateUntrustedCerts,W=X?U!==!1:!0;z("ssl",`Trust check: hasFlag=${X}, flagValue=${U}, shouldCheckTrust=${W}`,$.verbose);let J=w.basePath||k0(xf(),".stacks","ssl"),B=lT(J);if(!(W?await pT(B.caCertPath,$):!0))return z("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[j,T,F]=await Promise.all([q0.readFile(w.keyPath,"utf8"),q0.readFile(w.certPath,"utf8"),f&&w.caCertPath?q0.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return z("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(Sw($))try{let{X509Certificate:H}=await import("node:crypto"),K=new H(T).subjectAltName||"",N=$.proxies.map((h)=>h.to).filter((h)=>!K.includes(`DNS:${h}`));if(N.length>0)return z("ssl",`Certificate missing SANs for: ${N.join(", ")}, will regenerate`,$.verbose),null}catch(H){z("ssl",`Could not verify cert SANs: ${H}`,$.verbose)}return z("ssl","Successfully loaded existing certificates",$.verbose),Tw={key:j,cert:T,ca:F},Tw}catch(A){return z("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function wA($,w){let A=Qf($);z("ssl",`Primary domain: ${A}`,w);let Y=gT($),f=k0(xf(),".stacks","ssl");if(typeof $.https==="object"){let X=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:f,U={domain:A,hostCertCN:A,basePath:X,caCertPath:$.https.caCertPath||Y.caCertPath,certPath:$.https.certPath||Y.certPath,keyPath:$.https.keyPath||Y.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(dT($)).map((W)=>({type:2,value:W}))};if(wJ($.https.rootCA))U.rootCA=$.https.rootCA;return U}return{domain:A,hostCertCN:A,basePath:f,...Y,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(dT($)).map((X)=>({type:2,value:X}))}}async function tT($,w){let A=gT({to:$,verbose:w}),Y=[A.caCertPath,A.certPath,A.keyPath];z("certificates","Attempting to clean up relating certificates",w),await Promise.all(Y.map((f)=>YJ(f,w)))}async function pT($,w){try{if(z("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),jw.platform==="darwin"){if(w?.serverName)return JJ($,w.serverName,{verbose:w?.verbose});return Zf($,{verbose:w?.verbose})}else if(jw.platform==="win32")try{let Y=C1(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!Y)return z("ssl","Could not extract certificate subject",w?.verbose),!1;let f=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(C1(f).toString().includes(Y))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(jw.platform==="linux")try{let Y=C1(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"",f=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of f)try{if(C1(`find ${X} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${Y}"`).toString().includes(Y))return z("ssl",`Certificate fingerprint found in ${X}`,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 ${jw.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}}var Tw=null,z7="rpx-root-ca.crt",G7="rpx-root-ca.key";var Pf=E0(()=>{T8();fw();H8();WJ();U0();WJ();K8()});import*as j$ from"node:path";function AA($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function N7($){let w=j$.extname($).toLowerCase();return R7[w]??"application/octet-stream"}function q7($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let A=j$.posix.normalize(`/${w}`);if(A.includes(".."))return null;return A.replace(/^\/+/,"")}function h7($,w){let A=q7($);if(A===null)return null;let Y=j$.posix.extname(A);if(w.cleanUrls&&Y===".html"){let f=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:j$.join(w.dir,A),redirectTo:f||"/"}}if(A===""||$.endsWith("/"))return{filePath:j$.join(w.dir,A,"index.html")};if(Y!=="")return{filePath:j$.join(w.dir,A)};if(w.pathRewriteStyle==="flat")return{filePath:j$.join(w.dir,`${A}.html`)};return{filePath:j$.join(w.dir,A,"index.html")}}async function rT($,w){let A=h7($,w);if(!A)return new Response("Forbidden",{status:403});if(A.redirectTo)return new Response(null,{status:301,headers:{Location:A.redirectTo}});let Y=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",f=Bun.file(A.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":N7(A.filePath),"Cache-Control":Y}});if(w.spa){let X=j$.join(w.dir,"index.html"),U=Bun.file(X);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var R7;var YA=E0(()=>{R7={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".pdf":"application/pdf",".wasm":"application/wasm",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"}});function M7($){return($.headers.get("host")||"").split(":")[0]}function sT($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let A=$.slice(w.length);return A===""?"/":A}return $}function aT($,w,A){let Y=new URL($.url),f=w.sourceHost??"",U=w.stripBasePathPrefix??!1?sT(Y.pathname,w.basePath):Y.pathname,W=AJ(U,w.pathRewrites);if(W)f=W.targetHost,U=W.targetPath,z("request",`Path rewrite: ${Y.pathname} → ${f}${U}`,A);return{targetHost:f,targetPath:U,search:Y.search}}function fA($,w){return async(A,Y)=>{let f=new URL(A.url),X=M7(A),U=$(X,f.pathname);if(!U)return z("request",`No route found for host: ${X}`,w),new Response(`No proxy configured for ${X}`,{status:404});if(U.static){let T=U.stripBasePathPrefix??!0?sT(f.pathname,U.basePath):f.pathname;return rT(T,U.static)}if(A.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!Y||!U.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:j,targetPath:T,search:F}=aT(A,U,w),H=`ws://${j}${T}${F}`,G={};for(let[N,h]of A.headers)if(!y7.has(N.toLowerCase())&&N.toLowerCase()!=="host")G[N]=h;G.host=j,G["x-forwarded-for"]="127.0.0.1",G["x-forwarded-proto"]="https",G["x-forwarded-host"]=X;let K={targetUrl:H,forwardHeaders:G};if(Y.upgrade(A,{data:K})){z("ws",`upgraded ${X}${T} → ${H}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}if(!U.sourceHost)return new Response(`No upstream configured for ${X}`,{status:502});let{targetHost:W,targetPath:J,search:B}=aT(A,U,w),E=`http://${W}${J}${B}`;try{let j=new Headers(A.headers);if(j.set("host",W),U.changeOrigin)j.set("origin",`http://${U.sourceHost}`);j.set("x-forwarded-for","127.0.0.1"),j.set("x-forwarded-proto","https"),j.set("x-forwarded-host",X);let T=await fetch(E,{method:A.method,headers:j,body:A.body,redirect:"manual"});if(U.cleanUrls&&f.pathname.endsWith(".html")){let H=f.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:H}})}let F=new Headers(T.headers);return new Response(T.body,{status:T.status,statusText:T.statusText,headers:F})}catch(j){return z("request",`Proxy error for ${X}: ${j}`,w),new Response(`Proxy Error: ${j}`,{status:502})}}}function XA($){let w=new WeakMap;return{open(A){let{targetUrl:Y,forwardHeaders:f}=A.data,X;try{X=new WebSocket(Y,{headers:f})}catch(W){z("ws",`failed to open upstream ${Y}: ${W}`,$),A.close(1011,"upstream connect failed");return}X.binaryType="arraybuffer";let U={upstream:X,upstreamOpen:!1,pending:[]};w.set(A,U),X.addEventListener("open",()=>{U.upstreamOpen=!0;for(let W of U.pending)X.send(W);U.pending=[]}),X.addEventListener("message",(W)=>{A.send(W.data)}),X.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),X.addEventListener("error",()=>{z("ws",`upstream error for ${Y}`,$);try{A.close(1011,"upstream error")}catch{}})},message(A,Y){let f=w.get(A);if(!f)return;let X=typeof Y==="string"?Y:new Uint8Array(Y);if(f.upstreamOpen)f.upstream.send(X);else f.pending.push(X)},close(A,Y,f){let X=w.get(A);if(!X)return;w.delete(A);try{X.upstream.close(Y||1000,f||"")}catch{}}}}var y7;var bf=E0(()=>{YA();U0();y7=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});function UA($){return $.startsWith("*.")}function cf($,w){if(!UA(w))return!1;let A=w.slice(1);return $.length>A.length&&$.endsWith(A)}function L1($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function C7($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function JA($){let w=new Map;for(let Y of $){let f=L1(Y.path),X=w.get(Y.host);if(!X)X=new Map,w.set(Y.host,X);X.set(f,Y.route)}let A=new Map;for(let[Y,f]of w){let X=[];for(let[U,W]of f)X.push({path:U,route:W});X.sort((U,W)=>W.path.length-U.path.length),A.set(Y,X)}return A}function S7($,w){let A=$.get(w);if(A!==void 0)return A;let Y,f=-1;for(let[X,U]of $){if(!UA(X))continue;if(cf(w,X)){let W=X.length-1;if(W>f)f=W,Y=U}}return Y}function WA($,w,A){let Y=S7($,w);if(!Y)return;for(let f of Y)if(C7(A,f.path))return f.route;return}var uf=()=>{};import*as BA from"node:fs/promises";import*as EJ from"node:path";function L7($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function V7($,w,A,Y){try{let[f,X]=await Promise.all([BA.readFile(w,"utf8"),BA.readFile(A,"utf8")]);return{serverName:$,cert:f,key:X}}catch(f){return z("sni",`skipping ${$}: ${f.message}`,Y),null}}async function jJ($,w){let A=new Map;if($.certsDir){let f=[];try{f=await BA.readdir($.certsDir)}catch(X){z("sni",`certsDir read failed (${$.certsDir}): ${X.message}`,w)}for(let X of f){let U=L7(X);if(!U)continue;let W=X.slice(0,-4);A.set(U,{certPath:EJ.join($.certsDir,X),keyPath:EJ.join($.certsDir,`${W}.key`)})}}if($.domains)for(let[f,X]of Object.entries($.domains))A.set(f,X);let Y=[];for(let[f,X]of A){let U=await V7(f,X.certPath,X.keyPath,w);if(U)Y.push(U)}return Y}var TJ=E0(()=>{U0()});import*as Fw from"node:fs/promises";import*as FJ from"node:path";function _7($,w){if(!w||w.length===0)return!1;return w.some((A)=>{let Y=A.startsWith(".")?A.slice(1):A;return $===Y||$.endsWith(`.${Y}`)})}function Q7($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class nf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??pY,this.issuer=$.issuer??rU,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??O7;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!Q7($))return!1;if(_7($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return z("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;let w=this.inFlight.get($);if(w)return w;let A=this.negativeCache.get($);if(A!==void 0&&Date.now()<A)return z("on-demand",`${$} negatively cached for ${A-Date.now()}ms`,this.verbose),!1;let Y=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,Y),Y}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return z("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),!1;try{z("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let A={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,A),this.negativeCache.delete($),z("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.negativeCache.set($,Date.now()+this.negativeCacheMs),z("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}async loadFromDisk($){let{certPath:w,keyPath:A}=this.pathsFor($);try{let[Y,f]=await Promise.all([Fw.readFile(w,"utf8"),Fw.readFile(A,"utf8")]),X={serverName:$,cert:Y,key:f};return this.certs.set($,X),z("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:FJ.join(this.certsDir,`${$}.crt`),keyPath:FJ.join(this.certsDir,`${$}.key`)}}async persist($,w,A){await Fw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:Y,keyPath:f}=this.pathsFor($);await Promise.all([Fw.writeFile(Y,w,"utf8"),Fw.writeFile(f,A,{encoding:"utf8",mode:384})])}}var O7=60000;var zJ=E0(()=>{T8();U0()});import*as vf from"node:fs";import*as n0 from"node:fs/promises";import{homedir as D7}from"node:os";import*as GJ from"node:path";import*as mf from"node:process";function zw(){return GJ.join(D7(),".stacks","rpx","registry.d")}function EA($){return typeof $==="string"&&$.length>0&&$.length<=128&&k7.test($)}function HJ($,w){if(!EA(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return GJ.join($,`${w}.json`)}function l0($){if(!Number.isInteger($)||$<=0)return!1;try{return mf.kill($,0),!0}catch(w){return w.code==="EPERM"}}function oT($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,f=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",X=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&EA(w.id)&&(Y||f)&&typeof w.to==="string"&&w.to.length>0&&X&&A&&typeof w.createdAt==="string"}async function Z7($){await n0.mkdir($,{recursive:!0})}async function eT($,w=zw(),A){if(!oT($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await Z7(w);let Y=HJ(w,$.id),f=`${Y}.tmp.${mf.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await n0.writeFile(f,X,{encoding:"utf8",mode:420}),await n0.rename(f,Y),z("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await n0.unlink(f).catch(()=>{}),U}}async function KJ($,w=zw(),A){let Y=HJ(w,$);try{await n0.unlink(Y),z("registry",`removed entry ${$}`,A)}catch(f){if(f.code!=="ENOENT")throw f}}async function x7($,w=zw(),A){let Y=HJ(w,$);try{let f=await n0.readFile(Y,"utf8"),X=JSON.parse(f);if(!oT(X))return z("registry",`entry ${$} failed validation, removing`,A),await n0.unlink(Y).catch(()=>{}),null;return X}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await n0.unlink(Y).catch(()=>{}),null;throw f}}async function Lw($=zw(),w){let A;try{A=await n0.readdir($)}catch(f){if(f.code==="ENOENT")return[];throw f}let Y=[];for(let f of A){if(!f.endsWith(".json"))continue;let X=f.slice(0,-5);if(!EA(X))continue;let U=await x7(X,$,w);if(U)Y.push(U)}return Y}async function df($=zw(),w){let A=await Lw($,w),Y=0;for(let f of A){if(f.pid===void 0)continue;if(!l0(f.pid))z("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,w),await KJ(f.id,$,w).catch(()=>{}),Y++}return Y}function RJ($,w={}){let A=w.dir??zw(),Y=w.debounceMs??100,f=w.pollMs??Math.max(Y*2,250),X=w.verbose;vf.mkdirSync(A,{recursive:!0});let U=null,W=!1,J=null,B=!1,E=(K)=>{return JSON.stringify(K.map((R)=>({id:R.id,from:R.from,to:R.to,path:R.path,pid:R.pid,pathRewrites:R.pathRewrites,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,static:R.static})).sort((R,N)=>R.id.localeCompare(N.id)))},j=()=>{if(U=null,W)return;Lw(A,X).then((K)=>{return J=E(K),$(K)}).catch((K)=>{z("registry",`watcher onChange failed: ${K}`,X)})},T=()=>{if(W)return;if(U)clearTimeout(U);U=setTimeout(j,Y)},H=setInterval(()=>{if(W||B)return;B=!0,Lw(A,X).then((K)=>{if(E(K)!==J)T()}).catch((K)=>{z("registry",`watcher poll failed: ${K}`,X)}).finally(()=>{B=!1})},f),G=vf.watch(A,{persistent:!0},(K,R)=>{if(R&&/\.tmp\.\d+\.\d+$/.test(R))return;T()});return G.on("error",(K)=>{z("registry",`watcher error: ${K}`,X)}),T(),{close:()=>{if(W=!0,U)clearTimeout(U);clearInterval(H),G.close()}}}var k7;var jA=E0(()=>{U0();k7=/^[a-zA-Z0-9._-]+$/});import{spawn as P7}from"node:child_process";import*as Vw from"node:fs/promises";import{homedir as i7}from"node:os";import*as TA from"node:path";import*as v0 from"node:process";function s$(){return TA.join(i7(),".stacks","rpx")}function wF($=s$()){return TA.join($,"daemon.pid")}async function $F($=s$()){try{let w=await Vw.readFile(wF($),"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 b7($=s$()){await Vw.unlink(wF($)).catch(()=>{})}function c7(){let $=v0.execPath,w=TA.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&v0.argv[1])return[$,v0.argv[1],"daemon:start"];return[$,"daemon:start"]}async function AF($={}){let w=$.rpxDir??s$(),A=$.verbose??!1;await Gw({rpxDir:w,verbose:A}).catch((E)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${E}`,A)});let Y=await $F(w);if(Y!==null&&l0(Y))return z("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await b7(w);await Vw.mkdir(w,{recursive:!0});let f=$.spawnCommand??c7();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${f.join(" ")}`,A);let X=P7(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??v0.cwd(),env:$.spawnEnv?{...v0.env,...$.spawnEnv}:v0.env});X.unref();let U=null;X.once("error",(E)=>{U=E});let W=$.startupTimeoutMs??5000,J=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let E=await $F(w);if(E!==null&&l0(E))return z("daemon",`daemon registered with pid=${E}`,A),{pid:E,spawned:!0};await new Promise((j)=>setTimeout(j,J))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var NJ=E0(()=>{fw();Pf();bf();uf();TJ();zJ();YA();jA();V1();U0()});import*as Hw from"node:fs/promises";import{homedir as u7}from"node:os";import*as qJ from"node:path";function fF(){return qJ.join(u7(),".stacks","rpx")}function hJ($=fF()){return qJ.join($,n7)}async function gf($=fF()){try{let w=await Hw.readFile(hJ($),"utf8"),A=JSON.parse(w);if(A.version!==lf||!Array.isArray(A.resolvers))return null;return{version:lf,resolvers:A.resolvers.filter((Y)=>typeof Y==="string"),domains:Array.isArray(A.domains)?A.domains.filter((Y)=>typeof Y==="string"):[],ownerPid:typeof A.ownerPid==="number"?A.ownerPid:null,updatedAt:typeof A.updatedAt==="string"?A.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function XF($,w){await Hw.mkdir($,{recursive:!0}),await Hw.writeFile(hJ($),`${JSON.stringify(w,null,2)}
|
|
204
|
+
`,"utf8")}async function yJ($){await Hw.rm(hJ($),{force:!0})}function UF($){let w=$.trim().toLowerCase().replace(/\.$/,"");if(!w||w.includes("127.0.0.1"))return null;if(w==="localhost"||w.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(w))return null;return w}function v7($){let w=UF($);if(!w)return null;let A=w.split(".");if(A.length<2)return null;return A.slice(-2).join(".")}function MJ($){let w=new Set;for(let A of $){let Y=v7(A);if(Y)w.add(Y)}return Array.from(w).sort()}function IJ($){let w=new Set;for(let A of $){let Y=UF(A);if(Y)w.add(Y)}return Array.from(w).sort()}var lf=1,n7="dns-state.json",YF;var JF=E0(()=>{YF=["com","test","dev","app","page","local","localhost","example","invalid"]});var af={};lJ(af,{tearDownDevelopmentDns:()=>Ow,syncDevelopmentDnsFromRegistry:()=>FA,stopDnsServer:()=>CJ,startDnsServer:()=>FF,setupResolver:()=>e7,setupDevelopmentDns:()=>OJ,resolverFilePath:()=>O1,removeResolver:()=>wR,removeLegacyTldResolvers:()=>VJ,reconcileStaleDevelopmentDns:()=>Gw,isDnsServerRunning:()=>p7,contentLooksLikeRpxResolver:()=>zF,RPX_RESOLVER_MARKER:()=>EF,DNS_PORT:()=>rf});import m7 from"node:dgram";import*as WF from"node:fs/promises";import*as BF from"node:path";import*as o$ from"node:process";function d7($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function TF($,w){let A=[],Y=w;while(!0){let f=$[Y];if(f===0){Y++;break}if((f&192)===192){let X=$.readUInt16BE(Y)&16383,{name:U}=TF($,X);A.push(U),Y+=2;break}Y++,A.push($.subarray(Y,Y+f).toString("ascii")),Y+=f}return{name:A.join("."),newOffset:Y}}function l7($,w){let{name:A,newOffset:Y}=TF($,w),f=$.readUInt16BE(Y),X=$.readUInt16BE(Y+2);return{question:{name:A,type:f,class:X},newOffset:Y+4}}function pf($){let w=$.split("."),A=[];for(let Y of w)A.push(Buffer.from([Y.length])),A.push(Buffer.from(Y,"ascii"));return A.push(Buffer.from([0])),Buffer.concat(A)}function g7($,w,A){let Y=[],f=Buffer.alloc(12);f.writeUInt16BE($,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),Y.push(f),Y.push(pf(w.name));let X=Buffer.alloc(4);X.writeUInt16BE(w.type,0),X.writeUInt16BE(w.class,2),Y.push(X),Y.push(pf(w.name));let U=Buffer.alloc(10);if(U.writeUInt16BE(w.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),w.type===1){U.writeUInt16BE(4,8),Y.push(U);let W=A.split(".").map((J)=>Number.parseInt(J,10));Y.push(Buffer.from(W))}else if(w.type===28)U.writeUInt16BE(16,8),Y.push(U),Y.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,pf(w.name),X]);return Buffer.concat(Y)}function t7($,w){let A=[],Y=Buffer.alloc(12);Y.writeUInt16BE($,0),Y.writeUInt16BE(33155,2),Y.writeUInt16BE(1,4),Y.writeUInt16BE(0,6),Y.writeUInt16BE(0,8),Y.writeUInt16BE(0,10),A.push(Y),A.push(pf(w.name));let f=Buffer.alloc(4);return f.writeUInt16BE(w.type,0),f.writeUInt16BE(w.class,2),A.push(f),Buffer.concat(A)}async function FF($,w){if(o$.platform!=="darwin")return!1;let A=IJ($);if(A.length===0)return!1;if(g0){for(let Y of A)tf.add(Y);return z("dns","DNS server already running — merged domains",w),!0}return tf=new Set(A),new Promise((Y)=>{g0=m7.createSocket("udp4"),g0.on("error",(f)=>{z("dns",`DNS server error: ${f.message}`,w),g0?.close(),g0=null,Y(!1)}),g0.on("message",(f,X)=>{try{let U=d7(f),{question:W}=l7(f,12);z("dns",`Query for ${W.name} type ${W.type} from ${X.address}`,w);let J=W.name.toLowerCase(),B=!1;for(let j of tf)if(J===j||J.endsWith(`.${j}`)){B=!0;break}let E;if(B&&(W.type===1||W.type===28))E=g7(U.id,W,"127.0.0.1"),z("dns",`Responding with localhost for ${W.name}`,w);else E=t7(U.id,W),z("dns",`NXDOMAIN for ${W.name}`,w);g0?.send(E,X.port,X.address)}catch(U){z("dns",`Error processing DNS query: ${U}`,w)}}),g0.on("listening",()=>{let f=g0?.address();z("dns",`DNS server listening on ${f?.address}:${f?.port}`,w),Y(!0)});try{g0.bind(rf,"127.0.0.1")}catch(f){z("dns",`Failed to bind DNS server: ${f}`,w),Y(!1)}})}function CJ($){if(g0)z("dns","Stopping DNS server",$),g0.close(),g0=null,tf=new Set}function p7(){return g0!==null}function r7(){return`${EF}
|
|
205
205
|
nameserver 127.0.0.1
|
|
206
|
-
port ${
|
|
207
|
-
`}function O1($){return BF.join(jF,$)}function zF($){return $.includes("127.0.0.1")&&$.includes(String(
|
|
206
|
+
port ${rf}
|
|
207
|
+
`}function O1($){return BF.join(jF,$)}function zF($){return $.includes("127.0.0.1")&&$.includes(String(rf))}async function a7($){try{return await WF.readFile(O1($),"utf8")}catch(w){if(w.code==="ENOENT")return null;throw w}}async function SJ($){if(o$.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A}=await Promise.resolve().then(() => (U0(),y1));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(Y){z("dns",`Could not flush DNS cache: ${Y}`,$)}}async function s7($,w){let{execSudoSync:A}=await Promise.resolve().then(() => (U0(),y1)),Y=r7().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${jF} && printf "%b" "${Y}" > ${O1($)}'`;A(f),z("dns",`Created ${O1($)}`,w)}async function o7($,w){let{execSudoSync:A}=await Promise.resolve().then(() => (U0(),y1));A(`rm -f ${O1($)}`),z("dns",`Removed ${O1($)}`,w)}async function e7($,w){return OJ({domains:w??[],verbose:$})}async function $R($,w){if(o$.platform!=="darwin")return!0;let{getSudoPassword:A}=await Promise.resolve().then(() => (U0(),y1));if(!A())return z("dns","SUDO_PASSWORD not set, cannot create resolver files",w),!1;try{for(let Y of $)await s7(Y,w);return await SJ(w),!0}catch(Y){return z("dns",`Failed to create resolver file: ${Y}`,w),!1}}async function LJ($,w){if(o$.platform!=="darwin")return;let{getSudoPassword:A}=await Promise.resolve().then(() => (U0(),y1));if(!A())return;try{for(let Y of $)await o7(Y,w);await SJ(w)}catch(Y){z("dns",`Failed to remove resolver files: ${Y}`,w)}}async function VJ($){if(o$.platform!=="darwin")return[];let w=[];for(let A of YF){let Y=await a7(A);if(Y&&zF(Y))await LJ([A],$),w.push(A)}return w}async function OJ($){let w=$.rpxDir??s$(),A=IJ($.domains);if(A.length===0)return!1;let Y=MJ(A);if(!await FF(A,$.verbose))return!1;if(!await $R(Y,$.verbose))return!1;let U={version:lf,resolvers:Y,domains:A,ownerPid:$.ownerPid??o$.pid,updatedAt:new Date().toISOString()};return await XF(w,U),!0}async function FA($,w={}){let A=$.map((J)=>J.to).filter(Boolean),Y=w.rpxDir??s$(),f=MJ(A),W=((await gf(Y))?.resolvers??[]).filter((J)=>!f.includes(J));if(W.length>0)await LJ(W,w.verbose);if(f.length===0){CJ(w.verbose),await yJ(Y);return}await OJ({domains:A,rpxDir:Y,verbose:w.verbose,ownerPid:w.ownerPid??o$.pid})}async function Ow($={}){let w=$.rpxDir??s$();CJ($.verbose);let Y=(await gf(w))?.resolvers??[];await LJ(Y,$.verbose),await VJ($.verbose),await yJ(w)}async function wR($){await Ow({verbose:$})}async function Gw($={}){let w=$.rpxDir??s$(),A=await gf(w),Y=A?.ownerPid!=null&&l0(A.ownerPid);if(A&&!Y){z("dns",`reconcile: owner pid ${A.ownerPid} is gone — tearing down DNS`,$.verbose),await Ow($);return}let f=await VJ($.verbose);if(f.length>0)z("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,$.verbose);await SJ($.verbose)}var rf=15353,EF="# managed-by: rpx",jF="/etc/resolver",g0=null,tf;var V1=E0(()=>{NJ();JF();jA();U0();tf=new Set});import{dirname as SR,join as LR}from"path";import*as d0 from"process";import{fileURLToPath as VR}from"url";import{existsSync as gF}from"node:fs";import WX from"node:fs/promises";import gJ from"node:os";import BX from"node:path";import Nw from"node:process";import{EventEmitter as tF}from"node:events";import $w from"node:process";import tJ from"node:process";import FX from"node:process";import MA from"node:process";import k1 from"node:process";import aJ from"node:tty";import Z9,{stdin as pR,stdout as rR}from"node:process";import oJ,{stdin as i9,stdout as b9}from"node:process";import c9 from"node:readline";class $W{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=gJ.homedir(),w=BX.join($,".config","clapp");this.configPath=BX.join(w,"telemetry.json")}async isEnabled(){if(Nw.env.DO_NOT_TRACK==="1"||Nw.env.DO_NOT_TRACK==="true")return!1;if(Nw.env.NO_TELEMETRY==="1"||Nw.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 Y={event:$,...w,timestamp:Date.now(),platform:gJ.platform(),nodeVersion:Nw.version};if(this.events.push(Y),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:Nw.env.DO_NOT_TRACK==="1"||Nw.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(gF(this.configPath)){let $=await WX.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=BX.dirname(this.configPath);await WX.mkdir(w,{recursive:!0}),await WX.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 PR=new $W;function pF($,w={}){let A={_:[]},Y=w.alias||{},f=new Set(w.boolean||[]),X={};for(let W of Object.keys(Y))for(let J of Y[W])X[J]=W;for(let W of f)if(Y[W])for(let J of Y[W])f.add(J);function U(W,J){let B=X[W]||W;if(A[B]=J,Y[B])for(let E of Y[B])A[E]=J;if(X[W]&&Y[X[W]])for(let E of Y[X[W]])A[E]=J;A[W]=J}for(let W=0;W<$.length;W++){let J=$[W];if(J==="--"){A._.push(...$.slice(W+1));break}if(J.startsWith("--")){let B=J.indexOf("=");if(B!==-1){let E=J.slice(2,B),j=J.slice(B+1);U(E,j)}else{let E=J.slice(2);if(E.startsWith("no-")){let T=E.slice(3);U(T,!1);continue}let j=X[E]||E;if(f.has(j)||f.has(E))U(E,!0);else{let T=$[W+1];if(T!==void 0&&!T.startsWith("-"))U(E,T),W++;else U(E,!0)}}}else if(J.startsWith("-")&&J.length>1){let B=J.slice(1);for(let E=0;E<B.length;E++){let j=B[E],T=X[j]||j;if(E===B.length-1&&!f.has(T)&&!f.has(j)){let F=$[W+1];if(F!==void 0&&!F.startsWith("-"))U(j,F),W++;else U(j,!0)}else U(j,!0)}}else A._.push(J)}return A}function TX($){return $.replace(/[<[].+/,"").trim()}function rF($){let w=/<([^>]+)>/g,A=/\[([^\]]+)\]/g,Y=[],f=(W)=>{let J=!1,B=W[1];if(B.startsWith("..."))B=B.slice(3),J=!0;return{required:W[0].startsWith("<"),value:B,variadic:J}},X;while(X=w.exec($))Y.push(f(X));let U;while(U=A.exec($))Y.push(f(U));return Y}function aF($){let w={alias:{},boolean:[]};for(let[A,Y]of $.entries()){if(Y.names.length>1)w.alias[Y.names[0]]=Y.names.slice(1);if(Y.isBoolean)if(Y.negated){if(!$.some((X,U)=>{return U!==A&&X.names.some((W)=>Y.names.includes(W))&&typeof X.required==="boolean"}))w.boolean.push(Y.names[0])}else w.boolean.push(Y.names[0])}return w}function pJ($){return $.reduce((w,A)=>w.length>=A.length?w:A,"")}function EX($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function sF($){return $.replace(/([a-z])-([a-z])/g,(w,A,Y)=>{return A+Y.toUpperCase()})}function oF($,w,A){let Y=0,f=w.length,X=$,U;for(;Y<f;++Y)U=X[w[Y]],X=X[w[Y]]=Y===f-1?A:U!=null?U:!!~w[Y+1].indexOf(".")||!(+w[Y+1]>-1)?{}:[]}function eF($,w){for(let A of Object.keys(w)){let Y=w[A];if(Y.shouldTransform){if($[A]=Array.prototype.concat.call([],$[A]),typeof Y.transformFunction==="function")$[A]=$[A].map(Y.transformFunction)}}}function $9($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function wW($){return $.split(".").map((w,A)=>{return A===0?sF(w):w}).join(".")}class yA 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}
|
|
208
208
|
|
|
209
209
|
Stack trace:
|
|
210
|
-
${this.stack}`;return this.message}}function
|
|
210
|
+
${this.stack}`;return this.message}}function w9(){let{env:$}=tJ,{TERM:w,TERM_PROGRAM:A}=$;if(tJ.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 SA="\x1B",J0=`${SA}[`;var V$={to($,w){if(!w)return`${J0}${$+1}G`;return`${J0}${w+1};${$+1}H`},move($,w){let A="";if($<0)A+=`${J0}${-$}D`;else if($>0)A+=`${J0}${$}C`;if(w<0)A+=`${J0}${-w}A`;else if(w>0)A+=`${J0}${w}B`;return A},up:($=1)=>`${J0}${$}A`,down:($=1)=>`${J0}${$}B`,forward:($=1)=>`${J0}${$}C`,backward:($=1)=>`${J0}${$}D`,nextLine:($=1)=>`${J0}E`.repeat($),prevLine:($=1)=>`${J0}F`.repeat($),left:`${J0}G`,hide:`${J0}?25l`,show:`${J0}?25h`,save:`${SA}7`,restore:`${SA}8`};var jX={screen:`${J0}2J`,up:($=1)=>`${J0}1J`.repeat($),down:($=1)=>`${J0}J`.repeat($),line:`${J0}2K`,lineEnd:`${J0}K`,lineStart:`${J0}1K`,lines($){let w="";for(let A=0;A<$;A++)w+=this.line+(A<$-1?V$.up():"");if($)w+=V$.left;return w}},uR={screen:`${SA}c`};function A9($,w){let A=[];for(let Y=0;Y<=w.length;Y++)A[Y]=[Y];for(let Y=0;Y<=$.length;Y++)A[0][Y]=Y;for(let Y=1;Y<=w.length;Y++)for(let f=1;f<=$.length;f++)if(w.charAt(Y-1)===$.charAt(f-1))A[Y][f]=A[Y-1][f-1];else A[Y][f]=Math.min(A[Y-1][f-1]+1,A[Y][f-1]+1,A[Y-1][f]+1);return A[w.length][$.length]}function AW($,w,A=2,Y=3){return w.map((f)=>({cmd:f,distance:A9($,f)})).filter(({distance:f})=>f<=A).sort((f,X)=>f.distance-X.distance).slice(0,Y).map(({cmd:f})=>f)}class YW{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=TX($).split(",").map((Y)=>{let f=Y.trim().replace(/^-{1,2}/,"");if(f.startsWith("no-"))this.negated=!0,f=f.replace(/^no-/,"");return wW(f)}).sort((Y,f)=>Y.length>f.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 vR=FX.argv,Y9=`${FX.platform}-${FX.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,rJ=MA.argv,f9=`${MA.platform}-${MA.arch} node-${MA.version}`;class zX{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,A,Y){this.rawName=$,this.description=w,this.config=A,this.cli=Y,this.options=[],this.aliasNames=[],this.name=TX($);let f=TX($),X=f.indexOf(":");if(X>0)this.namespace=f.substring(0,X),this.name=f.substring(X+1);if(this.args=rF($),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 Y=new YW($,w,A);return this.options.push(Y),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 GX}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:Y,helpCallback:f}=this.cli.globalCommand,X=[{body:`${$}${A?`/${A}`:""}`}];if(X.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let J=pJ(w.map((F)=>F.rawName)),B=new Map,E=[];for(let F of w)if(F.namespace){if(!B.has(F.namespace))B.set(F.namespace,[]);B.get(F.namespace).push(F)}else E.push(F);let j="";if(E.length>0)j+=E.map((F)=>{return` ${EX(F.rawName,J.length)} ${F.description}`}).join(`
|
|
211
211
|
`);let T=Array.from(B.keys()).sort();for(let F of T){let H=B.get(F);if(j.length>0)j+=`
|
|
212
212
|
|
|
213
213
|
`;j+=` ${F}:
|
|
214
|
-
`,j+=H.map((G)=>{return` ${
|
|
214
|
+
`,j+=H.map((G)=>{return` ${EX(G.rawName,J.length-2)} ${G.description}`}).join(`
|
|
215
215
|
`)}X.push({title:"Commands",body:j}),X.push({title:"For more info, run any command with the `--help` flag",body:w.map((F)=>` $ ${$}${F.displayName===""?"":` ${F.displayName}`} --help`).join(`
|
|
216
|
-
`)})}let W=this.isGlobalCommand?Y:[...this.options,...Y||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)W=W.filter((J)=>J.name!=="version");if(W.length>0){let J=
|
|
216
|
+
`)})}let W=this.isGlobalCommand?Y:[...this.options,...Y||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)W=W.filter((J)=>J.name!=="version");if(W.length>0){let J=pJ(W.map((B)=>B.rawName));X.push({title:"Options",body:W.map((B)=>{return` ${EX(B.rawName,J.length)} ${B.description} ${B.config.default===void 0?"":`(default: ${B.config.default})`}`}).join(`
|
|
217
217
|
`)})}if(this.examples.length>0)X.push({title:"Examples",body:this.examples.map((J)=>{if(typeof J==="function")return J($);return J}).join(`
|
|
218
218
|
`)});if(f)X=f(X)||X;console.log(X.map((J)=>{return J.title?`${J.title}:
|
|
219
219
|
${J.body}`:J.body}).join(`
|
|
220
220
|
|
|
221
|
-
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?
|
|
221
|
+
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?Y9:f9}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let A=this.args.filter((f)=>f.required).slice(this.cli.args.length),Y=A.map((f)=>`<${f.value}>`).join(" ");throw new yA(`Missing required argument${A.length>1?"s":""}: ${Y}
|
|
222
222
|
|
|
223
|
-
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 f=[...w.options,...this.options].flatMap((J)=>J.names),X=A.length>1?`--${A}`:`-${A}`,U=
|
|
223
|
+
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 f=[...w.options,...this.options].flatMap((J)=>J.names),X=A.length>1?`--${A}`:`-${A}`,U=AW(A,f),W=`Unknown option \`${X}\``;if(U.length>0)W+=`
|
|
224
224
|
|
|
225
225
|
Did you mean one of these?`,U.forEach((J)=>{let B=J.length>1?`--${J}`:`-${J}`;W+=`
|
|
226
226
|
• ${B}`});throw W+=`
|
|
227
227
|
|
|
228
228
|
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new yA(W)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,A=[...w.options,...this.options];for(let Y of A){let f=$[Y.name.split(".")[0]];if(Y.required){let X=A.some((U)=>U.negated&&U.names.includes(Y.name));if(f===!0||f===!1&&!X)throw new yA(`Option \`${Y.rawName}\` requires a value.
|
|
229
229
|
|
|
230
|
-
Example: ${this.cli.name} ${this.rawName} ${Y.rawName} <value>`)}}}}class
|
|
230
|
+
Example: ${this.cli.name} ${this.rawName} ${Y.rawName} <value>`)}}}}class GX extends zX{constructor($){super("@@global@@","",{},$)}}var X9=zX,ww={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 Q1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function U9(){return!0}function J9(){let $={};$.supportsColor=U9();function w(Y,f=[]){let X=Y===""?[]:[...f,Y],U=function(J){if(!$.supportsColor)return J;let B="",E="";for(let j of X)if(j in Q1&&Q1[j]in ww){let T=Q1[j];B+=ww[T][0],E=ww[T][1]+E}else if(j in ww)B+=ww[j][0],E=ww[j][1]+E;return B+J+E},W=[...Object.keys(ww),...Object.keys(Q1)];for(let J of W)if(!(J in U))Object.defineProperty(U,J,{get(){return w(J,X)}});return U}let A=[...Object.keys(ww),...Object.keys(Q1)];for(let Y of A)if(!(Y in $))Object.defineProperty($,Y,{get(){return w(Y)}});return $}var D1=J9();class HX extends tF{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 GX(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(A)=>{if(console.log(`
|
|
231
231
|
|
|
232
|
-
Received ${A}, cleaning up...`),$)try{await $()}catch(Y){console.error("Error during cleanup:",Y)}
|
|
232
|
+
Received ${A}, cleaning up...`),$)try{await $()}catch(Y){console.error("Error during cleanup:",Y)}$w.exit(0)};return $w.on("SIGINT",()=>w("SIGINT")),$w.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 Y=new X9($,w||"",A,this);return Y.globalCommand=this.globalCommand,this.commands.push(Y),Y}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,Y){if(this.args=$,this.options=w,A)this.matchedCommand=A;if(Y)this.matchedCommandName=Y;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(D1.red(`
|
|
233
233
|
✗ Command "${$}" not found.
|
|
234
|
-
`)),this.enableDidYouMean){let w=[];for(let Y of this.commands){if(Y.displayName)w.push(Y.displayName);if(Y.aliasNames)w.push(...Y.aliasNames)}let A=
|
|
235
|
-
Run \`${this.name??"cli"} --help\` for usage
|
|
236
|
-
`)
|
|
234
|
+
`)),this.enableDidYouMean){let w=[];for(let Y of this.commands){if(Y.displayName)w.push(Y.displayName);if(Y.aliasNames)w.push(...Y.aliasNames)}let A=AW($,w);if(A.length>0)console.log(D1.yellow("Did you mean one of these?")),A.forEach((Y)=>console.log(` ${D1.dim("•")} ${this.name} ${Y}`)),console.log("")}console.log(D1.dim("Run"),`${this.name} --help`,D1.dim("to see all available commands")),$w.exit(1)}async parse($=rJ,w={}){let{run:A=!0,exitOnError:Y=!1}=w;if(Y)try{return await this.parse($,{run:A})}catch(J){throw this.handleUsageError(J),J}if(this.rawArgs=$,!this.name)this.name=$[1]?$9($[1]):"cli";let f=!0,X=$.slice(2),U=X[0];if(U&&!U.startsWith("-")){for(let J of this.commands)if(J.isMatched(U)){let B=this.mri(X,J);f=!1;let E={...B,args:B.args.slice(1)};this.setParsedInfo(E,J,U),this.emit(`command:${U}`,J);break}}if(f){for(let J of this.commands)if(J.name===""){f=!1;let B=this.mri(X,J);this.setParsedInfo(B,J),this.emit("command:!",J);break}}if(f){let J=this.mri($.slice(2));this.setParsedInfo(J)}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 W={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 W}mri($,w){let A=[...this.globalCommand.options,...w?w.options:[]],Y=aF(A),f=[],X=$.indexOf("--");if(X>-1)f=$.slice(X+1),$=$.slice(0,X);let U=pF($,Y),W={_:U._};for(let T of Object.keys(U))if(T!=="_")W[wW(T)]=U[T];let J=W._,B={"--":f},E=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,j=Object.create(null);for(let T of A){if(!E&&T.config.default!==void 0)for(let F of T.names)B[F]=T.config.default;if(Array.isArray(T.config.type)){if(j[T.name]===void 0)j[T.name]={shouldTransform:!0,transformFunction:T.config.type[0]}}}for(let T of Object.keys(W))if(T!=="_"){let F=T.split(".");oF(B,F,W[T]),eF(B,j)}return{args:J,options:B}}async run($=rJ){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let Y=$,f=Y.message??"command-line error",X=this.name?`${this.name}: `:"",U=/--help/.test(f)?"":`
|
|
235
|
+
Run \`${this.name??"cli"} --help\` for usage.`;$w.stderr.write(`${X}${f}${U}
|
|
236
|
+
`),$w.exit(Y.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:A}=this;if(!A||!A.commandAction)return;A.checkUnknownOptions(),A.checkOptionValue(),A.checkRequiredArgs();let Y=[];A.args.forEach((W,J)=>{if(W.variadic)Y.push($.slice(J));else Y.push($[J])}),Y.push(w);let f={command:A,args:Y,options:w};for(let W of A.beforeHooks)await W(f);let X,U=async()=>{let W=A.commandAction.apply(this,Y);if(W instanceof Promise)X=await W;else X=W;return X};if(A.middleware.length>0){let W=0,J=async()=>{if(W<A.middleware.length){let B=A.middleware[W++];await B({...f,next:J})}else await U()};await J()}else await U();for(let W of A.afterHooks)await W(f);return X}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return $w.removeAllListeners("SIGINT"),$w.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 fW{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 dR=new fW;function W9(){if("FORCE_COLOR"in k1.env)return k1.env.FORCE_COLOR!=="0";if("NO_COLOR"in k1.env||k1.env.TERM==="dumb")return!1;if(k1.platform==="win32")return!0;return aJ.isatty(1)&&aJ.isatty(2)}var XW=W9();function w0($,w){if(!XW)return(A)=>A;return(A)=>$+A+w}var B9=w0("\x1B[0m","\x1B[0m"),E9=w0("\x1B[31m","\x1B[39m"),j9=w0("\x1B[32m","\x1B[39m"),T9=w0("\x1B[33m","\x1B[39m"),F9=w0("\x1B[34m","\x1B[39m"),z9=w0("\x1B[35m","\x1B[39m"),G9=w0("\x1B[36m","\x1B[39m"),H9=w0("\x1B[37m","\x1B[39m"),K9=w0("\x1B[90m","\x1B[39m"),R9=w0("\x1B[1m","\x1B[22m"),N9=w0("\x1B[3m","\x1B[23m"),q9=w0("\x1B[4m","\x1B[24m"),h9=w0("\x1B[2m","\x1B[22m"),y9=w0("\x1B[7m","\x1B[27m"),M9=w0("\x1B[8m","\x1B[28m"),I9=w0("\x1B[9m","\x1B[29m"),C9=w0("\x1B[41m","\x1B[49m"),S9=w0("\x1B[42m","\x1B[49m"),L9=w0("\x1B[43m","\x1B[49m"),V9=w0("\x1B[44m","\x1B[49m"),O9=w0("\x1B[45m","\x1B[49m"),_9=w0("\x1B[46m","\x1B[49m"),Q9=w0("\x1B[47m","\x1B[49m"),D9=XW,k9={reset:B9,red:E9,green:j9,yellow:T9,blue:F9,magenta:z9,cyan:G9,white:H9,gray:K9,bold:R9,italic:N9,underline:q9,dim:h9,inverse:y9,hidden:M9,strikethrough:I9,bgRed:C9,bgGreen:S9,bgYellow:L9,bgBlue:V9,bgMagenta:O9,bgCyan:_9,bgWhite:Q9,isColorSupported:D9},IA=k9,x9=["up","down","left","right","space","enter","cancel"],CA={actions:new Set(x9),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function UW($,w){if(typeof $==="string")return CA.aliases.get($)===w;for(let A of $){if(A===void 0)continue;if(UW(A,w))return!0}return!1}function P9($,w){if($===w)return[];let A=$.split(`
|
|
237
237
|
`),Y=w.split(`
|
|
238
|
-
`),f=[];for(let X=0;X<Math.max(A.length,Y.length);X++)if(A[X]!==Y[X])f.push(X);return f}var
|
|
239
|
-
`),U=[];for(let W of X){if(
|
|
240
|
-
`)}class
|
|
241
|
-
`),
|
|
242
|
-
`).length-1;this.output.write(
|
|
243
|
-
`);this.output.write(Y[A]),this._prevFrame=$,this.output.write(
|
|
238
|
+
`),f=[];for(let X=0;X<Math.max(A.length,Y.length);X++)if(A[X]!==Y[X])f.push(X);return f}var aR=Z9.platform.startsWith("win"),sJ=Symbol("clapp:cancel");function hA($,w){let A=$;if(A.isTTY)A.setRawMode(w)}function u9($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function n9($){return u9($).length}function eJ($,w,A){if(!w||w<1)return $;let Y=A?.hard??!1,f=A?.trim??!0,X=$.split(`
|
|
239
|
+
`),U=[];for(let W of X){if(n9(W)<=w){U.push(f?W.trimEnd():W);continue}if(Y){let J="",B=0,E=0;while(E<W.length){let j=W.slice(E).match(/^\x1b\[[0-9;]*m/);if(j){J+=j[0],E+=j[0].length;continue}if(B>=w)U.push(f?J.trimEnd():J),J="",B=0;J+=W[E],B++,E++}if(J)U.push(f?J.trimEnd():J)}else U.push(f?W.trimEnd():W)}return U.join(`
|
|
240
|
+
`)}class KX{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=i9,output:Y=b9,render:f,signal:X,...U}=$;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=f.bind(this),this._track=w,this._abortSignal=X,this.input=A,this.output=Y}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($)??[],Y=[];for(let f of A)if(f.cb(...w),f.once)Y.push(()=>A.splice(A.indexOf(f),1));for(let f of Y)f();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(sJ);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=c9.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),hA(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(V$.show),this.output.off("resize",this.render),hA(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(V$.show),this.output.off("resize",this.render),hA(this.input,!1),$(sJ)})})}_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 Y=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(Y)}if(this.state==="error")this.state="active",this.error="";if(w?.name){if(!this._track&&CA.aliases.has(w.name))this.emit("cursor",CA.aliases.get(w.name));if(CA.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(UW([$,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(`
|
|
241
|
+
`),hA(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 $=eJ(this._prevFrame,oJ.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
242
|
+
`).length-1;this.output.write(V$.move(-999,$*-1))}render(){let $=eJ(this._render(this)??"",oJ.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(V$.hide);else{let w=P9(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let A=w[0];this.output.write(V$.move(0,A)),this.output.write(jX.lines(1));let Y=$.split(`
|
|
243
|
+
`);this.output.write(Y[A]),this._prevFrame=$,this.output.write(V$.move(0,Y.length-A-1));return}if(w&&w?.length>1){let A=w[0];this.output.write(V$.move(0,A)),this.output.write(jX.down());let f=$.split(`
|
|
244
244
|
`).slice(A);this.output.write(f.join(`
|
|
245
|
-
`)),this._prevFrame=$;return}this.output.write(
|
|
246
|
-
`)}finally{await Y.close()}return w}catch(Y){if(Y.code!=="EEXIST")throw Y}let A=await
|
|
247
|
-
`),B.stdin.end();B.unref();let T=Hw($),F=Date.now()+15000;while(Date.now()<F){if(E)throw E;let H=await Gw($);if(H!==null&&l$(H)){if(Y)q.success(`rpx daemon elevated to root (pid=${H}, https on :${w})`);return{httpsPort:w,httpPort:A,pidPath:T,done:Promise.resolve(),stop:async()=>{try{P.kill(H,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1)}}if(j!==null&&j!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${j}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((G)=>setTimeout(G,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}async function HF($={}){let w=$.verbose??!1,A=$.rpxDir??j0(),Y=$.registryDir??E0.join(A,"registry.d"),f=$.httpsPort??443,X=$.httpPort??80,U=$.hostname??"0.0.0.0",W=$.gcIntervalMs??wR,J=f>0&&f<1024||X>0&&X<1024,B=typeof P.getuid==="function"&&P.getuid()===0;if(P.platform!=="win32"&&J&&!B)return UR(A,f,X,w);let E=await AR(A),j=new Map,T=(L,r)=>WA(j,L,r);function F(L){j=JA(L.map((e$)=>({host:e$.to,path:e$.path,route:YR(e$)})));let r=Array.from(j.keys());z("daemon",`routing table now covers ${r.length} host(s): ${r.join(", ")||"<empty>"}`,w)}await mf(Y,w).catch((L)=>{z("daemon",`initial gc failed: ${L}`,w)});let H=await Cw(Y,w);F(H),await Fw({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS reconcile on start failed: ${L}`,w)}),await FA(H,{rpxDir:A,verbose:w,ownerPid:P.pid}).catch((L)=>{z("daemon",`DNS setup on start failed: ${L}`,w)});let G=[];if($.productionCerts){if(G=await EJ($.productionCerts,w),w&&G.length>0)q.info(`SNI: serving ${G.length} real cert(s): ${G.map((L)=>L.serverName).join(", ")}`)}let K=fA(T,w),R=XA(w),h=null;if(G.length===0)h=await XR($,Y);let N=$.onDemandTls,M=N?.enabled?new uf({config:N,certsDir:N.certsDir??$.productionCerts?.certsDir??E0.join(A,"on-demand-certs"),initial:G,verbose:w,onCertAdded:(L)=>{B$(L)}}):null;function C(L){if(L.length>0)return L.map((r)=>({serverName:r.serverName,cert:r.cert,key:r.key}));return{key:h.key,cert:h.cert,ca:h.ca,requestCert:!1,rejectUnauthorized:!1}}function y(L){return Bun.serve({port:f,hostname:U,tls:C(L),fetch(r,e$){return K(r,e$)},websocket:R,error(r){return z("daemon",`https server error: ${r}`,w),new Response(`Server Error: ${r.message}`,{status:500})}})}let O=y(M?M.sniEntries():G);async function B$(L){if(Zw)return;z("daemon",`rebuilding :443 with ${L.length} SNI cert(s)`,w),O.stop(!1);let r;for(let e$=0;e$<20&&!Zw;e$++)try{O=y(L);return}catch(qA){r=qA,await new Promise((uF)=>setTimeout(uF,25))}q.error(`rpx: failed to rebuild :443 after issuing cert: ${r?.message}`)}let A$=null;if(X>0)A$=Bun.serve({port:X,hostname:U,fetch(L){let r=new URL(L.url),e$=(L.headers.get("host")??r.hostname).split(":")[0];if(M&&r.pathname.startsWith("/.well-known/acme-challenge/")){let qA=M.challengeStore.handlePath(r.pathname);if(qA!==void 0)return new Response(qA,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(M&&!M.hasCert(e$))M.ensureCert(e$).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${e$}${r.pathname}${r.search}`}})}});if(w)q.success(`rpx daemon listening on https://${U}:${f}${A$?` (http→https on :${X})`:""}`),q.info(`pid file: ${E}`),q.info(`registry: ${Y}`);let C0=KJ((L)=>{F(L),FA(L,{rpxDir:A,verbose:w,ownerPid:P.pid}).catch((r)=>{z("daemon",`DNS sync on registry change failed: ${r}`,w)})},{dir:Y,verbose:w}),N0=setInterval(()=>{mf(Y,w).then((L)=>{if(L>0)z("daemon",`gc reaped ${L} stale entries`,w)}).catch((L)=>{z("daemon",`periodic gc failed: ${L}`,w)})},W);if(typeof N0.unref==="function")N0.unref();let Zw=!1,Q1,s0=new Promise((L)=>{Q1=L});async function vJ(){if(Zw)return s0;if(Zw=!0,clearInterval(N0),C0.close(),O.stop(!1),A$?.stop(!1),await Lw({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS teardown failed: ${L}`,w)}),await zA(A),w)q.info("rpx daemon stopped");return Q1(),s0}let mJ=(L)=>{z("daemon",`received ${L}, shutting down`,w),vJ().catch(()=>{})};return P.once("SIGINT",mJ),P.once("SIGTERM",mJ),{stop:vJ,done:s0,httpsPort:typeof O.port==="number"?O.port:f,httpPort:A$&&typeof A$.port==="number"?A$.port:X,pidPath:E,ensureCert:(L)=>M?M.ensureCert(L):Promise.resolve(!1)}}function JR(){let $=P.execPath,w=E0.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&P.argv[1])return[$,P.argv[1],"daemon:start"];return[$,"daemon:start"]}async function KF($={}){let w=$.rpxDir??j0(),A=$.verbose??!1;await Fw({rpxDir:w,verbose:A}).catch((E)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${E}`,A)});let Y=await Gw(w);if(Y!==null&&l$(Y))return z("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await zA(w);await y0.mkdir(w,{recursive:!0});let f=$.spawnCommand??JR();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${f.join(" ")}`,A);let X=GF(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??P.cwd(),env:$.spawnEnv?{...P.env,...$.spawnEnv}:P.env});X.unref();let U=null;X.once("error",(E)=>{U=E});let W=$.startupTimeoutMs??5000,J=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let E=await Gw(w);if(E!==null&&l$(E))return z("daemon",`daemon registered with pid=${E}`,A),{pid:E,spawned:!0};await new Promise((j)=>setTimeout(j,J))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function RF($={}){let w=$.rpxDir??j0(),A=$.verbose??!1,Y=$.timeoutMs??5000,f=$.pollIntervalMs??50,X=$.forceAfterTimeout??!0,U=await Gw(w);if(U===null||!l$(U)){if(U!==null)await zA(w);return await Fw({rpxDir:w,verbose:A}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{P.kill(U,"SIGTERM")}catch(J){if(J.code==="ESRCH")return await zA(w),{stopped:!1,pid:U,forced:!1};throw J}let W=Date.now()+Y;while(Date.now()<W){if(!l$(U))return z("daemon",`daemon pid=${U} stopped cleanly`,A),{stopped:!0,pid:U,forced:!1};await new Promise((J)=>setTimeout(J,f))}if(!X)throw Error(`rpx daemon (pid=${U}) did not exit within ${Y}ms`);z("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,A);try{P.kill(U,"SIGKILL")}catch(J){if(J.code!=="ESRCH")throw J}return await zA(w),await Lw({rpxDir:w,verbose:A}).catch((J)=>{z("daemon",`DNS teardown after SIGKILL: ${J}`,A)}),{stopped:!0,pid:U,forced:!0}}async function hF($={}){let w=$.rpxDir??j0();if(await af(w))return;await Fw({rpxDir:w,verbose:$.verbose})}Aw();U$();import{spawn as WR}from"node:child_process";import*as Ow from"node:process";class qF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[Y,...f]=w.command.split(" "),X=w.cwd||Ow.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${Y} ${f.join(" ")}`,A),z("start",` Working directory: ${X}`,A),z("start",` Environment variables: ${W0(w.env)}`,A);let U=WR(Y,f,{cwd:X,env:{...Ow.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:U,env:w.env}),new Promise((W,J)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),J(B),Ow.emit("SIGINT")}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)z("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),J(Error(`Process ${$} exited with code ${B}`)),Ow.emit("SIGINT")}),A)U.stdout?.on("data",(B)=>{z("process",`[${$}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{z("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),J(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},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((Y)=>{if(!A.process){Y();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),Y()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){z("start",`Error stopping process ${$}: ${f}`,w),this.processes.delete($),Y()}})}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((Y)=>{q.error(`Failed to stop process ${A}:`,Y)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var sf=new qF;U$();import*as m$ from"node:fs/promises";import{homedir as BR}from"node:os";import*as QJ from"node:path";import*as _J from"node:process";var ER=/^[a-zA-Z0-9._-]+$/;function Vw(){return QJ.join(BR(),".stacks","rpx","registry.d")}function V1($){return typeof $==="string"&&$.length>0&&$.length<=128&&ER.test($)}function DJ($,w){if(!V1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return QJ.join($,`${w}.json`)}function NF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,f=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",X=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&V1(w.id)&&(Y||f)&&typeof w.to==="string"&&w.to.length>0&&X&&A&&typeof w.createdAt==="string"}async function jR($){await m$.mkdir($,{recursive:!0})}async function yF($,w=Vw(),A){if(!NF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await jR(w);let Y=DJ(w,$.id),f=`${Y}.tmp.${_J.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await m$.writeFile(f,X,{encoding:"utf8",mode:420}),await m$.rename(f,Y),z("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await m$.unlink(f).catch(()=>{}),U}}async function MF($,w=Vw(),A){let Y=DJ(w,$);try{await m$.unlink(Y),z("registry",`removed entry ${$}`,A)}catch(f){if(f.code!=="ENOENT")throw f}}async function kJ($,w=Vw(),A){let Y=DJ(w,$);try{let f=await m$.readFile(Y,"utf8"),X=JSON.parse(f);if(!NF(X))return z("registry",`entry ${$} failed validation, removing`,A),await m$.unlink(Y).catch(()=>{}),null;return X}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await m$.unlink(Y).catch(()=>{}),null;throw f}}async function IF($=Vw(),w){let A;try{A=await m$.readdir($)}catch(f){if(f.code==="ENOENT")return[];throw f}let Y=[];for(let f of A){if(!f.endsWith(".json"))continue;let X=f.slice(0,-5);if(!V1(X))continue;let U=await kJ(X,$,w);if(U)Y.push(U)}return Y}Aw();import{execSync as KR}from"node:child_process";import*as kw from"node:http";import*as DF from"node:http2";import*as kF from"node:net";import*as w$ from"node:process";var of=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,M0={bold:of(1,22),dim:of(2,22),green:of(32,39),cyan:of(36,39)};GU();RJ();Aw();jA();U$();import*as CF from"node:fs";import*as SF from"node:path";import*as I0 from"node:process";function TR($,w){let Y=(w&&w!=="/"?`${$}${w}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return Y.length>0?Y:"rpx"}async function ZJ($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,Y=new Set,f=$.proxies.map((T)=>{let F=T.id??TR(T.to,T.path);if(!EA(F))throw Error(`invalid registry id "${F}" derived from to="${T.to}"`);if(Y.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return Y.add(F),{...T,id:F}}),X=new Date().toISOString();for(let T of f)await eT({id:T.id,from:T.from,to:T.to,path:T.path,pid:$.persistent?void 0:I0.pid,cwd:I0.cwd(),createdAt:X,cleanUrls:T.cleanUrls,changeOrigin:T.changeOrigin,pathRewrites:T.pathRewrites,static:T.static},A,w);let U=await AF({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let T of f){let F=T.static?`static ${typeof T.static==="string"?T.static:T.static.dir}`:T.from;q.success(`https://${T.to} → ${F}`)}if(q.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,J=A??Tw(),B=f.map((T)=>T.id),E=async()=>{if(W)return;W=!0;for(let T of B)await HJ(T,A,w).catch((F)=>{z("runner",`removeEntry(${T}) failed: ${F}`,w)})},j=(T)=>{z("runner",`received ${T}, unregistering ${B.length} entries`,w),E().finally(()=>I0.exit(0))};I0.once("SIGINT",j),I0.once("SIGTERM",j),I0.once("exit",()=>{if(W)return;for(let T of B)try{CF.unlinkSync(SF.join(J,`${T}.json`))}catch{}}),await new Promise(()=>{})}U$();import{exec as FR}from"node:child_process";import Qw from"node:fs";import OF from"node:os";import PJ from"node:path";import*as GA from"node:process";import{promisify as zR}from"node:util";var ef=zR(FR);function LF($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var T0=GA.platform==="win32"?PJ.join(GA.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",xJ=!1;async function $X($){if(GA.platform==="win32")throw Error("Administrator privileges required on Windows");let w=Mw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:Y}=await ef(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return xJ=!0,Y}if(xJ)try{let{stdout:Y}=await ef(`sudo -n sh -c '${A}'`);return Y}catch(Y){z("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:Y}=await ef(`sudo -n sh -c '${A}'`);return xJ=!0,Y}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(Y){throw Error(`Failed to execute sudo command: ${Y.message}`)}}async function HA($,w){let A=$.filter((f)=>!LF(f)),Y=$.filter((f)=>LF(f));if(Y.length>0)z("hosts",`Skipping /etc/hosts for loopback dev names: ${Y.join(", ")}`,w);if(A.length===0)return;z("hosts",`Adding hosts: ${A.join(", ")}`,w),z("hosts",`Using hosts file at: ${T0}`,w);try{let f;try{f=await Qw.promises.readFile(T0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{f=await $X(`cat "${T0}"`)}catch(J){throw console.log(" Could not read hosts file — skipping hosts setup"),z("hosts",`sudo read also failed: ${J}`,w),Error(`Cannot read hosts file: ${J}`)}}let X=A.filter((J)=>{let B=`127.0.0.1 ${J}`,E=`::1 ${J}`;return!f.includes(B)&&!f.includes(E)});if(X.length===0){z("hosts","All hosts already exist in hosts file",w);return}let U=X.map((J)=>`
|
|
245
|
+
`)),this._prevFrame=$;return}this.output.write(jX.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function v9($,w){if($===void 0)return 0;if(w.length===0)return 0;let Y=w.findIndex((f)=>f.value===$);return Y!==-1?Y:0}function m9($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function d9($,w){if(!w)return;if($)return w;return w[0]}class l9 extends KX{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#A="";#Y;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return IA.inverse(IA.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`${$}${IA.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.#Y=$.filter??m9;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 Y of A){let f=w.findIndex((X)=>X.value===Y);if(f!==-1)this.toggleSelected(Y),this.#$=f}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Y,f)=>this.#f(Y,f)),this.on("userInput",(Y)=>this.#X(Y))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#f($,w){let A=w.name==="up",Y=w.name==="down",f=w.name==="return";if(A||Y){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(f)this.value=d9(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=[$]}#X($){if($!==this.#A){this.#A=$;let w=this.options;if($)this.filteredOptions=w.filter((A)=>this.#Y($,A));else this.filteredOptions=[...w];if(this.#$=v9(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 g9 extends KX{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((Y)=>A.includes(Y.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((Y)=>A.findIndex((f)=>f.value===Y)===-1);else this.value=[...this.value,...A.map((Y)=>Y.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,Y])=>[{value:A,group:!0,label:A},...Y.map((f)=>({...f,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 Y=this.options[this.cursor]?.group===!0;if(!this.#$&&Y)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 Y=this.options[this.cursor]?.group===!0;if(!this.#$&&Y)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var t9=w9();var s=($,w)=>t9?$:w,eR=s("◆","*"),$N=s("■","x"),wN=s("▲","x"),AN=s("◇","o"),YN=s("┌","T"),p9=s("│","|"),fN=s("└","—"),XN=s("●",">"),UN=s("○"," "),JN=s("◻","[•]"),WN=s("◼","[+]"),BN=s("◻","[ ]"),EN=s("▪","•"),jN=s("─","-"),TN=s("╮","+"),FN=s("├","+"),zN=s("╯","+"),GN=s("●","•"),HN=s("◆","*"),KN=s("▲","!"),RN=s("■","x");var NN={light:s("─","-"),heavy:s("━","="),block:s("█","#")};function r9(){return`${IA.gray(p9)} `}var qN=r9();XU();import{homedir as UU}from"node:os";import{join as JU,resolve as Bh}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",XG={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:JU(UU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:JU(UU(),".stacks","ssl","stacks.localhost.crt"),keyPath:JU(UU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var rw=XG;fw();Pf();bf();uf();TJ();zJ();YA();jA();V1();U0();import{spawn as GF}from"node:child_process";import*as M$ from"node:fs/promises";import{homedir as _J}from"node:os";import*as T$ from"node:path";import*as i from"node:process";var AR=5000;function F$(){return T$.join(_J(),".stacks","rpx")}function Rw($=F$()){return T$.join($,"daemon.pid")}async function Kw($=F$()){try{let w=await M$.readFile(Rw($),"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 sf($=F$()){let w=await Kw($);return w!==null&&l0(w)}async function YR($=F$()){await M$.mkdir($,{recursive:!0});let w=Rw($);while(!0){try{let Y=await M$.open(w,"wx");try{await Y.write(`${i.pid}
|
|
246
|
+
`)}finally{await Y.close()}return w}catch(Y){if(Y.code!=="EEXIST")throw Y}let A=await Kw($);if(A!==null&&l0(A))throw Error(`rpx daemon already running (pid=${A})`);await M$.unlink(w).catch(()=>{})}}async function zA($=F$()){await M$.unlink(Rw($)).catch(()=>{})}function fR($){let w=$.cleanUrls??!1,A=L1($.path);if($.static)return{static:AA($.static,w),cleanUrls:w,basePath:A};let Y=$.from??"localhost:1";return{sourceHost:new URL(Y.startsWith("http")?Y:`http://${Y}`).host,cleanUrls:w,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites,basePath:A}}function XR($){return $.find((A)=>!/^api\./.test(A)&&!/^docs\./.test(A)&&!/^dashboard\./.test(A))??$[0]??"rpx.localhost"}async function UR($,w){let A=await Lw(w,$.verbose),Y=[...new Set(A.map((E)=>E.to))],f=XR(Y),X=[...new Set([f,...Y,"rpx.localhost"])],U=T$.join(_J(),".stacks","ssl"),W=T$.join(U,"rpx.localhost.crt"),J={https:typeof $.https==="object"?{...$.https,certPath:W,keyPath:T$.join(U,"rpx.localhost.key"),commonName:f}:{certPath:W,keyPath:T$.join(U,"rpx.localhost.key"),caCertPath:T$.join(U,"rpx.localhost.ca.crt"),commonName:f},verbose:$.verbose,regenerateUntrustedCerts:!0,...X.length>1?{proxies:X.map((E)=>({from:"localhost:1",to:E}))}:{to:f,from:"localhost:1"}},B=await a$(J);if(!B)z("daemon","no usable cert on disk, generating one",$.verbose),await S1(J),B=await a$(J);if(!B)throw Error("failed to bootstrap TLS for rpx daemon");return B}async function JR($,w,A,Y){let f=i.env.SUDO_PASSWORD,X=i.env.HOME??_J(),U=[i.execPath,...i.argv.slice(1)],W=[`HOME=${X}`,`PATH=${i.env.PATH??""}`];if(Y)W.push("RPX_VERBOSE=1");let J=f?["-S","-p","","env",...W,...U]:["-n","env",...W,...U];z("daemon",`elevating daemon via sudo for privileged ports ${w}/${A}`,Y);let B=GF("sudo",J,{detached:!0,stdio:["pipe","ignore","ignore"]}),E=null,j=null;if(B.once("error",(H)=>{E=H}),B.once("exit",(H)=>{j=H??0}),f&&B.stdin)B.stdin.write(`${f}
|
|
247
|
+
`),B.stdin.end();B.unref();let T=Rw($),F=Date.now()+15000;while(Date.now()<F){if(E)throw E;let H=await Kw($);if(H!==null&&l0(H)){if(Y)q.success(`rpx daemon elevated to root (pid=${H}, https on :${w})`);return{httpsPort:w,httpPort:A,pidPath:T,done:Promise.resolve(),stop:async()=>{try{i.kill(H,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1)}}if(j!==null&&j!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${j}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((G)=>setTimeout(G,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}async function HF($={}){let w=$.verbose??!1,A=$.rpxDir??F$(),Y=$.registryDir??T$.join(A,"registry.d"),f=$.httpsPort??443,X=$.httpPort??80,U=$.hostname??"0.0.0.0",W=$.gcIntervalMs??AR,J=f>0&&f<1024||X>0&&X<1024,B=typeof i.getuid==="function"&&i.getuid()===0;if(i.platform!=="win32"&&J&&!B)return JR(A,f,X,w);let E=await YR(A),j=new Map,T=(L,a)=>WA(j,L,a);function F(L){j=JA(L.map((w$)=>({host:w$.to,path:w$.path,route:fR(w$)})));let a=Array.from(j.keys());z("daemon",`routing table now covers ${a.length} host(s): ${a.join(", ")||"<empty>"}`,w)}await df(Y,w).catch((L)=>{z("daemon",`initial gc failed: ${L}`,w)});let H=await Lw(Y,w);F(H),await Gw({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS reconcile on start failed: ${L}`,w)}),await FA(H,{rpxDir:A,verbose:w,ownerPid:i.pid}).catch((L)=>{z("daemon",`DNS setup on start failed: ${L}`,w)});let G=[];if($.productionCerts){if(G=await jJ($.productionCerts,w),w&&G.length>0)q.info(`SNI: serving ${G.length} real cert(s): ${G.map((L)=>L.serverName).join(", ")}`)}let K=fA(T,w),R=XA(w),N=null;if(G.length===0)N=await UR($,Y);let h=$.onDemandTls,y=h?.enabled?new nf({config:h,certsDir:h.certsDir??$.productionCerts?.certsDir??T$.join(A,"on-demand-certs"),initial:G,verbose:w,onCertAdded:(L)=>{V(L)}}):null;function I(L){if(L.length>0)return L.map((a)=>({serverName:a.serverName,cert:a.cert,key:a.key}));return{key:N.key,cert:N.cert,ca:N.ca,requestCert:!1,rejectUnauthorized:!1}}function S(L){return Bun.serve({port:f,hostname:U,tls:I(L),fetch(a,w$){return K(a,w$)},websocket:R,error(a){return z("daemon",`https server error: ${a}`,w),new Response(`Server Error: ${a.message}`,{status:500})}})}let B0=S(y?y.sniEntries():G);async function V(L){if(S$)return;z("daemon",`rebuilding :443 with ${L.length} SNI cert(s)`,w),B0.stop(!1);let a;for(let w$=0;w$<20&&!S$;w$++)try{B0=S(L);return}catch(qA){a=qA,await new Promise((nF)=>setTimeout(nF,25))}q.error(`rpx: failed to rebuild :443 after issuing cert: ${a?.message}`)}let O=null;if(X>0)O=Bun.serve({port:X,hostname:U,fetch(L){let a=new URL(L.url),w$=(L.headers.get("host")??a.hostname).split(":")[0];if(y&&a.pathname.startsWith("/.well-known/acme-challenge/")){let qA=y.challengeStore.handlePath(a.pathname);if(qA!==void 0)return new Response(qA,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(y&&!y.hasCert(w$))y.ensureCert(w$).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${w$}${a.pathname}${a.search}`}})}});if(w)q.success(`rpx daemon listening on https://${U}:${f}${O?` (http→https on :${X})`:""}`),q.info(`pid file: ${E}`),q.info(`registry: ${Y}`);let e0=RJ((L)=>{F(L),FA(L,{rpxDir:A,verbose:w,ownerPid:i.pid}).catch((a)=>{z("daemon",`DNS sync on registry change failed: ${a}`,w)})},{dir:Y,verbose:w}),$$=setInterval(()=>{df(Y,w).then((L)=>{if(L>0)z("daemon",`gc reaped ${L} stale entries`,w)}).catch((L)=>{z("daemon",`periodic gc failed: ${L}`,w)})},W);if(typeof $$.unref==="function")$$.unref();let S$=!1,L$,e$=new Promise((L)=>{L$=L});async function mJ(){if(S$)return e$;if(S$=!0,clearInterval($$),e0.close(),B0.stop(!1),O?.stop(!1),await Ow({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS teardown failed: ${L}`,w)}),await zA(A),w)q.info("rpx daemon stopped");return L$(),e$}let dJ=(L)=>{z("daemon",`received ${L}, shutting down`,w),mJ().catch(()=>{})};return i.once("SIGINT",dJ),i.once("SIGTERM",dJ),{stop:mJ,done:e$,httpsPort:typeof B0.port==="number"?B0.port:f,httpPort:O&&typeof O.port==="number"?O.port:X,pidPath:E,ensureCert:(L)=>y?y.ensureCert(L):Promise.resolve(!1)}}function WR(){let $=i.execPath,w=T$.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&i.argv[1])return[$,i.argv[1],"daemon:start"];return[$,"daemon:start"]}async function KF($={}){let w=$.rpxDir??F$(),A=$.verbose??!1;await Gw({rpxDir:w,verbose:A}).catch((E)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${E}`,A)});let Y=await Kw(w);if(Y!==null&&l0(Y))return z("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await zA(w);await M$.mkdir(w,{recursive:!0});let f=$.spawnCommand??WR();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${f.join(" ")}`,A);let X=GF(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??i.cwd(),env:$.spawnEnv?{...i.env,...$.spawnEnv}:i.env});X.unref();let U=null;X.once("error",(E)=>{U=E});let W=$.startupTimeoutMs??5000,J=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let E=await Kw(w);if(E!==null&&l0(E))return z("daemon",`daemon registered with pid=${E}`,A),{pid:E,spawned:!0};await new Promise((j)=>setTimeout(j,J))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function RF($={}){let w=$.rpxDir??F$(),A=$.verbose??!1,Y=$.timeoutMs??5000,f=$.pollIntervalMs??50,X=$.forceAfterTimeout??!0,U=await Kw(w);if(U===null||!l0(U)){if(U!==null)await zA(w);return await Gw({rpxDir:w,verbose:A}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{i.kill(U,"SIGTERM")}catch(J){if(J.code==="ESRCH")return await zA(w),{stopped:!1,pid:U,forced:!1};throw J}let W=Date.now()+Y;while(Date.now()<W){if(!l0(U))return z("daemon",`daemon pid=${U} stopped cleanly`,A),{stopped:!0,pid:U,forced:!1};await new Promise((J)=>setTimeout(J,f))}if(!X)throw Error(`rpx daemon (pid=${U}) did not exit within ${Y}ms`);z("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,A);try{i.kill(U,"SIGKILL")}catch(J){if(J.code!=="ESRCH")throw J}return await zA(w),await Ow({rpxDir:w,verbose:A}).catch((J)=>{z("daemon",`DNS teardown after SIGKILL: ${J}`,A)}),{stopped:!0,pid:U,forced:!0}}async function NF($={}){let w=$.rpxDir??F$();if(await sf(w))return;await Gw({rpxDir:w,verbose:$.verbose})}fw();U0();import{spawn as BR}from"node:child_process";import*as _w from"node:process";class qF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[Y,...f]=w.command.split(" "),X=w.cwd||_w.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${Y} ${f.join(" ")}`,A),z("start",` Working directory: ${X}`,A),z("start",` Environment variables: ${E$(w.env)}`,A);let U=BR(Y,f,{cwd:X,env:{..._w.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:U,env:w.env}),new Promise((W,J)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),J(B),_w.emit("SIGINT")}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)z("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),J(Error(`Process ${$} exited with code ${B}`)),_w.emit("SIGINT")}),A)U.stdout?.on("data",(B)=>{z("process",`[${$}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{z("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),J(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},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((Y)=>{if(!A.process){Y();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),Y()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){z("start",`Error stopping process ${$}: ${f}`,w),this.processes.delete($),Y()}})}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((Y)=>{q.error(`Failed to stop process ${A}:`,Y)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var of=new qF;U0();import*as m0 from"node:fs/promises";import{homedir as ER}from"node:os";import*as QJ from"node:path";import*as DJ from"node:process";var jR=/^[a-zA-Z0-9._-]+$/;function Qw(){return QJ.join(ER(),".stacks","rpx","registry.d")}function _1($){return typeof $==="string"&&$.length>0&&$.length<=128&&jR.test($)}function kJ($,w){if(!_1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return QJ.join($,`${w}.json`)}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,Y=typeof w.from==="string"&&w.from.length>0,f=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",X=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&_1(w.id)&&(Y||f)&&typeof w.to==="string"&&w.to.length>0&&X&&A&&typeof w.createdAt==="string"}async function TR($){await m0.mkdir($,{recursive:!0})}async function yF($,w=Qw(),A){if(!hF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await TR(w);let Y=kJ(w,$.id),f=`${Y}.tmp.${DJ.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await m0.writeFile(f,X,{encoding:"utf8",mode:420}),await m0.rename(f,Y),z("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await m0.unlink(f).catch(()=>{}),U}}async function MF($,w=Qw(),A){let Y=kJ(w,$);try{await m0.unlink(Y),z("registry",`removed entry ${$}`,A)}catch(f){if(f.code!=="ENOENT")throw f}}async function ZJ($,w=Qw(),A){let Y=kJ(w,$);try{let f=await m0.readFile(Y,"utf8"),X=JSON.parse(f);if(!hF(X))return z("registry",`entry ${$} failed validation, removing`,A),await m0.unlink(Y).catch(()=>{}),null;return X}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await m0.unlink(Y).catch(()=>{}),null;throw f}}async function IF($=Qw(),w){let A;try{A=await m0.readdir($)}catch(f){if(f.code==="ENOENT")return[];throw f}let Y=[];for(let f of A){if(!f.endsWith(".json"))continue;let X=f.slice(0,-5);if(!_1(X))continue;let U=await ZJ(X,$,w);if(U)Y.push(U)}return Y}fw();import{execSync as qR}from"node:child_process";import*as xw from"node:http";import*as kF from"node:http2";import*as ZF from"node:net";import*as A0 from"node:process";var ef=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,I$={bold:ef(1,22),dim:ef(2,22),green:ef(32,39),cyan:ef(36,39)};H8();NJ();fw();jA();U0();import*as CF from"node:fs";import*as SF from"node:path";import*as C$ from"node:process";function FR($,w){let Y=(w&&w!=="/"?`${$}${w}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return Y.length>0?Y:"rpx"}async function xJ($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,Y=new Set,f=$.proxies.map((T)=>{let F=T.id??FR(T.to,T.path);if(!EA(F))throw Error(`invalid registry id "${F}" derived from to="${T.to}"`);if(Y.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return Y.add(F),{...T,id:F}}),X=new Date().toISOString();for(let T of f)await eT({id:T.id,from:T.from,to:T.to,path:T.path,pid:$.persistent?void 0:C$.pid,cwd:C$.cwd(),createdAt:X,cleanUrls:T.cleanUrls,changeOrigin:T.changeOrigin,pathRewrites:T.pathRewrites,static:T.static},A,w);let U=await AF({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let T of f){let F=T.static?`static ${typeof T.static==="string"?T.static:T.static.dir}`:T.from;q.success(`https://${T.to} → ${F}`)}if(q.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,J=A??zw(),B=f.map((T)=>T.id),E=async()=>{if(W)return;W=!0;for(let T of B)await KJ(T,A,w).catch((F)=>{z("runner",`removeEntry(${T}) failed: ${F}`,w)})},j=(T)=>{z("runner",`received ${T}, unregistering ${B.length} entries`,w),E().finally(()=>C$.exit(0))};C$.once("SIGINT",j),C$.once("SIGTERM",j),C$.once("exit",()=>{if(W)return;for(let T of B)try{CF.unlinkSync(SF.join(J,`${T}.json`))}catch{}}),await new Promise(()=>{})}U0();import{exec as zR}from"node:child_process";import Dw from"node:fs";import VF from"node:os";import iJ from"node:path";import*as GA from"node:process";import{promisify as GR}from"node:util";var $X=GR(zR);function LF($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var z$=GA.platform==="win32"?iJ.join(GA.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",PJ=!1;async function wX($){if(GA.platform==="win32")throw Error("Administrator privileges required on Windows");let w=Cw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:Y}=await $X(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return PJ=!0,Y}if(PJ)try{let{stdout:Y}=await $X(`sudo -n sh -c '${A}'`);return Y}catch(Y){z("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:Y}=await $X(`sudo -n sh -c '${A}'`);return PJ=!0,Y}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(Y){throw Error(`Failed to execute sudo command: ${Y.message}`)}}async function HA($,w){let A=$.filter((f)=>!LF(f)),Y=$.filter((f)=>LF(f));if(Y.length>0)z("hosts",`Skipping /etc/hosts for loopback dev names: ${Y.join(", ")}`,w);if(A.length===0)return;z("hosts",`Adding hosts: ${A.join(", ")}`,w),z("hosts",`Using hosts file at: ${z$}`,w);try{let f;try{f=await Dw.promises.readFile(z$,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{f=await wX(`cat "${z$}"`)}catch(J){throw console.log(" Could not read hosts file — skipping hosts setup"),z("hosts",`sudo read also failed: ${J}`,w),Error(`Cannot read hosts file: ${J}`)}}let X=A.filter((J)=>{let B=`127.0.0.1 ${J}`,E=`::1 ${J}`;return!f.includes(B)&&!f.includes(E)});if(X.length===0){z("hosts","All hosts already exist in hosts file",w);return}let U=X.map((J)=>`
|
|
248
248
|
# Added by rpx
|
|
249
249
|
127.0.0.1 ${J}
|
|
250
250
|
::1 ${J}`).join(`
|
|
251
|
-
`),W=
|
|
251
|
+
`),W=iJ.join(VF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Dw.promises.writeFile(W,f+U,"utf8"),await wX(`cat "${W}" | tee "${z$}" > /dev/null`),console.log(` Hosts updated: ${X.join(", ")}`)}catch(J){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),X.forEach((B)=>{console.log(` 127.0.0.1 ${B}`),console.log(` ::1 ${B}`)}),console.log(` Or run: sudo nano ${z$}`)}finally{try{await Dw.promises.unlink(W)}catch{}}}catch(f){z("hosts",`Failed to manage hosts file: ${f.message}`,w)}}async function OF($,w){z("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let A;try{A=await Dw.promises.readFile(z$,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await wX(`cat "${z$}"`)}catch(J){throw z("hosts",`sudo read also failed: ${J}`,w),Error(`Cannot read hosts file: ${J}`)}}let Y=A.split(`
|
|
252
252
|
`),f=!1,X=Y.filter((J)=>{if($.some((E)=>J.includes(` ${E}`)&&(J.includes("127.0.0.1")||J.includes("::1"))))return f=!0,!1;if(J.trim()==="# Added by rpx")return f=!0,!1;return!0});if(!f){z("hosts","No matching hosts found to remove",w);return}while(X[X.length-1]?.trim()==="")X.pop();let U=`${X.join(`
|
|
253
253
|
`)}
|
|
254
|
-
`,W=PJ.join(OF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Qw.promises.writeFile(W,U,"utf8"),await $X(`cat "${W}" | tee "${T0}" > /dev/null`),z("hosts","Hosts removed successfully",w)}catch(J){z("hosts","Could not clean up hosts file automatically",w)}finally{try{await Qw.promises.unlink(W)}catch(J){z("hosts",`Failed to remove temporary file: ${J}`,w)}}}catch(A){z("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function KA($,w){z("hosts",`Checking hosts: ${$}`,w);let A;try{A=await Qw.promises.readFile(T0,"utf-8")}catch(Y){z("hosts",`Error reading hosts file: ${Y}`,w);try{let f=Mw(),X;if(f)X=`echo '${f}' | sudo -S cat "${T0}" 2>/dev/null`;else X=`sudo -n cat "${T0}" 2>/dev/null || cat "${T0}" 2>/dev/null || echo ""`;let{stdout:U}=await ef(X);A=U}catch(f){return z("hosts",`Cannot read hosts file, assuming entries don't exist: ${f}`,w),$.map(()=>!1)}}return $.map((Y)=>{let f=`127.0.0.1 ${Y}`,X=`::1 ${Y}`;return A.includes(f)||A.includes(X)})}Pf();U$();import*as wX from"node:net";function _w($,w,A){return z("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((Y)=>{let f=wX.createServer(),X=setTimeout(()=>{z("port",`Checking port ${$} timed out, assuming it's in use`,A),f.close(),Y(!0)},3000);f.once("error",(U)=>{if(clearTimeout(X),U.code==="EADDRINUSE")z("port",`Port ${$} is in use`,A),Y(!0);else z("port",`Error checking port ${$}: ${U.message}`,A),Y(!0)}),f.once("listening",()=>{clearTimeout(X),z("port",`Port ${$} is available`,A),f.close(),Y(!1)});try{f.listen($,w)}catch(U){clearTimeout(X),z("port",`Exception checking port ${$}: ${U}`,A),Y(!0)}})}async function GR($,w,A,Y=50){z("port",`Finding available port starting from ${$} (max attempts: ${Y})`,A);let f=$,X=0;while(X<Y){if(X++,!await _w(f,w,A))return z("port",`Found available port: ${f} after ${X} attempts`,A),f;z("port",`Port ${f} is in use, trying ${f+1} (attempt ${X}/${Y})`,A),f++}throw Error(`Unable to find available port after ${Y} attempts starting from ${$}`)}function QF($,w,A=5000,Y){return z("port",`Testing connection to ${w}:${$}`,Y),new Promise((f)=>{let X=wX.connect({host:w,port:$,timeout:A});X.once("connect",()=>{z("port",`Successfully connected to ${w}:${$}`,Y),X.end(),f(!0)}),X.once("timeout",()=>{z("port",`Connection to ${w}:${$} timed out`,Y),X.destroy(),f(!1)}),X.once("error",(U)=>{z("port",`Failed to connect to ${w}:${$}: ${U.message}`,Y),X.destroy(),f(!1)})})}class AX{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 _w($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await QF($,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 GR($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await QF(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 TS=new AX;Aw();U$();import{spawn as HR}from"node:child_process";import*as Dw from"node:process";class YX{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[Y,...f]=w.command.split(" "),X=w.cwd||Dw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${Y} ${f.join(" ")}`,A),z("start",` Working directory: ${X}`,A),z("start",` Environment variables: ${W0(w.env)}`,A);let U=HR(Y,f,{cwd:X,env:{...Dw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:U,env:w.env}),new Promise((W,J)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),J(B),Dw.emit("SIGINT")}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)z("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),J(Error(`Process ${$} exited with code ${B}`)),Dw.emit("SIGINT")}),A)U.stdout?.on("data",(B)=>{z("process",`[${$}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{z("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),J(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},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((Y)=>{if(!A.process){Y();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),Y()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){z("start",`Error stopping process ${$}: ${f}`,w),this.processes.delete($),Y()}})}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((Y)=>{q.error(`Failed to stop process ${A}:`,Y)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var KS=new YX;bf();cf();YA();U$();var XX=new YX,RR="0.12.0",hR=new AX("0.0.0.0"),RA=new Set,iJ=!1,fX=null,bJ=null;async function UX($){if(iJ)return z("cleanup","Cleanup already in progress, skipping",$?.verbose),bJ||Promise.resolve();iJ=!0,z("cleanup","Starting cleanup process",$?.verbose),bJ=new Promise((w)=>{fX=w});try{await XX.stopAll($?.verbose),q.info("Shutting down proxy servers...");let w=[],A=Array.from(RA).map((Y)=>new Promise((f)=>{Y.close(()=>{z("cleanup","Server closed successfully",$?.verbose),f()})}));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 Y=$.domains.filter((f)=>{if(f==="test.local")return!0;return f!=="localhost"&&!f.startsWith("localhost.")&&f!=="127.0.0.1"});if(z("cleanup",`Filtered domains for cleanup: ${JSON.stringify(Y)}`,$?.verbose),Y.length>0)q.info("Cleaning up hosts file entries..."),w.push(VF(Y,$?.verbose).then(()=>{z("cleanup",`Removed hosts entries for ${Y.join(", ")}`,$?.verbose)}).catch((f)=>{z("cleanup",`Failed to remove hosts entries: ${f}`,$?.verbose),q.warn(`Failed to clean up hosts file entries for ${Y.join(", ")}:`,f)}))}if($?.certs&&$.domains?.length){z("cleanup","Cleaning up SSL certificates",$?.verbose),q.info("Cleaning up SSL certificates...");let Y=$.domains.map(async(f)=>{try{await gT(f,$?.verbose),z("cleanup",`Removed certificates for ${f}`,$?.verbose)}catch(X){z("cleanup",`Failed to remove certificates for ${f}: ${X}`,$?.verbose),q.warn(`Failed to clean up certificates for ${f}:`,X)}});w.push(...Y)}await Promise.allSettled(w),z("cleanup","All cleanup tasks completed successfully",$?.verbose),q.success("All cleanup tasks completed successfully")}catch(w){z("cleanup",`Error during cleanup: ${w}`,$?.verbose),q.error("Error during cleanup:",w)}finally{if(fX)fX();fX=null,iJ=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(w$.env.NODE_ENV!=="test"&&w$.env.BUN_ENV!=="test"&&!w)w$.exit(0)}return bJ}var cJ=!1;function uJ($){if(cJ){z("signal",`Received second ${$} signal, forcing exit`,!0),w$.exit(1);return}cJ=!0,z("signal",`Received ${$} signal, initiating cleanup`,!0),UX().catch((w)=>{z("signal",`Cleanup failed after ${$}: ${w}`,!0),w$.exit(1)}).finally(()=>{cJ=!1})}w$.once("SIGINT",()=>uJ("SIGINT"));w$.once("SIGTERM",()=>uJ("SIGTERM"));w$.on("uncaughtException",($)=>{z("process",`Uncaught exception: ${$}`,!0),q.error("Uncaught exception:",$),uJ("uncaughtException")});async function hA($,w,A,Y=5){z("connection",`Testing connection to ${$}:${w} (retries left: ${Y})`,A);let f=15000,X=Date.now();if(w$.env.RPX_BYPASS_CONNECTION_TEST==="true"){z("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let U=()=>new Promise((W,J)=>{let B=kF.connect({host:$,port:w,timeout:3000});B.once("connect",()=>{z("connection",`Successfully connected to ${$}:${w}`,A),B.end(),W()}),B.once("timeout",()=>{z("connection",`Connection to ${$}:${w} timed out`,A),B.destroy(),J(Error("Connection timed out"))}),B.once("error",(E)=>{z("connection",`Failed to connect to ${$}:${w}: ${E}`,A),B.destroy(),J(E)})});try{await U()}catch(W){if(Date.now()-X>f){z("connection",`Connection test timed out after ${f}ms, but continuing anyway`,A),q.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&Y>0)return z("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${Y} retries left)`,A),await new Promise((B)=>setTimeout(B,2000)),hA($,w,A,Y-1);if(Y>0)try{z("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((B,E)=>{let j=kw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(T)=>{z("connection",`Received HTTP response with status: ${T.statusCode}`,A),B()});j.on("error",(T)=>E(T)),j.on("timeout",()=>{j.destroy(),E(Error("HTTP request timed out"))}),j.end()}),z("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(B){return z("connection",`HTTP request to ${$}:${w} failed: ${B}`,A),z("connection",`Retrying socket connection in 2 seconds... (${Y} retries left)`,A),await new Promise((E)=>setTimeout(E,2000)),hA($,w,A,Y-1)}let J=`Failed to connect to ${$}:${w} after ${5-Y} attempts: ${W.message}`;z("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),q.warn(J),q.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 ZF($){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"),Y=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),f=[A.hostname];if(nJ($)&&!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 KA(f,$.verbose))[0]){q.info(`Adding ${A.hostname} to hosts file...`),q.info("This may require sudo/administrator privileges");try{await HA(f,$.verbose)}catch(W){if(q.error("Failed to add hosts entry:",W.message),q.warn("You can manually add this entry to your hosts file:"),q.warn(`127.0.0.1 ${A.hostname}`),q.warn(`::1 ${A.hostname}`),w$.platform==="win32")q.warn("On Windows:"),q.warn("1. Run notepad as administrator"),q.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else q.warn("On Unix systems:"),q.warn("sudo nano /etc/hosts")}}else z("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(U){q.error("Failed to check hosts file:",U.message)}}try{await hA(w.hostname,Y,$.verbose)}catch(U){z("server",`Connection test failed: ${U}`,$.verbose),q.error(U.message),q.warn("Continuing with proxy setup despite connection test failure..."),q.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let X=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=wA({...$,to:A.hostname});if(X=await p0({...$,to:A.hostname,https:$.https}),!X){if(z("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await C1({...$,from:w.toString(),to:A.hostname,https:$.https}),X=await p0({...$,to:A.hostname,https:$.https}),!X)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(U){throw z("server",`SSL setup failed: ${U}`,$.verbose),U}z("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await NR({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:Y,sourceUrl:{hostname:w.hostname,host:w.host},ssl:X})}async function qR($,w,A,Y,f,X,U,W,J,B,E){z("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,J);function j(G){let K={};for(let[R,h]of Object.entries(G))if(!R.startsWith(":"))K[R]=h;return K}let T=(G,K)=>{z("request",`Incoming request: ${G.method} ${G.url}`,J);let R=G.url||"/",h=G.method||"GET";if(G instanceof DF.Http2ServerRequest){let y=G.headers;h=y[":method"]||h,R=y[":path"]||R}if(B){if(!R.match(/\.[a-z0-9]+$/i))if(R.endsWith("/"))R=`${R}index.html`;else R=`${R}.html`}let N=j(G.headers);if(E)N.host=`${X.hostname}:${A}`,z("request",`Changed origin: setting host header to ${N.host}`,J);let M={hostname:X.hostname,port:A,path:R,method:h,headers:N};z("request",`Proxy request options: ${W0(M)}`,J);let C=kw.request(M,(y)=>{if(z("response",`Proxy response received with status ${y.statusCode}`,J),B&&y.statusCode===404){let B$=[];if(R.endsWith(".html"))B$.push(R.slice(0,-5));else if(!R.match(/\.[a-z0-9]+$/i))B$.push(`${R}.html`);if(!R.endsWith("/"))B$.push(`${R}/index.html`);if(B$.length>0){z("cleanUrls",`Trying alternative paths: ${B$.join(", ")}`,J);let A$=(C0)=>{if(C0.length===0){K.writeHead(y.statusCode||404,y.headers),y.pipe(K);return}let N0=C0[0],Zw={...M,path:N0},Q1=kw.request(Zw,(s0)=>{if(s0.statusCode===200)z("cleanUrls",`Found matching path: ${N0}`,J),K.writeHead(s0.statusCode,s0.headers),s0.pipe(K);else A$(C0.slice(1))});Q1.on("error",()=>A$(C0.slice(1))),Q1.end()};A$(B$);return}}let O={...y.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};K.writeHead(y.statusCode||500,O),y.pipe(K)});C.on("error",(y)=>{z("request",`Proxy request failed: ${y}`,J),q.error("Proxy request failed:",y),K.writeHead(502),K.end(`Proxy Error: ${y.message}`)}),G.pipe(C)};if(z("server",`Creating server with SSL config: ${!!U}`,J),U)return new Promise((G,K)=>{try{let R=Bun.serve({port:Y,hostname:f,tls:{key:U.key,cert:U.cert,ca:U.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(h){let N=new URL(h.url);z("request",`Bun.serve received: ${h.method} ${N.pathname}`,J);let M=`http://${X.host}`,C=new URL(N.pathname+N.search,M);try{let y=new Headers(h.headers);if(y.set("host",X.host),E)y.set("origin",M);y.set("x-forwarded-for","127.0.0.1"),y.set("x-forwarded-proto","https"),y.set("x-forwarded-host",w);let O=await fetch(C.toString(),{method:h.method,headers:y,body:h.body,redirect:"manual"}),B$=new Headers(O.headers);if(B&&N.pathname.endsWith(".html")){let A$=N.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:A$}})}return new Response(O.body,{status:O.status,statusText:O.statusText,headers:B$})}catch(y){return z("request",`Proxy error: ${y}`,J),new Response(`Proxy Error: ${y}`,{status:502})}},error(h){return z("server",`Bun.serve error: ${h}`,J),new Response(`Server Error: ${h.message}`,{status:500})}});RA.add(R),_F({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!0,cleanUrls:B,verbose:J}),G()}catch(R){K(R)}});let F=kw.createServer(T);function H(G){return RA.add(G),new Promise((K,R)=>{G.listen(Y,f,()=>{z("server",`Server listening on port ${Y}`,J),_F({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!!U,cleanUrls:B,verbose:J}),K()}),G.on("error",(h)=>{z("server",`Server error: ${h}`,J),R(h)})})}return H(F)}async function NR($){z("setup",`Setting up reverse proxy: ${W0($)}`,$.verbose);let{from:w,to:A,fromPort:Y,sourceUrl:f,ssl:X,verbose:U,cleanup:W,vitePluginUsage:J,changeOrigin:B,cleanUrls:E}=$,j=80,T=443,F="0.0.0.0",H=$.portManager||hR,G=nJ($);try{if(G&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await KA([A],U))[0]){q.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await HA([A],U),q.success(`Added ${A} to your hosts file.`)}catch(M){q.error(`Failed to add ${A} to your hosts file: ${M}`),q.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(G&&w$.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await KA([A],U))[0]){z("hosts",`${A} not found in hosts file, adding...`,U);try{await HA([A],U)}catch(M){z("hosts",`Failed to add ${A} to hosts file: ${M}`,U)}}}if(X&&!H.usedPorts.has(j)){if(!await _w(j,F,U))z("setup","Starting HTTP redirect server",U),xF(U),H.usedPorts.add(j);else if(z("setup","Port 80 is in use, skipping HTTP redirect",U),U)q.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let K=X?T:j,R=await _w(K,F,U),h;if(R){if(z("setup",`Port ${K} is already in use`,U),U)q.warn(`Port ${K} is already in use. This may be another instance of rpx or another service.`);if(K===443){if(h=await H.getNextAvailablePort(3443,!0),z("setup",`Using port ${h} instead of ${K}`,U),U)q.info(`Using port ${h} instead. Access your site at https://${A}:${h}`)}else if(h=await H.getNextAvailablePort(K+1000,!0),z("setup",`Using port ${h} instead of ${K}`,U),U)q.info(`Using port ${h} instead. Access your site at http://${A}:${h}`)}else h=K,H.usedPorts.add(h),z("setup",`Using standard ${K===443?"HTTPS":"HTTP"} port ${K} for ${A}`,U);await qR(w,A,Y,h,F,f,X,J,U,E,B)}catch(K){z("setup",`Setup failed: ${K}`,U),q.error(`Failed to setup reverse proxy: ${K.message}`),UX({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:U,vitePluginUsage:J})}}function xF($){z("redirect","Starting HTTP redirect server",$);let w=kw.createServer((A,Y)=>{let f=A.headers.host||"";z("redirect",`Redirecting request from ${f}${A.url} to HTTPS`,$),Y.writeHead(301,{Location:`https://${f}${A.url}`}),Y.end()}).listen(80);RA.add(w),z("redirect","HTTP redirect server started",$)}function PF($){let w={...zU,...$};if(z("proxy",`Starting proxy with options: ${W0(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){q.error("viaDaemon mode requires both `from` and `to`");return}ZJ({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((J)=>{q.error(`Failed to register with rpx daemon: ${J.message}`),w$.exit(1)});return}let A=w.to||"",Y=A.split(".").pop()?.toLowerCase()||"",f=w$.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),X=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(f&&X.includes(Y)&&w?.verbose)q.warn(`The .${Y} TLD may not work reliably for local development`),q.info(` Google owns .${Y} with HSTS preloading, which can bypass local DNS`),q.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(f)Promise.resolve().then(() => (L1(),rf)).then(({setupDevelopmentDns:J})=>{J({domains:[A],verbose:w.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(Y))q.success(`DNS server started for .${Y} domains`);else q.success(`DNS server started for .${Y} domains (hosts file entry also added)`)});else z("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((J)=>{z("dns",`Failed to start DNS server: ${J}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:wA(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};z("proxy",`Server options: ${W0(W)}`,w.verbose),ZF(W).catch((J)=>{z("proxy",`Failed to start proxy: ${J}`,w.verbose),q.error(`Failed to start proxy: ${J.message}`),UX({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 yR($){return $?.verbose||!1}function nJ($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function iF($){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=yR(w),Y=nJ(w);if(z("config",`Starting with config: ${W0(w,2)}`,A),z("config",`Is multi-proxy? ${"proxies"in w}`,A),z("config",`Hosts management enabled? ${Y}`,A),w.viaDaemon){let G="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((K)=>({id:K.id,from:K.from,to:K.to,path:K.path,cleanUrls:K.cleanUrls??w.cleanUrls,changeOrigin:K.changeOrigin??w.changeOrigin,pathRewrites:K.pathRewrites})):[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await ZJ({proxies:G,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){z("servers",`Found ${w.proxies.length} proxies in config`,A);for(let H of w.proxies)if(H.start){let G=`${H.from}-${H.to}`;try{z("watch",`Starting command for ${G} with command: ${H.start.command}`,A),q.info(`Starting command for ${G}...`),await XX.startProcess(G,H.start,A);let K=new URL(H.from.startsWith("http")?H.from:`http://${H.from}`),R=K.hostname||"localhost",h=Number(K.port)||80;try{await hA(R,h,A),z("watch",`Dev server is ready at ${R}:${h}`,A)}catch(N){z("watch",`Connection check failed, but continuing with proxy setup: ${N}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(K){throw z("watch",`Failed to start command for ${G}: ${K}`,A),Error(`Failed to start command for ${G}: ${K}`)}}else z("watch",`No start command for proxy ${H.from} -> ${H.to}`,A)}else if("start"in w&&w.start){z("watch","Found start command in single proxy config",A);let H=`${w.from}-${w.to}`;try{if(w.start)z("watch",`Starting command: ${w.start.command}`,A),await XX.startProcess(H,w.start,A);let G=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),K=G.hostname||"localhost",R=Number(G.port)||80;try{await hA(K,R,A),z("watch",`Dev server is ready at ${K}:${R}`,A)}catch(h){z("watch",`Connection check failed, but continuing with proxy setup: ${h}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(G){throw z("watch",`Failed to run start command: ${G}`,A),Error(`Failed to run start command: ${G}`)}}else z("watch","No start command found in config",A);let f="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(w$.platform!=="win32"&&(w.https||Y)){if(!Mw())try{z("sudo","Pre-acquiring sudo credentials for privileged operations",A),KR("sudo -v",{stdio:"inherit"})}catch{z("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let H=await p0(w);if(!H){if(z("ssl",`No valid or trusted certificates found for ${f}, generating new ones`,w.verbose),await C1(w),H=await p0(w),!H)throw Error(`Failed to load SSL certificates after generation for ${f}`)}else z("ssl",`Using existing and trusted certificates for ${f}`,w.verbose);w._cachedSSLConfig=H}let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({...H,https:w.https,cleanup:w.cleanup,cleanUrls:H.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:H.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}],U=X.map((H)=>H.to||"rpx.localhost"),W=w._cachedSSLConfig,J=U.filter((H)=>H&&!H.includes("localhost")&&!H.includes("127.0.0.1")),B=["dev","app","page","new","day","foo"],E=["test","localhost","local","example","invalid"],j=[...new Set(J.map((H)=>H.split(".").pop()?.toLowerCase()))],T=j.filter((H)=>!!H&&B.includes(H));if(T.length>0&&A)q.warn(`The following TLDs may not work reliably for local development: ${T.map((H)=>`.${H}`).join(", ")}`),q.info(" These TLDs have HSTS preloading which can bypass local DNS"),q.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(Y&&w$.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:H}=await Promise.resolve().then(() => (L1(),rf));if(await H({domains:J,verbose:A})){if(A)if(j.every((R)=>!!R&&E.includes(R)))q.success(`DNS server started for ${j.map((R)=>`.${R}`).join(", ")} domains`);else q.success(`DNS server started for ${j.map((R)=>`.${R}`).join(", ")} domains (hosts file entries also added)`)}else z("dns","Could not start DNS server - custom domains may not resolve",A)}let F=async()=>{z("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:H}=await Promise.resolve().then(() => (L1(),rf));await H({verbose:w.verbose})}catch(H){z("cleanup",`Error stopping DNS server: ${H}`,w.verbose)}try{await XX.stopAll(w.verbose)}catch(H){z("cleanup",`Error stopping processes: ${H}`,w.verbose)}await UX({domains:U,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(w$.on("SIGINT",F),w$.on("SIGTERM",F),w$.on("uncaughtException",(H)=>{z("process",`Uncaught exception: ${H}`,!0),console.error("Uncaught exception:",H),F()}),W&&X.length>1){z("proxies",`Creating shared HTTPS server for ${X.length} domains`,A);let H=[],G=new Set;for(let y of X){let O=y.to||"rpx.localhost",B$=y.cleanUrls||!1,A$=y.path,C0=S1(A$);if(y.static)H.push({host:O,path:A$,route:{static:AA(y.static,B$),cleanUrls:B$,basePath:C0}}),z("proxies",`Route: ${O}${A$??""} → static ${typeof y.static==="string"?y.static:y.static.dir}`,A);else{let N0=new URL(y.from?.startsWith("http")?y.from:`http://${y.from}`);H.push({host:O,path:A$,route:{sourceHost:N0.host,cleanUrls:B$,changeOrigin:y.changeOrigin||!1,pathRewrites:y.pathRewrites,basePath:C0}}),z("proxies",`Route: ${O}${A$??""} → ${N0.host}`,A)}if(G.has(O))continue;if(G.add(O),Y&&!UA(O)&&!O.includes("localhost")&&!O.includes("127.0.0.1"))try{if(!(await KA([O],A))[0])await HA([O],A)}catch{z("hosts",`Could not add hosts entry for ${O}`,A)}}if(!await _w(80,"0.0.0.0",A))xF(A);let R=443;if(await _w(R,"0.0.0.0",A)){if(z("proxies",`Port ${R} is already in use, cannot start shared proxy`,A),A)q.warn(`Port ${R} is in use. Shared HTTPS proxy cannot start.`);return}let N=JA(H),M=fA((y,O)=>WA(N,y,O),A),C=XA(A);try{let y=Bun.serve({port:R,hostname:"0.0.0.0",tls:{key:W.key,cert:W.cert,ca:W.ca,requestCert:!1,rejectUnauthorized:!1},fetch(O,B$){return M(O,B$)},websocket:C,error(O){return z("server",`Shared proxy server error: ${O}`,A),new Response(`Server Error: ${O.message}`,{status:500})}});RA.add(y),z("proxies",`Shared HTTPS proxy listening on port ${R} for ${N.size} domains`,A)}catch(y){z("proxies",`Failed to start shared proxy: ${y}`,A),console.error("Failed to start shared HTTPS proxy:",y),F()}}else for(let H of X)try{let G=H.to||"rpx.localhost";z("proxy",`Starting proxy for ${G} with SSL config: ${!!W}`,H.verbose),await ZF({from:H.from||"localhost:5173",to:G,cleanUrls:H.cleanUrls||!1,https:H.https||!1,cleanup:H.cleanup||!1,vitePluginUsage:H.vitePluginUsage||!1,verbose:H.verbose||!1,_cachedSSLConfig:W,changeOrigin:H.changeOrigin||!1})}catch(G){z("proxies",`Failed to start proxy for ${H.to}: ${G}`,H.verbose),console.error(`Failed to start proxy for ${H.to}:`,G),F()}}function _F($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${M0.green(M0.bold("rpx"))} ${M0.green(`v${RR}`)}`),console.log(` ${M0.green("➜")} ${M0.dim($?.from??"")} ${M0.dim("➜")} ${M0.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${M0.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${M0.green("➜")} Clean URLs enabled`)}eU();var bS=new yw("rpx",{showTags:!1});function bF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}d$.chdir(IR(MR(CR(import.meta.url)),".."));var t$=new GX("rpx"),cF="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 iF(pw);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(Y){console.error("Failed to parse start-env JSON:",Y),d$.exit(1)}w.start=A}return PF(w)});t$.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=bF(pw)?pw.proxies.find((Y)=>Y.to===$||`${Y.from}-${Y.to}`===$):pw.to===$?pw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),d$.exit(1);try{await sf.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(Y){console.error(`Failed to start dev server for ${$}:`,Y),d$.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 sf.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),d$.exit(1)}});t$.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await sf.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),d$.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("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--verbose","Enable verbose logging").action(async($)=>{try{await(await HF({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,verbose:$.verbose??!0})).done,d$.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),d$.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 RF({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??j0(),A=await Gw(w),Y=await af(w),f=$.registryDir,X=await IF(f).catch(()=>[]);if($.json){console.log(JSON.stringify({running:Y,pid:A,pidFile:Hw(w),rpxDir:w,registryDir:f??Vw(),entries:X},null,2));return}if(!Y){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Hw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Hw(w)}`);if(console.log(`registry: ${f??Vw()}`),X.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${X.length}):`);for(let U of X){let W=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${W})`)}});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"),d$.exit(1);if(!V1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),d$.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}`),d$.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`"),d$.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(!V1($))console.error(`invalid id: ${JSON.stringify($)}`),d$.exit(1);let A=await kJ($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await MF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});t$.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??j0();if(await af(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await hF({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});t$.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(cF)});t$.version(cF);t$.help();t$.run();
|
|
254
|
+
`,W=iJ.join(VF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Dw.promises.writeFile(W,U,"utf8"),await wX(`cat "${W}" | tee "${z$}" > /dev/null`),z("hosts","Hosts removed successfully",w)}catch(J){z("hosts","Could not clean up hosts file automatically",w)}finally{try{await Dw.promises.unlink(W)}catch(J){z("hosts",`Failed to remove temporary file: ${J}`,w)}}}catch(A){z("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function KA($,w){z("hosts",`Checking hosts: ${$}`,w);let A;try{A=await Dw.promises.readFile(z$,"utf-8")}catch(Y){z("hosts",`Error reading hosts file: ${Y}`,w);try{let f=Cw(),X;if(f)X=`echo '${f}' | sudo -S cat "${z$}" 2>/dev/null`;else X=`sudo -n cat "${z$}" 2>/dev/null || cat "${z$}" 2>/dev/null || echo ""`;let{stdout:U}=await $X(X);A=U}catch(f){return z("hosts",`Cannot read hosts file, assuming entries don't exist: ${f}`,w),$.map(()=>!1)}}return $.map((Y)=>{let f=`127.0.0.1 ${Y}`,X=`::1 ${Y}`;return A.includes(f)||A.includes(X)})}Pf();U0();import*as AX from"node:net";function kw($,w,A){return z("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((Y)=>{let f=AX.createServer(),X=setTimeout(()=>{z("port",`Checking port ${$} timed out, assuming it's in use`,A),f.close(),Y(!0)},3000);f.once("error",(U)=>{if(clearTimeout(X),U.code==="EADDRINUSE")z("port",`Port ${$} is in use`,A),Y(!0);else z("port",`Error checking port ${$}: ${U.message}`,A),Y(!0)}),f.once("listening",()=>{clearTimeout(X),z("port",`Port ${$} is available`,A),f.close(),Y(!1)});try{f.listen($,w)}catch(U){clearTimeout(X),z("port",`Exception checking port ${$}: ${U}`,A),Y(!0)}})}async function HR($,w,A,Y=50){z("port",`Finding available port starting from ${$} (max attempts: ${Y})`,A);let f=$,X=0;while(X<Y){if(X++,!await kw(f,w,A))return z("port",`Found available port: ${f} after ${X} attempts`,A),f;z("port",`Port ${f} is in use, trying ${f+1} (attempt ${X}/${Y})`,A),f++}throw Error(`Unable to find available port after ${Y} attempts starting from ${$}`)}function _F($,w,A=5000,Y){return z("port",`Testing connection to ${w}:${$}`,Y),new Promise((f)=>{let X=AX.connect({host:w,port:$,timeout:A});X.once("connect",()=>{z("port",`Successfully connected to ${w}:${$}`,Y),X.end(),f(!0)}),X.once("timeout",()=>{z("port",`Connection to ${w}:${$} timed out`,Y),X.destroy(),f(!1)}),X.once("error",(U)=>{z("port",`Failed to connect to ${w}:${$}: ${U.message}`,Y),X.destroy(),f(!1)})})}class YX{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 kw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await _F($,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 HR($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await _F(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 HS=new YX;fw();U0();import{spawn as KR}from"node:child_process";import*as Zw from"node:process";class fX{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[Y,...f]=w.command.split(" "),X=w.cwd||Zw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${Y} ${f.join(" ")}`,A),z("start",` Working directory: ${X}`,A),z("start",` Environment variables: ${E$(w.env)}`,A);let U=KR(Y,f,{cwd:X,env:{...Zw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:U,env:w.env}),new Promise((W,J)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),J(B),Zw.emit("SIGINT")}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)z("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),J(Error(`Process ${$} exited with code ${B}`)),Zw.emit("SIGINT")}),A)U.stdout?.on("data",(B)=>{z("process",`[${$}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{z("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),J(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},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((Y)=>{if(!A.process){Y();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),Y()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){z("start",`Error stopping process ${$}: ${f}`,w),this.processes.delete($),Y()}})}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((Y)=>{q.error(`Failed to stop process ${A}:`,Y)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var hS=new fX;var RR=["/.well-known/acme-challenge/"];function NR($){let w=$.headers.get("host");if(w)return w.split(":")[0].toLowerCase();try{return new URL($.url).hostname.toLowerCase()}catch{return""}}function QF($){let w=$.header.toLowerCase(),A=new Set,Y=[];for(let J of $.hosts){let B=J.toLowerCase();if(B.startsWith("*."))Y.push(B);else A.add(B)}let f=$.exemptPaths??RR,X=$.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
255
|
+
`,U=(J)=>{let B=J.toLowerCase();return A.has(B)||Y.some((E)=>cf(B,E))},W=(J)=>{let B=NR(J);if(!U(B))return;let E="/";try{E=new URL(J.url).pathname}catch{}if(f.some((j)=>E.startsWith(j)))return;if(J.headers.get(w)===$.value)return;return new Response(X,{status:403,headers:{"content-type":"text/plain"}})};return W.protects=U,W}bf();uf();YA();U0();var UX=new fX,hR="0.12.0",yR=new YX("0.0.0.0"),RA=new Set,bJ=!1,XX=null,cJ=null;async function JX($){if(bJ)return z("cleanup","Cleanup already in progress, skipping",$?.verbose),cJ||Promise.resolve();bJ=!0,z("cleanup","Starting cleanup process",$?.verbose),cJ=new Promise((w)=>{XX=w});try{await UX.stopAll($?.verbose),q.info("Shutting down proxy servers...");let w=[],A=Array.from(RA).map((Y)=>new Promise((f)=>{Y.close(()=>{z("cleanup","Server closed successfully",$?.verbose),f()})}));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 Y=$.domains.filter((f)=>{if(f==="test.local")return!0;return f!=="localhost"&&!f.startsWith("localhost.")&&f!=="127.0.0.1"});if(z("cleanup",`Filtered domains for cleanup: ${JSON.stringify(Y)}`,$?.verbose),Y.length>0)q.info("Cleaning up hosts file entries..."),w.push(OF(Y,$?.verbose).then(()=>{z("cleanup",`Removed hosts entries for ${Y.join(", ")}`,$?.verbose)}).catch((f)=>{z("cleanup",`Failed to remove hosts entries: ${f}`,$?.verbose),q.warn(`Failed to clean up hosts file entries for ${Y.join(", ")}:`,f)}))}if($?.certs&&$.domains?.length){z("cleanup","Cleaning up SSL certificates",$?.verbose),q.info("Cleaning up SSL certificates...");let Y=$.domains.map(async(f)=>{try{await tT(f,$?.verbose),z("cleanup",`Removed certificates for ${f}`,$?.verbose)}catch(X){z("cleanup",`Failed to remove certificates for ${f}: ${X}`,$?.verbose),q.warn(`Failed to clean up certificates for ${f}:`,X)}});w.push(...Y)}await Promise.allSettled(w),z("cleanup","All cleanup tasks completed successfully",$?.verbose),q.success("All cleanup tasks completed successfully")}catch(w){z("cleanup",`Error during cleanup: ${w}`,$?.verbose),q.error("Error during cleanup:",w)}finally{if(XX)XX();XX=null,bJ=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(A0.env.NODE_ENV!=="test"&&A0.env.BUN_ENV!=="test"&&!w)A0.exit(0)}return cJ}var uJ=!1;function nJ($){if(uJ){z("signal",`Received second ${$} signal, forcing exit`,!0),A0.exit(1);return}uJ=!0,z("signal",`Received ${$} signal, initiating cleanup`,!0),JX().catch((w)=>{z("signal",`Cleanup failed after ${$}: ${w}`,!0),A0.exit(1)}).finally(()=>{uJ=!1})}A0.once("SIGINT",()=>nJ("SIGINT"));A0.once("SIGTERM",()=>nJ("SIGTERM"));A0.on("uncaughtException",($)=>{z("process",`Uncaught exception: ${$}`,!0),q.error("Uncaught exception:",$),nJ("uncaughtException")});async function NA($,w,A,Y=5){z("connection",`Testing connection to ${$}:${w} (retries left: ${Y})`,A);let f=15000,X=Date.now();if(A0.env.RPX_BYPASS_CONNECTION_TEST==="true"){z("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let U=()=>new Promise((W,J)=>{let B=ZF.connect({host:$,port:w,timeout:3000});B.once("connect",()=>{z("connection",`Successfully connected to ${$}:${w}`,A),B.end(),W()}),B.once("timeout",()=>{z("connection",`Connection to ${$}:${w} timed out`,A),B.destroy(),J(Error("Connection timed out"))}),B.once("error",(E)=>{z("connection",`Failed to connect to ${$}:${w}: ${E}`,A),B.destroy(),J(E)})});try{await U()}catch(W){if(Date.now()-X>f){z("connection",`Connection test timed out after ${f}ms, but continuing anyway`,A),q.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&Y>0)return z("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${Y} retries left)`,A),await new Promise((B)=>setTimeout(B,2000)),NA($,w,A,Y-1);if(Y>0)try{z("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((B,E)=>{let j=xw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(T)=>{z("connection",`Received HTTP response with status: ${T.statusCode}`,A),B()});j.on("error",(T)=>E(T)),j.on("timeout",()=>{j.destroy(),E(Error("HTTP request timed out"))}),j.end()}),z("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(B){return z("connection",`HTTP request to ${$}:${w} failed: ${B}`,A),z("connection",`Retrying socket connection in 2 seconds... (${Y} retries left)`,A),await new Promise((E)=>setTimeout(E,2000)),NA($,w,A,Y-1)}let J=`Failed to connect to ${$}:${w} after ${5-Y} attempts: ${W.message}`;z("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),q.warn(J),q.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 xF($){z("server",`Starting server with options: ${E$($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),Y=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),f=[A.hostname];if(vJ($)&&!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 KA(f,$.verbose))[0]){q.info(`Adding ${A.hostname} to hosts file...`),q.info("This may require sudo/administrator privileges");try{await HA(f,$.verbose)}catch(W){if(q.error("Failed to add hosts entry:",W.message),q.warn("You can manually add this entry to your hosts file:"),q.warn(`127.0.0.1 ${A.hostname}`),q.warn(`::1 ${A.hostname}`),A0.platform==="win32")q.warn("On Windows:"),q.warn("1. Run notepad as administrator"),q.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else q.warn("On Unix systems:"),q.warn("sudo nano /etc/hosts")}}else z("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(U){q.error("Failed to check hosts file:",U.message)}}try{await NA(w.hostname,Y,$.verbose)}catch(U){z("server",`Connection test failed: ${U}`,$.verbose),q.error(U.message),q.warn("Continuing with proxy setup despite connection test failure..."),q.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let X=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=wA({...$,to:A.hostname});if(X=await a$({...$,to:A.hostname,https:$.https}),!X){if(z("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await S1({...$,from:w.toString(),to:A.hostname,https:$.https}),X=await a$({...$,to:A.hostname,https:$.https}),!X)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(U){throw z("server",`SSL setup failed: ${U}`,$.verbose),U}z("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await IR({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:Y,sourceUrl:{hostname:w.hostname,host:w.host},ssl:X})}async function MR($,w,A,Y,f,X,U,W,J,B,E){z("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,J);function j(G){let K={};for(let[R,N]of Object.entries(G))if(!R.startsWith(":"))K[R]=N;return K}let T=(G,K)=>{z("request",`Incoming request: ${G.method} ${G.url}`,J);let R=G.url||"/",N=G.method||"GET";if(G instanceof kF.Http2ServerRequest){let S=G.headers;N=S[":method"]||N,R=S[":path"]||R}if(B){if(!R.match(/\.[a-z0-9]+$/i))if(R.endsWith("/"))R=`${R}index.html`;else R=`${R}.html`}let h=j(G.headers);if(E)h.host=`${X.hostname}:${A}`,z("request",`Changed origin: setting host header to ${h.host}`,J);let y={hostname:X.hostname,port:A,path:R,method:N,headers:h};z("request",`Proxy request options: ${E$(y)}`,J);let I=xw.request(y,(S)=>{if(z("response",`Proxy response received with status ${S.statusCode}`,J),B&&S.statusCode===404){let V=[];if(R.endsWith(".html"))V.push(R.slice(0,-5));else if(!R.match(/\.[a-z0-9]+$/i))V.push(`${R}.html`);if(!R.endsWith("/"))V.push(`${R}/index.html`);if(V.length>0){z("cleanUrls",`Trying alternative paths: ${V.join(", ")}`,J);let O=(e0)=>{if(e0.length===0){K.writeHead(S.statusCode||404,S.headers),S.pipe(K);return}let $$=e0[0],S$={...y,path:$$},L$=xw.request(S$,(e$)=>{if(e$.statusCode===200)z("cleanUrls",`Found matching path: ${$$}`,J),K.writeHead(e$.statusCode,e$.headers),e$.pipe(K);else O(e0.slice(1))});L$.on("error",()=>O(e0.slice(1))),L$.end()};O(V);return}}let B0={...S.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};K.writeHead(S.statusCode||500,B0),S.pipe(K)});I.on("error",(S)=>{z("request",`Proxy request failed: ${S}`,J),q.error("Proxy request failed:",S),K.writeHead(502),K.end(`Proxy Error: ${S.message}`)}),G.pipe(I)};if(z("server",`Creating server with SSL config: ${!!U}`,J),U)return new Promise((G,K)=>{try{let R=Bun.serve({port:Y,hostname:f,tls:{key:U.key,cert:U.cert,ca:U.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(N){let h=new URL(N.url);z("request",`Bun.serve received: ${N.method} ${h.pathname}`,J);let y=`http://${X.host}`,I=new URL(h.pathname+h.search,y);try{let S=new Headers(N.headers);if(S.set("host",X.host),E)S.set("origin",y);S.set("x-forwarded-for","127.0.0.1"),S.set("x-forwarded-proto","https"),S.set("x-forwarded-host",w);let B0=await fetch(I.toString(),{method:N.method,headers:S,body:N.body,redirect:"manual"}),V=new Headers(B0.headers);if(B&&h.pathname.endsWith(".html")){let O=h.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:O}})}return new Response(B0.body,{status:B0.status,statusText:B0.statusText,headers:V})}catch(S){return z("request",`Proxy error: ${S}`,J),new Response(`Proxy Error: ${S}`,{status:502})}},error(N){return z("server",`Bun.serve error: ${N}`,J),new Response(`Server Error: ${N.message}`,{status:500})}});RA.add(R),DF({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!0,cleanUrls:B,verbose:J}),G()}catch(R){K(R)}});let F=xw.createServer(T);function H(G){return RA.add(G),new Promise((K,R)=>{G.listen(Y,f,()=>{z("server",`Server listening on port ${Y}`,J),DF({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!!U,cleanUrls:B,verbose:J}),K()}),G.on("error",(N)=>{z("server",`Server error: ${N}`,J),R(N)})})}return H(F)}async function IR($){z("setup",`Setting up reverse proxy: ${E$($)}`,$.verbose);let{from:w,to:A,fromPort:Y,sourceUrl:f,ssl:X,verbose:U,cleanup:W,vitePluginUsage:J,changeOrigin:B,cleanUrls:E}=$,j=80,T=443,F="0.0.0.0",H=$.portManager||yR,G=vJ($);try{if(G&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await KA([A],U))[0]){q.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await HA([A],U),q.success(`Added ${A} to your hosts file.`)}catch(y){q.error(`Failed to add ${A} to your hosts file: ${y}`),q.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(G&&A0.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await KA([A],U))[0]){z("hosts",`${A} not found in hosts file, adding...`,U);try{await HA([A],U)}catch(y){z("hosts",`Failed to add ${A} to hosts file: ${y}`,U)}}}if(X&&!H.usedPorts.has(j)){if(!await kw(j,F,U))z("setup","Starting HTTP redirect server",U),PF(U),H.usedPorts.add(j);else if(z("setup","Port 80 is in use, skipping HTTP redirect",U),U)q.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let K=X?T:j,R=await kw(K,F,U),N;if(R){if(z("setup",`Port ${K} is already in use`,U),U)q.warn(`Port ${K} is already in use. This may be another instance of rpx or another service.`);if(K===443){if(N=await H.getNextAvailablePort(3443,!0),z("setup",`Using port ${N} instead of ${K}`,U),U)q.info(`Using port ${N} instead. Access your site at https://${A}:${N}`)}else if(N=await H.getNextAvailablePort(K+1000,!0),z("setup",`Using port ${N} instead of ${K}`,U),U)q.info(`Using port ${N} instead. Access your site at http://${A}:${N}`)}else N=K,H.usedPorts.add(N),z("setup",`Using standard ${K===443?"HTTPS":"HTTP"} port ${K} for ${A}`,U);await MR(w,A,Y,N,F,f,X,J,U,E,B)}catch(K){z("setup",`Setup failed: ${K}`,U),q.error(`Failed to setup reverse proxy: ${K.message}`),JX({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:U,vitePluginUsage:J})}}function PF($){z("redirect","Starting HTTP redirect server",$);let w=xw.createServer((A,Y)=>{let f=A.headers.host||"";z("redirect",`Redirecting request from ${f}${A.url} to HTTPS`,$),Y.writeHead(301,{Location:`https://${f}${A.url}`}),Y.end()}).listen(80);RA.add(w),z("redirect","HTTP redirect server started",$)}function iF($){let w={...G8,...$};if(z("proxy",`Starting proxy with options: ${E$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){q.error("viaDaemon mode requires both `from` and `to`");return}xJ({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((J)=>{q.error(`Failed to register with rpx daemon: ${J.message}`),A0.exit(1)});return}let A=w.to||"",Y=A.split(".").pop()?.toLowerCase()||"",f=A0.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),X=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(f&&X.includes(Y)&&w?.verbose)q.warn(`The .${Y} TLD may not work reliably for local development`),q.info(` Google owns .${Y} with HSTS preloading, which can bypass local DNS`),q.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(f)Promise.resolve().then(() => (V1(),af)).then(({setupDevelopmentDns:J})=>{J({domains:[A],verbose:w.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(Y))q.success(`DNS server started for .${Y} domains`);else q.success(`DNS server started for .${Y} domains (hosts file entry also added)`)});else z("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((J)=>{z("dns",`Failed to start DNS server: ${J}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:wA(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};z("proxy",`Server options: ${E$(W)}`,w.verbose),xF(W).catch((J)=>{z("proxy",`Failed to start proxy: ${J}`,w.verbose),q.error(`Failed to start proxy: ${J.message}`),JX({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 CR($){return $?.verbose||!1}function vJ($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function bF($){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=CR(w),Y=vJ(w);if(z("config",`Starting with config: ${E$(w,2)}`,A),z("config",`Is multi-proxy? ${"proxies"in w}`,A),z("config",`Hosts management enabled? ${Y}`,A),w.viaDaemon){let G="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((K)=>({id:K.id,from:K.from,to:K.to,path:K.path,cleanUrls:K.cleanUrls??w.cleanUrls,changeOrigin:K.changeOrigin??w.changeOrigin,pathRewrites:K.pathRewrites})):[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await xJ({proxies:G,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){z("servers",`Found ${w.proxies.length} proxies in config`,A);for(let H of w.proxies)if(H.start){let G=`${H.from}-${H.to}`;try{z("watch",`Starting command for ${G} with command: ${H.start.command}`,A),q.info(`Starting command for ${G}...`),await UX.startProcess(G,H.start,A);let K=new URL(H.from.startsWith("http")?H.from:`http://${H.from}`),R=K.hostname||"localhost",N=Number(K.port)||80;try{await NA(R,N,A),z("watch",`Dev server is ready at ${R}:${N}`,A)}catch(h){z("watch",`Connection check failed, but continuing with proxy setup: ${h}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(K){throw z("watch",`Failed to start command for ${G}: ${K}`,A),Error(`Failed to start command for ${G}: ${K}`)}}else z("watch",`No start command for proxy ${H.from} -> ${H.to}`,A)}else if("start"in w&&w.start){z("watch","Found start command in single proxy config",A);let H=`${w.from}-${w.to}`;try{if(w.start)z("watch",`Starting command: ${w.start.command}`,A),await UX.startProcess(H,w.start,A);let G=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),K=G.hostname||"localhost",R=Number(G.port)||80;try{await NA(K,R,A),z("watch",`Dev server is ready at ${K}:${R}`,A)}catch(N){z("watch",`Connection check failed, but continuing with proxy setup: ${N}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(G){throw z("watch",`Failed to run start command: ${G}`,A),Error(`Failed to run start command: ${G}`)}}else z("watch","No start command found in config",A);let f="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(A0.platform!=="win32"&&(w.https||Y)){if(!Cw())try{z("sudo","Pre-acquiring sudo credentials for privileged operations",A),qR("sudo -v",{stdio:"inherit"})}catch{z("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let H=await a$(w);if(!H){if(z("ssl",`No valid or trusted certificates found for ${f}, generating new ones`,w.verbose),await S1(w),H=await a$(w),!H)throw Error(`Failed to load SSL certificates after generation for ${f}`)}else z("ssl",`Using existing and trusted certificates for ${f}`,w.verbose);w._cachedSSLConfig=H}let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({...H,https:w.https,cleanup:w.cleanup,cleanUrls:H.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:H.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}],U=X.map((H)=>H.to||"rpx.localhost"),W=w._cachedSSLConfig,J=U.filter((H)=>H&&!H.includes("localhost")&&!H.includes("127.0.0.1")),B=["dev","app","page","new","day","foo"],E=["test","localhost","local","example","invalid"],j=[...new Set(J.map((H)=>H.split(".").pop()?.toLowerCase()))],T=j.filter((H)=>!!H&&B.includes(H));if(T.length>0&&A)q.warn(`The following TLDs may not work reliably for local development: ${T.map((H)=>`.${H}`).join(", ")}`),q.info(" These TLDs have HSTS preloading which can bypass local DNS"),q.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(Y&&A0.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:H}=await Promise.resolve().then(() => (V1(),af));if(await H({domains:J,verbose:A})){if(A)if(j.every((R)=>!!R&&E.includes(R)))q.success(`DNS server started for ${j.map((R)=>`.${R}`).join(", ")} domains`);else q.success(`DNS server started for ${j.map((R)=>`.${R}`).join(", ")} domains (hosts file entries also added)`)}else z("dns","Could not start DNS server - custom domains may not resolve",A)}let F=async()=>{z("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:H}=await Promise.resolve().then(() => (V1(),af));await H({verbose:w.verbose})}catch(H){z("cleanup",`Error stopping DNS server: ${H}`,w.verbose)}try{await UX.stopAll(w.verbose)}catch(H){z("cleanup",`Error stopping processes: ${H}`,w.verbose)}await JX({domains:U,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(A0.on("SIGINT",F),A0.on("SIGTERM",F),A0.on("uncaughtException",(H)=>{z("process",`Uncaught exception: ${H}`,!0),console.error("Uncaught exception:",H),F()}),W&&X.length>1){z("proxies",`Creating shared HTTPS server for ${X.length} domains`,A);let H=[],G=new Set;for(let V of X){let O=V.to||"rpx.localhost",e0=V.cleanUrls||!1,$$=V.path,S$=L1($$);if(V.static)H.push({host:O,path:$$,route:{static:AA(V.static,e0),cleanUrls:e0,basePath:S$}}),z("proxies",`Route: ${O}${$$??""} → static ${typeof V.static==="string"?V.static:V.static.dir}`,A);else{let L$=new URL(V.from?.startsWith("http")?V.from:`http://${V.from}`);H.push({host:O,path:$$,route:{sourceHost:L$.host,cleanUrls:e0,changeOrigin:V.changeOrigin||!1,pathRewrites:V.pathRewrites,basePath:S$}}),z("proxies",`Route: ${O}${$$??""} → ${L$.host}`,A)}if(G.has(O))continue;if(G.add(O),Y&&!UA(O)&&!O.includes("localhost")&&!O.includes("127.0.0.1"))try{if(!(await KA([O],A))[0])await HA([O],A)}catch{z("hosts",`Could not add hosts entry for ${O}`,A)}}if(!await kw(80,"0.0.0.0",A))PF(A);let R=443;if(await kw(R,"0.0.0.0",A)){if(z("proxies",`Port ${R} is already in use, cannot start shared proxy`,A),A)q.warn(`Port ${R} is in use. Shared HTTPS proxy cannot start.`);return}let h=JA(H),y=fA((V,O)=>WA(h,V,O),A),I=w.originGuard?QF(w.originGuard):null,S=I?(V,O)=>I(V)??y(V,O):y,B0=XA(A);try{let V=Bun.serve({port:R,hostname:"0.0.0.0",tls:{key:W.key,cert:W.cert,ca:W.ca,requestCert:!1,rejectUnauthorized:!1},fetch(O,e0){return S(O,e0)},websocket:B0,error(O){return z("server",`Shared proxy server error: ${O}`,A),new Response(`Server Error: ${O.message}`,{status:500})}});RA.add(V),z("proxies",`Shared HTTPS proxy listening on port ${R} for ${h.size} domains`,A)}catch(V){z("proxies",`Failed to start shared proxy: ${V}`,A),console.error("Failed to start shared HTTPS proxy:",V),F()}}else for(let H of X)try{let G=H.to||"rpx.localhost";z("proxy",`Starting proxy for ${G} with SSL config: ${!!W}`,H.verbose),await xF({from:H.from||"localhost:5173",to:G,cleanUrls:H.cleanUrls||!1,https:H.https||!1,cleanup:H.cleanup||!1,vitePluginUsage:H.vitePluginUsage||!1,verbose:H.verbose||!1,_cachedSSLConfig:W,changeOrigin:H.changeOrigin||!1})}catch(G){z("proxies",`Failed to start proxy for ${H.to}: ${G}`,H.verbose),console.error(`Failed to start proxy for ${H.to}:`,G),F()}}function DF($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${I$.green(I$.bold("rpx"))} ${I$.green(`v${hR}`)}`),console.log(` ${I$.green("➜")} ${I$.dim($?.from??"")} ${I$.dim("➜")} ${I$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${I$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${I$.green("➜")} Clean URLs enabled`)}$J();var lS=new Iw("rpx",{showTags:!1});function cF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}d0.chdir(LR(SR(VR(import.meta.url)),".."));var t0=new HX("rpx"),uF="0.12.0";t0.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 bF(rw);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(Y){console.error("Failed to parse start-env JSON:",Y),d0.exit(1)}w.start=A}return iF(w)});t0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=cF(rw)?rw.proxies.find((Y)=>Y.to===$||`${Y.from}-${Y.to}`===$):rw.to===$?rw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),d0.exit(1);try{await of.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(Y){console.error(`Failed to start dev server for ${$}:`,Y),d0.exit(1)}});t0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await of.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),d0.exit(1)}});t0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await of.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),d0.exit(1)}});t0.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("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--verbose","Enable verbose logging").action(async($)=>{try{await(await HF({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,verbose:$.verbose??!0})).done,d0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),d0.exit(1)}});t0.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 RF({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)":""}`)});t0.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??F$(),A=await Kw(w),Y=await sf(w),f=$.registryDir,X=await IF(f).catch(()=>[]);if($.json){console.log(JSON.stringify({running:Y,pid:A,pidFile:Rw(w),rpxDir:w,registryDir:f??Qw(),entries:X},null,2));return}if(!Y){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Rw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Rw(w)}`);if(console.log(`registry: ${f??Qw()}`),X.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${X.length}):`);for(let U of X){let W=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${W})`)}});t0.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"),d0.exit(1);if(!_1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),d0.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}`),d0.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`"),d0.exit(1)}});t0.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(!_1($))console.error(`invalid id: ${JSON.stringify($)}`),d0.exit(1);let A=await ZJ($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await MF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});t0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??F$();if(await sf(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await NF({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});t0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(uF)});t0.version(uF);t0.help();t0.run();
|