@stacksjs/rpx 0.11.45 → 0.11.47

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 CHANGED
@@ -1,256 +1,315 @@
1
1
  #!/usr/bin/env bun
2
- import{createRequire as r6}from"node:module";var n6=Object.defineProperty;var l6=(w)=>w;function p6(w,$){this[w]=l6.bind(null,$)}var ej=(w,$)=>{for(var Y in $)n6(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:p6.bind($,Y)})};var s=(w,$)=>()=>(w&&($=w(w=0)),$);var i=r6(import.meta.url);import{existsSync as FQ,statSync as EQ}from"fs";import{existsSync as eG,mkdirSync as mM,readdirSync as gM,readFileSync as w5,writeFileSync as dM}from"fs";import{homedir as r$}from"os";import{dirname as pM,resolve as jw}from"path";import kA from"process";import{existsSync as TQ,statSync as NQ}from"fs";import{existsSync as ZJ,mkdirSync as $5,readdirSync as Y5,writeFileSync as A5}from"fs";import{homedir as t$}from"os";import{dirname as qQ,resolve as g0}from"path";import S$ from"process";import{join as X5,relative as J5,resolve as HQ}from"path";import RA from"process";import{existsSync as Az,mkdirSync as A4,readdirSync as X4,writeFileSync as J4}from"fs";import{homedir as FJ}from"os";import{dirname as j4,resolve as m0}from"path";import s1 from"process";import{join as U5,relative as W5,resolve as RQ}from"path";import MA from"process";import{existsSync as Xz,mkdirSync as G4,readdirSync as K4,writeFileSync as F4}from"fs";import{dirname as T4,resolve as IA}from"path";import PJ from"process";import{Buffer as j$}from"buffer";import{createCipheriv as j5,createDecipheriv as Q5,randomBytes as EJ}from"crypto";import{closeSync as TJ,createReadStream as MQ,createWriteStream as z5,existsSync as NJ,fsyncSync as IQ,openSync as yQ,writeFileSync as f5}from"fs";import{access as B5,constants as CQ,mkdir as G5,readdir as $A,rename as VQ,stat as a$,unlink as YA,writeFile as qJ}from"fs/promises";import{join as s$}from"path";import L0 from"process";import{pipeline as K5}from"stream/promises";import{createGzip as LQ}from"zlib";import o$ from"process";import Pw from"process";import{Buffer as kw}from"buffer";import{createCipheriv as F5,createDecipheriv as E5,randomBytes as HJ}from"crypto";import{closeSync as RJ,createReadStream as OQ,createWriteStream as T5,existsSync as AA,fsyncSync as SQ,openSync as _Q,writeFileSync as N5}from"fs";import{access as q5,constants as hQ,mkdir as H5,readdir as XA,rename as DQ,stat as e$,unlink as JA,writeFile as MJ}from"fs/promises";import{isAbsolute as R5,join as w1,resolve as M5}from"path";import x from"process";import{pipeline as I5}from"stream/promises";import{createGzip as xQ}from"zlib";import $1 from"process";import iw from"process";import UA from"process";import{existsSync as WA}from"fs";import{resolve as IJ}from"path";import{existsSync as y5}from"fs";import{existsSync as C5,readdirSync as V5}from"fs";import{extname as yJ,resolve as kQ}from"path";import L5 from"process";import{join as O5,relative as S5,resolve as ZQ}from"path";import yA from"process";import{Buffer as Zw}from"buffer";import{createCipheriv as _5,createDecipheriv as h5,randomBytes as CJ}from"crypto";import{closeSync as VJ,createReadStream as PQ,createWriteStream as D5,existsSync as jA,fsyncSync as iQ,openSync as bQ,writeFileSync as x5}from"fs";import{access as k5,constants as uQ,mkdir as Z5,readdir as QA,rename as vQ,stat as Y1,unlink as zA,writeFile as LJ}from"fs/promises";import{isAbsolute as P5,join as A1,resolve as i5}from"path";import k from"process";import{pipeline as b5}from"stream/promises";import{createGzip as cQ}from"zlib";import X1 from"process";import bw from"process";import BA from"process";import{existsSync as GA}from"fs";import{resolve as xJ}from"path";import{existsSync as XF}from"fs";class $z{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!FQ(w))return!0;return EQ(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=FQ(Y)?EQ(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Yz{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function c5(w,$){this[w]=v5.bind(null,$)}class rJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!TQ(w))return!0;return NQ(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=TQ(Y)?NQ(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class tJ{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function d5(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function n5(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function l5(w){return w.getStats().size*2}function aJ(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&Y0($[0])&&"id"in $[0]&&$[0].id===3&&Y0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(Y0($)&&Y0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(Y0(w)&&"arr"in w&&Array.isArray(w.arr)&&Y0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&Y0($[0])&&Y0(w[0])){let A=[...$];for(let X of w)if(Y0(X)&&"name"in X){if(!A.find((U)=>Y0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(Y0(X)&&"path"in X){if(!A.find((U)=>Y0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>CA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!Y0($)||!Y0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(Y0(X)&&Y0(Y[A]))Y[A]=aJ(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&Y0(X[0])&&Y0(Y[A][0])){let J=[...X];for(let U of Y[A])if(Y0(U)&&"name"in U){if(!J.find((W)=>Y0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(Y0(U)&&"path"in U){if(!J.find((W)=>Y0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>CA(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function CA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!CA(w[Y],$[Y]))return!1;return!0}if(Y0(w)&&Y0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!CA(w[X],$[X]))return!1}return!0}return!1}function Y0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function p5(w,$){if(!Xz(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return aJ($,A)}catch{return null}}catch{return null}}async function r5({name:w="",cwd:$,defaultConfig:Y}){let A=$||PJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=IA(A,`${U}${j}`),Q=await p5(W,Y);if(Q!==null)return Q}try{let U=IA(A,"package.json");if(Xz(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return aJ(Y,W)}catch{}}}catch{}return Y}function t5(w,$={}){let Y=MA.cwd();while(Y.includes("storage"))Y=RQ(Y,"..");let A=RQ(Y,w||"");if($?.relative)return W5(MA.cwd(),A);return A}async function a5(){try{let w=await r5({name:"clarity",defaultConfig:EA,cwd:MA.cwd(),endpoint:"",headers:{}});return{...EA,...w}}catch{return EA}}function U0(){if(Pw.env.NODE_ENV==="test"||Pw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function s5(){if(Pw.env.NODE_ENV==="test"||Pw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Pw<"u"){let w=Pw.type;if(w==="renderer"||w==="worker")return!1;return!!(Pw.versions&&(Pw.versions.node||Pw.versions.bun))}return!1}class Uz{async format(w){let $=await s5(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:o$.pid,hostname:$(),environment:o$.env.NODE_ENV||"development",platform:o$.platform,version:o$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:o$.env.NODE_ENV||o$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class VA{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=w,this.config={...bJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Uz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...TA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...TA};return{...TA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:bJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await B5(this.config.logDirectory,CQ.F_OK|CQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await G5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:j$.from(w);try{if(!NJ(this.currentLogFile))await qJ(this.currentLogFile,"",{mode:420});if(X=yQ(this.currentLogFile,"a",420),f5(X,W,{flag:"a"}),IQ(X),X!==void 0)TJ(X),X=void 0;if((await a$(this.currentLogFile)).size===0){if(await qJ(this.currentLogFile,W,{flag:"w",mode:420}),(await a$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{TJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 s$(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 s$(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return s$(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return EJ(16).toString("hex")}generateKey(){return EJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=EJ(16),A=j5("aes-256-gcm",$,Y),X=j$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:j$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=LQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(j$.from(j$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(U0())return;let w=await a$(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await $A(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await a$(Y).catch(()=>null))try{if(await VQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await YA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await qJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await a$(Y).catch(()=>null))await VQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await $A(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await YA(s$(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=MQ(w),A=z5($),X=LQ();await K5(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),NJ(this.currentLogFile))try{let w=yQ(this.currentLogFile,"r+");IQ(w),TJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await $A(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await YA(s$(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?o.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=L0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${o.cyan(X)}`;if(!U)return Q.trim();let z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!U0()){let Q=Ez[w],z=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",f;switch(w){case"debug":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:o.gray(U),level:w}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:o.green(U),level:w}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f),j){let B=j.split(`
3
- `);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:o.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
4
- `;if(j)W+=`${j}
5
- `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!U0()){let Y=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:o.blue("◐"),tag:Y,message:`${o.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
6
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let z=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:o.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!U0())console.error(Q.trim());await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new VA($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(U0())throw Error("createReadStream is not supported in browser environments");if(!NJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return MQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=j$.isBuffer(w)?w:j$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),j=Q5("aes-256-gcm",Y,X);return j.setAuthTag(J),j$.concat([j.update(U),j.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U0()}isServerMode(){return!U0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!U0()){let J=w.split(`
7
- `),U=Math.max(...J.map((z)=>z.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((z)=>{let f=" ".repeat(U-z.length-2);return`│ ${z}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:o.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(j)})),Q.forEach((z)=>console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(z),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(W),showTimestamp:!1}))}else if(!U0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
8
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(U0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${o.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();L0.stdin.removeListener("data",Y);try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!1)}catch{}L0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!0)}catch{}L0.stdin.resume(),L0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let z=$[j++];switch(Q){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!U0()){let U=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",j=o.blue("◐");console.error(`${j} ${U} ${o.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
9
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||U0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),j!==void 0)this.activeProgressBar.message=j;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())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,j="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;L0.stdout.write(`${"\r".padEnd(L0.stdout.columns||80)}\r`),this.log(j,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=o.green("━".repeat(A)),U=o.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",z=$||Y===100?o.green("✓"):o.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${o.gray(this.formatTag(this.name))}`:"",B=`\r${z}${f} ${j} ${W}${Q}`,G=L0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,L0.stdout.write(w.lastRenderedLine),$)L0.stdout.write(`
10
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await $A(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=s$(this.config.logDirectory,A);if(w.before)try{if((await a$(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await YA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function FA(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&l($[0])&&"id"in $[0]&&$[0].id===3&&l($[1])&&"id"in $[1]&&$[1].id===4)return $;if(l($)&&l(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(l(w)&&"arr"in w&&Array.isArray(w.arr)&&l($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&l($[0])&&l(w[0])){let A=[...$];for(let X of w)if(l(X)&&"name"in X){if(!A.find((U)=>l(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(l(X)&&"path"in X){if(!A.find((U)=>l(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>LA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!l($)||!l(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(l(X)&&l(Y[A]))Y[A]=FA(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&l(X[0])&&l(Y[A][0])){let J=[...X];for(let U of Y[A])if(l(U)&&"name"in U){if(!J.find((W)=>l(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(l(U)&&"path"in U){if(!J.find((W)=>l(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>LA(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function sJ(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:FA(w,$);if(Array.isArray(w))return Y==="replace"?$:FA(w,$);if(!l($)||!l(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=FA(U,J);else if(l(J)&&l(U))A[X]=sJ(U,J,Y);else A[X]=J}return A}function LA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!LA(w[Y],$[Y]))return!1;return!0}if(l(w)&&l($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!LA(w[X],$[X]))return!1}return!0}return!1}function l(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function fA(w,$,Y="replace"){if(!Az(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return sJ($,X,Y)}catch{return null}}catch{return null}}function o5(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,z]of Object.entries(U)){let f=[...j,Q],B=(F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${f.map(B).join("_")}`,T=`${A}_${f.map((F)=>F.toUpperCase()).join("_")}`;if(Y)S0.info(`Checking environment variable ${G} for config ${w}.${f.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[Q]=J(z,f);else{let F=s1.env[G]||s1.env[T];if(F!==void 0){if(Y)S0.info(`Using environment variable ${F?G:T} for config ${w}.${f.join(".")}`);if(typeof z==="number")W[Q]=Number(F);else if(typeof z==="boolean")W[Q]=F.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(F);if(Array.isArray(E))W[Q]=E;else W[Q]=F.split(",").map((N)=>N.trim())}catch{W[Q]=F.split(",").map((E)=>E.trim())}else W[Q]=F}}}return W}return J(X)}async function e5({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?o5(w,X,J):X,Q=Y||s1.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)S0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let f=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],F=Array.from(new Set([Q,m0(Q,"config"),m0(Q,".config"),A?m0(Q,A):void 0].filter(Boolean)));for(let E of F){if(J)S0.info(`Searching for configuration in: ${E}`);let R=[m0(Q,"config"),m0(Q,".config")].concat(A?[m0(Q,A)]:[]).includes(E)?[...f,...B,...G,...T]:[...B,...f,...T,...G];for(let V of R)for(let L of z){let q=m0(E,`${V}${L}`),C=await fA(q,W,j);if(C!==null){if(J)S0.success(`Configuration loaded from: ${q}`);return C}}}if(w){let E=m0(FJ(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)S0.info(`Checking user config directory: ${E}`);for(let R of N)for(let V of z){let L=m0(E,`${R}${V}`),q=await fA(L,W,j);if(q!==null){if(J)S0.success(`Configuration loaded from user config directory: ${L}`);return q}}}if(w){let E=m0(FJ(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)S0.info(`Checking user config directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=m0(E,`${R}${V}`),q=await fA(L,W,j);if(q!==null){if(J)S0.success(`Configuration loaded from user config directory dotfile: ${L}`);return q}}}if(w){let E=FJ(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)S0.info(`Checking user home directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=m0(E,`${R}${V}`),q=await fA(L,W,j);if(q!==null){if(J)S0.success(`Configuration loaded from user home directory: ${L}`);return q}}}try{let E=m0(Q,"package.json");if(Az(E)){let N=await import(E),R=N[w];if(!R&&$){if(R=N[$],R&&J)S0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)S0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return sJ(W,R,j)}catch(V){if(J)S0.warn("Failed to merge package.json config:",V)}}}catch(E){if(J)S0.warn("Failed to load package.json:",E)}if(J)S0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function wK(w,$={}){let Y=RA.cwd();while(Y.includes("storage"))Y=HQ(Y,"..");let A=HQ(Y,w||"");if($?.relative)return J5(RA.cwd(),A);return A}async function $K(){try{let w=await e5({name:"clarity",alias:"logging",defaultConfig:NA,cwd:RA.cwd()});return{...NA,...w||{}}}catch{return NA}}function K0(){if(iw.env.NODE_ENV==="test"||iw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YK(){if(iw.env.NODE_ENV==="test"||iw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof iw<"u"){let w=iw.type;if(w==="renderer"||w==="worker")return!1;return!!(iw.versions&&(iw.versions.node||iw.versions.bun))}return!1}class Wz{async format(w){let $=await YK(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:$1.pid,hostname:$(),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 OA{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=w,this.config={...uJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Wz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...qA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...qA};return{...qA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:uJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!K0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await q5(this.config.logDirectory,hQ.F_OK|hQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await H5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:kw.from(w);try{if(!AA(this.currentLogFile))await MJ(this.currentLogFile,"",{mode:420});if(X=_Q(this.currentLogFile,"a",420),N5(X,W,{flag:"a"}),SQ(X),X!==void 0)RJ(X),X=void 0;if((await e$(this.currentLogFile)).size===0){if(await MJ(this.currentLogFile,W,{flag:"w",mode:420}),(await e$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{RJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 w=new Date().toISOString().split("T")[0];return w1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(K0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return HJ(16).toString("hex")}generateKey(){return HJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=HJ(16),A=F5("aes-256-gcm",$,Y),X=kw.isBuffer(w)?w:kw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=kw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=xQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(kw.from(kw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(K0())return;if(!this.shouldWriteToFile())return;let w=await e$(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await XA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await e$(Y).catch(()=>null))try{if(await DQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await JA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await MJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await e$(Y).catch(()=>null))await DQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await XA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await JA(w1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=OQ(w),A=T5($),X=xQ();await I5(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),AA(this.currentLogFile))try{let w=_Q(this.currentLogFile,"r+");SQ(w),RJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!K0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await XA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await JA(w1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?b.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||K0())return!1;let w=typeof x.env.NO_COLOR<"u",$=x.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${b.cyan(X)}`;if(!U)return Q.trim();let z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=b.underline(b.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>b.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>b.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>b.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>b.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>b.strikethrough(A)),$}supportsHyperlinks(){if(K0())return!1;let w=x.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=x.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(R5($)||$.startsWith("./")||$.startsWith("../"))$=M5($);else return null;return AA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Tz[w],B=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:b.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:b.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
11
- `);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:b.gray(` ${F}`),level:w,showTimestamp:!1}))}break}}else if(!K0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let z=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
12
- `;if(j)z+=`${j}
13
- `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!K0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!K0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!K0()&&x.stdout.isTTY)x.stdout.write(`
14
- `);if(this[W==="warning"?"warn":W](j),this.activeProgressBar&&this.shouldStyleConsole()&&!K0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":b.blue("◐"),tag:Y,message:`${b.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
15
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":b.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!K0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new OA($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(K0())throw Error("createReadStream is not supported in browser environments");if(!AA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return OQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=kw.isBuffer(w)?w:kw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=E5("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),z=W.length+Q.length,f=kw.allocUnsafe(z);return W.copy(f,0),Q.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
16
- `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,f=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:b.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:b.cyan(Q),showTimestamp:!1})),f.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:b.cyan(z),showTimestamp:!1}))}else if(!K0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
17
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(K0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${b.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();x.stdin.removeListener("data",Y);try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!1)}catch{}x.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!0)}catch{}x.stdin.resume(),x.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,Q=0;if(Y=w.replace(W,(z,f)=>{if(f==="%")return"%";if(Q>=$.length)return z;let B=$[Q++];switch(f){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return z}}),Q<$.length)Y+=` ${$.slice(Q).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${b.blue("◐")} `;console.error(`${Q}${W} ${b.cyan(A)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
18
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!x.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=b.green("━".repeat(A)),U=b.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",z=this.options.showIcons===!1?"":$||Y===100?b.green("✓"):b.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",B=`\r${z}${f} ${j} ${W}${Q}`,G=x.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,x.stdout.write(w.lastRenderedLine),$)x.stdout.write(`
19
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||K0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(K0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await XA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=w1(this.config.logDirectory,A);if(w.before)try{if((await e$(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await JA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function jz(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function Qz(w){return w instanceof e0}function AK(w){return w instanceof SA}function XK(w){if(Qz(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class ZA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix(w),f={...$};return this.processObject(f,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return wY.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=UA.env[W]||(Q?UA.env[Q]:void 0);if(z!==void 0){if(A.verbose){let f=UA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(f){if(f instanceof _A)throw f;throw Q$.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw Q$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(UA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
2
+ import{createRequire as Pb}from"node:module";var Sb=Object.defineProperty;var Eb=(e)=>e;function Tb(e,t){this[e]=Eb.bind(null,t)}var nl=(e,t)=>{for(var r in t)Sb(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Tb.bind(t,r)})};var te=(e,t)=>()=>(e&&(t=e(e=0)),t);var U=Pb(import.meta.url);import{existsSync as _d,statSync as jd}from"fs";import{existsSync as C$,mkdirSync as I1,readdirSync as M1,readFileSync as x$,writeFileSync as _1}from"fs";import{homedir as nn}from"os";import{dirname as K1,resolve as gt}from"path";import wo from"process";import{existsSync as Ud,statSync as Kd}from"fs";import{existsSync as Nl,mkdirSync as S$,readdirSync as E$,writeFileSync as T$}from"fs";import{homedir as sn}from"os";import{dirname as Wd,resolve as Ye}from"path";import _r from"process";import{join as P$,relative as A$,resolve as Vd}from"path";import io from"process";import{existsSync as Pm,mkdirSync as Z1,readdirSync as Q1,writeFileSync as eO}from"fs";import{homedir as hl}from"os";import{dirname as nO,resolve as qe}from"path";import wi from"process";import{join as R$,relative as k$,resolve as Hd}from"path";import so from"process";import{existsSync as Am,mkdirSync as cO,readdirSync as lO,writeFileSync as uO}from"fs";import{dirname as hO,resolve as oo}from"path";import Dl from"process";import{Buffer as wr}from"buffer";import{createCipheriv as O$,createDecipheriv as N$,randomBytes as dl}from"crypto";import{closeSync as ml,createReadStream as zd,createWriteStream as D$,existsSync as gl,fsyncSync as Gd,openSync as qd,writeFileSync as F$}from"fs";import{access as L$,constants as Yd,mkdir as B$,readdir as Ms,rename as Jd,stat as on,unlink as _s,writeFile as pl}from"fs/promises";import{join as an}from"path";import Be from"process";import{pipeline as I$}from"stream/promises";import{createGzip as Xd}from"zlib";import cn from"process";import Wt from"process";import{Buffer as Ut}from"buffer";import{createCipheriv as M$,createDecipheriv as _$,randomBytes as yl}from"crypto";import{closeSync as wl,createReadStream as Zd,createWriteStream as j$,existsSync as js,fsyncSync as Qd,openSync as em,writeFileSync as U$}from"fs";import{access as K$,constants as tm,mkdir as W$,readdir as Us,rename as rm,stat as ln,unlink as Ks,writeFile as vl}from"fs/promises";import{isAbsolute as V$,join as un,resolve as H$}from"path";import I from"process";import{pipeline as z$}from"stream/promises";import{createGzip as nm}from"zlib";import fn from"process";import Vt from"process";import Ws from"process";import{existsSync as Vs}from"fs";import{resolve as bl}from"path";import{existsSync as G$}from"fs";import{existsSync as q$,readdirSync as Y$}from"fs";import{extname as $l,resolve as im}from"path";import J$ from"process";import{join as X$,relative as Z$,resolve as sm}from"path";import ao from"process";import{Buffer as Kt}from"buffer";import{createCipheriv as Q$,createDecipheriv as eC,randomBytes as Cl}from"crypto";import{closeSync as xl,createReadStream as om,createWriteStream as tC,existsSync as Hs,fsyncSync as am,openSync as cm,writeFileSync as rC}from"fs";import{access as nC,constants as lm,mkdir as iC,readdir as zs,rename as um,stat as hn,unlink as Gs,writeFile as Sl}from"fs/promises";import{isAbsolute as sC,join as dn,resolve as oC}from"path";import M from"process";import{pipeline as aC}from"stream/promises";import{createGzip as fm}from"zlib";import mn from"process";import Ht from"process";import Ys from"process";import{existsSync as Js}from"fs";import{resolve as kl}from"path";import{existsSync as Px}from"fs";class Em{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!_d(e))return!0;return jd(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=_d(r)?jd(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Tm{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function uC(e,t){this[e]=lC.bind(null,t)}class Hl{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Ud(e))return!0;return Kd(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Ud(r)?Kd(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class zl{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function dC(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function mC(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function gC(e){return e.getStats().size*2}function Gl(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ae(t[0])&&"id"in t[0]&&t[0].id===3&&ae(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ae(t)&&ae(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(ae(e)&&"arr"in e&&Array.isArray(e.arr)&&ae(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ae(t[0])&&ae(e[0])){let n=[...t];for(let i of e)if(ae(i)&&"name"in i){if(!n.find((o)=>ae(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(ae(i)&&"path"in i){if(!n.find((o)=>ae(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>co(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!ae(t)||!ae(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(ae(i)&&ae(r[n]))r[n]=Gl(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&ae(i[0])&&ae(r[n][0])){let s=[...i];for(let o of r[n])if(ae(o)&&"name"in o){if(!s.find((a)=>ae(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(ae(o)&&"path"in o){if(!s.find((a)=>ae(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>co(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function co(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!co(e[r],t[r]))return!1;return!0}if(ae(e)&&ae(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!co(e[i],t[i]))return!1}return!0}return!1}function ae(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function pC(e,t){if(!Am(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Gl(t,n)}catch{return null}}catch{return null}}async function yC({name:e="",cwd:t,defaultConfig:r}){let n=t||Dl.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=oo(n,`${o}${c}`),l=await pC(a,r);if(l!==null)return l}try{let o=oo(n,"package.json");if(Am(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Gl(r,a)}catch{}}}catch{}return r}function wC(e,t={}){let r=so.cwd();while(r.includes("storage"))r=Hd(r,"..");let n=Hd(r,e||"");if(t?.relative)return k$(so.cwd(),n);return n}async function vC(){try{let e=await yC({name:"clarity",defaultConfig:Qs,cwd:so.cwd(),endpoint:"",headers:{}});return{...Qs,...e}}catch{return Qs}}function he(){if(Wt.env.NODE_ENV==="test"||Wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bC(){if(Wt.env.NODE_ENV==="test"||Wt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Wt<"u"){let e=Wt.type;if(e==="renderer"||e==="worker")return!1;return!!(Wt.versions&&(Wt.versions.node||Wt.versions.bun))}return!1}class km{async format(e){let t=await bC(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:cn.pid,hostname:t(),environment:cn.env.NODE_ENV||"development",platform:cn.platform,version:cn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:cn.env.NODE_ENV||cn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class lo{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(e,t={}){this.name=e,this.config={...Ll},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new km,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Be.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...eo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...eo};return{...eo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ll.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await L$(this.config.logDirectory,Yd.F_OK|Yd.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await B$(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:wr.from(e);try{if(!gl(this.currentLogFile))await pl(this.currentLogFile,"",{mode:420});if(i=qd(this.currentLogFile,"a",420),F$(i,a,{flag:"a"}),Gd(i),i!==void 0)ml(i),i=void 0;if((await on(this.currentLogFile)).size===0){if(await pl(this.currentLogFile,a,{flag:"w",mode:420}),(await on(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{ml(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 an(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 an(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return an(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(he())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return dl(16).toString("hex")}generateKey(){return dl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=dl(16),n=O$("aes-256-gcm",t,r),i=wr.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:wr.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Xd(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(wr.from(wr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(he())return;let e=await on(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Ms(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await on(r).catch(()=>null))try{if(await Jd(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await _s(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await pl(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await on(r).catch(()=>null))await Jd(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Ms(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await _s(an(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=zd(e),n=D$(t),i=Xd();await I$(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),gl(this.currentLogFile))try{let e=qd(this.currentLogFile,"r+");Gd(e),ml(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!he()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ms(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await _s(an(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?re.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=Be.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${re.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!he()){let l=jm[e],u=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:re.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:re.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
3
+ `);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:re.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!he()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
4
+ `;if(c)a+=`${c}
5
+ `;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!he()){let r=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:re.blue("◐"),tag:r,message:`${re.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
6
+ `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!he()){let u=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:re.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!he())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new lo(t,{...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(r),r}createReadStream(){if(he())throw Error("createReadStream is not supported in browser environments");if(!gl(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return zd(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=wr.isBuffer(e)?e:wr.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=N$("aes-256-gcm",r,i);return c.setAuthTag(s),wr.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return he()}isServerMode(){return!he()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!he()){let s=e.split(`
7
+ `),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:re.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:re.cyan(c)})),l.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:re.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:re.cyan(a),showTimestamp:!1}))}else if(!he())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(he())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${re.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Be.stdin.removeListener("data",r);try{if(typeof Be.stdin.setRawMode==="function")Be.stdin.setRawMode(!1)}catch{}Be.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Be.stdin.setRawMode==="function")Be.stdin.setRawMode(!0)}catch{}Be.stdin.resume(),Be.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!he()){let o=this.options.showTags!==!1&&this.name?re.gray(this.formatTag(this.name)):"",c=re.blue("◐");console.error(`${c} ${o} ${re.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||he()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||he())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||he())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||he())return;Be.stdout.write(`${"\r".padEnd(Be.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||he()||!Be.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=re.green("━".repeat(n)),o=re.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=t||r===100?re.green("✓"):re.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${re.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=Be.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,Be.stdout.write(e.lastRenderedLine),t)Be.stdout.write(`
10
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||he()||!Be.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(he()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ms(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=an(this.config.logDirectory,n);if(e.before)try{if((await on(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await _s(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Zs(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Y(t[0])&&"id"in t[0]&&t[0].id===3&&Y(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Y(t)&&Y(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Y(e)&&"arr"in e&&Array.isArray(e.arr)&&Y(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Y(t[0])&&Y(e[0])){let n=[...t];for(let i of e)if(Y(i)&&"name"in i){if(!n.find((o)=>Y(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(Y(i)&&"path"in i){if(!n.find((o)=>Y(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>uo(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Y(t)||!Y(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Y(i)&&Y(r[n]))r[n]=Zs(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Y(i[0])&&Y(r[n][0])){let s=[...i];for(let o of r[n])if(Y(o)&&"name"in o){if(!s.find((a)=>Y(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(Y(o)&&"path"in o){if(!s.find((a)=>Y(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>uo(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function ql(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Zs(e,t);if(Array.isArray(e))return r==="replace"?t:Zs(e,t);if(!Y(t)||!Y(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=Zs(o,s);else if(Y(s)&&Y(o))n[i]=ql(o,s,r);else n[i]=s}return n}function uo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!uo(e[r],t[r]))return!1;return!0}if(Y(e)&&Y(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!uo(e[i],t[i]))return!1}return!0}return!1}function Y(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function qs(e,t,r="replace"){if(!Pm(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return ql(t,i,r)}catch{return null}}catch{return null}}function $C(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${n}_${f.map(h).join("_")}`,y=`${n}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)Me.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=wi.env[d]||wi.env[y];if(g!==void 0){if(r)Me.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(i)}async function CC({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?$C(e,i,s):i,l=r||wi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Me.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,qe(l,"config"),qe(l,".config"),n?qe(l,n):void 0].filter(Boolean)));for(let p of g){if(s)Me.info(`Searching for configuration in: ${p}`);let v=[qe(l,"config"),qe(l,".config")].concat(n?[qe(l,n)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let P of v)for(let A of u){let R=qe(p,`${P}${A}`),D=await qs(R,a,c);if(D!==null){if(s)Me.success(`Configuration loaded from: ${R}`);return D}}}if(e){let p=qe(hl(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)Me.info(`Checking user config directory: ${p}`);for(let v of w)for(let P of u){let A=qe(p,`${v}${P}`),R=await qs(A,a,c);if(R!==null){if(s)Me.success(`Configuration loaded from user config directory: ${A}`);return R}}}if(e){let p=qe(hl(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)Me.info(`Checking user config directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=qe(p,`${v}${P}`),R=await qs(A,a,c);if(R!==null){if(s)Me.success(`Configuration loaded from user config directory dotfile: ${A}`);return R}}}if(e){let p=hl(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)Me.info(`Checking user home directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=qe(p,`${v}${P}`),R=await qs(A,a,c);if(R!==null){if(s)Me.success(`Configuration loaded from user home directory: ${A}`);return R}}}try{let p=qe(l,"package.json");if(Pm(p)){let w=await import(p),v=w[e];if(!v&&t){if(v=w[t],v&&s)Me.success(`Using alias "${t}" configuration from package.json`)}if(v&&typeof v==="object"&&!Array.isArray(v))try{if(s)Me.success(`Configuration loaded from package.json: ${v===w[e]?e:t}`);return ql(a,v,c)}catch(P){if(s)Me.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)Me.warn("Failed to load package.json:",p)}if(s)Me.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function xC(e,t={}){let r=io.cwd();while(r.includes("storage"))r=Vd(r,"..");let n=Vd(r,e||"");if(t?.relative)return A$(io.cwd(),n);return n}async function SC(){try{let e=await CC({name:"clarity",alias:"logging",defaultConfig:to,cwd:io.cwd()});return{...to,...e||{}}}catch{return to}}function be(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function EC(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Vt<"u"){let e=Vt.type;if(e==="renderer"||e==="worker")return!1;return!!(Vt.versions&&(Vt.versions.node||Vt.versions.bun))}return!1}class Om{async format(e){let t=await EC(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:fn.pid,hostname:t(),environment:fn.env.NODE_ENV||"development",platform:fn.platform,version:fn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:fn.env.NODE_ENV||fn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class fo{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(e,t={}){this.name=e,this.config={...Bl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Om,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ro,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ro};return{...ro,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Bl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!be()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await K$(this.config.logDirectory,tm.F_OK|tm.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await W$(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ut.from(e);try{if(!js(this.currentLogFile))await vl(this.currentLogFile,"",{mode:420});if(i=em(this.currentLogFile,"a",420),U$(i,a,{flag:"a"}),Qd(i),i!==void 0)wl(i),i=void 0;if((await ln(this.currentLogFile)).size===0){if(await vl(this.currentLogFile,a,{flag:"w",mode:420}),(await ln(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{wl(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 un(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 un(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return un(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(be())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return yl(16).toString("hex")}generateKey(){return yl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=yl(16),n=M$("aes-256-gcm",t,r),i=Ut.isBuffer(e)?e:Ut.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=Ut.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=nm(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Ut.from(Ut.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(be())return;if(!this.shouldWriteToFile())return;let e=await ln(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Us(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ln(r).catch(()=>null))try{if(await rm(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ks(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await vl(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await ln(r).catch(()=>null))await rm(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Us(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Ks(un(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Zd(e),n=j$(t),i=nm();await z$(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),js(this.currentLogFile))try{let e=em(this.currentLogFile,"r+");Qd(e),wl(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!be()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Us(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ks(un(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?K.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||be())return!1;let e=typeof I.env.NO_COLOR<"u",t=I.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=I.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${K.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=K.underline(K.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>K.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>K.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>K.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>K.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>K.strikethrough(n)),t}supportsHyperlinks(){if(be())return!1;let e=I.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=I.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(V$(t)||t.startsWith("./")||t.startsWith("../"))t=H$(t);else return null;return js(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Um[e],h=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:K.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:K.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
11
+ `);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:K.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!be()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
12
+ `;if(c)u+=`${c}
13
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!be()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!be()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!be()&&I.stdout.isTTY)I.stdout.write(`
14
+ `);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!be()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":K.blue("◐"),tag:r,message:`${K.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
15
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":K.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!be())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new fo(t,{...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(r),r}createReadStream(){if(be())throw Error("createReadStream is not supported in browser environments");if(!js(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Zd(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Ut.isBuffer(e)?e:Ut.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=_$("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Ut.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return be()}isServerMode(){return!be()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
16
+ `),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:K.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(u),showTimestamp:!1}))}else if(!be())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(be())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${K.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();I.stdin.removeListener("data",r);try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!1)}catch{}I.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!0)}catch{}I.stdin.resume(),I.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${l}${a} ${K.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!I.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=K.green("━".repeat(n)),o=K.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?K.green("✓"):K.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=I.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,I.stdout.write(e.lastRenderedLine),t)I.stdout.write(`
19
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||be()||!I.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(be()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Us(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=un(this.config.logDirectory,n);if(e.before)try{if((await ln(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ks(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Nm(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Dm(e){return e instanceof ot}function TC(e){return e instanceof ho}function PC(e){if(Dm(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class vo{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return $i.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Ws.env[a]||(l?Ws.env[l]:void 0);if(u!==void 0){if(n.verbose){let f=Ws.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(u,typeof s,a,n.customParsers,n.configName)}catch(f){if(f instanceof mo)throw f;throw vr.envVar(a,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw vr.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Ws.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
20
20
 
21
- `;for(let A of w)Y+=`${A.key}
22
- `,Y+=` Type: ${A.type}
23
- `,Y+=` Description: ${A.description}
24
- `,Y+=` Example: ${A.example}
21
+ `;for(let n of e)r+=`${n.key}
22
+ `,r+=` Type: ${n.type}
23
+ `,r+=` Description: ${n.description}
24
+ `,r+=` Example: ${n.example}
25
25
 
26
- `;return Y}formatAsMarkdown(w,$){let Y=`# Environment Variables for ${$}
26
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
27
27
 
28
- `;Y+=`| Variable | Type | Description | Example |
29
- `,Y+=`|----------|------|-------------|----------|
30
- `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
31
- `;return Y}}function JK(w,$){let Y=Kz("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function zz(w,$,Y={}){return fz(w,$,Y,new WeakMap)}function fz(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return Bz(w,$,X,A);if(!Qw($)||!Qw(w))return $;return QK(w,$,Y,A)}function Bz(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return UK(w,$);case"smart":return WK(w,$,A);default:return $}return $}function UK(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>iJ(X,A)))Y.push(A);return Y}function WK(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Qw($[0])&&Qw(w[0]))return jK(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function jK(w,$,Y){let A=[...$];for(let X of w){if(!Qw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Qw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function QK(w,$,Y,A){let X=$;if(Qw(X)&&A.has(X))return A.get(X);let J={...w};if(Qw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Qw(j)&&Qw(W))J[U]=fz(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=Bz(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function oJ(w,$,Y="replace"){return zz(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function iJ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!iJ(w[Y],$[Y]))return!1;return!0}if(Qw(w)&&Qw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!iJ(w[X],$[X]))return!1}return!0}return!1}function Qw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class PA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=J1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!WA(w))return null;try{let Q=`?t=${Date.now()}`,z=await import(w+Q),f=z.default||z,B="default"in z,G=Object.keys(z).length>0;if(!B&&!G)throw new o1(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new o1(w,Error("Configuration must export a valid object"),"unknown");let E={config:oJ($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)J1.setWithFileCheck("file",E,w,J);return E}catch(Q){throw Q instanceof Error?Q$.configLoad(w,Q):Q$.configLoad(w,Error(String(Q)))}};if(U)return wY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(IJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return jz(async()=>{return WA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!WA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=IJ(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=IJ(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!WA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class eJ{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let z=[],f=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return z.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:z,warnings:f}}};if(j)return await wY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!y5($))throw new e1($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new e1($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:qz},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class wU{fileLoader=new PA;envProcessor=new ZA;validator=new eJ;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||z))throw W;if(f&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Nw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Nw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:z=!1}=w,f=J||S$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,f,U,j,Q,z,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,B,W,A,z);let T=await this.loadHomeConfiguration(A,X,j,Q,z,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,z);let F=await this.loadPackageJsonConfiguration(A,X,f,j,Q,z,W);if(F)return B.push(g0(f,"package.json")),this.finalizeResult(F,B,W,A,z);if(B.push(...this.getAllSearchPaths(A,X,f,U)),$)throw Q$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?a1(w,X,U):X,z=this.getLocalDirectories(Y,A);for(let f of z){if(U)Nw.info(`Searching for configuration in: ${f}`);let B=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Nw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?a1(w,Y,X):Y,j=[g0(t$(),".config",w),g0(t$(),".config"),t$()];for(let W of j){if(X)Nw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),z=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(z){if(X)Nw.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?a1(w,A,J):A;try{let W=g0(Y,"package.json");if(!ZJ(W))return null;let Q=await import(W),z=Q[w],f=w;if(!z&&$)z=Q[$],f=$;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)Nw.success(`Configuration loaded from package.json: ${f}`);return{config:oJ(j,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Nw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:a1(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw Q$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return J1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);J1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,g0(w,"config"),g0(w,".config"),$?g0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(g0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[g0(t$(),".config",w),g0(t$(),".config"),t$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function mQ(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function zK(w){return uw.loadConfig({...w,__strictErrorHandling:!0})}async function Gz(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await uw.loadConfig(w);else A=await uw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Nw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await uw.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}async function fK(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await uw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&mQ(Y)))return(await uw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await uw.loadConfig({...w,cwd:w.cwd||S$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&mQ($)))return(await uw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function BK(w,$,Y="replace"){let A=new PA;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function a1(w,$,Y=!1){let A=new ZA,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,z]of Object.entries(U)){let f=[...j,Q],B=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((F)=>F.toUpperCase()).join("")}`,`${X}_${f.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let F of B)if(G=S$.env[F],G!==void 0){T=F;break}if(G!==void 0&&T)if(typeof z==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof z==="number"){let F=Number(G);if(!Number.isNaN(F))W[Q]=F}else if(Array.isArray(z))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((F)=>F.trim())}else W[Q]=G;else if(z&&typeof z==="object"&&!Array.isArray(z))W[Q]=J(z,f)}return W}return J($)}function GK(w){let $=g0(S$.cwd(),w.configDir),Y=g0(S$.cwd(),w.generatedDir),A=g0(Y,"config-types.ts");if(!ZJ(qQ(A)))$5(qQ(A),{recursive:!0,mode:511});let X=ZJ($)?Y5($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${mK}
32
- export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
33
- `;A5(A,J,{mode:438})}function KK(w){let $=null,Y=null,A=()=>{if(!Y)Y=Gz(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Nw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function FK(w){let $=kQ(L5.cwd(),w?.configDir||"./config");function Y(){if(!C5($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=V5($).filter((W)=>X.has(yJ(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let z=yJ(Q).toLowerCase(),f=j.get(W);if(!f){j.set(W,Q);continue}let B=yJ(f).toLowerCase();if(J.indexOf(z)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((Q)=>Q.base),U=J.length?J.map((Q)=>`'${Q}'`).join(" | "):"string",j=X.length?`{
34
- ${X.map((Q)=>{let z=kQ($,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${z}').default`}).join(`,
28
+ `;r+=`| Variable | Type | Description | Example |
29
+ `,r+=`|----------|------|-------------|----------|
30
+ `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
31
+ `;return r}}function AC(e,t){let r=Mm("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Fm(e,t,r={}){return Lm(e,t,r,new WeakMap)}function Lm(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Bm(e,t,i,n);if(!pt(t)||!pt(e))return t;return NC(e,t,r,n)}function Bm(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return RC(e,t);case"smart":return kC(e,t,n);default:return t}return t}function RC(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Fl(i,n)))r.push(n);return r}function kC(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(pt(t[0])&&pt(e[0]))return OC(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function OC(e,t,r){let n=[...t];for(let i of e){if(!pt(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>pt(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function NC(e,t,r,n){let i=t;if(pt(i)&&n.has(i))return n.get(i);let s={...e};if(pt(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(pt(c)&&pt(a))s[o]=Lm(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=Bm(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function Yl(e,t,r="replace"){return Fm(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Fl(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Fl(e[r],t[r]))return!1;return!0}if(pt(e)&&pt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Fl(e[i],t[i]))return!1}return!0}return!1}function pt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class bo{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=gn.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Vs(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new vi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new vi(e,Error("Configuration must export a valid object"),"unknown");let p={config:Yl(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)gn.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?vr.configLoad(e,l):vr.configLoad(e,Error(String(l)))}};if(o)return $i.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(bl(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Nm(async()=>Vs(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Vs(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=bl(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=bl(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Vs(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Jl{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await $i.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!G$(t))throw new bi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new bi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Wm},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Xl{fileLoader=new bo;envProcessor=new vo;validator=new Jl;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)Et.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw Et.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||_r.cwd(),h=[],d=await this.loadLocalConfiguration(n,i,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(n,i,f,o)),this.finalizeResult(d,h,a,n,u);let y=await this.loadHomeConfiguration(n,i,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(y,h,a,n,u);let g=await this.loadPackageJsonConfiguration(n,i,f,c,l,u,a);if(g)return h.push(Ye(f,"package.json")),this.finalizeResult(g,h,a,n,u);if(h.push(...this.getAllSearchPaths(n,i,f,o)),t)throw vr.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?yi(e,i,o):i,u=this.getLocalDirectories(r,n);for(let f of u){if(o)Et.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Et.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?yi(e,r,i):r,c=[Ye(sn(),".config",e),Ye(sn(),".config"),sn()];for(let a of c){if(i)Et.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(u){if(i)Et.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?yi(e,n,s):n;try{let a=Ye(r,"package.json");if(!Nl(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Et.success(`Configuration loaded from package.json: ${f}`);return{config:Yl(c,u,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Et.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:yi(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw vr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return gn.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);gn.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ye(e,"config"),Ye(e,".config"),t?Ye(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Ye(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ye(sn(),".config",e),Ye(sn(),".config"),sn()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function hm(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function DC(e){return zt.loadConfig({...e,__strictErrorHandling:!0})}async function Im(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await zt.loadConfig(e);else n=await zt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)Et.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await zt.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function FC(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await zt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&hm(r)))return(await zt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await zt.loadConfig({...e,cwd:e.cwd||_r.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&hm(t)))return(await zt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function LC(e,t,r="replace"){let n=new bo;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function yi(e,t,r=!1){let n=new vo,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((g)=>g.toUpperCase()).join("")}`,`${i}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=_r.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function BC(e){let t=Ye(_r.cwd(),e.configDir),r=Ye(_r.cwd(),e.generatedDir),n=Ye(r,"config-types.ts");if(!Nl(Wd(n)))S$(Wd(n),{recursive:!0,mode:511});let i=Nl(t)?E$(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${fx}
32
+ export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
33
+ `;T$(n,s,{mode:438})}function IC(e){let t=null,r=null,n=()=>{if(!r)r=Im(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)Et.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function MC(e){let t=im(J$.cwd(),e?.configDir||"./config");function r(){if(!q$(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Y$(t).filter((a)=>i.has($l(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=$l(l).toLowerCase(),f=c.get(a);if(!f){c.set(a,l);continue}let h=$l(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=i.length?`{
34
+ ${i.map((l)=>{let u=im(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${u}').default`}).join(`,
35
35
  `)}
36
- }`:"Record<string, any>";return`export type ConfigNames = ${U}
37
- export type ConfigByName = ${j}
36
+ }`:"Record<string, any>";return`export type ConfigNames = ${o}
37
+ export type ConfigByName = ${c}
38
38
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
39
  export type ConfigOf = Config
40
- `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function dK(w,$={}){let Y=yA.cwd();while(Y.includes("storage"))Y=ZQ(Y,"..");let A=ZQ(Y,w||"");if($?.relative)return S5(yA.cwd(),A);return A}function E0(){if(bw.env.NODE_ENV==="test"||bw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lK(){if(bw.env.NODE_ENV==="test"||bw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bw<"u"){let w=bw.type;if(w==="renderer"||w==="worker")return!1;return!!(bw.versions&&(bw.versions.node||bw.versions.bun))}return!1}class Iz{async format(w){let $=await lK(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:X1.pid,hostname:$(),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 iA{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=w,this.config={...hA},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Iz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...DJ,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...DJ};return{...DJ,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:hA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await k5(this.config.logDirectory,uQ.F_OK|uQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await Z5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:Zw.from(w);try{if(!jA(this.currentLogFile))await LJ(this.currentLogFile,"",{mode:420});if(X=bQ(this.currentLogFile,"a",420),x5(X,W,{flag:"a"}),iQ(X),X!==void 0)VJ(X),X=void 0;if((await Y1(this.currentLogFile)).size===0){if(await LJ(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(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{VJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 w=new Date().toISOString().split("T")[0];return A1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return CJ(16).toString("hex")}generateKey(){return CJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=CJ(16),A=_5("aes-256-gcm",$,Y),X=Zw.isBuffer(w)?w:Zw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=Zw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=cQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(Zw.from(Zw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let w=await Y1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await QA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await Y1(Y).catch(()=>null))try{if(await vQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await zA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await LJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await Y1(Y).catch(()=>null))await vQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await QA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await zA(A1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=PQ(w),A=D5($),X=cQ();await b5(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),jA(this.currentLogFile))try{let w=bQ(this.currentLogFile,"r+");iQ(w),VJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await QA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await zA(A1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?c.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let w=typeof k.env.NO_COLOR<"u",$=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(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=k.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${c.cyan(X)}`;if(!U)return Q.trim();let z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),$}supportsHyperlinks(){if(E0())return!1;let w=k.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=k.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(P5($)||$.startsWith("./")||$.startsWith("../"))$=i5($);else return null;return jA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":sK[w],B=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:c.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:c.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
41
- `);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:c.gray(` ${F}`),level:w,showTimestamp:!1}))}break}}else if(!E0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}let z=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
42
- `;if(j)z+=`${j}
43
- `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!E0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!E0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!E0()&&k.stdout.isTTY)k.stdout.write(`
44
- `);if(this[W==="warning"?"warn":W](j),this.activeProgressBar&&this.shouldStyleConsole()&&!E0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":c.blue("◐"),tag:Y,message:`${c.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
45
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":c.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!E0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new iA($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(E0())throw Error("createReadStream is not supported in browser environments");if(!jA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return PQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Zw.isBuffer(w)?w:Zw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=h5("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),z=W.length+Q.length,f=Zw.allocUnsafe(z);return W.copy(f,0),Q.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return E0()}isServerMode(){return!E0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
46
- `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,f=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:c.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(Q),showTimestamp:!1})),f.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(z),showTimestamp:!1}))}else if(!E0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
47
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(E0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${c.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();k.stdin.removeListener("data",Y);try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!1)}catch{}k.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!0)}catch{}k.stdin.resume(),k.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,Q=0;if(Y=w.replace(W,(z,f)=>{if(f==="%")return"%";if(Q>=$.length)return z;let B=$[Q++];switch(f){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return z}}),Q<$.length)Y+=` ${$.slice(Q).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${c.blue("◐")} `;console.error(`${Q}${W} ${c.cyan(A)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
48
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!k.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=c.green("━".repeat(A)),U=c.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",z=this.options.showIcons===!1?"":$||Y===100?c.green("✓"):c.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",B=`\r${z}${f} ${j} ${W}${Q}`,G=k.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,k.stdout.write(w.lastRenderedLine),$)k.stdout.write(`
49
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||E0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(E0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await QA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=A1(this.config.logDirectory,A);if(w.before)try{if((await Y1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await zA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function oK(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class YU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix(w),f={...$};return this.processObject(f,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return pJ.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=BA.env[W]||(Q?BA.env[Q]:void 0);if(z!==void 0){if(A.verbose){let f=BA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(f){if(f instanceof $U)throw f;throw U1.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw U1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(BA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
40
+ `}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function dx(e,t={}){let r=ao.cwd();while(r.includes("storage"))r=sm(r,"..");let n=sm(r,e||"");if(t?.relative)return Z$(ao.cwd(),n);return n}function Ce(){if(Ht.env.NODE_ENV==="test"||Ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gx(){if(Ht.env.NODE_ENV==="test"||Ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ht<"u"){let e=Ht.type;if(e==="renderer"||e==="worker")return!1;return!!(Ht.versions&&(Ht.versions.node||Ht.versions.bun))}return!1}class Gm{async format(e){let t=await gx(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:mn.pid,hostname:t(),environment:mn.env.NODE_ENV||"development",platform:mn.platform,version:mn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:mn.env.NODE_ENV||mn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $o{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(e,t={}){this.name=e,this.config={...go},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Gm,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Rl,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Rl};return{...Rl,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:go.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ce()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await nC(this.config.logDirectory,lm.F_OK|lm.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await iC(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Kt.from(e);try{if(!Hs(this.currentLogFile))await Sl(this.currentLogFile,"",{mode:420});if(i=cm(this.currentLogFile,"a",420),rC(i,a,{flag:"a"}),am(i),i!==void 0)xl(i),i=void 0;if((await hn(this.currentLogFile)).size===0){if(await Sl(this.currentLogFile,a,{flag:"w",mode:420}),(await hn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{xl(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 dn(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 dn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return dn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ce())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Cl(16).toString("hex")}generateKey(){return Cl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Cl(16),n=Q$("aes-256-gcm",t,r),i=Kt.isBuffer(e)?e:Kt.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=Kt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=fm(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Kt.from(Kt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ce())return;if(!this.shouldWriteToFile())return;let e=await hn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await zs(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await hn(r).catch(()=>null))try{if(await um(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Gs(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Sl(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await hn(r).catch(()=>null))await um(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await zs(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Gs(dn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=om(e),n=tC(t),i=fm();await aC(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Hs(this.currentLogFile))try{let e=cm(this.currentLogFile,"r+");am(e),xl(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ce()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await zs(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Gs(dn(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?H.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ce())return!1;let e=typeof M.env.NO_COLOR<"u",t=M.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=M.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${H.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=H.underline(H.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>H.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>H.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>H.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>H.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>H.strikethrough(n)),t}supportsHyperlinks(){if(Ce())return!1;let e=M.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=M.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(sC(t)||t.startsWith("./")||t.startsWith("../"))t=oC(t);else return null;return Hs(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":bx[e],h=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:H.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:H.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
41
+ `);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:H.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!Ce()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
42
+ `;if(c)u+=`${c}
43
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ce()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!Ce()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!Ce()&&M.stdout.isTTY)M.stdout.write(`
44
+ `);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!Ce()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":H.blue("◐"),tag:r,message:`${H.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
45
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":H.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ce())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new $o(t,{...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(r),r}createReadStream(){if(Ce())throw Error("createReadStream is not supported in browser environments");if(!Hs(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return om(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Kt.isBuffer(e)?e:Kt.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=eC("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Kt.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ce()}isServerMode(){return!Ce()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
46
+ `),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:H.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(u),showTimestamp:!1}))}else if(!Ce())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Ce())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${H.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();M.stdin.removeListener("data",r);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${H.blue("◐")} `;console.error(`${l}${a} ${H.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=H.green("━".repeat(n)),o=H.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?H.green("✓"):H.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${H.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=M.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,M.stdout.write(e.lastRenderedLine),t)M.stdout.write(`
49
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ce()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ce()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await zs(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=dn(this.config.logDirectory,n);if(e.before)try{if((await hn(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Gs(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function $x(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class Ql{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Vl.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Ys.env[a]||(l?Ys.env[l]:void 0);if(u!==void 0){if(n.verbose){let f=Ys.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(u,typeof s,a,n.customParsers,n.configName)}catch(f){if(f instanceof Zl)throw f;throw pn.envVar(a,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw pn.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Ys.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
50
50
 
51
- `;for(let A of w)Y+=`${A.key}
52
- `,Y+=` Type: ${A.type}
53
- `,Y+=` Description: ${A.description}
54
- `,Y+=` Example: ${A.example}
51
+ `;for(let n of e)r+=`${n.key}
52
+ `,r+=` Type: ${n.type}
53
+ `,r+=` Description: ${n.description}
54
+ `,r+=` Example: ${n.example}
55
55
 
56
- `;return Y}formatAsMarkdown(w,$){let Y=`# Environment Variables for ${$}
56
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
57
57
 
58
- `;Y+=`| Variable | Type | Description | Example |
59
- `,Y+=`|----------|------|-------------|----------|
60
- `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
61
- `;return Y}}function eK(w,$,Y={}){return hz(w,$,Y,new WeakMap)}function hz(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return Dz(w,$,X,A);if(!zw($)||!zw(w))return $;return AF(w,$,Y,A)}function Dz(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return wF(w,$);case"smart":return $F(w,$,A);default:return $}return $}function wF(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>lJ(X,A)))Y.push(A);return Y}function $F(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(zw($[0])&&zw(w[0]))return YF(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function YF(w,$,Y){let A=[...$];for(let X of w){if(!zw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>zw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function AF(w,$,Y,A){let X=$;if(zw(X)&&A.has(X))return A.get(X);let J={...w};if(zw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(zw(j)&&zw(W))J[U]=hz(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=Dz(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function xz(w,$,Y="replace"){return eK(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function lJ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!lJ(w[Y],$[Y]))return!1;return!0}if(zw(w)&&zw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!lJ(w[X],$[X]))return!1}return!0}return!1}function zw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class kz{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=HA.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!GA(w))return null;try{let Q=`?t=${Date.now()}`,z=await import(w+Q),f=z.default||z,B="default"in z,G=Object.keys(z).length>0;if(!B&&!G)throw new DA(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new DA(w,Error("Configuration must export a valid object"),"unknown");let E={config:xz($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)HA.setWithFileCheck("file",E,w,J);return E}catch(Q){throw Q instanceof Error?U1.configLoad(w,Q):U1.configLoad(w,Error(String(Q)))}};if(U)return pJ.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(xJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return oK(async()=>{return GA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!GA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=xJ(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=xJ(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!GA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class Zz{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let z=[],f=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return z.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:z,warnings:f}}};if(j)return await pJ.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!XF($))throw new xA($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new xA($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:JF},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function UF(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class Pz{fileLoader=new kz;envProcessor=new YU;validator=new Zz;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||z))throw W;if(f&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Sw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let W=Date.now()-$;throw Sw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:z=!1}=w,f=J||kA.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,f,U,j,Q,z,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,B,W,A,z);let T=await this.loadHomeConfiguration(A,X,j,Q,z,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,z);let F=await this.loadPackageJsonConfiguration(A,X,f,j,Q,z,W);if(F)return B.push(jw(f,"package.json")),this.finalizeResult(F,B,W,A,z);if(B.push(...this.getAllSearchPaths(A,X,f,U)),$)throw U1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,z),warnings:[`No configuration file found for "${A}"${UF(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?KA(w,X,U):X,z=this.getLocalDirectories(Y,A);for(let f of z){if(U)Sw.info(`Searching for configuration in: ${f}`);let B=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Sw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?KA(w,Y,X):Y,j=[jw(r$(),".config",w),jw(r$(),".config"),r$()];for(let W of j){if(X)Sw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),z=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(z){if(X)Sw.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?KA(w,A,J):A;try{let W=jw(Y,"package.json");if(!eG(W))return null;let Q={};try{Q=JSON.parse(w5(W,"utf8"))}catch(B){if(J)Sw.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let z=Q[w],f=w;if(!z&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){z=Q[G],f=G;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)Sw.success(`Configuration loaded from package.json: ${f}`);return{config:xz(j,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Sw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:KA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw U1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return HA.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);HA.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,jw(w,"config"),jw(w,".config"),$?jw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(jw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[jw(r$(),".config",w),jw(r$(),".config"),r$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}async function iz(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await kJ.loadConfig(w);else A=await kJ.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Sw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await kJ.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}function KA(w,$,Y=!1){let A=new YU,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,z]of Object.entries(U)){let f=[...j,Q],B=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((F)=>F.toUpperCase()).join("")}`,`${X}_${f.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let F of B)if(G=kA.env[F],G!==void 0){T=F;break}if(G!==void 0&&T)if(typeof z==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof z==="number"){let F=Number(G);if(!Number.isNaN(F))W[Q]=F}else if(Array.isArray(z))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((F)=>F.trim())}else W[Q]=G;else if(z&&typeof z==="object"&&!Array.isArray(z))W[Q]=J(z,f)}return W}return J($)}var HA,pJ,u5,v5=(w)=>w,m5=(w,$)=>{for(var Y in $)u5(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:c5.bind($,Y)})},g5=(w,$)=>()=>(w&&($=w(w=0)),$),Jz,Kz,J1,wY,Fz,EK,TK,gQ,EA,bJ,O0,o,NK,dQ,qK,nQ,HK,RK,OJ,MK,lQ,pQ,SJ,IK,yK,CK,VK,TA,Ez,LK,S0,OK,SK,rQ,NA,uJ,F0,b,_K,tQ,hK,aQ,DK,xK,_J,kK,sQ,oQ,ZK,hJ,PK,iK,bK,uK,vK,qA,Tz,cK,mK="0.15.6",e0,SA,o1,vJ,cJ,_A,mJ,gJ,e1,dJ,nJ,Q$,Nz,qz,Nw,uw,Hz,Rz,gK,nK,Mz,hA,XI,I0,c,JI,pK,UI,rK,WI,jI,eQ,QI,tK,aK,zI,wz,fI,BI,GI,KI,FI,DJ,sK,EI,qw,yz,DA,Cz,Vz,$U,Lz,Oz,xA,Sz,_z,U1,JF,Sw,kJ,RI,MI;var bz=s(()=>{HA=new $z,pJ=new Yz,u5=Object.defineProperty;Jz={};m5(Jz,{withErrorRecovery:()=>jz,tryLoadConfig:()=>BK,loadConfigWithResult:()=>zK,loadConfig:()=>Gz,isRetryableError:()=>XK,isConfigNotFoundError:()=>AK,isBunfigError:()=>Qz,globalPerformanceMonitor:()=>wY,globalCache:()=>J1,getEnvOrDefault:()=>JK,generateConfigTypes:()=>GK,defaultGeneratedDir:()=>Rz,defaultConfigDir:()=>Hz,deepMergeWithArrayStrategy:()=>oJ,deepMerge:()=>zz,createLibraryConfig:()=>KK,config:()=>fK,bunfigPlugin:()=>FK,applyEnvVarsToConfig:()=>a1,TypeGenerationError:()=>gJ,SchemaValidationError:()=>e1,PluginError:()=>nJ,PerformanceMonitor:()=>tJ,FileSystemError:()=>mJ,ErrorFactory:()=>Q$,EnvVarError:()=>_A,EnvProcessor:()=>ZA,ConfigValidator:()=>eJ,ConfigValidationError:()=>vJ,ConfigNotFoundError:()=>SA,ConfigMergeError:()=>cJ,ConfigLoader:()=>wU,ConfigLoadError:()=>o1,ConfigFileLoader:()=>PA,ConfigCache:()=>rJ,CacheUtils:()=>Fz,BunfigError:()=>e0,BrowserConfigError:()=>dJ,ArrayMergeStrategies:()=>Nz});gK=g5(async()=>{Kz=import.meta.require,J1=new rJ,wY=new tJ,Fz={createKey:d5,isEquivalent:n5,estimateMemoryUsage:l5},EK=IA(PJ.cwd(),"config"),TK=IA(PJ.cwd(),"src/generated"),gQ=MA.env.CLARITY_LOG_DIR||U5(t5(),"logs"),EA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},bJ=await a5(),O0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},o=O0,NK=O0.red,dQ=O0.green,qK=O0.yellow,nQ=O0.blue,HK=O0.magenta,RK=O0.cyan,OJ=O0.white,MK=O0.gray,lQ=O0.bgRed,pQ=O0.bgYellow,SJ=O0.bold,IK=O0.dim,yK=O0.italic,CK=O0.underline,VK=O0.reset,TA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ez={debug:"\uD83D\uDD0D",info:nQ("ℹ"),success:dQ("✓"),warning:pQ(OJ(SJ(" WARN "))),error:lQ(OJ(SJ(" ERROR ")))},LK=new VA("stacks"),S0=new VA("bunfig",{showTags:!0}),OK=m0(s1.cwd(),"config"),SK=m0(s1.cwd(),"src/generated"),rQ=RA.env.CLARITY_LOG_DIR||X5(wK(),"logs"),NA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:rQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},uJ=await $K(),F0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},b=F0,_K=F0.red,tQ=F0.green,hK=F0.yellow,aQ=F0.blue,DK=F0.magenta,xK=F0.cyan,_J=F0.white,kK=F0.gray,sQ=F0.bgRed,oQ=F0.bgYellow,ZK=F0.bgGray,hJ=F0.bold,PK=F0.dim,iK=F0.italic,bK=F0.underline,uK=F0.strikethrough,vK=F0.reset,qA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Tz={debug:"\uD83D\uDD0D",info:aQ("ℹ"),success:tQ("✓"),warning:oQ(_J(hJ(" WARN "))),error:sQ(_J(hJ(" ERROR ")))},cK=new OA("stacks"),e0=class extends Error{timestamp;context;constructor($,Y={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},SA=class extends e0{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},o1=class extends e0{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},vJ=class extends e0{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},cJ=class extends e0{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},_A=class extends e0{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},mJ=class extends e0{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},gJ=class extends e0{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},e1=class extends e0{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},dJ=class extends e0{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},nJ=class extends e0{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Q$={configNotFound(w,$,Y){return new SA(w,$,Y)},configLoad(w,$,Y){return new o1(w,$,Y)},configValidation(w,$,Y){return new vJ(w,$,Y)},configMerge(w,$,Y,A){return new cJ(w,$,Y,A)},envVar(w,$,Y,A){return new _A(w,$,Y,A)},fileSystem(w,$,Y){return new mJ(w,$,Y)},typeGeneration(w,$,Y){return new gJ(w,$,Y)},schemaValidation(w,$,Y){return new e1(w,$,Y)},browserConfig(w,$,Y,A){return new dJ(w,$,Y,A)},plugin(w,$,Y){return new nJ(w,$,Y)}},Nz={replace:"replace",concat:"concat",smart:"smart"},qz=/^https?:\/\//,Nw=new OA("bunfig",{showTags:!0}),uw=new wU,Hz=g0(S$.cwd(),"config"),Rz=g0(S$.cwd(),"src/generated")});nK=yA.env.CLARITY_LOG_DIR||O5(dK(),"logs"),Mz={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:nK,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},hA={...Mz},XI=(async()=>{try{let{loadConfig:w}=await gK().then(()=>Jz),$=await w({name:"clarity",alias:"logging",defaultConfig:Mz,cwd:yA.cwd()});if($)Object.assign(hA,$)}catch{}return hA})();I0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},c=I0,JI=I0.red,pK=I0.green,UI=I0.yellow,rK=I0.blue,WI=I0.magenta,jI=I0.cyan,eQ=I0.white,QI=I0.gray,tK=I0.bgRed,aK=I0.bgYellow,zI=I0.bgGray,wz=I0.bold,fI=I0.dim,BI=I0.italic,GI=I0.underline,KI=I0.strikethrough,FI=I0.reset,DJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sK={debug:"\uD83D\uDD0D",info:rK("ℹ"),success:pK("✓"),warning:aK(eQ(wz(" WARN "))),error:tK(eQ(wz(" ERROR ")))};EI=new iA("stacks");qw=class qw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,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(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};yz=class yz extends qw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};DA=class DA extends qw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};Cz=class Cz extends qw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Vz=class Vz extends qw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};$U=class $U extends qw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};Lz=class Lz extends qw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};Oz=class Oz extends qw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};xA=class xA extends qw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Sz=class Sz extends qw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};_z=class _z extends qw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};U1={configNotFound(w,$,Y){return new yz(w,$,Y)},configLoad(w,$,Y){return new DA(w,$,Y)},configValidation(w,$,Y){return new Cz(w,$,Y)},configMerge(w,$,Y,A){return new Vz(w,$,Y,A)},envVar(w,$,Y,A){return new $U(w,$,Y,A)},fileSystem(w,$,Y){return new Lz(w,$,Y)},typeGeneration(w,$,Y){return new Oz(w,$,Y)},schemaValidation(w,$,Y){return new xA(w,$,Y)},browserConfig(w,$,Y,A){return new Sz(w,$,Y,A)},plugin(w,$,Y){return new _z(w,$,Y)}};JF=/^https?:\/\//;Sw=new iA("bunfig",{showTags:!0});kJ=new Pz;RI=jw(kA.cwd(),"config"),MI=jw(kA.cwd(),"src/generated")});import{homedir as AU}from"node:os";import{join as XU,resolve as WF}from"node:path";async function vz(){if(!JU)JU=await iz({name:"rpx",cwd:WF(__dirname,".."),defaultConfig:uz});return JU}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",uz,JU=null,vw;var bA=s(()=>{bz();uz={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:XU(AU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:XU(AU(),".stacks","ssl","stacks.localhost.crt"),keyPath:XU(AU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};vw=uz});function W1(w){return w.startsWith("*.")}function h$(w,$){if(!W1($))return!1;let Y=$.slice(1);return w.length>Y.length&&w.endsWith(Y)}function cz(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!W1(J))continue;if(h$($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}import{existsSync as jF,readdirSync as QF,readFileSync as zF,statSync as fF}from"node:fs";import{homedir as gz}from"node:os";import{isAbsolute as BF,join as j1}from"node:path";function WU(w,$){if(w==="~")return $;if(w.startsWith("~/"))return j1($,w.slice(2));return w}function KF(w){let $=w.indexOf(":");return($===-1?w:w.slice(0,$)).toLowerCase()}function uA(w){return w.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function FF(w,$){for(let Y of $){let A=`.${Y}`;if(w.endsWith(A)){let X=w.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function EF(w,$){let Y=$.readText(j1(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText(j1(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function TF(w){let $=w.selfRegisters??!1;return{command:w.command,env:w.env,urlEnv:w.urlEnv,selfRegisters:$,routes:w.routes??($?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function NF(w,$){let Y=EF(w,$);if(Y?.command)return TF(Y);let A=$.fileExists(j1(w,"buddy")),X=$.readText(j1(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((W)=>W==="stacks"||W.startsWith("@stacksjs/")))return{command:A?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(J?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function jU(w,$={}){let Y={dirExists:$.dirExists??UU.dirExists,fileExists:$.fileExists??UU.fileExists,readText:$.readText??UU.readText},A=$.detect??NF,X=$.homeDir??gz(),J=w.tlds??nz,U=(w.roots??dz).map((B)=>WU(B,X)),j=w.idleTimeoutMs??GF,W=new Map;for(let B of w.sites??[])W.set(B.to,B);let Q=(B)=>B.idleTimeoutMs??j;function z(B){let G=cz(W,B);if(!G)return null;let T=BF(G.dir)?G.dir:WU(G.dir,X),F=G.selfRegisters??!1,E=G.routes??[];if(!F&&E.length===0)E=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let N=mz({...G.env??{}},void 0,B);return{host:B,id:uA(B),dir:T,command:G.command,env:N,routes:E,selfRegisters:F,idleTimeoutMs:Q(G),source:"config"}}function f(B){let G=FF(B,J);if(!G)return null;for(let T of U){let F=j1(T,G);if(!Y.dirExists(F))continue;let E=A(F,Y);if(!E)continue;let N=E.selfRegisters??!1;return{host:B,id:uA(B),dir:F,command:E.command,env:mz({...E.env??{}},E.urlEnv,B),routes:N?[]:E.routes??[],selfRegisters:N,idleTimeoutMs:j,source:"discovered"}}return null}return{resolve(B){let G=KF(B);if(!G)return null;return z(G)??f(G)}}}function qF(w){try{return QF(w,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name)}catch{return[]}}function lz(w,$={}){let Y=$.homeDir??gz(),A=w.tlds??nz,X=(w.roots??dz).map((f)=>WU(f,Y)),J=$.readdir??qF,U=jU(w,$),j=[],W=new Set,Q=(f)=>{if(f&&!W.has(f.host))W.add(f.host),j.push(f)};for(let f of w.sites??[])if(!f.to.includes("*"))Q(U.resolve(f.to));let z=A[0]??"localhost";for(let f of X)for(let B of J(f))Q(U.resolve(`${B}.${z}`));return j}function mz(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}var dz,nz,GF=1800000,UU;var QU=s(()=>{dz=["~/Code"],nz=["localhost","test"],UU={dirExists:(w)=>{try{return fF(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return jF(w)}catch{return!1}},readText:(w)=>{try{return zF(w,"utf8")}catch{return null}}}});var H;var D$=s(()=>{H={info:(...w)=>console.log("[info]",...w),success:(...w)=>console.log("[success]",...w),warn:(...w)=>console.warn("[warn]",...w),error:(...w)=>console.error("[error]",...w),debug:(...w)=>console.debug("[debug]",...w),log:(...w)=>console.log(...w),start:(...w)=>console.log("[start]",...w),box:(...w)=>console.log("[box]",...w)}});import{createRequire as HF}from"node:module";import{Resolver as zU}from"node:dns/promises";import{createHash as MF,sign as IF}from"node:crypto";import{createHash as yF}from"node:crypto";import{sign as CF}from"node:crypto";import{generateKeyPairSync as ef,X509Certificate as kF}from"node:crypto";import fU from"node:os";import BU from"node:path";import{existsSync as rz,statSync as tz}from"fs";import{existsSync as PF,mkdirSync as nI,readdirSync as lI,readFileSync as iF,writeFileSync as pI}from"fs";import{homedir as Q1}from"os";import{dirname as aI,resolve as Bw}from"path";import VX from"process";import{existsSync as az,statSync as sz}from"fs";import{existsSync as PU,mkdirSync as bF,readdirSync as uF,writeFileSync as vF}from"fs";import{homedir as z1}from"os";import{dirname as oz,resolve as n0}from"path";import k$ from"process";import{join as cF,relative as mF,resolve as ez}from"path";import QX from"process";import{existsSync as wB,mkdirSync as Uy,readdirSync as Wy,writeFileSync as jy}from"fs";import{homedir as GU}from"os";import{dirname as fy,resolve as d0}from"path";import JY from"process";import{join as gF,relative as dF,resolve as wf}from"path";import zX from"process";import{existsSync as $B,mkdirSync as Ey,readdirSync as Ty,writeFileSync as Ny}from"fs";import{dirname as Hy,resolve as fX}from"path";import iU from"process";import{Buffer as z$}from"buffer";import{createCipheriv as nF,createDecipheriv as lF,randomBytes as KU}from"crypto";import{closeSync as FU,createReadStream as $f,createWriteStream as pF,existsSync as EU,fsyncSync as Yf,openSync as Af,writeFileSync as rF}from"fs";import{access as tF,constants as Xf,mkdir as aF,readdir as vA,rename as Jf,stat as f1,unlink as cA,writeFile as TU}from"fs/promises";import{join as B1}from"path";import _0 from"process";import{pipeline as sF}from"stream/promises";import{createGzip as Uf}from"zlib";import G1 from"process";import dw from"process";import{Buffer as cw}from"buffer";import{createCipheriv as oF,createDecipheriv as eF,randomBytes as NU}from"crypto";import{closeSync as qU,createReadStream as Wf,createWriteStream as wE,existsSync as mA,fsyncSync as jf,openSync as Qf,writeFileSync as $E}from"fs";import{access as YE,constants as zf,mkdir as AE,readdir as gA,rename as ff,stat as K1,unlink as dA,writeFile as HU}from"fs/promises";import{isAbsolute as XE,join as F1,resolve as JE}from"path";import p from"process";import{pipeline as UE}from"stream/promises";import{createGzip as Bf}from"zlib";import E1 from"process";import nw from"process";import nA from"process";import{existsSync as lA}from"fs";import{resolve as RU}from"path";import{existsSync as WE}from"fs";import{existsSync as jE,readdirSync as QE}from"fs";import{extname as MU,resolve as Gf}from"path";import zE from"process";import{join as fE,relative as BE,resolve as Kf}from"path";import BX from"process";import{Buffer as mw}from"buffer";import{createCipheriv as GE,createDecipheriv as KE,randomBytes as IU}from"crypto";import{closeSync as yU,createReadStream as Ff,createWriteStream as FE,existsSync as pA,fsyncSync as Ef,openSync as Tf,writeFileSync as EE}from"fs";import{access as TE,constants as Nf,mkdir as NE,readdir as rA,rename as qf,stat as T1,unlink as tA,writeFile as CU}from"fs/promises";import{isAbsolute as qE,join as N1,resolve as HE}from"path";import r from"process";import{pipeline as RE}from"stream/promises";import{createGzip as Hf}from"zlib";import q1 from"process";import lw from"process";import aA from"process";import{existsSync as sA}from"fs";import{resolve as VU}from"path";import{existsSync as ME}from"fs";import{exec as dT}from"node:child_process";import rU from"node:fs";import nT from"node:os";import Hw from"node:path";import iB from"node:process";import{promisify as lT}from"node:util";import I1 from"node:crypto";import pw from"node:fs";import sU from"node:path";import F7 from"node:crypto";import{execSync as N7}from"node:child_process";import yX from"node:os";async function wX(w,$={},Y=30000){try{return await fetch(w,{...$,signal:AbortSignal.timeout(Y)})}catch(A){if(A&&typeof A==="object"&&A.name==="TimeoutError"){let X=Error(`ACME HTTP request to ${w} timed out after ${Y}ms`);throw X.name="AcmeRequestTimeoutError",X}throw A}}async function vf(w,$,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=w.split(".").slice(-2).join("."),U;try{let Q=new zU,z=await Q.resolveNs(J),f=(await Promise.all(z.map((B)=>Q.resolve4(B).catch(()=>[])))).flat();if(f.length>0)U=new zU,U.setServers(f)}catch{}let j=Date.now()+A,W=U??new zU;for(;;){try{if((await W.resolveTxt(w)).some((Q)=>Q.join("")===$))return!0}catch{}if(Date.now()>=j)return!1;await new Promise((Q)=>setTimeout(Q,X))}}class XY{tokens=new Map;add(w,$){this.tokens.set(w,$)}get(w){return this.tokens.get(w)}remove(w){this.tokens.delete(w)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(w){let $=w.indexOf(XY.PATH_PREFIX);if($===-1)return;let Y=w.slice($+XY.PATH_PREFIX.length);return this.get(Y)}}function $X(w){return(typeof w==="string"?Buffer.from(w,"utf8"):Buffer.from(w)).toString("base64url")}function DU(w){return Buffer.from(w,"base64url")}function cf(w){let $=w.export({format:"jwk"});if($.kty!=="EC"||$.crv!=="P-256"||!$.x||!$.y)throw Error(`Expected a P-256 EC public key, got kty=${$.kty} crv=${$.crv}`);return{crv:"P-256",kty:"EC",x:$.x,y:$.y}}function mf(w){let $=`{"crv":"${w.crv}","kty":"${w.kty}","x":"${w.x}","y":"${w.y}"}`;return MF("sha256").update($).digest("base64url")}function gf(w){let{protectedHeader:$,payload:Y,privateKey:A}=w,X=$X(JSON.stringify($)),J=Y===""?"":$X(JSON.stringify(Y)),U=`${X}.${J}`,j=IF("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:$X(j)}}class jX{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(w){this.directoryUrl=w.directoryUrl,this.accountKey=w.accountKey,this.jwk=cf(w.accountPublicKey),this.thumbprint=mf(this.jwk),this.requestTimeoutMs=w.requestTimeoutMs??uf}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let w=await wX(this.directoryUrl,{},this.requestTimeoutMs);if(!w.ok)throw Error(`Failed to fetch ACME directory: HTTP ${w.status}`);return this.directoryCache=await w.json(),this.directoryCache}async newNonce(){let w=await this.directory(),$=(await wX(w.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!$)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=$,$}async ensureNonce(){if(this.nonce){let w=this.nonce;return this.nonce=void 0,w}return this.newNonce()}async signedPost(w){let{url:$,payload:Y,useJwk:A}=w,X={alg:"ES256",nonce:await this.ensureNonce(),url:$};if(A)X.jwk=this.jwk;else X.kid=this.requireKid();let J=gf({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await wX($,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)},this.requestTimeoutMs),j=U.headers.get("replay-nonce");if(j)this.nonce=j;let W=U.headers.get("content-type")??"",Q;if(W.includes("application/pem-certificate-chain")||W.startsWith("text/"))Q=await U.text();else{let z=await U.text();Q=z?JSON.parse(z):{}}if(U.status>=400){let z=Q??{};throw new WX(`ACME request to ${$} failed (HTTP ${U.status}): ${z.type??""} ${z.detail??""}`.trim(),z,U.status)}return{status:U.status,headers:U.headers,body:Q,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(w={}){let $=await this.directory(),Y={termsOfServiceAgreed:!0};if(w.email)Y.contact=[`mailto:${w.email}`];let A=await this.signedPost({url:$.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder(w){let $=await this.directory(),Y={identifiers:w.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:$.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization(w){return(await this.signedPost({url:w,payload:""})).body}keyAuthorization(w){return`${w}.${this.thumbprint}`}dns01TxtValue(w){return yF("sha256").update(this.keyAuthorization(w)).digest("base64url")}async notifyChallengeReady(w){await this.signedPost({url:w,payload:{}})}async pollAuthorization(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization(w);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((j)=>j.status==="invalid");throw new WX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await pz(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${w} to become valid`)}async finalizeOrder(w,$){return(await this.signedPost({url:w,payload:{csr:$}})).body}async getOrder(w){return(await this.signedPost({url:w,payload:""})).body}async pollOrder(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getOrder(w);if(J.status==="valid"){if(!J.certificate)throw Error("ACME order is valid but has no certificate URL");return J.certificate}if(J.status==="invalid")throw Error(`ACME order ${w} became invalid`);await pz(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${w} to become valid`)}async downloadCertificate(w){let $=await this.signedPost({url:w,payload:""});return typeof $.body==="string"?$.body:String($.body)}static selectChallenge(w,$){let Y=w.challenges.find((A)=>A.type===$);if(!Y)throw Error(`No ${$} challenge available for ${w.identifier.value}`);return Y}}function lf(w){let $=w.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=$[0];if(!Y)return{certPem:`${w.trim()}
62
- `,chainPem:""};let A=`${Y.trim()}
63
- `,X=$.slice(1).map((J)=>J.trim()).join(`
64
- `);return{certPem:A,chainPem:X?`${X}
65
- `:""}}function pf(w){return`_acme-challenge.${w.startsWith("*.")?w.slice(2):w}`}function pz(w){return new Promise(($)=>setTimeout($,w))}function VF(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function G$(w,$){return Buffer.concat([Buffer.from([w]),VF($.length),$])}function rf(w){let $;if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=[],A=w;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);$=Buffer.from(Y)}else if($=w.length===0?Buffer.from([0]):w,$[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return G$(2,$)}function x$(w){let $=w.split(".").map(Number);if($.length<2)throw Error(`Invalid OID: ${w}`);let Y=[40*$[0]+$[1]];for(let A=2;A<$.length;A++){let X=$[A],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);Y.push(...J)}return G$(6,Buffer.from(Y))}function fw(...w){return G$(48,Buffer.concat(w))}function xU(...w){return G$(49,Buffer.concat(w))}function kU(w){return G$(3,Buffer.concat([Buffer.from([0]),w]))}function tf(w){return G$(4,w)}function af(w){return G$(12,Buffer.from(w,"utf8"))}function ZU(w,$,Y){let A=128|(Y?32:0)|w;return G$(A,$)}function xF(w){let $=w.export({format:"jwk"});if(!$.x||!$.y)throw Error("Public key JWK is missing x/y coordinates");let Y=DU($.x),A=DU($.y);if(Y.length!==32||A.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${Y.length} y=${A.length}`);return Buffer.concat([Buffer.from([4]),Y,A])}function sf(w){let{domains:$,publicKey:Y,privateKey:A}=w;if($.length===0)throw Error("At least one domain is required to build a CSR");let X=fw(xU(fw(x$(_F),af($[0])))),J=fw(fw(x$(LF),x$(OF)),kU(xF(Y))),U=$.map((F)=>ZU(2,Buffer.from(F,"ascii"),!1)),j=fw(...U),W=fw(x$(DF),tf(j)),Q=fw(W),z=fw(x$(hF),xU(Q)),f=ZU(0,z,!0),B=fw(rf(0),X,J,f),G=CF("sha256",B,A),T=fw(x$(SF));return fw(B,T,kU(G))}function of(w){return sf(w).toString("base64url")}function ZF(w){if(w){let{createPrivateKey:X,createPublicKey:J}=RF("node:crypto"),U=X(w),j=J(U.export({format:"pem",type:"pkcs8"}));return{privateKey:U,publicKey:j,pem:w}}let{privateKey:$,publicKey:Y}=ef("ec",{namedCurve:"P-256"}),A=$.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:$,publicKey:Y,pem:A}}async function oU(w){let{domains:$,method:Y}=w;if($.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!w.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if($.some((f)=>f.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=w.directoryUrl??(w.staging===!1?nf:df),X=ZF(w.accountKeyPem),J=new jX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey,requestTimeoutMs:w.requestTimeoutMs});await J.newAccount({email:w.email});let{order:U,orderUrl:j}=await J.newOrder($),W=w.http01Store??CX,Q=[],z=[];try{for(let q of U.authorizations){let C=await J.getAuthorization(q);if(C.status==="valid")continue;let M=jX.selectChallenge(C,Y);if(Y==="dns-01"){let D=pf(C.identifier.value),n=J.dns01TxtValue(M.token);await w.dnsProvider.setTxt(D,n),Q.push({name:D,value:n}),await vf(D,n,{timeoutMs:w.dnsPropagationTimeoutMs??120000})}else W.add(M.token,J.keyAuthorization(M.token)),z.push(M.token);await J.notifyChallengeReady(M.url),await J.pollAuthorization(q,{timeoutMs:w.timeoutMs})}let{privateKey:f,publicKey:B}=ef("ec",{namedCurve:"P-256"}),G=of({domains:$,publicKey:B,privateKey:f});await J.finalizeOrder(U.finalize,G);let T=await J.pollOrder(j,{timeoutMs:w.timeoutMs}),F=await J.downloadCertificate(T),{certPem:E,chainPem:N}=lf(F),R=N?`${E}${N}`:E,V=f.export({format:"pem",type:"pkcs8"}).toString(),L=new Date(new kF(E).validTo);return{certPem:E,keyPem:V,chainPem:N,fullChainPem:R,accountKeyPem:X.pem,notAfter:L}}finally{for(let{name:f,value:B}of Q)await w.dnsProvider?.removeTxt(f,B).catch(()=>{});for(let f of z)W.remove(f)}}class YB{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!rz(w))return!0;return tz(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=rz(Y)?tz(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class AB{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function CE(w,$){this[w]=yE.bind(null,$)}class wW{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!az(w))return!0;return sz(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=az(Y)?sz(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class $W{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function OE(w,$={}){let Y=Object.keys($).sort().map((A)=>`${A}:${$[A]}`).join("|");return Y?`${w}:${Y}`:w}function SE(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function _E(w){return w.getStats().size*2}function YW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&A0($[0])&&"id"in $[0]&&$[0].id===3&&A0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(A0($)&&A0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(A0(w)&&"arr"in w&&Array.isArray(w.arr)&&A0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&A0($[0])&&A0(w[0])){let A=[...$];for(let X of w)if(A0(X)&&"name"in X){if(!A.find((J)=>A0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(A0(X)&&"path"in X){if(!A.find((J)=>A0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>KX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!A0($)||!A0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(A0(X)&&A0(Y[A]))Y[A]=YW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&A0(X[0])&&A0(Y[A][0])){let J=[...X];for(let U of Y[A])if(A0(U)&&"name"in U){if(!J.find((j)=>A0(j)&&("name"in j)&&j.name===U.name))J.push(U)}else if(A0(U)&&"path"in U){if(!J.find((j)=>A0(j)&&("path"in j)&&j.path===U.path))J.push(U)}else if(!J.some((j)=>KX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function KX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!KX(w[Y],$[Y]))return!1;return!0}if(A0(w)&&A0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!KX(w[X],$[X]))return!1}return!0}return!1}function A0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function hE(w,$){if(!$B(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return YW($,A)}catch{return null}}catch{return null}}async function DE({name:w="",cwd:$,defaultConfig:Y}){let A=$||iU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=fX(A,`${U}${j}`),Q=await hE(W,Y);if(Q!==null)return Q}try{let U=fX(A,"package.json");if($B(U)){let j=(await import(U))[w];if(j&&typeof j==="object"&&!Array.isArray(j))try{return YW(Y,j)}catch{}}}catch{}return Y}function xE(w,$={}){let Y=zX.cwd();while(Y.includes("storage"))Y=wf(Y,"..");let A=wf(Y,w||"");if($?.relative)return dF(zX.cwd(),A);return A}async function kE(){try{let w=await DE({name:"clarity",defaultConfig:AX,cwd:zX.cwd(),endpoint:"",headers:{}});return{...AX,...w}}catch{return AX}}function W0(){if(dw.env.NODE_ENV==="test"||dw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ZE(){if(dw.env.NODE_ENV==="test"||dw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof dw<"u"){let w=dw.type;if(w==="renderer"||w==="worker")return!1;return!!(dw.versions&&(dw.versions.node||dw.versions.bun))}return!1}class JB{async format(w){let $=await ZE(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:G1.pid,hostname:$(),environment:G1.env.NODE_ENV||"development",platform:G1.platform,version:G1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:G1.env.NODE_ENV||G1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class FX{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=w,this.config={...uU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new JB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??_0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...XX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...XX};return{...XX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:uU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await tF(this.config.logDirectory,Xf.F_OK|Xf.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await aF(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:z$.from(w);try{if(!EU(this.currentLogFile))await TU(this.currentLogFile,"",{mode:420});if(A=Af(this.currentLogFile,"a",420),rF(A,j,{flag:"a"}),Yf(A),A!==void 0)FU(A),A=void 0;if((await f1(this.currentLogFile)).size===0){if(await TU(this.currentLogFile,j,{flag:"w",mode:420}),(await f1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let z=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let f=U*2**X;await new Promise((B)=>setTimeout(B,f)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{FU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,z=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}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 B1(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 B1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return B1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return KU(16).toString("hex")}generateKey(){return KU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=KU(16),A=nF("aes-256-gcm",$,Y),X=z$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:z$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Uf(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(z$.from(z$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(W0())return;let w=await f1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await vA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await f1(Y).catch(()=>null))try{if(await Jf(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await cA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await TU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await f1(Y).catch(()=>null))await Jf(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await vA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await cA(B1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=$f(w),A=pF($),X=Uf();await sF(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),EU(this.currentLogFile))try{let w=Af(this.currentLogFile,"r+");Yf(w),FU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await vA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await cA(B1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?e.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=_0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${e.cyan(X)}`;if(!U)return Q.trim();let z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!W0()){let Q=FB[w],z=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",f;switch(w){case"debug":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:e.gray(U),level:w}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:e.green(U),level:w}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f),j){let B=j.split(`
66
- `);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:e.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!W0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
67
- `;if(j)W+=`${j}
68
- `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!W0()){let Y=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:e.blue("◐"),tag:Y,message:`${e.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
69
- `,W=W.replace(this.ANSI_PATTERN,""),this.fancy&&!W0()){let Q=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:e.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!W0())console.error(W.trim());await this.writeToFile(W)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new FX($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(W0())throw Error("createReadStream is not supported in browser environments");if(!EU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $f(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=z$.isBuffer(w)?w:z$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),j=lF("aes-256-gcm",Y,X);return j.setAuthTag(J),z$.concat([j.update(U),j.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return W0()}isServerMode(){return!W0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!W0()){let J=w.split(`
70
- `),U=Math.max(...J.map((z)=>z.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((z)=>{let f=" ".repeat(U-z.length-2);return`│ ${z}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:e.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(j)})),Q.forEach((z)=>console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(z),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(W),showTimestamp:!1}))}else if(!W0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
71
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(W0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${e.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();_0.stdin.removeListener("data",Y);try{if(typeof _0.stdin.setRawMode==="function")_0.stdin.setRawMode(!1)}catch{}_0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof _0.stdin.setRawMode==="function")_0.stdin.setRawMode(!0)}catch{}_0.stdin.resume(),_0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let X=/%([sdijfo%])/g,J=0;if(Y=w.replace(X,(U,j)=>{if(j==="%")return"%";if(J>=$.length)return U;let W=$[J++];switch(j){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 U}}),J<$.length)Y+=` ${$.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!W0()){let X=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",J=e.blue("◐");console.error(`${J} ${X} ${e.cyan(Y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
72
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress(w,$=""){if(!this.enabled||!this.fancy||W0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,X)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,A)),X!==void 0)this.activeProgressBar.message=X;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(A)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,A!==void 0)this.activeProgressBar.message=A;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(A,X="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;_0.stdout.write(`${"\r".padEnd(_0.stdout.columns||80)}\r`),this.log(X,A),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||W0()||!_0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=e.green("━".repeat(A)),U=e.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",z=$||Y===100?e.green("✓"):e.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${e.gray(this.formatTag(this.name))}`:"",B=`\r${z}${f} ${j} ${W}${Q}`,G=_0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,_0.stdout.write(w.lastRenderedLine),$)_0.stdout.write(`
73
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||W0()||!_0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await vA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=B1(this.config.logDirectory,A);if(w.before)try{if((await f1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await cA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function YX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&t($[0])&&"id"in $[0]&&$[0].id===3&&t($[1])&&"id"in $[1]&&$[1].id===4)return $;if(t($)&&t(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(t(w)&&"arr"in w&&Array.isArray(w.arr)&&t($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&t($[0])&&t(w[0])){let A=[...$];for(let X of w)if(t(X)&&"name"in X){if(!A.find((J)=>t(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(t(X)&&"path"in X){if(!A.find((J)=>t(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>EX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!t($)||!t(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(t(X)&&t(Y[A]))Y[A]=YX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&t(X[0])&&t(Y[A][0])){let J=[...X];for(let U of Y[A])if(t(U)&&"name"in U){if(!J.find((j)=>t(j)&&("name"in j)&&j.name===U.name))J.push(U)}else if(t(U)&&"path"in U){if(!J.find((j)=>t(j)&&("path"in j)&&j.path===U.path))J.push(U)}else if(!J.some((j)=>EX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function AW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:YX(w,$);if(Array.isArray(w))return Y==="replace"?$:YX(w,$);if(!t($)||!t(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=YX(U,J);else if(t(J)&&t(U))A[X]=AW(U,J,Y);else A[X]=J}return A}function EX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!EX(w[Y],$[Y]))return!1;return!0}if(t(w)&&t($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!EX(w[X],$[X]))return!1}return!0}return!1}function t(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function oA(w,$,Y="replace"){if(!wB(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return AW($,X,Y)}catch{return null}}catch{return null}}function PE(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,z]of Object.entries(U)){let f=[...j,Q],B=(F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${f.map(B).join("_")}`,T=`${A}_${f.map((F)=>F.toUpperCase()).join("_")}`;if(Y)D0.info(`Checking environment variable ${G} for config ${w}.${f.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[Q]=J(z,f);else{let F=JY.env[G]||JY.env[T];if(F!==void 0){if(Y)D0.info(`Using environment variable ${F?G:T} for config ${w}.${f.join(".")}`);if(typeof z==="number")W[Q]=Number(F);else if(typeof z==="boolean")W[Q]=F.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(F);if(Array.isArray(E))W[Q]=E;else W[Q]=F.split(",").map((N)=>N.trim())}catch{W[Q]=F.split(",").map((E)=>E.trim())}else W[Q]=F}}}return W}return J(X)}async function iE({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?PE(w,X,J):X,Q=Y||JY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let f=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],F=Array.from(new Set([Q,d0(Q,"config"),d0(Q,".config"),A?d0(Q,A):void 0].filter(Boolean)));for(let E of F){if(J)D0.info(`Searching for configuration in: ${E}`);let N=[d0(Q,"config"),d0(Q,".config")].concat(A?[d0(Q,A)]:[]).includes(E)?[...f,...B,...G,...T]:[...B,...f,...T,...G];for(let R of N)for(let V of z){let L=d0(E,`${R}${V}`),q=await oA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from: ${L}`);return q}}}if(w){let E=d0(GU(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)D0.info(`Checking user config directory: ${E}`);for(let R of N)for(let V of z){let L=d0(E,`${R}${V}`),q=await oA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user config directory: ${L}`);return q}}}if(w){let E=d0(GU(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=d0(E,`${R}${V}`),q=await oA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user config directory dotfile: ${L}`);return q}}}if(w){let E=GU(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=d0(E,`${R}${V}`),q=await oA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user home directory: ${L}`);return q}}}try{let E=d0(Q,"package.json");if(wB(E)){let N=await import(E),R=N[w];if(!R&&$){if(R=N[$],R&&J)D0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)D0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return AW(W,R,j)}catch(V){if(J)D0.warn("Failed to merge package.json config:",V)}}}catch(E){if(J)D0.warn("Failed to load package.json:",E)}if(J)D0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function bE(w,$={}){let Y=QX.cwd();while(Y.includes("storage"))Y=ez(Y,"..");let A=ez(Y,w||"");if($?.relative)return mF(QX.cwd(),A);return A}async function uE(){try{let w=await iE({name:"clarity",alias:"logging",defaultConfig:JX,cwd:QX.cwd()});return{...JX,...w||{}}}catch{return JX}}function T0(){if(nw.env.NODE_ENV==="test"||nw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vE(){if(nw.env.NODE_ENV==="test"||nw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof nw<"u"){let w=nw.type;if(w==="renderer"||w==="worker")return!1;return!!(nw.versions&&(nw.versions.node||nw.versions.bun))}return!1}class UB{async format(w){let $=await vE(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:E1.pid,hostname:$(),environment:E1.env.NODE_ENV||"development",platform:E1.platform,version:E1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:E1.env.NODE_ENV||E1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class TX{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=w,this.config={...vU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new UB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??p.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...UX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...UX};return{...UX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:vU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await YE(this.config.logDirectory,zf.F_OK|zf.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await AE(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:cw.from(w);try{if(!mA(this.currentLogFile))await HU(this.currentLogFile,"",{mode:420});if(A=Qf(this.currentLogFile,"a",420),$E(A,j,{flag:"a"}),jf(A),A!==void 0)qU(A),A=void 0;if((await K1(this.currentLogFile)).size===0){if(await HU(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(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let z=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let f=U*2**X;await new Promise((B)=>setTimeout(B,f)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{qU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,z=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}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 w=new Date().toISOString().split("T")[0];return F1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return NU(16).toString("hex")}generateKey(){return NU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=NU(16),A=oF("aes-256-gcm",$,Y),X=cw.isBuffer(w)?w:cw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=cw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Bf(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(cw.from(cw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let w=await K1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await gA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await K1(Y).catch(()=>null))try{if(await ff(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await dA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await HU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await K1(Y).catch(()=>null))await ff(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await gA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await dA(F1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Wf(w),A=wE($),X=Bf();await UE(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),mA(this.currentLogFile))try{let w=Qf(this.currentLogFile,"r+");jf(w),qU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await gA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await dA(F1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?u.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let w=typeof p.env.NO_COLOR<"u",$=p.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof p.stderr<"u"&&p.stderr.isTTY||typeof p.stdout<"u"&&p.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=p.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${u.cyan(X)}`;if(!U)return Q.trim();let z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),$}supportsHyperlinks(){if(T0())return!1;let w=p.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=p.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(XE($)||$.startsWith("./")||$.startsWith("../"))$=JE($);else return null;return mA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":EB[w],B=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:u.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:u.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
74
- `);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:u.gray(` ${F}`),level:w,showTimestamp:!1}))}break}}else if(!T0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let z=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
75
- `;if(j)z+=`${j}
76
- `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!T0()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!T0()&&p.stdout.isTTY)p.stdout.write(`
77
- `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!T0()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":u.blue("◐"),tag:Y,message:`${u.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
78
- `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":u.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T0())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new TX($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(T0())throw Error("createReadStream is not supported in browser environments");if(!mA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Wf(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=cw.isBuffer(w)?w:cw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=eF("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),z=W.length+Q.length,f=cw.allocUnsafe(z);return W.copy(f,0),Q.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T0()}isServerMode(){return!T0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
79
- `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,f=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:u.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(Q),showTimestamp:!1})),f.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(z),showTimestamp:!1}))}else if(!T0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
80
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(T0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${u.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();p.stdin.removeListener("data",Y);try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!1)}catch{}p.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!0)}catch{}p.stdin.resume(),p.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let z=$[j++];switch(Q){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${j}${U} ${u.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
81
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!p.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=u.green("━".repeat(A)),U=u.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",z=this.options.showIcons===!1?"":$||Y===100?u.green("✓"):u.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",B=`\r${z}${f} ${j} ${W}${Q}`,G=p.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,p.stdout.write(w.lastRenderedLine),$)p.stdout.write(`
82
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||T0()||!p.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(T0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await gA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=F1(this.config.logDirectory,A);if(w.before)try{if((await K1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await dA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function WB(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function jB(w){return w instanceof ww}function cE(w){return w instanceof NX}function mE(w){if(jB(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some(($)=>w.message.toLowerCase().includes($.toLowerCase()))}class LX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix(w),f={...$};return this.processObject(f,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return QY.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=nA.env[W]||(Q?nA.env[Q]:void 0);if(z!==void 0){if(A.verbose){let f=nA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(f){if(f instanceof qX)throw f;throw B$.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw B$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(nA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
58
+ `;r+=`| Variable | Type | Description | Example |
59
+ `,r+=`|----------|------|-------------|----------|
60
+ `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
61
+ `;return r}}function Cx(e,t,r={}){return tg(e,t,r,new WeakMap)}function tg(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return rg(e,t,i,n);if(!yt(t)||!yt(e))return t;return Tx(e,t,r,n)}function rg(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return xx(e,t);case"smart":return Sx(e,t,n);default:return t}return t}function xx(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Wl(i,n)))r.push(n);return r}function Sx(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(yt(t[0])&&yt(e[0]))return Ex(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function Ex(e,t,r){let n=[...t];for(let i of e){if(!yt(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>yt(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function Tx(e,t,r,n){let i=t;if(yt(i)&&n.has(i))return n.get(i);let s={...e};if(yt(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(yt(c)&&yt(a))s[o]=tg(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=rg(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function ng(e,t,r="replace"){return Cx(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Wl(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Wl(e[r],t[r]))return!1;return!0}if(yt(e)&&yt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Wl(e[i],t[i]))return!1}return!0}return!1}function yt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ig{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=no.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Js(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new po(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new po(e,Error("Configuration must export a valid object"),"unknown");let p={config:ng(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)no.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?pn.configLoad(e,l):pn.configLoad(e,Error(String(l)))}};if(o)return Vl.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(kl(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of n){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let i=new Set;return r.filter((s)=>{if(!s||i.has(s))return!1;return i.add(s),!0})}checkFileAccess(e){return $x(async()=>Js(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Js(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=kl(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=kl(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Js(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class sg{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await Vl.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Px(t))throw new yo(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new yo(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Ax},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function Rx(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class og{fileLoader=new ig;envProcessor=new Ql;validator=new sg;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)Dt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw Dt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||wo.cwd(),h=[],d=await this.loadLocalConfiguration(n,i,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(n,i,f,o)),this.finalizeResult(d,h,a,n,u);let y=await this.loadHomeConfiguration(n,i,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(y,h,a,n,u);let g=await this.loadPackageJsonConfiguration(n,i,f,c,l,u,a);if(g)return h.push(gt(f,"package.json")),this.finalizeResult(g,h,a,n,u);if(h.push(...this.getAllSearchPaths(n,i,f,o)),t)throw pn.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,u),warnings:[`No configuration file found for "${n}"${Rx(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?Xs(e,i,o):i,u=this.getLocalDirectories(r,n);for(let f of u){if(o)Dt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Dt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?Xs(e,r,i):r,c=[gt(nn(),".config",e),gt(nn(),".config"),nn()];for(let a of c){if(i)Dt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(u){if(i)Dt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?Xs(e,n,s):n;try{let a=gt(r,"package.json");if(!C$(a))return null;let l={};try{l=JSON.parse(x$(a,"utf8"))}catch(h){if(s)Dt.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=l[e],f=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){u=l[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Dt.success(`Configuration loaded from package.json: ${f}`);return{config:ng(c,u,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Dt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Xs(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw pn.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return no.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);no.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,gt(e,"config"),gt(e,".config"),t?gt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(gt(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[gt(nn(),".config",e),gt(nn(),".config"),nn()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}async function ag(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Ol.loadConfig(e);else n=await Ol.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)Dt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Ol.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function Xs(e,t,r=!1){let n=new Ql,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((g)=>g.toUpperCase()).join("")}`,`${i}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=wo.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}var no,Vl,cC,lC=(e)=>e,fC=(e,t)=>{for(var r in t)cC(e,r,{get:t[r],enumerable:!0,configurable:!0,set:uC.bind(t,r)})},hC=(e,t)=>()=>(e&&(t=e(e=0)),t),Rm,Mm,gn,$i,_m,_C,jC,dm,Qs,Ll,Ie,re,UC,mm,KC,gm,WC,VC,El,HC,pm,ym,Tl,zC,GC,qC,YC,eo,jm,JC,Me,XC,ZC,wm,to,Bl,$e,K,QC,vm,ex,bm,tx,rx,Pl,nx,$m,Cm,ix,Al,sx,ox,ax,cx,lx,ro,Um,ux,fx="0.15.6",ot,ho,vi,Il,Ml,mo,_l,jl,bi,Ul,Kl,vr,Km,Wm,Et,zt,Vm,Hm,hx,mx,zm,go,QO,ke,H,eN,px,tN,yx,rN,nN,xm,iN,wx,vx,sN,Sm,oN,aN,cN,lN,uN,Rl,bx,fN,Tt,qm,po,Ym,Jm,Zl,Xm,Zm,yo,Qm,eg,pn,Ax,Dt,Ol,pN,yN;var cg=te(()=>{no=new Em,Vl=new Tm,cC=Object.defineProperty;Rm={};fC(Rm,{withErrorRecovery:()=>Nm,tryLoadConfig:()=>LC,loadConfigWithResult:()=>DC,loadConfig:()=>Im,isRetryableError:()=>PC,isConfigNotFoundError:()=>TC,isBunfigError:()=>Dm,globalPerformanceMonitor:()=>$i,globalCache:()=>gn,getEnvOrDefault:()=>AC,generateConfigTypes:()=>BC,defaultGeneratedDir:()=>Hm,defaultConfigDir:()=>Vm,deepMergeWithArrayStrategy:()=>Yl,deepMerge:()=>Fm,createLibraryConfig:()=>IC,config:()=>FC,bunfigPlugin:()=>MC,applyEnvVarsToConfig:()=>yi,TypeGenerationError:()=>jl,SchemaValidationError:()=>bi,PluginError:()=>Kl,PerformanceMonitor:()=>zl,FileSystemError:()=>_l,ErrorFactory:()=>vr,EnvVarError:()=>mo,EnvProcessor:()=>vo,ConfigValidator:()=>Jl,ConfigValidationError:()=>Il,ConfigNotFoundError:()=>ho,ConfigMergeError:()=>Ml,ConfigLoader:()=>Xl,ConfigLoadError:()=>vi,ConfigFileLoader:()=>bo,ConfigCache:()=>Hl,CacheUtils:()=>_m,BunfigError:()=>ot,BrowserConfigError:()=>Ul,ArrayMergeStrategies:()=>Km});hx=hC(async()=>{Mm=import.meta.require,gn=new Hl,$i=new zl,_m={createKey:dC,isEquivalent:mC,estimateMemoryUsage:gC},_C=oo(Dl.cwd(),"config"),jC=oo(Dl.cwd(),"src/generated"),dm=so.env.CLARITY_LOG_DIR||R$(wC(),"logs"),Qs={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:dm,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ll=await vC(),Ie={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},re=Ie,UC=Ie.red,mm=Ie.green,KC=Ie.yellow,gm=Ie.blue,WC=Ie.magenta,VC=Ie.cyan,El=Ie.white,HC=Ie.gray,pm=Ie.bgRed,ym=Ie.bgYellow,Tl=Ie.bold,zC=Ie.dim,GC=Ie.italic,qC=Ie.underline,YC=Ie.reset,eo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jm={debug:"\uD83D\uDD0D",info:gm("ℹ"),success:mm("✓"),warning:ym(El(Tl(" WARN "))),error:pm(El(Tl(" ERROR ")))},JC=new lo("stacks"),Me=new lo("bunfig",{showTags:!0}),XC=qe(wi.cwd(),"config"),ZC=qe(wi.cwd(),"src/generated"),wm=io.env.CLARITY_LOG_DIR||P$(xC(),"logs"),to={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wm,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Bl=await SC(),$e={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},K=$e,QC=$e.red,vm=$e.green,ex=$e.yellow,bm=$e.blue,tx=$e.magenta,rx=$e.cyan,Pl=$e.white,nx=$e.gray,$m=$e.bgRed,Cm=$e.bgYellow,ix=$e.bgGray,Al=$e.bold,sx=$e.dim,ox=$e.italic,ax=$e.underline,cx=$e.strikethrough,lx=$e.reset,ro={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Um={debug:"\uD83D\uDD0D",info:bm("ℹ"),success:vm("✓"),warning:Cm(Pl(Al(" WARN "))),error:$m(Pl(Al(" ERROR ")))},ux=new fo("stacks"),ot=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,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 t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},ho=class extends ot{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},vi=class extends ot{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Il=class extends ot{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Ml=class extends ot{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},mo=class extends ot{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},_l=class extends ot{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},jl=class extends ot{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},bi=class extends ot{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Ul=class extends ot{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},Kl=class extends ot{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},vr={configNotFound(e,t,r){return new ho(e,t,r)},configLoad(e,t,r){return new vi(e,t,r)},configValidation(e,t,r){return new Il(e,t,r)},configMerge(e,t,r,n){return new Ml(e,t,r,n)},envVar(e,t,r,n){return new mo(e,t,r,n)},fileSystem(e,t,r){return new _l(e,t,r)},typeGeneration(e,t,r){return new jl(e,t,r)},schemaValidation(e,t,r){return new bi(e,t,r)},browserConfig(e,t,r,n){return new Ul(e,t,r,n)},plugin(e,t,r){return new Kl(e,t,r)}},Km={replace:"replace",concat:"concat",smart:"smart"},Wm=/^https?:\/\//,Et=new fo("bunfig",{showTags:!0}),zt=new Xl,Vm=Ye(_r.cwd(),"config"),Hm=Ye(_r.cwd(),"src/generated")});mx=ao.env.CLARITY_LOG_DIR||X$(dx(),"logs"),zm={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:mx,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},go={...zm},QO=(async()=>{try{let{loadConfig:e}=await hx().then(()=>Rm),t=await e({name:"clarity",alias:"logging",defaultConfig:zm,cwd:ao.cwd()});if(t)Object.assign(go,t)}catch{}return go})();ke={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},H=ke,eN=ke.red,px=ke.green,tN=ke.yellow,yx=ke.blue,rN=ke.magenta,nN=ke.cyan,xm=ke.white,iN=ke.gray,wx=ke.bgRed,vx=ke.bgYellow,sN=ke.bgGray,Sm=ke.bold,oN=ke.dim,aN=ke.italic,cN=ke.underline,lN=ke.strikethrough,uN=ke.reset,Rl={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bx={debug:"\uD83D\uDD0D",info:yx("ℹ"),success:px("✓"),warning:vx(xm(Sm(" WARN "))),error:wx(xm(Sm(" ERROR ")))};fN=new $o("stacks");Tt=class Tt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};qm=class qm extends Tt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};po=class po extends Tt{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};Ym=class Ym extends Tt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Jm=class Jm extends Tt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};Zl=class Zl extends Tt{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};Xm=class Xm extends Tt{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Zm=class Zm extends Tt{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};yo=class yo extends Tt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Qm=class Qm extends Tt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};eg=class eg extends Tt{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};pn={configNotFound(e,t,r){return new qm(e,t,r)},configLoad(e,t,r){return new po(e,t,r)},configValidation(e,t,r){return new Ym(e,t,r)},configMerge(e,t,r,n){return new Jm(e,t,r,n)},envVar(e,t,r,n){return new Zl(e,t,r,n)},fileSystem(e,t,r){return new Xm(e,t,r)},typeGeneration(e,t,r){return new Zm(e,t,r)},schemaValidation(e,t,r){return new yo(e,t,r)},browserConfig(e,t,r,n){return new Qm(e,t,r,n)},plugin(e,t,r){return new eg(e,t,r)}};Ax=/^https?:\/\//;Dt=new $o("bunfig",{showTags:!0});Ol=new og;pN=gt(wo.cwd(),"config"),yN=gt(wo.cwd(),"src/generated")});import{homedir as eu}from"node:os";import{join as tu,resolve as kx}from"node:path";async function ug(){if(!ru)ru=await ag({name:"rpx",cwd:kx(__dirname,".."),defaultConfig:lg});return ru}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",lg,ru=null,Gt;var Co=te(()=>{cg();lg={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:tu(eu(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:tu(eu(),".stacks","ssl","stacks.localhost.crt"),keyPath:tu(eu(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};Gt=lg});function yn(e){return e.startsWith("*.")}function Ur(e,t){if(!yn(t))return!1;let r=t.slice(1);return e.length>r.length&&e.endsWith(r)}function fg(e,t){let r=e.get(t);if(r!==void 0)return r;let n,i=-1;for(let[s,o]of e){if(!yn(s))continue;if(Ur(t,s)){let c=s.length-1;if(c>i)i=c,n=o}}return n}import{existsSync as Ox,readdirSync as Nx,readFileSync as Dx,statSync as Fx}from"node:fs";import{homedir as dg}from"node:os";import{isAbsolute as Lx,join as wn}from"node:path";function iu(e,t){if(e==="~")return t;if(e.startsWith("~/"))return wn(t,e.slice(2));return e}function Ix(e){let t=e.indexOf(":");return(t===-1?e:e.slice(0,t)).toLowerCase()}function xo(e){return e.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function Mx(e,t){for(let r of t){let n=`.${r}`;if(e.endsWith(n)){let i=e.slice(0,-n.length);if(i.length>0&&!i.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(i))return i}}return null}function _x(e,t){let r=t.readText(wn(e,"rpx.site.json"));if(r)try{let i=JSON.parse(r);if(i&&typeof i==="object")return i}catch{}let n=t.readText(wn(e,"package.json"));if(n)try{let i=JSON.parse(n);if(i.rpx&&typeof i.rpx==="object")return i.rpx}catch{}return null}function jx(e){let t=e.selfRegisters??!1;return{command:e.command,env:e.env,urlEnv:e.urlEnv,selfRegisters:t,routes:e.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function Ux(e,t){let r=_x(e,t);if(r?.command)return jx(r);let n=t.fileExists(wn(e,"buddy")),i=t.readText(wn(e,"package.json")),s=null;if(i)try{s=JSON.parse(i)}catch{s=null}let o={...s?.dependencies??{},...s?.devDependencies??{}};if(n||Object.keys(o).some((a)=>a==="stacks"||a.startsWith("@stacksjs/")))return{command:n?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(s?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function su(e,t={}){let r={dirExists:t.dirExists??nu.dirExists,fileExists:t.fileExists??nu.fileExists,readText:t.readText??nu.readText},n=t.detect??Ux,i=t.homeDir??dg(),s=e.tlds??gg,o=(e.roots??mg).map((h)=>iu(h,i)),c=e.idleTimeoutMs??Bx,a=new Map;for(let h of e.sites??[])a.set(h.to,h);let l=(h)=>h.idleTimeoutMs??c;function u(h){let d=fg(a,h);if(!d)return null;let y=Lx(d.dir)?d.dir:iu(d.dir,i),g=d.selfRegisters??!1,p=d.routes??[];if(!g&&p.length===0)p=n(y,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let w=hg({...d.env??{}},void 0,h);return{host:h,id:xo(h),dir:y,command:d.command,env:w,routes:p,selfRegisters:g,idleTimeoutMs:l(d),source:"config"}}function f(h){let d=Mx(h,s);if(!d)return null;for(let y of o){let g=wn(y,d);if(!r.dirExists(g))continue;let p=n(g,r);if(!p)continue;let w=p.selfRegisters??!1;return{host:h,id:xo(h),dir:g,command:p.command,env:hg({...p.env??{}},p.urlEnv,h),routes:w?[]:p.routes??[],selfRegisters:w,idleTimeoutMs:c,source:"discovered"}}return null}return{resolve(h){let d=Ix(h);if(!d)return null;return u(d)??f(d)}}}function Kx(e){try{return Nx(e,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function pg(e,t={}){let r=t.homeDir??dg(),n=e.tlds??gg,i=(e.roots??mg).map((f)=>iu(f,r)),s=t.readdir??Kx,o=su(e,t),c=[],a=new Set,l=(f)=>{if(f&&!a.has(f.host))a.add(f.host),c.push(f)};for(let f of e.sites??[])if(!f.to.includes("*"))l(o.resolve(f.to));let u=n[0]??"localhost";for(let f of i)for(let h of s(f))l(o.resolve(`${h}.${u}`));return c}function hg(e,t,r){if(!t)return e;let n=`https://${r}`;for(let i of t)if(e[i]===void 0)e[i]=n;return e}var mg,gg,Bx=1800000,nu;var ou=te(()=>{mg=["~/Code"],gg=["localhost","test"],nu={dirExists:(e)=>{try{return Fx(e).isDirectory()}catch{return!1}},fileExists:(e)=>{try{return Ox(e)}catch{return!1}},readText:(e)=>{try{return Dx(e,"utf8")}catch{return null}}}});var b;var qt=te(()=>{b={info:(...e)=>console.log("[info]",...e),success:(...e)=>console.log("[success]",...e),warn:(...e)=>console.warn("[warn]",...e),error:(...e)=>console.error("[error]",...e),debug:(...e)=>console.debug("[debug]",...e),log:(...e)=>console.log(...e),start:(...e)=>console.log("[start]",...e),box:(...e)=>console.log("[box]",...e)}});import{createRequire as Wx}from"node:module";import{Resolver as au}from"node:dns/promises";import yg from"node:process";import{createHash as Vx,sign as Hx}from"node:crypto";import{createHash as zx}from"node:crypto";import{sign as Gx}from"node:crypto";import{generateKeyPairSync as dp,X509Certificate as rS}from"node:crypto";import cu from"node:os";import lu from"node:path";import{existsSync as vg,statSync as bg}from"fs";import{existsSync as iS,mkdirSync as UN,readdirSync as KN,readFileSync as sS,writeFileSync as WN}from"fs";import{homedir as vn}from"os";import{dirname as zN,resolve as wt}from"path";import ua from"process";import{existsSync as $g,statSync as Cg}from"fs";import{existsSync as Ou,mkdirSync as oS,readdirSync as aS,writeFileSync as cS}from"fs";import{homedir as bn}from"os";import{dirname as xg,resolve as Xe}from"path";import Vr from"process";import{join as lS,relative as uS,resolve as Sg}from"path";import qo from"process";import{existsSync as gp,mkdirSync as rD,readdirSync as nD,writeFileSync as iD}from"fs";import{homedir as uu}from"os";import{dirname as aD,resolve as Je}from"path";import Ni from"process";import{join as fS,relative as hS,resolve as Eg}from"path";import Yo from"process";import{existsSync as pp,mkdirSync as hD,readdirSync as dD,writeFileSync as mD}from"fs";import{dirname as pD,resolve as Jo}from"path";import Nu from"process";import{Buffer as br}from"buffer";import{createCipheriv as dS,createDecipheriv as mS,randomBytes as fu}from"crypto";import{closeSync as hu,createReadStream as Tg,createWriteStream as gS,existsSync as du,fsyncSync as Pg,openSync as Ag,writeFileSync as pS}from"fs";import{access as yS,constants as Rg,mkdir as wS,readdir as So,rename as kg,stat as $n,unlink as Eo,writeFile as mu}from"fs/promises";import{join as Cn}from"path";import _e from"process";import{pipeline as vS}from"stream/promises";import{createGzip as Og}from"zlib";import xn from"process";import Xt from"process";import{Buffer as Yt}from"buffer";import{createCipheriv as bS,createDecipheriv as $S,randomBytes as gu}from"crypto";import{closeSync as pu,createReadStream as Ng,createWriteStream as CS,existsSync as To,fsyncSync as Dg,openSync as Fg,writeFileSync as xS}from"fs";import{access as SS,constants as Lg,mkdir as ES,readdir as Po,rename as Bg,stat as Sn,unlink as Ao,writeFile as yu}from"fs/promises";import{isAbsolute as TS,join as En,resolve as PS}from"path";import J from"process";import{pipeline as AS}from"stream/promises";import{createGzip as Ig}from"zlib";import Tn from"process";import Zt from"process";import Ro from"process";import{existsSync as ko}from"fs";import{resolve as wu}from"path";import{existsSync as RS}from"fs";import{existsSync as kS,readdirSync as OS}from"fs";import{extname as vu,resolve as Mg}from"path";import NS from"process";import{join as DS,relative as FS,resolve as _g}from"path";import Xo from"process";import{Buffer as Jt}from"buffer";import{createCipheriv as LS,createDecipheriv as BS,randomBytes as bu}from"crypto";import{closeSync as $u,createReadStream as jg,createWriteStream as IS,existsSync as Oo,fsyncSync as Ug,openSync as Kg,writeFileSync as MS}from"fs";import{access as _S,constants as Wg,mkdir as jS,readdir as No,rename as Vg,stat as Pn,unlink as Do,writeFile as Cu}from"fs/promises";import{isAbsolute as US,join as An,resolve as KS}from"path";import X from"process";import{pipeline as WS}from"stream/promises";import{createGzip as Hg}from"zlib";import Rn from"process";import Qt from"process";import Fo from"process";import{existsSync as Lo}from"fs";import{resolve as xu}from"path";import{existsSync as VS}from"fs";import{exec as d0}from"node:child_process";import On from"node:fs";import Wu from"node:os";import nt from"node:path";import Zp from"node:process";import{promisify as m0}from"node:util";import Ii from"node:crypto";import Kr from"node:fs";import b0 from"node:tls";import C0 from"node:crypto";import x0 from"node:fs";import A0 from"node:crypto";import jn from"node:crypto";import Lt from"node:fs";import Ln from"node:path";import z0 from"node:process";import er from"node:fs";import zu from"node:path";import{execSync as X0}from"node:child_process";import Nn from"node:fs";import Bt from"node:os";async function kn(e,t={},r=30000){try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(n){if(n&&typeof n==="object"&&n.name==="TimeoutError"){let i=Error(`ACME HTTP request to ${e} timed out after ${r}ms`);throw i.name="AcmeRequestTimeoutError",i}throw n}}async function Gu(e,t,r={}){let n=r.timeoutMs??120000,i=r.intervalMs??3000,s=e.split(".").slice(-2).join("."),o;try{let l=new au,u=await l.resolveNs(s),f=(await Promise.all(u.map((h)=>l.resolve4(h).catch(()=>[])))).flat();if(f.length>0)o=new au,o.setServers(f)}catch{}let c=Date.now()+n,a=o??new au;for(;;){try{if((await a.resolveTxt(e)).some((l)=>l.join("")===t))return!0}catch{}if(Date.now()>=c)return!1;await new Promise((l)=>setTimeout(l,i))}}function Vo(e){let t=e.split(".");if(t.length<=2)return{apex:e,subdomain:""};let r=t.slice(-2).join("."),n=t.slice(0,-2).join(".");return{apex:r,subdomain:n}}class qu{apiKey;secretApiKey;baseUrl;requestTimeoutMs;constructor(e){let t=e?.apiKey??yg.env.PORKBUN_API_KEY,r=e?.secretApiKey??yg.env.PORKBUN_SECRET_KEY;if(!t||!r)throw Error("Porkbun credentials missing: set PORKBUN_API_KEY and PORKBUN_SECRET_KEY (or pass them in)");this.apiKey=t,this.secretApiKey=r,this.baseUrl=e?.baseUrl??"https://api.porkbun.com/api/json/v3",this.requestTimeoutMs=e?.requestTimeoutMs??ca}async post(e,t){let r=await kn(`${this.baseUrl}${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretApiKey,...t})},this.requestTimeoutMs),n=await r.json().catch(()=>({}));if(!r.ok||n.status!=="SUCCESS")throw Error(`Porkbun API ${e} failed: ${n.message??`HTTP ${r.status}`}`);return n}async setTxt(e,t){let{apex:r,subdomain:n}=Vo(e);await this.post(`/dns/create/${r}`,{type:"TXT",name:n,content:t,ttl:"600"})}async removeTxt(e,t){let{apex:r,subdomain:n}=Vo(e),i=n?`${n}.${r}`:r,s=(await this.post(`/dns/retrieveByNameType/${r}/TXT/${n}`,{}).catch(()=>null))?.records??[];for(let o of s)if(o.content===t&&(o.name===i||o.name===r))await this.post(`/dns/delete/${r}/${o.id}`,{}).catch(()=>{})}}class Wr{tokens=new Map;add(e,t){this.tokens.set(e,t)}get(e){return this.tokens.get(e)}remove(e){this.tokens.delete(e)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(e){let t=e.indexOf(Wr.PATH_PREFIX);if(t===-1)return;let r=e.slice(t+Wr.PATH_PREFIX.length);return this.get(r)}}function Pi(e){return(typeof e==="string"?Buffer.from(e,"utf8"):Buffer.from(e)).toString("base64url")}function Ri(e){return Buffer.from(e,"base64url")}function up(e){return Ri(e).toString("utf8")}function Ju(e){let t=e.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function Xu(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}","y":"${e.y}"}`;return Vx("sha256").update(t).digest("base64url")}function Zu(e){let{protectedHeader:t,payload:r,privateKey:n}=e,i=Pi(JSON.stringify(t)),s=r===""?"":Pi(JSON.stringify(r)),o=`${i}.${s}`,c=Hx("sha256",Buffer.from(o),{key:n,dsaEncoding:"ieee-p1363"});return{protected:i,payload:s,signature:Pi(c)}}class Oi{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(e){this.directoryUrl=e.directoryUrl,this.accountKey=e.accountKey,this.jwk=Ju(e.accountPublicKey),this.thumbprint=Xu(this.jwk),this.requestTimeoutMs=e.requestTimeoutMs??ca}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let e=await kn(this.directoryUrl,{},this.requestTimeoutMs);if(!e.ok)throw Error(`Failed to fetch ACME directory: HTTP ${e.status}`);return this.directoryCache=await e.json(),this.directoryCache}async newNonce(){let e=await this.directory(),t=(await kn(e.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let e=this.nonce;return this.nonce=void 0,e}return this.newNonce()}async signedPost(e){let{url:t,payload:r,useJwk:n}=e,i={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(n)i.jwk=this.jwk;else i.kid=this.requireKid();let s=Zu({protectedHeader:i,payload:r,privateKey:this.accountKey}),o=await kn(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(s)},this.requestTimeoutMs),c=o.headers.get("replay-nonce");if(c)this.nonce=c;let a=o.headers.get("content-type")??"",l;if(a.includes("application/pem-certificate-chain")||a.startsWith("text/"))l=await o.text();else{let u=await o.text();l=u?JSON.parse(u):{}}if(o.status>=400){let u=l??{};throw new ki(`ACME request to ${t} failed (HTTP ${o.status}): ${u.type??""} ${u.detail??""}`.trim(),u,o.status)}return{status:o.status,headers:o.headers,body:l,location:o.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(e={}){let t=await this.directory(),r={termsOfServiceAgreed:!0};if(e.email)r.contact=[`mailto:${e.email}`];let n=await this.signedPost({url:t.newAccount,payload:r,useJwk:!0});if(!n.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=n.location,this.accountKid}async newOrder(e){let t=await this.directory(),r={identifiers:e.map((i)=>({type:"dns",value:i}))},n=await this.signedPost({url:t.newOrder,payload:r});if(!n.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:n.body,orderUrl:n.location}}async getAuthorization(e){return(await this.signedPost({url:e,payload:""})).body}keyAuthorization(e){return`${e}.${this.thumbprint}`}dns01TxtValue(e){return zx("sha256").update(this.keyAuthorization(e)).digest("base64url")}async notifyChallengeReady(e){await this.signedPost({url:e,payload:{}})}async pollAuthorization(e,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,i=Date.now()+r;while(Date.now()<i){let s=await this.getAuthorization(e);if(s.status==="valid")return;if(s.status==="invalid"){let o=s.challenges.find((c)=>c.status==="invalid");throw new ki(`Authorization for ${s.identifier.value} became invalid: ${o?.error?.detail??"unknown reason"}`,o?.error??{},0)}await wg(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for authorization ${e} to become valid`)}async finalizeOrder(e,t){return(await this.signedPost({url:e,payload:{csr:t}})).body}async getOrder(e){return(await this.signedPost({url:e,payload:""})).body}async pollOrder(e,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,i=Date.now()+r;while(Date.now()<i){let s=await this.getOrder(e);if(s.status==="valid"){if(!s.certificate)throw Error("ACME order is valid but has no certificate URL");return s.certificate}if(s.status==="invalid")throw Error(`ACME order ${e} became invalid`);await wg(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for order ${e} to become valid`)}async downloadCertificate(e){let t=await this.signedPost({url:e,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(e,t){let r=e.challenges.find((n)=>n.type===t);if(!r)throw Error(`No ${t} challenge available for ${e.identifier.value}`);return r}}function tf(e){let t=e.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${e.trim()}
62
+ `,chainPem:""};let n=`${r.trim()}
63
+ `,i=t.slice(1).map((s)=>s.trim()).join(`
64
+ `);return{certPem:n,chainPem:i?`${i}
65
+ `:""}}function rf(e){return`_acme-challenge.${e.startsWith("*.")?e.slice(2):e}`}function wg(e){return new Promise((t)=>setTimeout(t,e))}function qx(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function rr(e,t){return Buffer.concat([Buffer.from([e]),qx(t.length),t])}function nf(e){let t;if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=[],n=e;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=e.length===0?Buffer.from([0]):e,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return rr(2,t)}function $r(e){let t=e.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${e}`);let r=[40*t[0]+t[1]];for(let n=2;n<t.length;n++){let i=t[n],s=[i&127];i=Math.floor(i/128);while(i>0)s.unshift(i&127|128),i=Math.floor(i/128);r.push(...s)}return rr(6,Buffer.from(r))}function fp(){return Buffer.from([5,0])}function at(...e){return rr(48,Buffer.concat(e))}function Ho(...e){return rr(49,Buffer.concat(e))}function zo(e){return rr(3,Buffer.concat([Buffer.from([0]),e]))}function sf(e){return rr(4,e)}function hp(e){return rr(19,Buffer.from(e,"ascii"))}function of(e){return rr(12,Buffer.from(e,"utf8"))}function Go(e,t,r){let n=128|(r?32:0)|e;return rr(n,t)}function tS(e){let t=e.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=Ri(t.x),n=Ri(t.y);if(r.length!==32||n.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${n.length}`);return Buffer.concat([Buffer.from([4]),r,n])}function af(e){let{domains:t,publicKey:r,privateKey:n}=e;if(t.length===0)throw Error("At least one domain is required to build a CSR");let i=at(Ho(at($r(Zx),of(t[0])))),s=at(at($r(Yx),$r(Jx)),zo(tS(r))),o=t.map((g)=>Go(2,Buffer.from(g,"ascii"),!1)),c=at(...o),a=at($r(eS),sf(c)),l=at(a),u=at($r(Qx),Ho(l)),f=Go(0,u,!0),h=at(nf(0),i,s,f),d=Gx("sha256",h,n),y=at($r(Xx));return at(h,y,zo(d))}function cf(e){return af(e).toString("base64url")}function nS(e){if(e){let{createPrivateKey:i,createPublicKey:s}=xi("node:crypto"),o=i(e),c=s(o.export({format:"pem",type:"pkcs8"}));return{privateKey:o,publicKey:c,pem:e}}let{privateKey:t,publicKey:r}=dp("ec",{namedCurve:"P-256"}),n=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:n}}async function la(e){let{domains:t,method:r}=e;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!e.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((f)=>f.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=e.directoryUrl??(e.staging===!1?ef:Qu),i=nS(e.accountKeyPem),s=new Oi({directoryUrl:n,accountKey:i.privateKey,accountPublicKey:i.publicKey,requestTimeoutMs:e.requestTimeoutMs});await s.newAccount({email:e.email});let{order:o,orderUrl:c}=await s.newOrder(t),a=e.http01Store??Ui,l=[],u=[];try{for(let R of o.authorizations){let D=await s.getAuthorization(R);if(D.status==="valid")continue;let F=Oi.selectChallenge(D,r);if(r==="dns-01"){let x=rf(D.identifier.value),k=s.dns01TxtValue(F.token);await e.dnsProvider.setTxt(x,k),l.push({name:x,value:k}),await Gu(x,k,{timeoutMs:e.dnsPropagationTimeoutMs??120000})}else a.add(F.token,s.keyAuthorization(F.token)),u.push(F.token);await s.notifyChallengeReady(F.url),await s.pollAuthorization(R,{timeoutMs:e.timeoutMs})}let{privateKey:f,publicKey:h}=dp("ec",{namedCurve:"P-256"}),d=cf({domains:t,publicKey:h,privateKey:f});await s.finalizeOrder(o.finalize,d);let y=await s.pollOrder(c,{timeoutMs:e.timeoutMs}),g=await s.downloadCertificate(y),{certPem:p,chainPem:w}=tf(g),v=w?`${p}${w}`:p,P=f.export({format:"pem",type:"pkcs8"}).toString(),A=new Date(new rS(p).validTo);return{certPem:p,keyPem:P,chainPem:w,fullChainPem:v,accountKeyPem:i.pem,notAfter:A}}finally{for(let{name:f,value:h}of l)await e.dnsProvider?.removeTxt(f,h).catch(()=>{});for(let f of u)a.remove(f)}}class yp{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!vg(e))return!0;return bg(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=vg(r)?bg(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class wp{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function GS(e,t){this[e]=zS.bind(null,t)}class uf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!$g(e))return!0;return Cg(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=$g(r)?Cg(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ff{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function JS(e,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${e}:${r}`:e}function XS(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function ZS(e){return e.getStats().size*2}function hf(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ce(t[0])&&"id"in t[0]&&t[0].id===3&&ce(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ce(t)&&ce(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(ce(e)&&"arr"in e&&Array.isArray(e.arr)&&ce(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ce(t[0])&&ce(e[0])){let n=[...t];for(let i of e)if(ce(i)&&"name"in i){if(!n.find((s)=>ce(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(ce(i)&&"path"in i){if(!n.find((s)=>ce(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>Qo(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!ce(t)||!ce(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(ce(i)&&ce(r[n]))r[n]=hf(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&ce(i[0])&&ce(r[n][0])){let s=[...i];for(let o of r[n])if(ce(o)&&"name"in o){if(!s.find((c)=>ce(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(ce(o)&&"path"in o){if(!s.find((c)=>ce(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((c)=>Qo(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function Qo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Qo(e[r],t[r]))return!1;return!0}if(ce(e)&&ce(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Qo(e[i],t[i]))return!1}return!0}return!1}function ce(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function QS(e,t){if(!pp(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return hf(t,n)}catch{return null}}catch{return null}}async function eE({name:e="",cwd:t,defaultConfig:r}){let n=t||Nu.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=Jo(n,`${o}${c}`),l=await QS(a,r);if(l!==null)return l}try{let o=Jo(n,"package.json");if(pp(o)){let c=(await import(o))[e];if(c&&typeof c==="object"&&!Array.isArray(c))try{return hf(r,c)}catch{}}}catch{}return r}function tE(e,t={}){let r=Yo.cwd();while(r.includes("storage"))r=Eg(r,"..");let n=Eg(r,e||"");if(t?.relative)return hS(Yo.cwd(),n);return n}async function rE(){try{let e=await eE({name:"clarity",defaultConfig:jo,cwd:Yo.cwd(),endpoint:"",headers:{}});return{...jo,...e}}catch{return jo}}function de(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nE(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Xt<"u"){let e=Xt.type;if(e==="renderer"||e==="worker")return!1;return!!(Xt.versions&&(Xt.versions.node||Xt.versions.bun))}return!1}class bp{async format(e){let t=await nE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:xn.pid,hostname:t(),environment:xn.env.NODE_ENV||"development",platform:xn.platform,version:xn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xn.env.NODE_ENV||xn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ea{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(e,t={}){this.name=e,this.config={...Fu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new bp,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_e.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Uo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Uo};return{...Uo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Fu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await yS(this.config.logDirectory,Rg.F_OK|Rg.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await wS(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:br.from(e);try{if(!du(this.currentLogFile))await mu(this.currentLogFile,"",{mode:420});if(n=Ag(this.currentLogFile,"a",420),pS(n,c,{flag:"a"}),Pg(n),n!==void 0)hu(n),n=void 0;if((await $n(this.currentLogFile)).size===0){if(await mu(this.currentLogFile,c,{flag:"w",mode:420}),(await $n(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(i<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let f=o*2**i;await new Promise((h)=>setTimeout(h,f)),i++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(n!==void 0)try{hu(n)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(i===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}i++;let a=o*2**(i-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 Cn(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 Cn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Cn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(de())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return fu(16).toString("hex")}generateKey(){return fu(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=fu(16),n=dS("aes-256-gcm",t,r),i=br.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:br.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Og(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(br.from(br.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(de())return;let e=await $n(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await So(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await $n(r).catch(()=>null))try{if(await kg(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Eo(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await mu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await $n(r).catch(()=>null))await kg(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await So(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Eo(Cn(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Tg(e),n=gS(t),i=Og();await vS(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),du(this.currentLogFile))try{let e=Ag(this.currentLogFile,"r+");Pg(e),hu(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!de()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await So(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Eo(Cn(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?ne.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=_e.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${ne.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!de()){let l=kp[e],u=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:ne.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:ne.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
66
+ `);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:ne.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!de()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
67
+ `;if(c)a+=`${c}
68
+ `;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!de()){let r=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:ne.blue("◐"),tag:r,message:`${ne.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),a=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
69
+ `,a=a.replace(this.ANSI_PATTERN,""),this.fancy&&!de()){let l=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:ne.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!de())console.error(a.trim());await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ea(t,{...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(r),r}createReadStream(){if(de())throw Error("createReadStream is not supported in browser environments");if(!du(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Tg(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=br.isBuffer(e)?e:br.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=mS("aes-256-gcm",r,i);return c.setAuthTag(s),br.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return de()}isServerMode(){return!de()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!de()){let s=e.split(`
70
+ `),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:ne.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ne.cyan(c)})),l.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:ne.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:ne.cyan(a),showTimestamp:!1}))}else if(!de())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
71
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(de())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ne.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();_e.stdin.removeListener("data",r);try{if(typeof _e.stdin.setRawMode==="function")_e.stdin.setRawMode(!1)}catch{}_e.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof _e.stdin.setRawMode==="function")_e.stdin.setRawMode(!0)}catch{}_e.stdin.resume(),_e.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let i=/%([sdijfo%])/g,s=0;if(r=e.replace(i,(o,c)=>{if(c==="%")return"%";if(s>=t.length)return o;let a=t[s++];switch(c){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!de()){let i=this.options.showTags!==!1&&this.name?ne.gray(this.formatTag(this.name)):"",s=ne.blue("◐");console.error(`${s} ${i} ${ne.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
72
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(e,t=""){if(!this.enabled||!this.fancy||de()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||de())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,n)),i!==void 0)this.activeProgressBar.message=i;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||de())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,i="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||de())return;_e.stdout.write(`${"\r".padEnd(_e.stdout.columns||80)}\r`),this.log(i,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||de()||!_e.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=ne.green("━".repeat(n)),o=ne.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=t||r===100?ne.green("✓"):ne.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${ne.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=_e.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,_e.stdout.write(e.lastRenderedLine),t)_e.stdout.write(`
73
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||de()||!_e.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(de()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await So(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=Cn(this.config.logDirectory,n);if(e.before)try{if((await $n(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Eo(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function _o(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Z(t[0])&&"id"in t[0]&&t[0].id===3&&Z(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Z(t)&&Z(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Z(e)&&"arr"in e&&Array.isArray(e.arr)&&Z(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Z(t[0])&&Z(e[0])){let n=[...t];for(let i of e)if(Z(i)&&"name"in i){if(!n.find((s)=>Z(s)&&("name"in s)&&s.name===i.name))n.push(i)}else if(Z(i)&&"path"in i){if(!n.find((s)=>Z(s)&&("path"in s)&&s.path===i.path))n.push(i)}else if(!n.some((s)=>ta(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Z(t)||!Z(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Z(i)&&Z(r[n]))r[n]=_o(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Z(i[0])&&Z(r[n][0])){let s=[...i];for(let o of r[n])if(Z(o)&&"name"in o){if(!s.find((c)=>Z(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(Z(o)&&"path"in o){if(!s.find((c)=>Z(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((c)=>ta(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function df(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:_o(e,t);if(Array.isArray(e))return r==="replace"?t:_o(e,t);if(!Z(t)||!Z(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=_o(o,s);else if(Z(s)&&Z(o))n[i]=df(o,s,r);else n[i]=s}return n}function ta(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ta(e[r],t[r]))return!1;return!0}if(Z(e)&&Z(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ta(e[i],t[i]))return!1}return!0}return!1}function Z(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Bo(e,t,r="replace"){if(!gp(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return df(t,i,r)}catch{return null}}catch{return null}}function iE(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${n}_${f.map(h).join("_")}`,y=`${n}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)Ue.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=Ni.env[d]||Ni.env[y];if(g!==void 0){if(r)Ue.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(i)}async function sE({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?iE(e,i,s):i,l=r||Ni.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Ue.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Je(l,"config"),Je(l,".config"),n?Je(l,n):void 0].filter(Boolean)));for(let p of g){if(s)Ue.info(`Searching for configuration in: ${p}`);let w=[Je(l,"config"),Je(l,".config")].concat(n?[Je(l,n)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let v of w)for(let P of u){let A=Je(p,`${v}${P}`),R=await Bo(A,a,c);if(R!==null){if(s)Ue.success(`Configuration loaded from: ${A}`);return R}}}if(e){let p=Je(uu(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)Ue.info(`Checking user config directory: ${p}`);for(let v of w)for(let P of u){let A=Je(p,`${v}${P}`),R=await Bo(A,a,c);if(R!==null){if(s)Ue.success(`Configuration loaded from user config directory: ${A}`);return R}}}if(e){let p=Je(uu(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)Ue.info(`Checking user config directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=Je(p,`${v}${P}`),R=await Bo(A,a,c);if(R!==null){if(s)Ue.success(`Configuration loaded from user config directory dotfile: ${A}`);return R}}}if(e){let p=uu(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)Ue.info(`Checking user home directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=Je(p,`${v}${P}`),R=await Bo(A,a,c);if(R!==null){if(s)Ue.success(`Configuration loaded from user home directory: ${A}`);return R}}}try{let p=Je(l,"package.json");if(gp(p)){let w=await import(p),v=w[e];if(!v&&t){if(v=w[t],v&&s)Ue.success(`Using alias "${t}" configuration from package.json`)}if(v&&typeof v==="object"&&!Array.isArray(v))try{if(s)Ue.success(`Configuration loaded from package.json: ${v===w[e]?e:t}`);return df(a,v,c)}catch(P){if(s)Ue.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)Ue.warn("Failed to load package.json:",p)}if(s)Ue.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function oE(e,t={}){let r=qo.cwd();while(r.includes("storage"))r=Sg(r,"..");let n=Sg(r,e||"");if(t?.relative)return uS(qo.cwd(),n);return n}async function aE(){try{let e=await sE({name:"clarity",alias:"logging",defaultConfig:Ko,cwd:qo.cwd()});return{...Ko,...e||{}}}catch{return Ko}}function xe(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cE(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Zt<"u"){let e=Zt.type;if(e==="renderer"||e==="worker")return!1;return!!(Zt.versions&&(Zt.versions.node||Zt.versions.bun))}return!1}class $p{async format(e){let t=await cE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Tn.pid,hostname:t(),environment:Tn.env.NODE_ENV||"development",platform:Tn.platform,version:Tn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Tn.env.NODE_ENV||Tn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ra{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...Lu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new $p,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??J.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Wo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Wo};return{...Wo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Lu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!xe()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await SS(this.config.logDirectory,Lg.F_OK|Lg.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await ES(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Yt.from(e);try{if(!To(this.currentLogFile))await yu(this.currentLogFile,"",{mode:420});if(n=Fg(this.currentLogFile,"a",420),xS(n,c,{flag:"a"}),Dg(n),n!==void 0)pu(n),n=void 0;if((await Sn(this.currentLogFile)).size===0){if(await yu(this.currentLogFile,c,{flag:"w",mode:420}),(await Sn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(i<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let f=o*2**i;await new Promise((h)=>setTimeout(h,f)),i++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(n!==void 0)try{pu(n)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(i===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}i++;let a=o*2**(i-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 En(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 En(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return En(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(xe())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return gu(16).toString("hex")}generateKey(){return gu(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=gu(16),n=bS("aes-256-gcm",t,r),i=Yt.isBuffer(e)?e:Yt.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=Yt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Ig(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Yt.from(Yt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(xe())return;if(!this.shouldWriteToFile())return;let e=await Sn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Po(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Sn(r).catch(()=>null))try{if(await Bg(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ao(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await yu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Sn(r).catch(()=>null))await Bg(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await Po(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Ao(En(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Ng(e),n=CS(t),i=Ig();await AS(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),To(this.currentLogFile))try{let e=Fg(this.currentLogFile,"r+");Dg(e),pu(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!xe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Po(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ao(En(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?W.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||xe())return!1;let e=typeof J.env.NO_COLOR<"u",t=J.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof J.stderr<"u"&&J.stderr.isTTY||typeof J.stdout<"u"&&J.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=J.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${W.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=W.underline(W.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>W.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>W.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>W.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>W.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>W.strikethrough(n)),t}supportsHyperlinks(){if(xe())return!1;let e=J.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=J.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(TS(t)||t.startsWith("./")||t.startsWith("../"))t=PS(t);else return null;return To(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Op[e],h=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:W.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:W.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
74
+ `);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:W.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!xe()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
75
+ `;if(c)u+=`${c}
76
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!xe()&&J.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!xe()&&J.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!xe()&&J.stdout.isTTY)J.stdout.write(`
77
+ `);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!xe()&&J.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":W.blue("◐"),tag:r,message:`${W.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),a=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
78
+ `,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":W.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!xe())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ra(t,{...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(r),r}createReadStream(){if(xe())throw Error("createReadStream is not supported in browser environments");if(!To(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ng(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Yt.isBuffer(e)?e:Yt.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=$S("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Yt.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return xe()}isServerMode(){return!xe()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
79
+ `),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:W.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:W.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:W.cyan(u),showTimestamp:!1}))}else if(!xe())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
80
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(xe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${W.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();J.stdin.removeListener("data",r);try{if(typeof J.stdin.setRawMode==="function")J.stdin.setRawMode(!1)}catch{}J.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof J.stdin.setRawMode==="function")J.stdin.setRawMode(!0)}catch{}J.stdin.resume(),J.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${W.blue("◐")} `;console.error(`${c}${o} ${W.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
81
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!J.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=W.green("━".repeat(n)),o=W.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?W.green("✓"):W.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${W.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=J.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,J.stdout.write(e.lastRenderedLine),t)J.stdout.write(`
82
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||xe()||!J.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(xe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Po(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=En(this.config.logDirectory,n);if(e.before)try{if((await Sn(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ao(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Cp(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function xp(e){return e instanceof ct}function lE(e){return e instanceof na}function uE(e){if(xp(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class fa{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Ki.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Ro.env[a]||(l?Ro.env[l]:void 0);if(u!==void 0){if(n.verbose){let f=Ro.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(u,typeof s,a,n.customParsers,n.configName)}catch(f){if(f instanceof ia)throw f;throw Cr.envVar(a,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Cr.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Ro.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
83
83
 
84
- `;for(let A of w)Y+=`${A.key}
85
- `,Y+=` Type: ${A.type}
86
- `,Y+=` Description: ${A.description}
87
- `,Y+=` Example: ${A.example}
84
+ `;for(let n of e)r+=`${n.key}
85
+ `,r+=` Type: ${n.type}
86
+ `,r+=` Description: ${n.description}
87
+ `,r+=` Example: ${n.example}
88
88
 
89
- `;return Y}formatAsMarkdown(w,$){let Y=`# Environment Variables for ${$}
89
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
90
90
 
91
- `;Y+=`| Variable | Type | Description | Example |
92
- `,Y+=`|----------|------|-------------|----------|
93
- `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
94
- `;return Y}}function gE(w,$){let Y=GB("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function QB(w,$,Y={}){return zB(w,$,Y,new WeakMap)}function zB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return fB(w,$,X,A);if(!Gw($)||!Gw(w))return $;return pE(w,$,Y,A)}function fB(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return dE(w,$);case"smart":return nE(w,$,A);default:return $}return $}function dE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>bU(X,A)))Y.push(A);return Y}function nE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Gw($[0])&&Gw(w[0]))return lE(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function lE(w,$,Y){let A=[...$];for(let X of w){if(!Gw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((W)=>Gw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function pE(w,$,Y,A){let X=$;if(Gw(X)&&A.has(X))return A.get(X);let J={...w};if(Gw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Gw(j)&&Gw(W))J[U]=zB(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=fB(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function XW(w,$,Y="replace"){return QB(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function bU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!bU(w[Y],$[Y]))return!1;return!0}if(Gw(w)&&Gw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!bU(w[X],$[X]))return!1}return!0}return!1}function Gw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class OX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=R1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!lA(w))return null;try{let Q=`?t=${Date.now()}`,z=await import(w+Q),f=z.default||z,B="default"in z,G=Object.keys(z).length>0;if(!B&&!G)throw new UY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new UY(w,Error("Configuration must export a valid object"),"unknown");let T={config:XW($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)R1.setWithFileCheck("file",T,w,J);return T}catch(Q){throw Q instanceof Error?B$.configLoad(w,Q):B$.configLoad(w,Error(String(Q)))}};if(U)return QY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(RU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return WB(async()=>{return lA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!lA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=RU(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=RU(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!lA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class JW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let z=[],f=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return z.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:z,warnings:f}}};if(j)return await QY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!WE($))throw new WY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new WY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:NB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class UW{fileLoader=new OX;envProcessor=new LX;validator=new JW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||z))throw W;if(f&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Rw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Rw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:z=!1}=w,f=J||k$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,f,U,j,Q,z,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,B,W,A,z);let T=await this.loadHomeConfiguration(A,X,j,Q,z,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,z);let F=await this.loadPackageJsonConfiguration(A,X,f,j,Q,z,W);if(F)return B.push(n0(f,"package.json")),this.finalizeResult(F,B,W,A,z);if(B.push(...this.getAllSearchPaths(A,X,f,U)),$)throw B$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?YY(w,X,U):X,z=this.getLocalDirectories(Y,A);for(let f of z){if(U)Rw.info(`Searching for configuration in: ${f}`);let B=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Rw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?YY(w,Y,X):Y,j=[n0(z1(),".config",w),n0(z1(),".config"),z1()];for(let W of j){if(X)Rw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),z=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(z){if(X)Rw.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?YY(w,A,J):A;try{let W=n0(Y,"package.json");if(!PU(W))return null;let Q=await import(W),z=Q[w],f=w;if(!z&&$)z=Q[$],f=$;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)Rw.success(`Configuration loaded from package.json: ${f}`);return{config:XW(j,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Rw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:YY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw B$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return R1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);R1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,n0(w,"config"),n0(w,".config"),$?n0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(n0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[n0(z1(),".config",w),n0(z1(),".config"),z1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function Rf(w){let $=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),Y=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return $||Y}async function rE(w){return rw.loadConfig({...w,__strictErrorHandling:!0})}async function BB(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await rw.loadConfig(w);else A=await rw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Rw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await rw.applyEnvironmentVariables(U.name||"",$,!0,U.verbose||!1))?.config??$;return $}}async function tE(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await rw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Rf(Y)))return(await rw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await rw.loadConfig({...w,cwd:w.cwd||k$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&Rf($)))return(await rw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function aE(w,$,Y="replace"){let A=new OX;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function YY(w,$,Y=!1){let A=new LX,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,z]of Object.entries(U)){let f=[...j,Q],B=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((F)=>F.toUpperCase()).join("")}`,`${X}_${f.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let F of B)if(G=k$.env[F],G!==void 0){T=F;break}if(G!==void 0&&T)if(typeof z==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof z==="number"){let F=Number(G);if(!Number.isNaN(F))W[Q]=F}else if(Array.isArray(z))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((F)=>F.trim())}else W[Q]=G;else if(z&&typeof z==="object"&&!Array.isArray(z))W[Q]=J(z,f)}return W}return J($)}function sE(w){let $=n0(k$.cwd(),w.configDir),Y=n0(k$.cwd(),w.generatedDir),A=n0(Y,"config-types.ts");if(!PU(oz(A)))bF(oz(A),{recursive:!0,mode:511});let X=PU($)?uF($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${VT}
95
- export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
96
- `;vF(A,J,{mode:438})}function oE(w){let $=null,Y=null,A=()=>{if(!Y)Y=BB(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Rw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function eE(w){let $=Gf(zE.cwd(),w?.configDir||"./config");function Y(){if(!jE($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=QE($).filter((W)=>X.has(MU(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let z=MU(Q).toLowerCase(),f=j.get(W);if(!f){j.set(W,Q);continue}let B=MU(f).toLowerCase();if(J.indexOf(z)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((W)=>W.base),U=J.length?J.map((W)=>`'${W}'`).join(" | "):"string",j=X.length?`{
97
- ${X.map((W)=>{let Q=Gf($,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${Q}').default`}).join(`,
91
+ `;r+=`| Variable | Type | Description | Example |
92
+ `,r+=`|----------|------|-------------|----------|
93
+ `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
94
+ `;return r}}function fE(e,t){let r=Ap("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function Sp(e,t,r={}){return Ep(e,t,r,new WeakMap)}function Ep(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Tp(e,t,i,n);if(!vt(t)||!vt(e))return t;return gE(e,t,r,n)}function Tp(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return hE(e,t);case"smart":return dE(e,t,n);default:return t}return t}function hE(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Du(i,n)))r.push(n);return r}function dE(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(vt(t[0])&&vt(e[0]))return mE(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function mE(e,t,r){let n=[...t];for(let i of e){if(!vt(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((a)=>vt(a)&&(c in a)&&a[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function gE(e,t,r,n){let i=t;if(vt(i)&&n.has(i))return n.get(i);let s={...e};if(vt(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(vt(c)&&vt(a))s[o]=Ep(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=Tp(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function mf(e,t,r="replace"){return Sp(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Du(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Du(e[r],t[r]))return!1;return!0}if(vt(e)&&vt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Du(e[i],t[i]))return!1}return!0}return!1}function vt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ha{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=Dn.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!ko(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new Di(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Di(e,Error("Configuration must export a valid object"),"unknown");let y={config:mf(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Dn.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?Cr.configLoad(e,l):Cr.configLoad(e,Error(String(l)))}};if(o)return Ki.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(wu(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Cp(async()=>ko(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!ko(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=wu(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=wu(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!ko(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class gf{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await Ki.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!RS(t))throw new Fi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Fi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Dp},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class pf{fileLoader=new ha;envProcessor=new fa;validator=new gf;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)Pt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw Pt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Vr.cwd(),h=[],d=await this.loadLocalConfiguration(n,i,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(n,i,f,o)),this.finalizeResult(d,h,a,n,u);let y=await this.loadHomeConfiguration(n,i,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(y,h,a,n,u);let g=await this.loadPackageJsonConfiguration(n,i,f,c,l,u,a);if(g)return h.push(Xe(f,"package.json")),this.finalizeResult(g,h,a,n,u);if(h.push(...this.getAllSearchPaths(n,i,f,o)),t)throw Cr.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?Si(e,i,o):i,u=this.getLocalDirectories(r,n);for(let f of u){if(o)Pt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Pt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?Si(e,r,i):r,c=[Xe(bn(),".config",e),Xe(bn(),".config"),bn()];for(let a of c){if(i)Pt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(u){if(i)Pt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?Si(e,n,s):n;try{let a=Xe(r,"package.json");if(!Ou(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Pt.success(`Configuration loaded from package.json: ${f}`);return{config:mf(c,u,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Pt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Si(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw Cr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Dn.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Dn.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Xe(e,"config"),Xe(e,".config"),t?Xe(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(Xe(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Xe(bn(),".config",e),Xe(bn(),".config"),bn()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function zg(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function pE(e){return tr.loadConfig({...e,__strictErrorHandling:!0})}async function Pp(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await tr.loadConfig(e);else n=await tr.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)Pt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await tr.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function yE(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await tr.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&zg(r)))return(await tr.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await tr.loadConfig({...e,cwd:e.cwd||Vr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&zg(t)))return(await tr.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function wE(e,t,r="replace"){let n=new ha;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function Si(e,t,r=!1){let n=new fa,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((g)=>g.toUpperCase()).join("")}`,`${i}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Vr.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function vE(e){let t=Xe(Vr.cwd(),e.configDir),r=Xe(Vr.cwd(),e.generatedDir),n=Xe(r,"config-types.ts");if(!Ou(xg(n)))oS(xg(n),{recursive:!0,mode:511});let i=Ou(t)?aS(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${qE}
95
+ export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
96
+ `;cS(n,s,{mode:438})}function bE(e){let t=null,r=null,n=()=>{if(!r)r=Pp(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)Pt.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function $E(e){let t=Mg(NS.cwd(),e?.configDir||"./config");function r(){if(!kS(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=OS(t).filter((a)=>i.has(vu(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=vu(l).toLowerCase(),f=c.get(a);if(!f){c.set(a,l);continue}let h=vu(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((a)=>a.base),o=s.length?s.map((a)=>`'${a}'`).join(" | "):"string",c=i.length?`{
97
+ ${i.map((a)=>{let l=Mg(t,a.file).replace(/\\/g,"/");return` '${a.base}': typeof import('${l}').default`}).join(`,
98
98
  `)}
99
- }`:"Record<string, any>";return`export type ConfigNames = ${U}
100
- export type ConfigByName = ${j}
99
+ }`:"Record<string, any>";return`export type ConfigNames = ${o}
100
+ export type ConfigByName = ${c}
101
101
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
102
102
  export type ConfigOf = Config
103
- `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function OT(w,$={}){let Y=BX.cwd();while(Y.includes("storage"))Y=Kf(Y,"..");let A=Kf(Y,w||"");if($?.relative)return BE(BX.cwd(),A);return A}function q0(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _T(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof lw<"u"){let w=lw.type;if(w==="renderer"||w==="worker")return!1;return!!(lw.versions&&(lw.versions.node||lw.versions.bun))}return!1}class MB{async format(w){let $=await _T(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:q1.pid,hostname:$(),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 SX{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=w,this.config={...HX},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new MB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??r.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...hU,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...hU};return{...hU,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:HX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await TE(this.config.logDirectory,Nf.F_OK|Nf.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await NE(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:mw.from(w);try{if(!pA(this.currentLogFile))await CU(this.currentLogFile,"",{mode:420});if(A=Tf(this.currentLogFile,"a",420),EE(A,j,{flag:"a"}),Ef(A),A!==void 0)yU(A),A=void 0;if((await T1(this.currentLogFile)).size===0){if(await CU(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(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let z=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let f=U*2**X;await new Promise((B)=>setTimeout(B,f)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{yU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,z=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}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 w=new Date().toISOString().split("T")[0];return N1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return IU(16).toString("hex")}generateKey(){return IU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=IU(16),A=GE("aes-256-gcm",$,Y),X=mw.isBuffer(w)?w:mw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=mw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Hf(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(mw.from(mw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let w=await T1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await rA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await T1(Y).catch(()=>null))try{if(await qf(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await tA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await CU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await T1(Y).catch(()=>null))await qf(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await rA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await tA(N1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Ff(w),A=FE($),X=Hf();await RE(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),pA(this.currentLogFile))try{let w=Tf(this.currentLogFile,"r+");Ef(w),yU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await rA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await tA(N1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?m.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let w=typeof r.env.NO_COLOR<"u",$=r.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof r.stderr<"u"&&r.stderr.isTTY||typeof r.stdout<"u"&&r.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=r.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${m.cyan(X)}`;if(!U)return Q.trim();let z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),$}supportsHyperlinks(){if(q0())return!1;let w=r.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=r.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(qE($)||$.startsWith("./")||$.startsWith("../"))$=HE($);else return null;return pA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":ZT[w],B=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:m.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:m.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
104
- `);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:m.gray(` ${F}`),level:w,showTimestamp:!1}))}break}}else if(!q0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}let z=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
105
- `;if(j)z+=`${j}
106
- `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!q0()&&r.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!q0()&&r.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!q0()&&r.stdout.isTTY)r.stdout.write(`
107
- `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!q0()&&r.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":m.blue("◐"),tag:Y,message:`${m.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
108
- `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":m.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!q0())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new SX($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(q0())throw Error("createReadStream is not supported in browser environments");if(!pA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ff(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=mw.isBuffer(w)?w:mw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=KE("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),z=W.length+Q.length,f=mw.allocUnsafe(z);return W.copy(f,0),Q.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q0()}isServerMode(){return!q0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
109
- `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,f=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:m.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(Q),showTimestamp:!1})),f.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(z),showTimestamp:!1}))}else if(!q0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
110
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(q0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${m.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();r.stdin.removeListener("data",Y);try{if(typeof r.stdin.setRawMode==="function")r.stdin.setRawMode(!1)}catch{}r.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof r.stdin.setRawMode==="function")r.stdin.setRawMode(!0)}catch{}r.stdin.resume(),r.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let z=$[j++];switch(Q){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${m.blue("◐")} `;console.error(`${j}${U} ${m.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
111
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!r.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=m.green("━".repeat(A)),U=m.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",z=this.options.showIcons===!1?"":$||Y===100?m.green("✓"):m.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",B=`\r${z}${f} ${j} ${W}${Q}`,G=r.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,r.stdout.write(w.lastRenderedLine),$)r.stdout.write(`
112
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||q0()||!r.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await rA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=N1(this.config.logDirectory,A);if(w.before)try{if((await T1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await tA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function PT(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class jW{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix(w),f={...$};return this.processObject(f,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return eU.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=aA.env[W]||(Q?aA.env[Q]:void 0);if(z!==void 0){if(A.verbose){let f=aA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(f){if(f instanceof WW)throw f;throw M1.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw M1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(aA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
103
+ `}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function JE(e,t={}){let r=Xo.cwd();while(r.includes("storage"))r=_g(r,"..");let n=_g(r,e||"");if(t?.relative)return FS(Xo.cwd(),n);return n}function Ee(){if(Qt.env.NODE_ENV==="test"||Qt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ZE(){if(Qt.env.NODE_ENV==="test"||Qt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Qt<"u"){let e=Qt.type;if(e==="renderer"||e==="worker")return!1;return!!(Qt.versions&&(Qt.versions.node||Qt.versions.bun))}return!1}class Ip{async format(e){let t=await ZE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Rn.pid,hostname:t(),environment:Rn.env.NODE_ENV||"development",platform:Rn.platform,version:Rn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Rn.env.NODE_ENV||Rn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class da{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...sa},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ip,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??X.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Au,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Au};return{...Au,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:sa.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ee()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let n,i=0,s=3,o=1000;while(i<s)try{try{try{await _S(this.config.logDirectory,Wg.F_OK|Wg.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await jS(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Jt.from(e);try{if(!Oo(this.currentLogFile))await Cu(this.currentLogFile,"",{mode:420});if(n=Kg(this.currentLogFile,"a",420),MS(n,c,{flag:"a"}),Ug(n),n!==void 0)$u(n),n=void 0;if((await Pn(this.currentLogFile)).size===0){if(await Cu(this.currentLogFile,c,{flag:"w",mode:420}),(await Pn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(i<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${s}:`,u);let f=o*2**i;await new Promise((h)=>setTimeout(h,f)),i++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(n!==void 0)try{$u(n)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(i===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}i++;let a=o*2**(i-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,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 An(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 An(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return An(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ee())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,i);if(n.length>s)for(let[o]of n.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return bu(16).toString("hex")}generateKey(){return bu(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=bu(16),n=LS("aes-256-gcm",t,r),i=Jt.isBuffer(e)?e:Jt.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=Jt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Hg(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(Jt.from(Jt.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ee())return;if(!this.shouldWriteToFile())return;let e=await Pn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await No(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Pn(r).catch(()=>null))try{if(await Vg(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Do(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Cu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Pn(r).catch(()=>null))await Vg(r,s)}if(this.currentLogFile=n,t.maxFiles){let i=(await No(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of i.slice(t.maxFiles))await Do(An(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=jg(e),n=IS(t),i=Hg();await WS(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Oo(this.currentLogFile))try{let e=Kg(this.currentLogFile,"r+");Ug(e),$u(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ee()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await No(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Do(An(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?z.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ee())return!1;let e=typeof X.env.NO_COLOR<"u",t=X.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof X.stderr<"u"&&X.stderr.isTTY||typeof X.stdout<"u"&&X.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=X.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${z.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=z.underline(z.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>z.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>z.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>z.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>z.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>z.strikethrough(n)),t}supportsHyperlinks(){if(Ee())return!1;let e=X.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=X.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(US(t)||t.startsWith("./")||t.startsWith("../"))t=KS(t);else return null;return Oo(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":n0[e],h=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:z.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:z.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
104
+ `);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:z.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!Ee()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
105
+ `;if(c)u+=`${c}
106
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(i,s)=>{},finish:(i)=>{},interrupt:(i,s)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ee()&&X.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Ee()&&X.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,s="info")=>{if(!Ee()&&X.stdout.isTTY)X.stdout.write(`
107
+ `);if(this[s==="warning"?"warn":s](i),this.activeProgressBar&&this.shouldStyleConsole()&&!Ee()&&X.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":z.blue("◐"),tag:r,message:`${z.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),a=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
108
+ `,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":z.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ee())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new da(t,{...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(r),r}createReadStream(){if(Ee())throw Error("createReadStream is not supported in browser environments");if(!Oo(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return jg(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Jt.isBuffer(e)?e:Jt.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=BS("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Jt.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ee()}isServerMode(){return!Ee()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
109
+ `),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:z.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(u),showTimestamp:!1}))}else if(!Ee())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
110
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Ee())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${z.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();X.stdin.removeListener("data",r);try{if(typeof X.stdin.setRawMode==="function")X.stdin.setRawMode(!1)}catch{}X.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof X.stdin.setRawMode==="function")X.stdin.setRawMode(!0)}catch{}X.stdin.resume(),X.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${z.blue("◐")} `;console.error(`${c}${o} ${z.cyan(n)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
111
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!X.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=z.green("━".repeat(n)),o=z.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?z.green("✓"):z.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=X.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,X.stdout.write(e.lastRenderedLine),t)X.stdout.write(`
112
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ee()||!X.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ee()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await No(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let i=An(this.config.logDirectory,n);if(e.before)try{if((await Pn(i)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${i}:`,s);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Do(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function i0(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class wf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return lf.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Fo.env[a]||(l?Fo.env[l]:void 0);if(u!==void 0){if(n.verbose){let f=Fo.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(u,typeof s,a,n.customParsers,n.configName)}catch(f){if(f instanceof yf)throw f;throw Fn.envVar(a,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Fn.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Fo.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
113
113
 
114
- `;for(let A of w)Y+=`${A.key}
115
- `,Y+=` Type: ${A.type}
116
- `,Y+=` Description: ${A.description}
117
- `,Y+=` Example: ${A.example}
114
+ `;for(let n of e)r+=`${n.key}
115
+ `,r+=` Type: ${n.type}
116
+ `,r+=` Description: ${n.description}
117
+ `,r+=` Example: ${n.example}
118
118
 
119
- `;return Y}formatAsMarkdown(w,$){let Y=`# Environment Variables for ${$}
119
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
120
120
 
121
- `;Y+=`| Variable | Type | Description | Example |
122
- `,Y+=`|----------|------|-------------|----------|
123
- `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
124
- `;return Y}}function iT(w,$,Y={}){return _B(w,$,Y,new WeakMap)}function _B(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return hB(w,$,X,A);if(!Kw($)||!Kw(w))return $;return cT(w,$,Y,A)}function hB(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return bT(w,$);case"smart":return uT(w,$,A);default:return $}return $}function bT(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>pU(X,A)))Y.push(A);return Y}function uT(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Kw($[0])&&Kw(w[0]))return vT(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function vT(w,$,Y){let A=[...$];for(let X of w){if(!Kw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((W)=>Kw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function cT(w,$,Y,A){let X=$;if(Kw(X)&&A.has(X))return A.get(X);let J={...w};if(Kw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Kw(j)&&Kw(W))J[U]=_B(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=hB(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function DB(w,$,Y="replace"){return iT(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function pU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!pU(w[Y],$[Y]))return!1;return!0}if(Kw(w)&&Kw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!pU(w[X],$[X]))return!1}return!0}return!1}function Kw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class xB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=GX.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!sA(w))return null;try{let Q=`?t=${Date.now()}`,z=await import(w+Q),f=z.default||z,B="default"in z,G=Object.keys(z).length>0;if(!B&&!G)throw new RX(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new RX(w,Error("Configuration must export a valid object"),"unknown");let T={config:DB($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)GX.setWithFileCheck("file",T,w,J);return T}catch(Q){throw Q instanceof Error?M1.configLoad(w,Q):M1.configLoad(w,Error(String(Q)))}};if(U)return eU.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(VU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return PT(async()=>{return sA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!sA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=VU(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=VU(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!sA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class kB{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let z=[],f=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return z.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:z,warnings:f}}};if(j)return await eU.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!ME($))throw new MX($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new MX($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:mT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function gT(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class ZB{fileLoader=new xB;envProcessor=new jW;validator=new kB;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||z))throw W;if(f&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)gw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let W=Date.now()-$;throw gw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:z=!1}=w,f=J||VX.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,f,U,j,Q,z,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,B,W,A,z);let T=await this.loadHomeConfiguration(A,X,j,Q,z,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,z);let F=await this.loadPackageJsonConfiguration(A,X,f,j,Q,z,W);if(F)return B.push(Bw(f,"package.json")),this.finalizeResult(F,B,W,A,z);if(B.push(...this.getAllSearchPaths(A,X,f,U)),$)throw M1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,z),warnings:[`No configuration file found for "${A}"${gT(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?eA(w,X,U):X,z=this.getLocalDirectories(Y,A);for(let f of z){if(U)gw.info(`Searching for configuration in: ${f}`);let B=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)gw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?eA(w,Y,X):Y,j=[Bw(Q1(),".config",w),Bw(Q1(),".config"),Q1()];for(let W of j){if(X)gw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),z=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(z){if(X)gw.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?eA(w,A,J):A;try{let W=Bw(Y,"package.json");if(!PF(W))return null;let Q={};try{Q=JSON.parse(iF(W,"utf8"))}catch(B){if(J)gw.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let z=Q[w],f=w;if(!z&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){z=Q[G],f=G;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)gw.success(`Configuration loaded from package.json: ${f}`);return{config:DB(j,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)gw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:eA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw M1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return GX.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);GX.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Bw(w,"config"),Bw(w,".config"),$?Bw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Bw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Bw(Q1(),".config",w),Bw(Q1(),".config"),Q1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function eA(w,$,Y=!1){let A=new jW,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,z]of Object.entries(U)){let f=[...j,Q],B=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((F)=>F.toUpperCase()).join("")}`,`${X}_${f.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let F of B)if(G=VX.env[F],G!==void 0){T=F;break}if(G!==void 0&&T)if(typeof z==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof z==="number"){let F=Number(G);if(!Number.isNaN(F))W[Q]=F}else if(Array.isArray(z))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((F)=>F.trim())}else W[Q]=G;else if(z&&typeof z==="object"&&!Array.isArray(z))W[Q]=J(z,f)}return W}return J($)}function bB(w){return rU.readFileSync(w,"utf8")}function tU(w,$){let Y=[];function A(X){let J;try{J=rU.readdirSync(X)}catch{return}for(let U of J){let j=Hw.join(X,U);try{if(rU.statSync(j).isDirectory())A(j);else if(U===$)Y.push(X)}catch{continue}}}return A(w),Y}function O(w,$,Y){if(Y||z0.verbose)console.debug(`[tlsx:${w}] ${$}`)}function uB(){return iB.env.SUDO_PASSWORD}function aT(w){let $=w.toLowerCase();return rT.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function IX(w){if(Array.isArray(w))return w.map((Y)=>IX(Y));if(typeof w==="string")return tT.test(w)?kf:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(aT(Y)){$[Y]=kf;continue}$[Y]=IX(A)}return $}function _X(w){return JSON.stringify(IX(w))}function sT(w){let $=uB();if(!$||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(w))return w;let Y=$.replace(/'/g,"'\\''"),A=w.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function f$(w,$={}){let Y=sT(w);try{let{stdout:A,stderr:X}=await pT(Y,{cwd:$.cwd||iB.cwd(),timeout:$.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${w}
125
- Error: ${A.message}`);throw X.stack=A.stack,X}}function vB(w){if(w.domain)return w.domain;if(w.domains?.length)return w.domains[0];throw Error("Either domain or domains must be specified")}function QW(w){let $=Hw.join(nT.homedir(),".stacks","ssl"),Y=w.basePath&&w.basePath.trim()!==""?w.basePath:z0.basePath&&z0.basePath.trim()!==""?z0.basePath:$,A=w.certPath?Hw.isAbsolute(w.certPath)?w.certPath:Hw.join(Y,w.certPath):Hw.join(Y,z0.certPath),X=w.keyPath?Hw.isAbsolute(w.keyPath)?w.keyPath:Hw.join(Y,w.keyPath):Hw.join(Y,z0.keyPath),J=w.caCertPath?Hw.isAbsolute(w.caCertPath)?w.caCertPath:Hw.join(Y,w.caCertPath):Hw.join(Y,z0.caCertPath);return{certPath:A,keyPath:X,caCertPath:J,basePath:Y}}function cB(w){let $=[],Y=new Set;if(w.domain)Y.add(w.domain);if(w.domains?.length)w.domains.forEach((A)=>Y.add(A));for(let A of Y)$.push({type:2,value:A});if(w.altNameIPs?.length)for(let A of w.altNameIPs)$.push({type:7,ip:A});if(w.altNameURIs?.length)for(let A of w.altNameURIs)$.push({type:6,value:A});if(w.subjectAltNames?.length)$.push(...w.subjectAltNames);return O(S.CERT,`Generated ${$.length} Subject Alternative Names`,w.verbose),$}function zW(w){let $=w.notBeforeDays??Mw.DEFAULT_NOT_BEFORE_DAYS,Y=w.validityDays??(w.validityYears?w.validityYears*365:Mw.DEFAULT_VALIDITY_DAYS);O(S.CERT,"Calculating certificate validity dates",w.verbose);let A=new Date(Date.now()-86400*$*1000),X=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),O(S.CERT,`Validity period: ${A.toISOString()} to ${X.toISOString()}`,w.verbose),{notBefore:A,notAfter:X}}function AY(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function Yw(w,$){let Y=AY($.length);return Buffer.concat([Buffer.from([w]),Y,$])}function jY(w){let $=w.split(".").map(Number),Y=[];Y.push(40*$[0]+$[1]);for(let A=2;A<$.length;A++){let X=$[A],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;Y.push(...J)}return Yw(Iw.OID,Buffer.from(Y))}function aU(w){let $;if(typeof w==="bigint"){let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else $=w;if($[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return Yw(Iw.INTEGER,$)}function mB(w,$=0){return Yw(Iw.BIT_STRING,Buffer.concat([Buffer.from([$]),w]))}function gB(w){return Yw(Iw.OCTET_STRING,w)}function $w(...w){return Yw(Iw.SEQUENCE,Buffer.concat(w))}function oT(...w){return Yw(Iw.SET,Buffer.concat(w))}function eT(w){return Yw(Iw.PRINTABLE_STRING,Buffer.from(w,"ascii"))}function w7(w){return Yw(Iw.UTF8_STRING,Buffer.from(w,"utf8"))}function $7(){return Buffer.from([Iw.NULL,0])}function Zf(w,$,Y=!0){let A=160|w|(Y?0:0),X=AY($.length);return Buffer.concat([Buffer.from([A]),X,$])}function Pf(w){let $=w.getUTCFullYear();if($>=2050){let Y=w.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Yw(Iw.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=($%100).toString().padStart(2,"0"),A=(w.getUTCMonth()+1).toString().padStart(2,"0"),X=w.getUTCDate().toString().padStart(2,"0"),J=w.getUTCHours().toString().padStart(2,"0"),U=w.getUTCMinutes().toString().padStart(2,"0"),j=w.getUTCSeconds().toString().padStart(2,"0"),W=`${Y}${A}${X}${J}${U}${j}Z`;return Yw(Iw.UTC_TIME,Buffer.from(W,"ascii"))}}function Y7(w,$){return $w(Pf(w),Pf($))}function bf(w){let $=[];for(let Y of w){let A;switch(Y.shortName){case"CN":A=l0.COMMON_NAME;break;case"C":A=l0.COUNTRY;break;case"L":A=l0.LOCALITY;break;case"ST":A=l0.STATE;break;case"O":A=l0.ORGANIZATION;break;case"OU":A=l0.ORGANIZATIONAL_UNIT;break;default:continue}let X=Y.shortName==="C"?eT(Y.value):w7(Y.value),J=$w(jY(A),X);$.push(oT(J))}return $w(...$)}function dB(w){return $w(jY(w),$7())}function A7(w){return w.export({type:"spki",format:"der"})}function X7(w){if(w.includes(":")){let $=w;if(w.includes("::")){let X=w.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],j=8-J.length-U.length,W=Array.from({length:j},()=>"0");$=[...J,...W,...U].join(":")}let Y=$.split(":"),A=Buffer.alloc(16);for(let X=0;X<8;X++){let J=Number.parseInt(Y[X]||"0",16);A.writeUInt16BE(J,X*2)}return A}else{let $=w.split(".").map((Y)=>Number.parseInt(Y,10));return Buffer.from($)}}function J7(w){let $=[];for(let Y of w)if(Y.type===2&&Y.value){let A=AY(Y.value.length);$.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=X7(Y.ip),X=AY(A.length);$.push(Buffer.concat([Buffer.from([135]),X,A]))}else if(Y.type===6&&Y.value){let A=AY(Y.value.length);$.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return $w(...$)}function U7(w,$){if(w){if($!==void 0)return $w(Yw(1,Buffer.from([255])),aU($));return $w(Yw(1,Buffer.from([255])))}return $w()}function W7(w){let $=0;if(w.digitalSignature)$|=128;if(w.keyEncipherment)$|=32;if(w.keyCertSign)$|=4;if(w.cRLSign)$|=2;let Y=0,A=$;while(A>0&&(A&1)===0)Y++,A>>=1;if($===0)Y=7;return mB(Buffer.from([$]),Y)}function j7(w){let $=[];if(w.serverAuth)$.push(jY(l0.SERVER_AUTH));if(w.clientAuth)$.push(jY(l0.CLIENT_AUTH));return $w(...$)}function $Y(w,$,Y){let A=[jY(w)];if($)A.push(Yw(1,Buffer.from([255])));return A.push(gB(Y)),$w(...A)}function Q7(w){let $=[];if($.push(Zf(0,aU(2))),$.push(aU(w.serialNumber)),$.push(dB(l0.SHA256_WITH_RSA)),$.push(bf(w.issuer)),$.push(Y7(w.notBefore,w.notAfter)),$.push(bf(w.subject)),$.push(A7(w.publicKey)),w.extensions){let Y=[];if(w.extensions.basicConstraints)Y.push($Y(l0.BASIC_CONSTRAINTS,w.extensions.basicConstraints.critical??!0,U7(w.extensions.basicConstraints.isCA,w.extensions.basicConstraints.pathLenConstraint)));if(w.extensions.keyUsage)Y.push($Y(l0.KEY_USAGE,w.extensions.keyUsage.critical??!0,W7(w.extensions.keyUsage)));if(w.extensions.extendedKeyUsage)Y.push($Y(l0.EXTENDED_KEY_USAGE,!1,j7(w.extensions.extendedKeyUsage)));if(w.extensions.subjectAltName?.length)Y.push($Y(l0.SUBJECT_ALT_NAME,!1,J7(w.extensions.subjectAltName)));if(w.extensions.subjectKeyIdentifier)Y.push($Y(l0.SUBJECT_KEY_IDENTIFIER,!1,gB(w.extensions.subjectKeyIdentifier)));if(Y.length>0)$.push(Zf(3,$w(...Y)))}return $w(...$)}function z7(w,$){let Y=I1.createSign("SHA256");Y.update(w);let A=Y.sign($);return $w(w,dB(l0.SHA256_WITH_RSA),mB(A))}function f7(w,$){let Y=w.toString("base64"),A=[];for(let X=0;X<Y.length;X+=64)A.push(Y.slice(X,X+64));return`-----BEGIN ${$}-----
126
- ${A.join(`
121
+ `;r+=`| Variable | Type | Description | Example |
122
+ `,r+=`|----------|------|-------------|----------|
123
+ `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
124
+ `;return r}}function s0(e,t,r={}){return Hp(e,t,r,new WeakMap)}function Hp(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return zp(e,t,i,n);if(!bt(t)||!bt(e))return t;return l0(e,t,r,n)}function zp(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return o0(e,t);case"smart":return a0(e,t,n);default:return t}return t}function o0(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>Ku(i,n)))r.push(n);return r}function a0(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(bt(t[0])&&bt(e[0]))return c0(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function c0(e,t,r){let n=[...t];for(let i of e){if(!bt(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((a)=>bt(a)&&(c in a)&&a[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function l0(e,t,r,n){let i=t;if(bt(i)&&n.has(i))return n.get(i);let s={...e};if(bt(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(bt(c)&&bt(a))s[o]=Hp(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=zp(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function Gp(e,t,r="replace"){return s0(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Ku(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ku(e[r],t[r]))return!1;return!0}if(bt(e)&&bt(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Ku(e[i],t[i]))return!1}return!0}return!1}function bt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class qp{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=Zo.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Lo(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new oa(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new oa(e,Error("Configuration must export a valid object"),"unknown");let y={config:Gp(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)Zo.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?Fn.configLoad(e,l):Fn.configLoad(e,Error(String(l)))}};if(o)return lf.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(xu(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of n){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let i=new Set;return r.filter((s)=>{if(!s||i.has(s))return!1;return i.add(s),!0})}checkFileAccess(e){return i0(async()=>Lo(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Lo(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=xu(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=xu(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Lo(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class Yp{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await lf.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!VS(t))throw new aa(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new aa(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:u0},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function f0(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Jp{fileLoader=new qp;envProcessor=new wf;validator=new Yp;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)Ft.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw Ft.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||ua.cwd(),h=[],d=await this.loadLocalConfiguration(n,i,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(n,i,f,o)),this.finalizeResult(d,h,a,n,u);let y=await this.loadHomeConfiguration(n,i,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(y,h,a,n,u);let g=await this.loadPackageJsonConfiguration(n,i,f,c,l,u,a);if(g)return h.push(wt(f,"package.json")),this.finalizeResult(g,h,a,n,u);if(h.push(...this.getAllSearchPaths(n,i,f,o)),t)throw Fn.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,u),warnings:[`No configuration file found for "${n}"${f0(i)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?Io(e,i,o):i,u=this.getLocalDirectories(r,n);for(let f of u){if(o)Ft.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Ft.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?Io(e,r,i):r,c=[wt(vn(),".config",e),wt(vn(),".config"),vn()];for(let a of c){if(i)Ft.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(u){if(i)Ft.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?Io(e,n,s):n;try{let a=wt(r,"package.json");if(!iS(a))return null;let l={};try{l=JSON.parse(sS(a,"utf8"))}catch(h){if(s)Ft.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=l[e],f=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){u=l[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Ft.success(`Configuration loaded from package.json: ${f}`);return{config:Gp(c,u,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Ft.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Io(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw Fn.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Zo.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);Zo.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,wt(e,"config"),wt(e,".config"),t?wt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(wt(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[wt(vn(),".config",e),wt(vn(),".config"),vn()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}async function h0(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await Ru.loadConfig(e);else n=await Ru.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)Ft.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Ru.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}function Io(e,t,r=!1){let n=new wf,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((g)=>g.toUpperCase()).join("")}`,`${i}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=ua.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}async function Xp(){if(!ku)ku=await h0({name:"tlsx",alias:"tls",defaultConfig:ma});return ku}function vf(e){return On.readFileSync(e,"utf8")}function Qp(e){let t=Wu.platform(),r;if(!e)if(t==="darwin")r="/etc/ssl/certs";else if(t==="win32")r="C:\\Windows\\System32\\certsrv\\CertEnroll";else if(t==="linux")r="/etc/ssl/certs";else throw Error(`Unsupported platform: ${t}`);else r=e;let n=On.readdirSync(r).filter((s)=>s.endsWith(".crt")).map((s)=>nt.join(r,s)),i=nt.join(Wu.homedir(),".stacks","ssl");if(On.existsSync(i))n.push(...On.readdirSync(i).filter((s)=>s.endsWith(".crt")).map((s)=>nt.join(i,s)));return n}function bf(e){let t=Number.parseInt(e[0],16);if(t<8)return e;return t-=8,t.toString()+e.substring(1)}function Li(e,t){let r=[];function n(i){let s;try{s=On.readdirSync(i)}catch{return}for(let o of s){let c=nt.join(i,o);try{if(On.statSync(c).isDirectory())n(c);else if(o===t)r.push(i)}catch{continue}}}return n(e),r}function C(e,t,r){if(r||B.verbose)console.debug(`[tlsx:${e}] ${t}`)}function $f(){return Zp.env.SUDO_PASSWORD}function w0(e){let t=e.toLowerCase();return p0.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function Bi(e){if(Array.isArray(e))return e.map((r)=>Bi(r));if(typeof e==="string")return y0.test(e)?sp:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e)){if(w0(r)){t[r]=sp;continue}t[r]=Bi(n)}return t}function Wi(e){return JSON.stringify(Bi(e))}function v0(e){let t=$f();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(e))return e;let r=t.replace(/'/g,"'\\''"),n=e.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function it(e,t={}){let r=v0(e);try{let{stdout:n,stderr:i}=await g0(r,{cwd:t.cwd||Zp.cwd(),timeout:t.timeout||30000});return{stdout:n.trim(),stderr:i.trim()}}catch(n){let i=Error(`Failed to execute command: ${e}
125
+ Error: ${n.message}`);throw i.stack=n.stack,i}}function Cf(e){if(e.domain)return e.domain;if(e.domains?.length)return e.domains[0];throw Error("Either domain or domains must be specified")}function In(e){let t=nt.join(Wu.homedir(),".stacks","ssl"),r=e.basePath&&e.basePath.trim()!==""?e.basePath:B.basePath&&B.basePath.trim()!==""?B.basePath:t,n=e.certPath?nt.isAbsolute(e.certPath)?e.certPath:nt.join(r,e.certPath):nt.join(r,B.certPath),i=e.keyPath?nt.isAbsolute(e.keyPath)?e.keyPath:nt.join(r,e.keyPath):nt.join(r,B.keyPath),s=e.caCertPath?nt.isAbsolute(e.caCertPath)?e.caCertPath:nt.join(r,e.caCertPath):nt.join(r,B.caCertPath);return{certPath:n,keyPath:i,caCertPath:s,basePath:r}}function ey(e){return e.startsWith("*.")?`_wildcard.${e.slice(2)}`:e}function ty(e){return e.replace(/\.crt$/,"")}function nr(e){let t;if(e.startsWith("-----BEGIN CERTIFICATE-----"))t=e;else t=vf(e);return new Ii.X509Certificate(t)}function Mn(e){return nr(e).fingerprint256.replace(/:/g,"").toUpperCase()}function xf(e){return e.match($0)??[]}function ga(e){let t=e.replace(/-----BEGIN [A-Z ]+-----/,"").replace(/-----END [A-Z ]+-----[\s\S]*$/,"").replace(/\s+/g,"");return Buffer.from(t,"base64")}function pa(e){return Ii.createHash("sha256").update(e).digest("hex").toUpperCase()}function Sf(e,t){let r=t.replace(/:/g,"").toUpperCase();for(let n of xf(e))try{if(pa(ga(n))===r)return!0}catch{}return!1}function _n(e){return Mi(nr(e).subject)}function Ef(e,t,r=443,n=4000){let i;try{i=t.includes("-----BEGIN")?t:Kr.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((s)=>{let o=!1,c=(l)=>{if(o)return;o=!0,s(l)},a=b0.connect({host:e,port:r,servername:e,ca:i,rejectUnauthorized:!0},()=>{c(a.authorized),a.end()});a.setTimeout(n,()=>{a.destroy(),c(!1)}),a.on("error",()=>c(!1))})}function Vu(e){let t=[],r=e.split(`
126
+ `);for(let n of r){let[i,...s]=n.split("="),o=s.join("=");if(i&&o)t.push({shortName:i.trim(),value:o.trim()})}return t}function Mi(e){return Vu(e).find((t)=>t.shortName==="CN")?.value||""}function ry(e){let t=[],r=Mi(e.subject);if(r&&!/^\d+\.\d+\.\d+\.\d+$/.test(r))t.push(r);let n=e.subjectAltName;if(n){let i=n.split(", ");for(let s of i)if(s.startsWith("DNS:"))t.push(s.slice(4))}return[...new Set(t)]}function ya(e,t){let r=nr(e),n=ry(r);for(let i of n){if(i===t)return!0;if(i.startsWith("*.")){let s=i.slice(2);if(t.endsWith(s)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}function ny(e){let t=nr(e);return{subject:Vu(t.subject),issuer:Vu(t.issuer),validFrom:new Date(t.validFrom),validTo:new Date(t.validTo),serialNumber:t.serialNumber}}function iy(e){let t=nr(e);return new Date>new Date(t.validTo)}function sy(e,t=30){let r=nr(e),n=new Date;return(new Date(r.validTo).getTime()-n.getTime())/86400000<=t}function oy(e,t,r){C(S.CERT,`Validating certificate: ${e}`,r);try{if(!Kr.existsSync(e))return{valid:!1,expired:!1,notYetValid:!1,issuerValid:!1,domains:[],validFrom:new Date,validTo:new Date,issuer:"",subject:"",message:`Certificate file not found: ${e}`};let n=Kr.readFileSync(e,"utf8"),i=new Ii.X509Certificate(n),s=new Date,o=new Date(i.validFrom),c=new Date(i.validTo),a=s>c,l=s<o,u=Mi(i.subject),f=Mi(i.issuer),h=ry(i),d=!1;if(t)if(Kr.existsSync(t))try{let y=Kr.readFileSync(t,"utf8"),g=new Ii.X509Certificate(y);d=i.verify(g.publicKey)}catch(y){C(S.CERT,`Error validating CA certificate: ${y}`,r)}else C(S.CERT,`CA certificate file not found: ${t}`,r);return{valid:!a&&!l&&(t?d:!0),expired:a,notYetValid:l,issuerValid:d,domains:h,validFrom:o,validTo:c,issuer:f,subject:u}}catch(n){return C(S.CERT,`Error validating certificate: ${n}`,r),{valid:!1,expired:!1,notYetValid:!1,issuerValid:!1,domains:[],validFrom:new Date,validTo:new Date,issuer:"",subject:"",message:`Error validating certificate: ${n}`}}}function ay(e,t){C(S.CERT,`Validating browser compatibility: ${e}`,t);try{if(!Kr.existsSync(e))return{compatible:!1,issues:[`Certificate file not found: ${e}`]};let r=Kr.readFileSync(e,"utf8"),n=new Ii.X509Certificate(r),i=[],s=!1,o=!1;if(Mi(n.subject)==="localhost")s=!0;let c=n.subjectAltName;if(c){let h=c.split(", ");for(let d of h){if(d==="DNS:localhost")s=!0;if(d.includes("*"))o=!0}}if(!s)i.push('Certificate does not include "localhost" in Subject Alternative Names, which may cause issues with some browsers.');if(o)i.push("Certificate contains wildcard domains, which may not be fully supported in all browsers for localhost development.");let a=n.keyUsage,l=n.extKeyUsage||"";if(!(l.includes("TLS Web Server Authentication")||l.includes("1.3.6.1.5.5.7.3.1")))i.push("Certificate lacks Extended Key Usage for serverAuth, which is required by modern browsers.");let u=new Date(n.validFrom),f=(new Date(n.validTo).getTime()-u.getTime())/86400000;if(f>398)i.push(`Certificate validity period is ${Math.floor(f)} days, which exceeds the 398-day maximum supported by modern browsers.`);return{compatible:i.length===0,issues:i}}catch(r){return C(S.CERT,`Error validating browser compatibility: ${r}`,t),{compatible:!1,issues:[`Error validating browser compatibility: ${r}`]}}}function T0(e){return Buffer.from(e.replace(/-/g,""),"hex")}function _i(e,t=Af){let r=C0.createHash("sha1").update(Buffer.concat([T0(t),Buffer.from(e,"utf8")])).digest(),n=Buffer.from(r.subarray(0,16));n[6]=n[6]&15|80,n[8]=n[8]&63|128;let i=n.toString("hex").toUpperCase();return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function Mo(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function cy(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"root-ca"}function op(e,t){for(let r of e.split(`
127
+ `)){let n=r.indexOf("=");if(n!==-1&&r.slice(0,n).trim()===t)return r.slice(n+1).trim()}return}function P0(e,t=64){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r.join(`
128
+ `)}function Rf(e){let t=e.fingerprint.replace(/:/g,"").toUpperCase(),r=_i(`${t}:profile`),n=_i(`${t}:root`),i=P0(Buffer.from(e.certificateDer).toString("base64")),s=Mo(e.displayName),o=Mo(e.organization),c=Mo(e.identifier);return`<?xml version="1.0" encoding="UTF-8"?>
129
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
130
+ <plist version="1.0">
131
+ <dict>
132
+ <key>PayloadContent</key>
133
+ <array>
134
+ <dict>
135
+ <key>PayloadCertificateFileName</key>
136
+ <string>${Mo(`${cy(e.displayName)}.cer`)}</string>
137
+ <key>PayloadContent</key>
138
+ <data>
139
+ ${i}
140
+ </data>
141
+ <key>PayloadDescription</key>
142
+ <string>Adds the ${s} root certificate</string>
143
+ <key>PayloadDisplayName</key>
144
+ <string>${s}</string>
145
+ <key>PayloadIdentifier</key>
146
+ <string>${c}.root</string>
147
+ <key>PayloadType</key>
148
+ <string>com.apple.security.root</string>
149
+ <key>PayloadUUID</key>
150
+ <string>${n}</string>
151
+ <key>PayloadVersion</key>
152
+ <integer>1</integer>
153
+ </dict>
154
+ </array>
155
+ <key>PayloadDescription</key>
156
+ <string>Trusts the ${s} certificate authority on this device (SHA-256 ${t.slice(0,16)})</string>
157
+ <key>PayloadDisplayName</key>
158
+ <string>${s}</string>
159
+ <key>PayloadIdentifier</key>
160
+ <string>${c}</string>
161
+ <key>PayloadOrganization</key>
162
+ <string>${o}</string>
163
+ <key>PayloadRemovalDisallowed</key>
164
+ <false/>
165
+ <key>PayloadType</key>
166
+ <string>Configuration</string>
167
+ <key>PayloadUUID</key>
168
+ <string>${r}</string>
169
+ <key>PayloadVersion</key>
170
+ <integer>1</integer>
171
+ </dict>
172
+ </plist>
173
+ `}async function ly(e){let t=e.caCertPath.startsWith("-----BEGIN")?e.caCertPath:x0.readFileSync(e.caCertPath,"utf8"),r=nr(t),n=ga(t),i=pa(n),s=e.name?.trim()||op(r.subject,"CN")||"tlsx Root CA",o=e.organization?.trim()||op(r.subject,"O")||"tlsx",c=e.identifier?.trim()||`${wa}.${i.slice(0,12).toLowerCase()}`,a=`${cy(s)}.${S0[e.format]}`,l=Pf[e.format];switch(e.format){case"pem":return{data:t.endsWith(`
174
+ `)?t:`${t}
175
+ `,filename:a,mime:l};case"der":return{data:new Uint8Array(n),filename:a,mime:l};case"mobileconfig":return{data:Rf({certificateDer:n,displayName:s,organization:o,identifier:c,fingerprint:i}),filename:a,mime:l};default:throw Error(`Unsupported export format: ${String(e.format)}`)}}function uy(e,t){switch(e){case"macos":return["macOS (system keychain, all users and browsers):",` sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`," Restart any open browser afterwards."].join(`
176
+ `);case"ios":return["iOS / iPadOS (configuration profile):",` 1. Export the profile if you have not yet: tlsx export-ca --format mobileconfig --out ${t}`,` 2. Send ${t} to the device (AirDrop, Mail, or a link) and open it.`," 3. Settings > Profile Downloaded > Install, and confirm with the passcode."," 4. Settings > General > About > Certificate Trust Settings, then enable full trust for the new root."," Without step 4 the profile is installed but Safari still rejects the certificate."].join(`
177
+ `);case"windows":return["Windows (Local Machine root store, run from an elevated prompt):",` certutil -addstore -f ROOT ${t}`," Or double-click the file, Install Certificate, Local Machine, Trusted Root Certification Authorities."].join(`
178
+ `);case"debian":return["Debian / Ubuntu / Raspberry Pi OS:",` sudo cp ${t} /usr/local/share/ca-certificates/tlsx-root-ca.crt`," sudo update-ca-certificates"," The file must end in .crt to be picked up. Browsers using NSS (Firefox, Chromium) keep their own store; see linux-nss."].join(`
179
+ `);case"rhel":return["RHEL / Fedora / Rocky / AlmaLinux:",` sudo cp ${t} /etc/pki/ca-trust/source/anchors/tlsx-root-ca.crt`," sudo update-ca-trust"].join(`
180
+ `);case"android":return["Android (user CA):",` 1. Copy ${t} to the device (it must be PEM or DER with a .crt or .cer extension).`," 2. Settings > Security > Encryption & credentials > Install a certificate > CA certificate."," Apps only trust user CAs when their network security config opts in (Android 7+); Chrome does, most apps do not."].join(`
181
+ `);case"linux-nss":return["Linux browser stores (Firefox, Chromium via NSS):",` certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n "tlsx Root CA" -i ${t}`," For Firefox, repeat with -d sql:$HOME/.mozilla/firefox/<profile>, or import via Settings > Privacy & Security > Certificates."," tlsx install does this for every cert9.db it finds under your home directory."].join(`
182
+ `);default:throw Error(`Unknown platform: ${String(e)}. Expected one of ${Tf.join(", ")}`)}}function va(e){let t=[],r=new Set;if(e.domain)r.add(e.domain);if(e.domains?.length)e.domains.forEach((n)=>r.add(n));for(let n of r)t.push({type:2,value:n});if(e.altNameIPs?.length)for(let n of e.altNameIPs)t.push({type:7,ip:n});if(e.altNameURIs?.length)for(let n of e.altNameURIs)t.push({type:6,value:n});if(e.subjectAltNames?.length)t.push(...e.subjectAltNames);return C(S.CERT,`Generated ${t.length} Subject Alternative Names`,e.verbose),t}function fy(e){C(S.CERT,"Generating random serial number",e);let t=A0.randomBytes(20),r=bf(t.toString("hex"));return C(S.CERT,`Generated serial number: ${r}`,e),r}function ba(e){let t=e.notBeforeDays??lt.DEFAULT_NOT_BEFORE_DAYS,r=e.validityDays??(e.validityYears?e.validityYears*365:lt.DEFAULT_VALIDITY_DAYS);C(S.CERT,"Calculating certificate validity dates",e.verbose);let n=new Date(Date.now()-86400*t*1000),i=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),i.setUTCHours(23,59,59,999),C(S.CERT,`Validity period: ${n.toISOString()} to ${i.toISOString()}`,e.verbose),{notBefore:n,notAfter:i}}function hy(e){let t=[];t.push({name:"basicConstraints",cA:e.isCA??!1,critical:!0,...e.basicConstraints||{}});let r=va(e);if(r.length>0)t.push({name:"subjectAltName",altNames:r});let n=e.keyUsage||{digitalSignature:!0,keyEncipherment:!0};t.push({name:"keyUsage",critical:!0,...n});let i=e.extKeyUsage||{serverAuth:!0};return t.push({name:"extKeyUsage",...i}),t}function Ai(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function ft(e,t){let r=Ai(t.length);return Buffer.concat([Buffer.from([e]),r,t])}function ji(e){let t=e.split(".").map(Number),r=[];r.push(40*t[0]+t[1]);for(let n=2;n<t.length;n++){let i=t[n],s=[];s.unshift(i&127),i>>=7;while(i>0)s.unshift(i&127|128),i>>=7;r.push(...s)}return ft(At.OID,Buffer.from(r))}function Hu(e){let t;if(typeof e==="bigint"){let r=e.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=e.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else t=e;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return ft(At.INTEGER,t)}function dy(e,t=0){return ft(At.BIT_STRING,Buffer.concat([Buffer.from([t]),e]))}function my(e){return ft(At.OCTET_STRING,e)}function ut(...e){return ft(At.SEQUENCE,Buffer.concat(e))}function R0(...e){return ft(At.SET,Buffer.concat(e))}function k0(e){return ft(At.PRINTABLE_STRING,Buffer.from(e,"ascii"))}function O0(e){return ft(At.UTF8_STRING,Buffer.from(e,"utf8"))}function N0(){return Buffer.from([At.NULL,0])}function ap(e,t,r=!0){let n=160|e|(r?0:0),i=Ai(t.length);return Buffer.concat([Buffer.from([n]),i,t])}function cp(e){let t=e.getUTCFullYear();if(t>=2050){let r=e.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return ft(At.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(t%100).toString().padStart(2,"0"),n=(e.getUTCMonth()+1).toString().padStart(2,"0"),i=e.getUTCDate().toString().padStart(2,"0"),s=e.getUTCHours().toString().padStart(2,"0"),o=e.getUTCMinutes().toString().padStart(2,"0"),c=e.getUTCSeconds().toString().padStart(2,"0"),a=`${r}${n}${i}${s}${o}${c}Z`;return ft(At.UTC_TIME,Buffer.from(a,"ascii"))}}function D0(e,t){return ut(cp(e),cp(t))}function lp(e){let t=[];for(let r of e){let n;switch(r.shortName){case"CN":n=Ze.COMMON_NAME;break;case"C":n=Ze.COUNTRY;break;case"L":n=Ze.LOCALITY;break;case"ST":n=Ze.STATE;break;case"O":n=Ze.ORGANIZATION;break;case"OU":n=Ze.ORGANIZATIONAL_UNIT;break;default:continue}let i=r.shortName==="C"?k0(r.value):O0(r.value),s=ut(ji(n),i);t.push(R0(s))}return ut(...t)}function gy(e){return ut(ji(e),N0())}function F0(e){return e.export({type:"spki",format:"der"})}function L0(e){if(e.includes(":")){let t=e;if(e.includes("::")){let i=e.split("::"),s=i[0]?i[0].split(":"):[],o=i[1]?i[1].split(":"):[],c=8-s.length-o.length,a=Array.from({length:c},()=>"0");t=[...s,...a,...o].join(":")}let r=t.split(":"),n=Buffer.alloc(16);for(let i=0;i<8;i++){let s=Number.parseInt(r[i]||"0",16);n.writeUInt16BE(s,i*2)}return n}else{let t=e.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(t)}}function B0(e){let t=[];for(let r of e)if(r.type===2&&r.value){let n=Ai(r.value.length);t.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=L0(r.ip),i=Ai(n.length);t.push(Buffer.concat([Buffer.from([135]),i,n]))}else if(r.type===6&&r.value){let n=Ai(r.value.length);t.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return ut(...t)}function I0(e,t){if(e){if(t!==void 0)return ut(ft(1,Buffer.from([255])),Hu(t));return ut(ft(1,Buffer.from([255])))}return ut()}function M0(e){let t=0;if(e.digitalSignature)t|=128;if(e.keyEncipherment)t|=32;if(e.keyCertSign)t|=4;if(e.cRLSign)t|=2;let r=0,n=t;while(n>0&&(n&1)===0)r++,n>>=1;if(t===0)r=7;return dy(Buffer.from([t]),r)}function _0(e){let t=[];if(e.serverAuth)t.push(ji(Ze.SERVER_AUTH));if(e.clientAuth)t.push(ji(Ze.CLIENT_AUTH));return ut(...t)}function Ci(e,t,r){let n=[ji(e)];if(t)n.push(ft(1,Buffer.from([255])));return n.push(my(r)),ut(...n)}function j0(e){let t=[];if(t.push(ap(0,Hu(2))),t.push(Hu(e.serialNumber)),t.push(gy(Ze.SHA256_WITH_RSA)),t.push(lp(e.issuer)),t.push(D0(e.notBefore,e.notAfter)),t.push(lp(e.subject)),t.push(F0(e.publicKey)),e.extensions){let r=[];if(e.extensions.basicConstraints)r.push(Ci(Ze.BASIC_CONSTRAINTS,e.extensions.basicConstraints.critical??!0,I0(e.extensions.basicConstraints.isCA,e.extensions.basicConstraints.pathLenConstraint)));if(e.extensions.keyUsage)r.push(Ci(Ze.KEY_USAGE,e.extensions.keyUsage.critical??!0,M0(e.extensions.keyUsage)));if(e.extensions.extendedKeyUsage)r.push(Ci(Ze.EXTENDED_KEY_USAGE,!1,_0(e.extensions.extendedKeyUsage)));if(e.extensions.subjectAltName?.length)r.push(Ci(Ze.SUBJECT_ALT_NAME,!1,B0(e.extensions.subjectAltName)));if(e.extensions.subjectKeyIdentifier)r.push(Ci(Ze.SUBJECT_KEY_IDENTIFIER,!1,my(e.extensions.subjectKeyIdentifier)));if(r.length>0)t.push(ap(3,ut(...r)))}return ut(...t)}function U0(e,t){let r=jn.createSign("SHA256");r.update(e);let n=r.sign(t);return ut(e,gy(Ze.SHA256_WITH_RSA),dy(n))}function K0(e,t){let r=e.toString("base64"),n=[];for(let i=0;i<r.length;i+=64)n.push(r.slice(i,i+64));return`-----BEGIN ${t}-----
183
+ ${n.join(`
127
184
  `)}
128
- -----END ${$}-----
129
- `}function fW(){let w=I1.randomBytes(20);return w[0]=w[0]&127||1,w}function nB(w=2048){let{privateKey:$,publicKey:Y}=I1.generateKeyPairSync("rsa",{modulusLength:w});return{privateKey:$,publicKey:Y}}function B7(w){let $=w.export({type:"spki",format:"der"});return I1.createHash("sha1").update($).digest()}function lB(w){let $={serialNumber:w.serialNumber||fW(),notBefore:w.notBefore,notAfter:w.notAfter,subject:w.subject,issuer:w.issuer||w.subject,publicKey:w.publicKey,extensions:{basicConstraints:{isCA:w.isCA??!1,critical:!0,pathLenConstraint:w.pathLenConstraint},subjectKeyIdentifier:B7(w.publicKey)}};if(w.keyUsage)$.extensions.keyUsage={...w.keyUsage,critical:!0};if(w.extendedKeyUsage)$.extensions.extendedKeyUsage=w.extendedKeyUsage;if(w.subjectAltName?.length)$.extensions.subjectAltName=w.subjectAltName;let Y=Q7($),A=z7(Y,w.signingKey);return{certificate:f7(A,"CERTIFICATE"),certificateDer:A}}function pB(w){return w.export({type:"pkcs8",format:"pem"})}function G7(w){return I1.createPrivateKey(w)}function K7(w){let $=new I1.X509Certificate(w),Y=$.publicKey,A=[],X=$.subject.split(`
130
- `);for(let J of X){let[U,...j]=J.split("="),W=j.join("=");if(U&&W)A.push({shortName:U.trim(),value:W.trim()})}return{publicKey:Y,subject:A}}async function BW(w={}){O("ca","Creating new Root CA Certificate",w.verbose);let $=w.keySize||Mw.DEFAULT_KEY_SIZE;O("ca",`Generating ${$}-bit RSA key pair`,w.verbose);let{privateKey:Y,publicKey:A}=nB($),X=[{shortName:"C",value:w.countryName||z0.countryName},{shortName:"ST",value:w.stateName||z0.stateName},{shortName:"L",value:w.localityName||z0.localityName},{shortName:"O",value:w.organization||"Local Development CA"},{shortName:"OU",value:w.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:w.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=zW({validityYears:w.validityYears||Mw.DEFAULT_CA_VALIDITY_YEARS,verbose:w.verbose}),{certificate:j}=lB({serialNumber:fW(),notBefore:J,notAfter:U,subject:X,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:j,privateKey:pB(Y),notBefore:J,notAfter:U}}async function GW(w){if(O("ca","Generating new certificate",w.verbose),O("ca",`Options: ${_X(w)}`,w.verbose),!w.domain&&!w.domains?.length)throw Error("Either domain or domains must be specified");if(!w.rootCA?.certificate||!w.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:$}=K7(w.rootCA.certificate),Y=G7(w.rootCA.privateKey);O("ca",`Generating ${Mw.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,w.verbose);let A=Mw.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=nB(A),U=w.commonName||vB(w),j=w.certificateAttributes||[{shortName:"C",value:w.countryName||z0.countryName},{shortName:"ST",value:w.stateName||z0.stateName},{shortName:"L",value:w.localityName||z0.localityName},{shortName:"O",value:w.organizationName||z0.organizationName},{shortName:"CN",value:U}],{notBefore:W,notAfter:Q}=zW({validityDays:w.validityDays||Mw.DEFAULT_VALIDITY_DAYS,verbose:w.verbose}),z=cB(w),f=w.keyUsage||{digitalSignature:!0,keyEncipherment:!0},B=w.extKeyUsage||{serverAuth:!0},{certificate:G}=lB({serialNumber:fW(),notBefore:W,notAfter:Q,subject:j,issuer:$,publicKey:J,signingKey:Y,isCA:w.basicConstraints?.cA??!1,pathLenConstraint:w.basicConstraints?.pathLenConstraint,keyUsage:f,extendedKeyUsage:B,subjectAltName:z});return{certificate:G,privateKey:pB(X),notBefore:W,notAfter:Q}}function rB(w,$){O(S.STORAGE,`Storing certificate and private key with options: ${_X($)}`,$?.verbose);let{certPath:Y,keyPath:A}=QW({basePath:$?.basePath,certPath:$?.certPath,keyPath:$?.keyPath});O(S.STORAGE,`Certificate path: ${Y}`,$?.verbose),O(S.STORAGE,`Private key path: ${A}`,$?.verbose);let X=sU.dirname(Y);if(!pw.existsSync(X))O(S.STORAGE,`Creating certificate directory: ${X}`,$?.verbose),pw.mkdirSync(X,{recursive:!0});O(S.STORAGE,"Writing certificate file",$?.verbose),pw.writeFileSync(Y,w.certificate);let J=sU.dirname(A);if(!pw.existsSync(J))O(S.STORAGE,`Creating private key directory: ${J}`,$?.verbose),pw.mkdirSync(J,{recursive:!0});return O(S.STORAGE,"Writing private key file",$?.verbose),pw.writeFileSync(A,w.privateKey),O(S.STORAGE,"Certificate and private key stored successfully",$?.verbose),Y}function tB(w,$){O(S.STORAGE,"Storing CA certificate",$?.verbose);let{caCertPath:Y}=QW({basePath:$?.basePath,caCertPath:$?.caCertPath});O(S.STORAGE,`CA certificate path: ${Y}`,$?.verbose);let A=sU.dirname(Y);if(!pw.existsSync(A))O(S.STORAGE,`Creating CA certificate directory: ${A}`,$?.verbose),pw.mkdirSync(A,{recursive:!0});return O(S.STORAGE,"Writing CA certificate file",$?.verbose),pw.writeFileSync(Y,w),O(S.STORAGE,"CA certificate stored successfully",$?.verbose),Y}function hX(w){let $;if(w.startsWith("-----BEGIN CERTIFICATE-----"))$=w;else $=bB(w);return new F7.X509Certificate($)}function DX(w){return hX(w).fingerprint256.replace(/:/g,"").toUpperCase()}function KW(w){return aB(hX(w).subject)}function E7(w){let $=[],Y=w.split(`
131
- `);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)$.push({shortName:X.trim(),value:U.trim()})}return $}function aB(w){return E7(w).find(($)=>$.shortName==="CN")?.value||""}function T7(w){let $=[],Y=aB(w.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))$.push(Y);let A=w.subjectAltName;if(A){let X=A.split(", ");for(let J of X)if(J.startsWith("DNS:"))$.push(J.slice(4))}return[...new Set($)]}function FW(w,$){let Y=hX(w),A=T7(Y);for(let X of A){if(X===$)return!0;if(X.startsWith("*.")){let J=X.slice(2);if($.endsWith(J)&&$.indexOf(".")===$.lastIndexOf("."))return!0}}return!1}async function q7(w,$){if(yX.platform()!=="darwin")return!1;try{let Y=DX(w);if(!Y)return O(S.TRUST,"Could not extract certificate fingerprint",$),!1;try{if(N7("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
132
- `).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return O(S.TRUST,"Certificate fingerprint found in system keychain",$),!0}catch{}return O(S.TRUST,"Certificate fingerprint not found in system keychain",$),!1}catch(Y){return O(S.TRUST,`Error checking certificate trust: ${Y}`,$),!1}}async function EW(w,$,Y){O(S.TRUST,`Adding certificate to system trust store with options: ${_X(Y)}`,Y?.verbose),O(S.TRUST,"Storing certificate and private key",Y?.verbose);let A=rB(w,Y);O(S.TRUST,"Storing CA certificate",Y?.verbose);let X=tB($,Y),J=yX.platform();O(S.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=I7[J];if(!U){let j=`Unsupported platform: ${J}`;throw O(S.TRUST,`Error: ${j}`,Y?.verbose),Error(j)}return await U.addCertificate(X,Y),O(S.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var RF,uf=30000,CX,df="https://acme-staging-v02.api.letsencrypt.org/directory",nf="https://acme-v02.api.letsencrypt.org/directory",WX,LF="1.2.840.10045.2.1",OF="1.2.840.10045.3.1.7",SF="1.2.840.10045.4.3.2",_F="2.5.4.3",hF="1.2.840.113549.1.9.14",DF="2.5.29.17",GX,eU,IE,yE=(w)=>w,VE=(w,$)=>{for(var Y in $)IE(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:CE.bind($,Y)})},LE=(w,$)=>()=>(w&&($=w(w=0)),$),XB,GB,R1,QY,KB,wT,$T,Mf,AX,uU,h0,e,YT,If,AT,yf,XT,JT,LU,UT,Cf,Vf,OU,WT,jT,QT,zT,XX,FB,fT,D0,BT,GT,Lf,JX,vU,N0,u,KT,Of,FT,Sf,ET,TT,SU,NT,_f,hf,qT,_U,HT,RT,MT,IT,yT,UX,EB,CT,VT="0.15.6",ww,NX,UY,cU,mU,qX,gU,dU,WY,nU,lU,B$,TB,NB,Rw,rw,qB,HB,LT,ST,RB,HX,fC,y0,m,BC,hT,GC,DT,KC,FC,Df,EC,xT,kT,TC,xf,NC,qC,HC,RC,MC,hU,ZT,IC,yw,IB,RX,yB,CB,WW,VB,LB,MX,OB,SB,M1,mT,gw,yC,CC,VC,PB,z0,Mw,S,H1,pT,kf="[redacted]",rT,tT,Iw,l0,H7,R7,M7,I7;var sB=s(()=>{RF=HF(import.meta.url);CX=new XY;WX=class WX extends Error{problem;httpStatus;constructor(w,$,Y){super(w);this.name="AcmeError",this.problem=$,this.httpStatus=Y}};GX=new YB,eU=new AB,IE=Object.defineProperty;XB={};VE(XB,{withErrorRecovery:()=>WB,tryLoadConfig:()=>aE,loadConfigWithResult:()=>rE,loadConfig:()=>BB,isRetryableError:()=>mE,isConfigNotFoundError:()=>cE,isBunfigError:()=>jB,globalPerformanceMonitor:()=>QY,globalCache:()=>R1,getEnvOrDefault:()=>gE,generateConfigTypes:()=>sE,defaultGeneratedDir:()=>HB,defaultConfigDir:()=>qB,deepMergeWithArrayStrategy:()=>XW,deepMerge:()=>QB,createLibraryConfig:()=>oE,config:()=>tE,bunfigPlugin:()=>eE,applyEnvVarsToConfig:()=>YY,TypeGenerationError:()=>dU,SchemaValidationError:()=>WY,PluginError:()=>lU,PerformanceMonitor:()=>$W,FileSystemError:()=>gU,ErrorFactory:()=>B$,EnvVarError:()=>qX,EnvProcessor:()=>LX,ConfigValidator:()=>JW,ConfigValidationError:()=>cU,ConfigNotFoundError:()=>NX,ConfigMergeError:()=>mU,ConfigLoader:()=>UW,ConfigLoadError:()=>UY,ConfigFileLoader:()=>OX,ConfigCache:()=>wW,CacheUtils:()=>KB,BunfigError:()=>ww,BrowserConfigError:()=>nU,ArrayMergeStrategies:()=>TB});LT=LE(async()=>{GB=import.meta.require,R1=new wW,QY=new $W,KB={createKey:OE,isEquivalent:SE,estimateMemoryUsage:_E},wT=fX(iU.cwd(),"config"),$T=fX(iU.cwd(),"src/generated"),Mf=zX.env.CLARITY_LOG_DIR||gF(xE(),"logs"),AX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},uU=await kE(),h0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},e=h0,YT=h0.red,If=h0.green,AT=h0.yellow,yf=h0.blue,XT=h0.magenta,JT=h0.cyan,LU=h0.white,UT=h0.gray,Cf=h0.bgRed,Vf=h0.bgYellow,OU=h0.bold,WT=h0.dim,jT=h0.italic,QT=h0.underline,zT=h0.reset,XX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},FB={debug:"\uD83D\uDD0D",info:yf("ℹ"),success:If("✓"),warning:Vf(LU(OU(" WARN "))),error:Cf(LU(OU(" ERROR ")))},fT=new FX("stacks"),D0=new FX("bunfig",{showTags:!0}),BT=d0(JY.cwd(),"config"),GT=d0(JY.cwd(),"src/generated"),Lf=QX.env.CLARITY_LOG_DIR||cF(bE(),"logs"),JX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Lf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},vU=await uE(),N0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},u=N0,KT=N0.red,Of=N0.green,FT=N0.yellow,Sf=N0.blue,ET=N0.magenta,TT=N0.cyan,SU=N0.white,NT=N0.gray,_f=N0.bgRed,hf=N0.bgYellow,qT=N0.bgGray,_U=N0.bold,HT=N0.dim,RT=N0.italic,MT=N0.underline,IT=N0.strikethrough,yT=N0.reset,UX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EB={debug:"\uD83D\uDD0D",info:Sf("ℹ"),success:Of("✓"),warning:hf(SU(_U(" WARN "))),error:_f(SU(_U(" ERROR ")))},CT=new TX("stacks"),ww=class extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,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(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},NX=class extends ww{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${A} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}},UY=class extends ww{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}},cU=class extends ww{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},mU=class extends ww{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},qX=class extends ww{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}},gU=class extends ww{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},dU=class extends ww{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},WY=class extends ww{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},nU=class extends ww{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}},lU=class extends ww{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},B$={configNotFound(w,$,Y){return new NX(w,$,Y)},configLoad(w,$,Y){return new UY(w,$,Y)},configValidation(w,$,Y){return new cU(w,$,Y)},configMerge(w,$,Y,A){return new mU(w,$,Y,A)},envVar(w,$,Y,A){return new qX(w,$,Y,A)},fileSystem(w,$,Y){return new gU(w,$,Y)},typeGeneration(w,$,Y){return new dU(w,$,Y)},schemaValidation(w,$,Y){return new WY(w,$,Y)},browserConfig(w,$,Y,A){return new nU(w,$,Y,A)},plugin(w,$,Y){return new lU(w,$,Y)}},TB={replace:"replace",concat:"concat",smart:"smart"},NB=/^https?:\/\//,Rw=new TX("bunfig",{showTags:!0}),rw=new UW,qB=n0(k$.cwd(),"config"),HB=n0(k$.cwd(),"src/generated")});ST=BX.env.CLARITY_LOG_DIR||fE(OT(),"logs"),RB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ST,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},HX={...RB},fC=(async()=>{try{let{loadConfig:w}=await LT().then(()=>XB),$=await w({name:"clarity",alias:"logging",defaultConfig:RB,cwd:BX.cwd()});if($)Object.assign(HX,$)}catch{}return HX})();y0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},m=y0,BC=y0.red,hT=y0.green,GC=y0.yellow,DT=y0.blue,KC=y0.magenta,FC=y0.cyan,Df=y0.white,EC=y0.gray,xT=y0.bgRed,kT=y0.bgYellow,TC=y0.bgGray,xf=y0.bold,NC=y0.dim,qC=y0.italic,HC=y0.underline,RC=y0.strikethrough,MC=y0.reset,hU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ZT={debug:"\uD83D\uDD0D",info:DT("ℹ"),success:hT("✓"),warning:kT(Df(xf(" WARN "))),error:xT(Df(xf(" ERROR ")))};IC=new SX("stacks");yw=class yw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,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(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};IB=class IB extends yw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};RX=class RX extends yw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};yB=class yB extends yw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};CB=class CB extends yw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};WW=class WW extends yw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};VB=class VB extends yw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};LB=class LB extends yw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};MX=class MX extends yw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};OB=class OB extends yw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};SB=class SB extends yw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};M1={configNotFound(w,$,Y){return new IB(w,$,Y)},configLoad(w,$,Y){return new RX(w,$,Y)},configValidation(w,$,Y){return new yB(w,$,Y)},configMerge(w,$,Y,A){return new CB(w,$,Y,A)},envVar(w,$,Y,A){return new WW(w,$,Y,A)},fileSystem(w,$,Y){return new VB(w,$,Y)},typeGeneration(w,$,Y){return new LB(w,$,Y)},schemaValidation(w,$,Y){return new MX(w,$,Y)},browserConfig(w,$,Y,A){return new OB(w,$,Y,A)},plugin(w,$,Y){return new SB(w,$,Y)}};mT=/^https?:\/\//;gw=new SX("bunfig",{showTags:!0});yC=new ZB;CC=Bw(VX.cwd(),"config"),VC=Bw(VX.cwd(),"src/generated"),PB={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:BU.join(fU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:BU.join(fU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:BU.join(fU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},z0=PB,Mw={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"},H1={info:(...w)=>console.log(...w),warn:(...w)=>console.warn(...w),success:(...w)=>console.log(...w),error:(...w)=>console.error(...w),debug:(...w)=>console.debug(...w)};pT=lT(dT);rT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),tT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;Iw={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},l0={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"};H7={platform:"darwin",async addCertificate(w,$){if(await q7(w,$?.verbose)){O(S.TRUST,"Certificate is already trusted, skipping trust store update",$?.verbose),H1.success("Certificate is already trusted in system keychain");return}O(S.TRUST,"Adding certificate to macOS keychain",$?.verbose),await f$(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${w}`)},async removeCertificate(w,$,Y){let A=Y||z0.commonName;O(S.TRUST,`Removing certificate ${A} from macOS keychain`,$?.verbose);try{await f$(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),O(S.TRUST,`Removed certificate ${A} from macOS keychain`,$?.verbose)}catch(X){throw O(S.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},R7={platform:"win32",async addCertificate(w,$){O(S.TRUST,"Adding certificate to Windows certificate store",$?.verbose),await f$(`certutil -f -v -addstore -enterprise Root ${w}`)},async removeCertificate(w,$,Y){let A=Y||z0.commonName;O(S.TRUST,`Removing certificate ${A} from Windows certificate store`,$?.verbose);try{await f$(`certutil -delstore -enterprise Root "${A}"`),O(S.TRUST,`Removed certificate ${A} from Windows certificate store`,$?.verbose)}catch(X){throw O(S.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},M7={platform:"linux",async addCertificate(w,$){O(S.TRUST,"Adding certificate to Linux certificate store",$?.verbose);let Y=yX.homedir(),A=Mw.LINUX_CERT_DB_FILENAME,X=Mw.LINUX_TRUST_ARGS;O(S.TRUST,`Searching for certificate databases in ${Y}`,$?.verbose);let J=tU(Y,A);if(J.length===0){H1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){O(S.TRUST,`Processing certificate database in ${U}`,$?.verbose);try{O(S.TRUST,`Attempting to delete existing cert for ${z0.commonName}`,$?.verbose),await f$(`certutil -d sql:${U} -D -n ${z0.commonName}`)}catch(j){O(S.TRUST,`Warning: Error deleting existing cert: ${j}`,$?.verbose),console.warn(`Error deleting existing cert: ${j}`)}O(S.TRUST,`Adding new certificate to ${U}`,$?.verbose),await f$(`certutil -d sql:${U} -A -t ${X} -n ${z0.commonName} -i ${w}`),H1.info(`Cert added to ${U}`)}},async removeCertificate(w,$,Y){let A=Y||z0.commonName;O(S.TRUST,`Removing certificate ${A} from Linux certificate store`,$?.verbose);let X=yX.homedir(),J=Mw.LINUX_CERT_DB_FILENAME;O(S.TRUST,`Searching for certificate databases in ${X}`,$?.verbose);let U=tU(X,J);if(U.length===0){H1.warn("No certificate databases found. Cannot remove certificate.");return}for(let j of U){O(S.TRUST,`Processing certificate database in ${j}`,$?.verbose);try{await f$(`certutil -d sql:${j} -D -n "${A}"`),H1.info(`Cert removed from ${j}`)}catch(W){O(S.TRUST,`Error removing cert from ${j}: ${W}`,$?.verbose),console.warn(`Error removing cert from ${j}: ${W}`)}}}},I7={darwin:H7,win32:R7,linux:M7}});var xX=s(()=>{sB()});function Z$(w){try{return DX(w)}catch{return null}}function TW(w){try{return KW(w)||null}catch{return null}}function NW(w,$){try{return $.every((Y)=>FW(w,Y))}catch{return!1}}var kX=s(()=>{xX()});import{existsSync as oB,statSync as eB}from"fs";import{existsSync as iW,mkdirSync as _7,readdirSync as h7,writeFileSync as D7}from"fs";import{homedir as y1}from"os";import{dirname as w9,resolve as r0}from"path";import P$ from"process";import{join as x7,relative as k7,resolve as $9}from"path";import sX from"process";import{existsSync as i9,mkdirSync as _V,readdirSync as hV,writeFileSync as DV}from"fs";import{homedir as qW}from"os";import{dirname as ZV,resolve as p0}from"path";import fY from"process";import{join as Z7,relative as P7,resolve as Y9}from"path";import oX from"process";import{existsSync as b9,mkdirSync as vV,readdirSync as cV,writeFileSync as mV}from"fs";import{dirname as dV,resolve as eX}from"path";import bW from"process";import{Buffer as K$}from"buffer";import{createCipheriv as i7,createDecipheriv as b7,randomBytes as HW}from"crypto";import{closeSync as RW,createReadStream as A9,createWriteStream as u7,existsSync as MW,fsyncSync as X9,openSync as J9,writeFileSync as v7}from"fs";import{access as c7,constants as U9,mkdir as m7,readdir as ZX,rename as W9,stat as C1,unlink as PX,writeFile as IW}from"fs/promises";import{join as V1}from"path";import x0 from"process";import{pipeline as g7}from"stream/promises";import{createGzip as j9}from"zlib";import L1 from"process";import sw from"process";import{Buffer as tw}from"buffer";import{createCipheriv as d7,createDecipheriv as n7,randomBytes as yW}from"crypto";import{closeSync as CW,createReadStream as Q9,createWriteStream as l7,existsSync as iX,fsyncSync as z9,openSync as f9,writeFileSync as p7}from"fs";import{access as r7,constants as B9,mkdir as t7,readdir as bX,rename as G9,stat as O1,unlink as uX,writeFile as VW}from"fs/promises";import{isAbsolute as a7,join as S1,resolve as s7}from"path";import Z from"process";import{pipeline as o7}from"stream/promises";import{createGzip as K9}from"zlib";import _1 from"process";import ow from"process";import vX from"process";import{existsSync as cX}from"fs";import{resolve as LW}from"path";import{existsSync as e7}from"fs";import{existsSync as wN,readdirSync as $N}from"fs";import{extname as OW,resolve as F9}from"path";import YN from"process";import{join as Aq,relative as Xq,resolve as L9}from"path";import U8 from"process";import{Buffer as aw}from"buffer";import{createCipheriv as Wq,createDecipheriv as jq,randomBytes as xW}from"crypto";import{closeSync as kW,createReadStream as O9,createWriteStream as Qq,existsSync as gX,fsyncSync as S9,openSync as _9,writeFileSync as zq}from"fs";import{access as fq,constants as h9,mkdir as Bq,readdir as dX,rename as D9,stat as h1,unlink as nX,writeFile as ZW}from"fs/promises";import{isAbsolute as Gq,join as D1,resolve as Kq}from"path";import P from"process";import{pipeline as Fq}from"stream/promises";import{createGzip as x9}from"zlib";import x1 from"process";import ew from"process";function L7(w,$){this[w]=V7.bind(null,$)}class rW{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!oB(w))return!0;return eB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=oB(Y)?eB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class tW{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function AN(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function XN(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function JN(w){return w.getStats().size*2}function aW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&X0($[0])&&"id"in $[0]&&$[0].id===3&&X0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(X0($)&&X0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(X0(w)&&"arr"in w&&Array.isArray(w.arr)&&X0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&X0($[0])&&X0(w[0])){let A=[...$];for(let X of w)if(X0(X)&&"name"in X){if(!A.find((U)=>X0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(X0(X)&&"path"in X){if(!A.find((U)=>X0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>w8(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!X0($)||!X0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(X0(X)&&X0(Y[A]))Y[A]=aW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&X0(X[0])&&X0(Y[A][0])){let J=[...X];for(let U of Y[A])if(X0(U)&&"name"in U){if(!J.find((W)=>X0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(X0(U)&&"path"in U){if(!J.find((W)=>X0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>w8(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function w8(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!w8(w[Y],$[Y]))return!1;return!0}if(X0(w)&&X0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!w8(w[X],$[X]))return!1}return!0}return!1}function X0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function UN(w,$){if(!b9(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return aW($,A)}catch{return null}}catch{return null}}async function WN({name:w="",cwd:$,defaultConfig:Y}){let A=$||bW.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=eX(A,`${U}${j}`),Q=await UN(W,Y);if(Q!==null)return Q}try{let U=eX(A,"package.json");if(b9(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return aW(Y,W)}catch{}}}catch{}return Y}function jN(w,$={}){let Y=oX.cwd();while(Y.includes("storage"))Y=Y9(Y,"..");let A=Y9(Y,w||"");if($?.relative)return P7(oX.cwd(),A);return A}async function QN(){try{let w=await WN({name:"clarity",defaultConfig:pX,cwd:oX.cwd(),endpoint:"",headers:{}});return{...pX,...w}}catch{return pX}}function j0(){if(sw.env.NODE_ENV==="test"||sw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zN(){if(sw.env.NODE_ENV==="test"||sw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof sw<"u"){let w=sw.type;if(w==="renderer"||w==="worker")return!1;return!!(sw.versions&&(sw.versions.node||sw.versions.bun))}return!1}class u9{async format(w){let $=await zN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:L1.pid,hostname:$(),environment:L1.env.NODE_ENV||"development",platform:L1.platform,version:L1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:L1.env.NODE_ENV||L1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $8{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=w,this.config={...vW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new u9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...rX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...rX};return{...rX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:vW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await c7(this.config.logDirectory,U9.F_OK|U9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await m7(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:K$.from(w);try{if(!MW(this.currentLogFile))await IW(this.currentLogFile,"",{mode:420});if(X=J9(this.currentLogFile,"a",420),v7(X,W,{flag:"a"}),X9(X),X!==void 0)RW(X),X=void 0;if((await C1(this.currentLogFile)).size===0){if(await IW(this.currentLogFile,W,{flag:"w",mode:420}),(await C1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{RW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 V1(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 V1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return V1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(j0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return HW(16).toString("hex")}generateKey(){return HW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=HW(16),A=i7("aes-256-gcm",$,Y),X=K$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:K$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=j9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(K$.from(K$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(j0())return;let w=await C1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await ZX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await C1(Y).catch(()=>null))try{if(await W9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await PX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await IW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await C1(Y).catch(()=>null))await W9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await ZX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await PX(V1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=A9(w),A=u7($),X=j9();await g7(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),MW(this.currentLogFile))try{let w=J9(this.currentLogFile,"r+");X9(w),RW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!j0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await ZX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await PX(V1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?w0.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${w0.cyan(X)}`;if(!U)return Q.trim();let z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!j0()){let Q=t9[w],z=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",f;switch(w){case"debug":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:w0.gray(U),level:w}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:w0.green(U),level:w}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f),j){let B=j.split(`
133
- `);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:w0.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!j0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
134
- `;if(j)W+=`${j}
135
- `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!j0()){let Y=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:w0.blue("◐"),tag:Y,message:`${w0.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
136
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!j0()){let z=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:w0.green(""),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!j0())console.error(Q.trim());await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new $8($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(j0())throw Error("createReadStream is not supported in browser environments");if(!MW(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return A9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=K$.isBuffer(w)?w:K$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),j=b7("aes-256-gcm",Y,X);return j.setAuthTag(J),K$.concat([j.update(U),j.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!j0()){let J=w.split(`
137
- `),U=Math.max(...J.map((z)=>z.length))+2,j=`┌${"".repeat(U)}┐`,W=`└${"".repeat(U)}┘`,Q=J.map((z)=>{let f=" ".repeat(U-z.length-2);return`│ ${z}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:w0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:w0.cyan(j)})),Q.forEach((z)=>console.error(this.formatConsoleMessage({timestamp:Y,message:w0.cyan(z),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:w0.cyan(W),showTimestamp:!1}))}else if(!j0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
138
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(j0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${w0.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();x0.stdin.removeListener("data",Y);try{if(typeof x0.stdin.setRawMode==="function")x0.stdin.setRawMode(!1)}catch{}x0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof x0.stdin.setRawMode==="function")x0.stdin.setRawMode(!0)}catch{}x0.stdin.resume(),x0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let z=$[j++];switch(Q){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!j0()){let U=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",j=w0.blue("◐");console.error(`${j} ${U} ${w0.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
139
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||j0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),j!==void 0)this.activeProgressBar.message=j;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())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,j="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;x0.stdout.write(`${"\r".padEnd(x0.stdout.columns||80)}\r`),this.log(j,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||j0()||!x0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=w0.green("".repeat(A)),U=w0.gray("".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",z=$||Y===100?w0.green("✓"):w0.blue(""),f=this.options.showTags!==!1&&this.name?` ${w0.gray(this.formatTag(this.name))}`:"",B=`\r${z}${f} ${j} ${W}${Q}`,G=x0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,x0.stdout.write(w.lastRenderedLine),$)x0.stdout.write(`
140
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||j0()||!x0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(j0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await ZX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=V1(this.config.logDirectory,A);if(w.before)try{if((await C1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await PX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function lX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&a($[0])&&"id"in $[0]&&$[0].id===3&&a($[1])&&"id"in $[1]&&$[1].id===4)return $;if(a($)&&a(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(a(w)&&"arr"in w&&Array.isArray(w.arr)&&a($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&a($[0])&&a(w[0])){let A=[...$];for(let X of w)if(a(X)&&"name"in X){if(!A.find((U)=>a(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(a(X)&&"path"in X){if(!A.find((U)=>a(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>Y8(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!a($)||!a(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(a(X)&&a(Y[A]))Y[A]=lX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&a(X[0])&&a(Y[A][0])){let J=[...X];for(let U of Y[A])if(a(U)&&"name"in U){if(!J.find((W)=>a(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(a(U)&&"path"in U){if(!J.find((W)=>a(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>Y8(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function sW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:lX(w,$);if(Array.isArray(w))return Y==="replace"?$:lX(w,$);if(!a($)||!a(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=lX(U,J);else if(a(J)&&a(U))A[X]=sW(U,J,Y);else A[X]=J}return A}function Y8(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!Y8(w[Y],$[Y]))return!1;return!0}if(a(w)&&a($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!Y8(w[X],$[X]))return!1}return!0}return!1}function a(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function mX(w,$,Y="replace"){if(!i9(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return sW($,X,Y)}catch{return null}}catch{return null}}function fN(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,z]of Object.entries(U)){let f=[...j,Q],B=(F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${f.map(B).join("_")}`,T=`${A}_${f.map((F)=>F.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${G} for config ${w}.${f.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[Q]=J(z,f);else{let F=fY.env[G]||fY.env[T];if(F!==void 0){if(Y)Z0.info(`Using environment variable ${F?G:T} for config ${w}.${f.join(".")}`);if(typeof z==="number")W[Q]=Number(F);else if(typeof z==="boolean")W[Q]=F.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(F);if(Array.isArray(E))W[Q]=E;else W[Q]=F.split(",").map((N)=>N.trim())}catch{W[Q]=F.split(",").map((E)=>E.trim())}else W[Q]=F}}}return W}return J(X)}async function BN({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?fN(w,X,J):X,Q=Y||fY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)Z0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let f=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],F=Array.from(new Set([Q,p0(Q,"config"),p0(Q,".config"),A?p0(Q,A):void 0].filter(Boolean)));for(let E of F){if(J)Z0.info(`Searching for configuration in: ${E}`);let R=[p0(Q,"config"),p0(Q,".config")].concat(A?[p0(Q,A)]:[]).includes(E)?[...f,...B,...G,...T]:[...B,...f,...T,...G];for(let V of R)for(let L of z){let q=p0(E,`${V}${L}`),C=await mX(q,W,j);if(C!==null){if(J)Z0.success(`Configuration loaded from: ${q}`);return C}}}if(w){let E=p0(qW(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)Z0.info(`Checking user config directory: ${E}`);for(let R of N)for(let V of z){let L=p0(E,`${R}${V}`),q=await mX(L,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user config directory: ${L}`);return q}}}if(w){let E=p0(qW(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)Z0.info(`Checking user config directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=p0(E,`${R}${V}`),q=await mX(L,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user config directory dotfile: ${L}`);return q}}}if(w){let E=qW(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)Z0.info(`Checking user home directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=p0(E,`${R}${V}`),q=await mX(L,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user home directory: ${L}`);return q}}}try{let E=p0(Q,"package.json");if(i9(E)){let N=await import(E),R=N[w];if(!R&&$){if(R=N[$],R&&J)Z0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)Z0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return sW(W,R,j)}catch(V){if(J)Z0.warn("Failed to merge package.json config:",V)}}}catch(E){if(J)Z0.warn("Failed to load package.json:",E)}if(J)Z0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function GN(w,$={}){let Y=sX.cwd();while(Y.includes("storage"))Y=$9(Y,"..");let A=$9(Y,w||"");if($?.relative)return k7(sX.cwd(),A);return A}async function KN(){try{let w=await BN({name:"clarity",alias:"logging",defaultConfig:tX,cwd:sX.cwd()});return{...tX,...w||{}}}catch{return tX}}function H0(){if(ow.env.NODE_ENV==="test"||ow.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function FN(){if(ow.env.NODE_ENV==="test"||ow.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ow<"u"){let w=ow.type;if(w==="renderer"||w==="worker")return!1;return!!(ow.versions&&(ow.versions.node||ow.versions.bun))}return!1}class v9{async format(w){let $=await FN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:_1.pid,hostname:$(),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 A8{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=w,this.config={...cW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new v9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...aX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...aX};return{...aX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:cW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await r7(this.config.logDirectory,B9.F_OK|B9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await t7(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:tw.from(w);try{if(!iX(this.currentLogFile))await VW(this.currentLogFile,"",{mode:420});if(X=f9(this.currentLogFile,"a",420),p7(X,W,{flag:"a"}),z9(X),X!==void 0)CW(X),X=void 0;if((await O1(this.currentLogFile)).size===0){if(await VW(this.currentLogFile,W,{flag:"w",mode:420}),(await O1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{CW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 S1(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 S1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return S1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return yW(16).toString("hex")}generateKey(){return yW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=yW(16),A=d7("aes-256-gcm",$,Y),X=tw.isBuffer(w)?w:tw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=tw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=K9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(tw.from(tw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let w=await O1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await bX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await O1(Y).catch(()=>null))try{if(await G9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await uX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await VW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await O1(Y).catch(()=>null))await G9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await bX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await uX(S1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=Q9(w),A=l7($),X=K9();await o7(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),iX(this.currentLogFile))try{let w=f9(this.currentLogFile,"r+");z9(w),CW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await bX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await uX(S1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?v.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let w=typeof Z.env.NO_COLOR<"u",$=Z.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof Z.stderr<"u"&&Z.stderr.isTTY||typeof Z.stdout<"u"&&Z.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=Z.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${v.cyan(X)}`;if(!U)return Q.trim();let z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=v.underline(v.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>v.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),$}supportsHyperlinks(){if(H0())return!1;let w=Z.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=Z.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(a7($)||$.startsWith("./")||$.startsWith("../"))$=s7($);else return null;return iX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":a9[w],B=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:v.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:v.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
141
- `);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:v.gray(` ${F}`),level:w,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let z=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
142
- `;if(j)z+=`${j}
143
- `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!H0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!H0()&&Z.stdout.isTTY)Z.stdout.write(`
144
- `);if(this[W==="warning"?"warn":W](j),this.activeProgressBar&&this.shouldStyleConsole()&&!H0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":v.blue(""),tag:Y,message:`${v.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
145
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":v.green(""),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!H0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new A8($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(H0())throw Error("createReadStream is not supported in browser environments");if(!iX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Q9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=tw.isBuffer(w)?w:tw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=n7("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),z=W.length+Q.length,f=tw.allocUnsafe(z);return W.copy(f,0),Q.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
146
- `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"".repeat(W)}┐`,z=`└${"".repeat(W)}┘`,f=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:v.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(Q),showTimestamp:!1})),f.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(z),showTimestamp:!1}))}else if(!H0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
147
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(H0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${v.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();Z.stdin.removeListener("data",Y);try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!1)}catch{}Z.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!0)}catch{}Z.stdin.resume(),Z.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,Q=0;if(Y=w.replace(W,(z,f)=>{if(f==="%")return"%";if(Q>=$.length)return z;let B=$[Q++];switch(f){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return z}}),Q<$.length)Y+=` ${$.slice(Q).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${v.blue("◐")} `;console.error(`${Q}${W} ${v.cyan(A)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
148
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!Z.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=v.green("".repeat(A)),U=v.gray("".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",z=this.options.showIcons===!1?"":$||Y===100?v.green("✓"):v.blue(""),f=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",B=`\r${z}${f} ${j} ${W}${Q}`,G=Z.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,Z.stdout.write(w.lastRenderedLine),$)Z.stdout.write(`
149
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||H0()||!Z.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await bX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=S1(this.config.logDirectory,A);if(w.before)try{if((await O1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await uX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function c9(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function m9(w){return w instanceof Aw}function EN(w){return w instanceof X8}function TN(w){if(m9(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class j8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix(w),f={...$};return this.processObject(f,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return KY.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=vX.env[W]||(Q?vX.env[Q]:void 0);if(z!==void 0){if(A.verbose){let f=vX.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(f){if(f instanceof J8)throw f;throw F$.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw F$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(vX.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
185
+ -----END ${t}-----
186
+ `}function kf(){let e=jn.randomBytes(20);return e[0]=e[0]&127||1,e}function py(e=2048){let{privateKey:t,publicKey:r}=jn.generateKeyPairSync("rsa",{modulusLength:e});return{privateKey:t,publicKey:r}}function W0(e){let t=e.export({type:"spki",format:"der"});return jn.createHash("sha1").update(t).digest()}function yy(e){let t={serialNumber:e.serialNumber||kf(),notBefore:e.notBefore,notAfter:e.notAfter,subject:e.subject,issuer:e.issuer||e.subject,publicKey:e.publicKey,extensions:{basicConstraints:{isCA:e.isCA??!1,critical:!0,pathLenConstraint:e.pathLenConstraint},subjectKeyIdentifier:W0(e.publicKey)}};if(e.keyUsage)t.extensions.keyUsage={...e.keyUsage,critical:!0};if(e.extendedKeyUsage)t.extensions.extendedKeyUsage=e.extendedKeyUsage;if(e.subjectAltName?.length)t.extensions.subjectAltName=e.subjectAltName;let r=j0(t),n=U0(r,e.signingKey);return{certificate:K0(n,"CERTIFICATE"),certificateDer:n}}function wy(e){return e.export({type:"pkcs8",format:"pem"})}function V0(e){return jn.createPrivateKey(e)}function H0(e){let t=new jn.X509Certificate(e),r=t.publicKey,n=[],i=t.subject.split(`
187
+ `);for(let s of i){let[o,...c]=s.split("="),a=c.join("=");if(o&&a)n.push({shortName:o.trim(),value:a.trim()})}return{publicKey:r,subject:n}}async function Vi(e={}){C("ca","Creating new Root CA Certificate",e.verbose);let t=e.keySize||lt.DEFAULT_KEY_SIZE;C("ca",`Generating ${t}-bit RSA key pair`,e.verbose);let{privateKey:r,publicKey:n}=py(t),i=[{shortName:"C",value:e.countryName||B.countryName},{shortName:"ST",value:e.stateName||B.stateName},{shortName:"L",value:e.localityName||B.localityName},{shortName:"O",value:e.organization||"Local Development CA"},{shortName:"OU",value:e.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:e.commonName||"Local Development Root CA"}],{notBefore:s,notAfter:o}=ba({validityYears:e.validityYears||lt.DEFAULT_CA_VALIDITY_YEARS,verbose:e.verbose}),{certificate:c}=yy({serialNumber:kf(),notBefore:s,notAfter:o,subject:i,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:wy(r),notBefore:s,notAfter:o}}async function Un(e){if(C("ca","Generating new certificate",e.verbose),C("ca",`Options: ${Wi(e)}`,e.verbose),!e.domain&&!e.domains?.length)throw Error("Either domain or domains must be specified");if(!e.rootCA?.certificate||!e.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=H0(e.rootCA.certificate),r=V0(e.rootCA.privateKey);C("ca",`Generating ${lt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,e.verbose);let n=lt.DEFAULT_KEY_SIZE,{privateKey:i,publicKey:s}=py(n),o=e.commonName||Cf(e),c=e.certificateAttributes||[{shortName:"C",value:e.countryName||B.countryName},{shortName:"ST",value:e.stateName||B.stateName},{shortName:"L",value:e.localityName||B.localityName},{shortName:"O",value:e.organizationName||B.organizationName},{shortName:"CN",value:o}],{notBefore:a,notAfter:l}=ba({validityDays:e.validityDays||lt.DEFAULT_VALIDITY_DAYS,verbose:e.verbose}),u=va(e),f=e.keyUsage||{digitalSignature:!0,keyEncipherment:!0},h=e.extKeyUsage||{serverAuth:!0},{certificate:d}=yy({serialNumber:kf(),notBefore:a,notAfter:l,subject:c,issuer:t,publicKey:s,signingKey:r,isCA:e.basicConstraints?.cA??!1,pathLenConstraint:e.basicConstraints?.pathLenConstraint,keyUsage:f,extendedKeyUsage:h,subjectAltName:u});return{certificate:d,privateKey:wy(i),notBefore:a,notAfter:l}}function Of(e){let t={};for(let r of e.split(`
188
+ `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf("=");if(i===-1)continue;let s=n.slice(0,i).trim(),o=n.slice(i+1).trim();if(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))o=o.slice(1,-1);t[s]=o}return t}function Nf(e){let t=Of(e),r=[t.ID??"",...(t.ID_LIKE??"").split(/\s+/)].map((n)=>n.trim().toLowerCase()).filter(Boolean);for(let n of r){if(G0.has(n))return"debian";if(q0.has(n))return"rhel";if(Y0.has(n))return"arch"}return"unknown"}function $a(e="/"){for(let t of["/etc/os-release","/usr/lib/os-release"]){let r=Ln.join(e,t);if(!Lt.existsSync(r))continue;try{let n=Nf(Lt.readFileSync(r,"utf8"));if(n!=="unknown")return n}catch{}}for(let t of Object.values(Kn))if(Lt.existsSync(Ln.join(e,t.anchorDir)))return t.family;return"unknown"}function Ca(e){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tlsx-root-ca"}.crt`}function Df(e="/"){let t=new Set;for(let r of Object.values(Kn))for(let n of r.bundles){if(t.has(n))continue;t.add(n);let i=Ln.join(e,n);if(Lt.existsSync(i))return i}return}function xa(e,t="/"){let r=Df(t);if(!r)return!1;try{let n=Mn(e);return Sf(Lt.readFileSync(r,"utf8"),n)}catch{return!1}}function Ei(e){return`'${e.replace(/'/g,"'\\''")}'`}function vy(e){return{root:e.root??"/",exec:e.exec??((t)=>it(t)),isRoot:e.isRoot??z0.getuid?.()===0}}function J0(e){try{return _n(e)||B.commonName}catch{return B.commonName}}async function Ff(e,t={}){let{root:r,exec:n,isRoot:i}=vy(t),s=$a(r),o=[];if(C(S.TRUST,`Linux distro family: ${s} (root=${r}, isRoot=${i})`,t.verbose),s==="unknown")return{family:s,commands:o,status:"unsupported",error:"could not detect a supported distro family from /etc/os-release (debian, rhel or arch)"};let c=Kn[s],a=Ln.join(r,c.anchorDir),l=Ln.join(a,Ca(t.name??J0(e))),u={family:s,anchorPath:l,updateCommand:c.updateCommand,commands:o};if(xa(e,r))return C(S.TRUST,"CA already present in the system bundle, not rerunning the update",t.verbose),{...u,status:"already-trusted"};try{if(i)Lt.mkdirSync(a,{recursive:!0}),Lt.copyFileSync(e,l),Lt.chmodSync(l,420),o.push(c.updateCommand),C(S.TRUST,`Wrote ${l}; running ${c.updateCommand}`,t.verbose),await n(c.updateCommand);else{let f=[`sudo mkdir -p ${Ei(a)}`,`sudo cp ${Ei(e)} ${Ei(l)}`,`sudo chmod 644 ${Ei(l)}`,`sudo ${c.updateCommand}`].join(" && ");o.push(f),C(S.TRUST,`Running: ${f}`,t.verbose),await n(f)}return{...u,status:"installed"}}catch(f){return C(S.TRUST,`System trust store install failed: ${f}`,t.verbose),{...u,status:"failed",error:f instanceof Error?f.message:String(f)}}}async function Lf(e,t={}){let{root:r,exec:n,isRoot:i}=vy(t),s=$a(r),o=[];if(s==="unknown")return{family:s,commands:o,status:"unsupported",error:"could not detect a supported distro family"};let c=Kn[s],a=Ln.join(r,c.anchorDir,Ca(e)),l={family:s,anchorPath:a,updateCommand:c.updateCommand,commands:o};if(!Lt.existsSync(a))return{...l,status:"not-found"};try{if(i)Lt.unlinkSync(a),o.push(c.updateCommand),await n(c.updateCommand);else{let u=`sudo rm -f ${Ei(a)} && sudo ${c.updateCommand}`;o.push(u),await n(u)}return{...l,status:"removed"}}catch(u){return{...l,status:"failed",error:u instanceof Error?u.message:String(u)}}}function Bf(e,t){C(S.STORAGE,`Storing certificate and private key with options: ${Wi(t)}`,t?.verbose);let{certPath:r,keyPath:n}=In({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});C(S.STORAGE,`Certificate path: ${r}`,t?.verbose),C(S.STORAGE,`Private key path: ${n}`,t?.verbose);let i=zu.dirname(r);if(!er.existsSync(i))C(S.STORAGE,`Creating certificate directory: ${i}`,t?.verbose),er.mkdirSync(i,{recursive:!0});C(S.STORAGE,"Writing certificate file",t?.verbose),er.writeFileSync(r,e.certificate);let s=zu.dirname(n);if(!er.existsSync(s))C(S.STORAGE,`Creating private key directory: ${s}`,t?.verbose),er.mkdirSync(s,{recursive:!0});return C(S.STORAGE,"Writing private key file",t?.verbose),er.writeFileSync(n,e.privateKey),C(S.STORAGE,"Certificate and private key stored successfully",t?.verbose),r}function Sa(e,t){C(S.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:r}=In({basePath:t?.basePath,caCertPath:t?.caCertPath});C(S.STORAGE,`CA certificate path: ${r}`,t?.verbose);let n=zu.dirname(r);if(!er.existsSync(n))C(S.STORAGE,`Creating CA certificate directory: ${n}`,t?.verbose),er.mkdirSync(n,{recursive:!0});return C(S.STORAGE,"Writing CA certificate file",t?.verbose),er.writeFileSync(r,e),C(S.STORAGE,"CA certificate stored successfully",t?.verbose),r}function Bn(e,t){return{platform:e,stores:t,trusted:t.some((r)=>r.status==="installed"||r.status==="already-trusted")}}async function If(e,t,r){let n=Bt.platform();if(n==="linux"){let i=xa(e,r?.root);return C(S.TRUST,i?"Certificate found in the system CA bundle":"Certificate not in the system CA bundle",t),i}if(n!=="darwin")return!1;try{let i=Mn(e);if(!i)return C(S.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(X0("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
189
+ `).some((s)=>{let o=s.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!o&&o[1].toUpperCase()===i}))return C(S.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return C(S.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(i){return C(S.TRUST,`Error checking certificate trust: ${i}`,t),!1}}async function by(e,t){return If(e,t?.verbose,t?.linux)}async function Ea(e,t,r){C(S.TRUST,`Adding certificate to system trust store with options: ${Wi(r)}`,r?.verbose),C(S.TRUST,"Storing certificate and private key",r?.verbose);let n=Bf(e,r);C(S.TRUST,"Storing CA certificate",r?.verbose);let i=Sa(t,r),s=Bt.platform();C(S.TRUST,`Detected platform: ${s}`,r?.verbose);let o=Wn[s];if(!o){let c=`Unsupported platform: ${s}`;throw C(S.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await o.addCertificate(i,r),C(S.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}async function $y(e,t){let r=Bt.platform();C(S.TRUST,`Adding ${e} to the ${r} trust store`,t?.verbose);let n=Wn[r];if(!n)throw Error(`Unsupported platform: ${r}`);return n.addCertificate(e,t)}async function Cy(e,t,r){C(S.TRUST,`Removing certificate for ${e} from system trust store`,t?.verbose);let n=t?.caCertPath||B.caCertPath,i=r||B.commonName,s=Bt.platform();C(S.TRUST,`Detected platform: ${s}`,t?.verbose);let o=Wn[s];if(!o){let c=`Unsupported platform: ${s}`;throw C(S.TRUST,`Error: ${c}`,t?.verbose),Error(c)}if(!o.removeCertificate)throw Error(`Removing certificates is not supported on ${s}`);await o.removeCertificate(n,t,i),C(S.TRUST,`Certificate for ${e} successfully removed from system trust store`,t?.verbose)}async function xy(e,t){let r=e?.verbose||B.verbose;C(S.TRUST,"Cleaning up all TLSX certificates from system trust store",r);let n=Bt.platform();C(S.TRUST,`Detected platform: ${n}`,r);let i=Wn[n];if(!i){let s=`Unsupported platform: ${n}`;throw C(S.TRUST,`Error: ${s}`,r),Error(s)}if(!i.removeCertificate)throw Error(`Removing certificates is not supported on ${n}`);try{if(n==="darwin"){C(S.TRUST,"Removing all TLSX certificates from macOS keychain",r);let s=t||B.commonName;await it(`sudo security find-certificate -a -c "${s}" -Z /Library/Keychains/System.keychain | grep SHA-1 | awk '{print $3}' | xargs -I {} sudo security delete-certificate -Z {} /Library/Keychains/System.keychain`),ie.success(`All certificates matching "${s}" removed from macOS keychain`)}else if(n==="win32"){C(S.TRUST,"Removing all TLSX certificates from Windows certificate store",r);let s=t||B.organizationName;await it(`certutil -delstore -enterprise Root "${s}"`),ie.success(`All certificates matching "${s}" removed from Windows certificate store`)}else if(n==="linux"){C(S.TRUST,"Removing all TLSX certificates from Linux certificate stores",r);let s=Bt.homedir(),o=lt.LINUX_CERT_DB_FILENAME;C(S.TRUST,`Searching for certificate databases in ${s}`,r);let c=Li(s,o);if(c.length===0){ie.warn("No certificate databases found. Cannot clean up certificates.");return}for(let a of c){C(S.TRUST,`Processing certificate database in ${a}`,r);try{let{stdout:l}=await it(`certutil -d sql:${a} -L`),u=l.split(`
190
+ `);for(let f of u)if(t?f.toLowerCase().includes(t.toLowerCase()):f.includes(B.organizationName)||f.includes("tlsx")||f.includes("Local Development")){let h=f.split(/\s+/)[0].trim();if(h){C(S.TRUST,`Removing certificate: ${h}`,r);try{await it(`certutil -d sql:${a} -D -n "${h}"`),ie.info(`Removed certificate ${h} from ${a}`)}catch(d){C(S.TRUST,`Error removing cert ${h}: ${d}`,r)}}}}catch(l){C(S.TRUST,`Error processing database ${a}: ${l}`,r),console.warn(`Error processing database ${a}: ${l}`)}}ie.success("All matching certificates removed from Linux certificate stores")}C(S.TRUST,"Trust store cleanup completed successfully",r)}catch(s){throw C(S.TRUST,`Error cleaning up trust store: ${s}`,r),Error(`Failed to clean up trust store: ${s}`)}}async function Ta(e){let t=e?.verbose??B.verbose,{caCertPath:r,basePath:n}=In({basePath:e?.basePath,caCertPath:e?.caCertPath}),i=r.replace(/\.crt$/,".key");C(S.TRUST,`installCA: caCertPath=${r}`,t),C(S.TRUST,`installCA: basePath=${n}`,t);let s=!1;if(!(Nn.existsSync(r)&&Nn.existsSync(i))){C(S.TRUST,"No existing Root CA found, generating one",t);let l=await Vi({...e?.ca,verbose:t});Sa(l.certificate,{...e,basePath:n,caCertPath:r}),Nn.writeFileSync(i,l.privateKey,{mode:384}),s=!0,ie.success(`Generated new Root CA at ${r}`)}else C(S.TRUST,"Reusing existing Root CA on disk",t),ie.info(`Using existing Root CA at ${r}`);let o=Bt.platform(),c=Wn[o];if(!c)throw Error(`installCA: unsupported platform: ${o}`);if(await If(r,t,e?.linux)){ie.success("Root CA is already trusted in the system store");let l=Bn(o,[{store:o==="linux"?"linux-system":"macos-keychain",location:o==="linux"?"system CA bundle":Ti,status:"already-trusted"}]);return{caCertPath:r,caKeyPath:i,generated:s,trustInstalled:!1,alreadyTrusted:!0,report:l}}let a=await c.addCertificate(r,e);if(a.trusted)ie.success("Root CA installed in the system trust store");else ie.warn("Root CA was not installed into any trust store; see the report for details");return{caCertPath:r,caKeyPath:i,generated:s,trustInstalled:a.trusted,alreadyTrusted:!1,report:a}}async function Sy(e){let t=e?.verbose??B.verbose,{caCertPath:r}=In({basePath:e?.basePath,caCertPath:e?.caCertPath}),n=r.replace(/\.crt$/,".key"),i=e?.certName;if(!i&&Nn.existsSync(r))try{i=_n(r)||void 0,C(S.TRUST,`uninstallCA: extracted CN from cert: ${i}`,t)}catch(l){C(S.TRUST,`uninstallCA: CN extraction failed: ${l}`,t)}i=i??B.commonName;let s=Bt.platform(),o=Wn[s];if(!o?.removeCertificate)throw Error(`uninstallCA: removing certificates is not supported on ${s}`);let c=!1;try{await o.removeCertificate(r,e,i),c=!0,ie.success(`Root CA "${i}" removed from the system trust store`)}catch(l){C(S.TRUST,`uninstallCA: handler.removeCertificate failed: ${l}`,t),ie.warn(`Could not remove Root CA from trust store: ${l.message}`)}let a=!1;if(e?.deleteFiles){for(let l of[r,n])try{if(Nn.existsSync(l))Nn.unlinkSync(l),C(S.TRUST,`uninstallCA: deleted ${l}`,t),a=!0}catch(u){C(S.TRUST,`uninstallCA: failed to delete ${l}: ${u}`,t)}if(a)ie.success("Removed CA cert + key from disk")}return{removedFromTrustStore:c,filesDeleted:a,caCertPath:r,caKeyPath:n}}var xi,ca=30000,Ui,Yu,Qu="https://acme-staging-v02.api.letsencrypt.org/directory",ef="https://acme-v02.api.letsencrypt.org/directory",ki,Yx="1.2.840.10045.2.1",Jx="1.2.840.10045.3.1.7",Xx="1.2.840.10045.4.3.2",Zx="2.5.4.3",Qx="1.2.840.113549.1.9.14",eS="2.5.29.17",lt,mp,S,Zo,lf,HS,zS=(e)=>e,qS=(e,t)=>{for(var r in t)HS(e,r,{get:t[r],enumerable:!0,configurable:!0,set:GS.bind(t,r)})},YS=(e,t)=>()=>(e&&(t=e(e=0)),t),vp,Ap,Dn,Ki,Rp,CE,xE,Gg,jo,Fu,je,ne,SE,qg,EE,Yg,TE,PE,Su,AE,Jg,Xg,Eu,RE,kE,OE,NE,Uo,kp,DE,Ue,FE,LE,Zg,Ko,Lu,Se,W,BE,Qg,IE,ep,ME,_E,Tu,jE,tp,rp,UE,Pu,KE,WE,VE,HE,zE,Wo,Op,GE,qE="0.15.6",ct,na,Di,Bu,Iu,ia,Mu,_u,Fi,ju,Uu,Cr,Np,Dp,Pt,tr,Fp,Lp,YE,XE,Bp,sa,aF,Oe,z,cF,QE,lF,e0,uF,fF,np,hF,t0,r0,dF,ip,mF,gF,pF,yF,wF,Au,n0,vF,Rt,Mp,oa,_p,jp,yf,Up,Kp,aa,Wp,Vp,Fn,u0,Ft,Ru,bF,$F,ma,ku=null,B,ie,g0,sp="[redacted]",p0,y0,$0,Tf,Pf,S0,wa="dev.stacksjs.tlsx",E0="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Af,At,Ze,Kn,G0,q0,Y0,Ti="/Library/Keychains/System.keychain",Z0,Q0,eT,Wn;var Ey=te(()=>{xi=Wx(import.meta.url);Ui=new Wr;Yu=class Yu extends Wr{webroot;written=new Set;constructor(e){super();this.webroot=e,xi("node:fs").mkdirSync(this.webroot,{recursive:!0})}filePath(e){let t=xi("node:path");return t.join(this.webroot,t.basename(e))}add(e,t){super.add(e,t),xi("node:fs").writeFileSync(this.filePath(e),t,"utf8"),this.written.add(e)}remove(e){super.remove(e);let t=xi("node:fs");try{t.unlinkSync(this.filePath(e))}catch{}this.written.delete(e)}cleanup(){for(let e of[...this.written])this.remove(e)}};ki=class ki extends Error{problem;httpStatus;constructor(e,t,r){super(e);this.name="AcmeError",this.problem=t,this.httpStatus=r}};lt={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"},mp={DEFAULT_CERT_DIR:".stacks/ssl",CERT_EXTENSION:".crt",KEY_EXTENSION:".crt.key",CA_CERT_EXTENSION:".ca.crt"},S={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"};Zo=new yp,lf=new wp,HS=Object.defineProperty;vp={};qS(vp,{withErrorRecovery:()=>Cp,tryLoadConfig:()=>wE,loadConfigWithResult:()=>pE,loadConfig:()=>Pp,isRetryableError:()=>uE,isConfigNotFoundError:()=>lE,isBunfigError:()=>xp,globalPerformanceMonitor:()=>Ki,globalCache:()=>Dn,getEnvOrDefault:()=>fE,generateConfigTypes:()=>vE,defaultGeneratedDir:()=>Lp,defaultConfigDir:()=>Fp,deepMergeWithArrayStrategy:()=>mf,deepMerge:()=>Sp,createLibraryConfig:()=>bE,config:()=>yE,bunfigPlugin:()=>$E,applyEnvVarsToConfig:()=>Si,TypeGenerationError:()=>_u,SchemaValidationError:()=>Fi,PluginError:()=>Uu,PerformanceMonitor:()=>ff,FileSystemError:()=>Mu,ErrorFactory:()=>Cr,EnvVarError:()=>ia,EnvProcessor:()=>fa,ConfigValidator:()=>gf,ConfigValidationError:()=>Bu,ConfigNotFoundError:()=>na,ConfigMergeError:()=>Iu,ConfigLoader:()=>pf,ConfigLoadError:()=>Di,ConfigFileLoader:()=>ha,ConfigCache:()=>uf,CacheUtils:()=>Rp,BunfigError:()=>ct,BrowserConfigError:()=>ju,ArrayMergeStrategies:()=>Np});YE=YS(async()=>{Ap=import.meta.require,Dn=new uf,Ki=new ff,Rp={createKey:JS,isEquivalent:XS,estimateMemoryUsage:ZS},CE=Jo(Nu.cwd(),"config"),xE=Jo(Nu.cwd(),"src/generated"),Gg=Yo.env.CLARITY_LOG_DIR||fS(tE(),"logs"),jo={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Gg,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Fu=await rE(),je={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},ne=je,SE=je.red,qg=je.green,EE=je.yellow,Yg=je.blue,TE=je.magenta,PE=je.cyan,Su=je.white,AE=je.gray,Jg=je.bgRed,Xg=je.bgYellow,Eu=je.bold,RE=je.dim,kE=je.italic,OE=je.underline,NE=je.reset,Uo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},kp={debug:"\uD83D\uDD0D",info:Yg("ℹ"),success:qg("✓"),warning:Xg(Su(Eu(" WARN "))),error:Jg(Su(Eu(" ERROR ")))},DE=new ea("stacks"),Ue=new ea("bunfig",{showTags:!0}),FE=Je(Ni.cwd(),"config"),LE=Je(Ni.cwd(),"src/generated"),Zg=qo.env.CLARITY_LOG_DIR||lS(oE(),"logs"),Ko={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Zg,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lu=await aE(),Se={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},W=Se,BE=Se.red,Qg=Se.green,IE=Se.yellow,ep=Se.blue,ME=Se.magenta,_E=Se.cyan,Tu=Se.white,jE=Se.gray,tp=Se.bgRed,rp=Se.bgYellow,UE=Se.bgGray,Pu=Se.bold,KE=Se.dim,WE=Se.italic,VE=Se.underline,HE=Se.strikethrough,zE=Se.reset,Wo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Op={debug:"\uD83D\uDD0D",info:ep("ℹ"),success:Qg("✓"),warning:rp(Tu(Pu(" WARN "))),error:tp(Tu(Pu(" ERROR ")))},GE=new ra("stacks"),ct=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},na=class extends ct{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},Di=class extends ct{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Bu=class extends ct{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Iu=class extends ct{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},ia=class extends ct{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}},Mu=class extends ct{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},_u=class extends ct{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Fi=class extends ct{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},ju=class extends ct{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}},Uu=class extends ct{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Cr={configNotFound(e,t,r){return new na(e,t,r)},configLoad(e,t,r){return new Di(e,t,r)},configValidation(e,t,r){return new Bu(e,t,r)},configMerge(e,t,r,n){return new Iu(e,t,r,n)},envVar(e,t,r,n){return new ia(e,t,r,n)},fileSystem(e,t,r){return new Mu(e,t,r)},typeGeneration(e,t,r){return new _u(e,t,r)},schemaValidation(e,t,r){return new Fi(e,t,r)},browserConfig(e,t,r,n){return new ju(e,t,r,n)},plugin(e,t,r){return new Uu(e,t,r)}},Np={replace:"replace",concat:"concat",smart:"smart"},Dp=/^https?:\/\//,Pt=new ra("bunfig",{showTags:!0}),tr=new pf,Fp=Xe(Vr.cwd(),"config"),Lp=Xe(Vr.cwd(),"src/generated")});XE=Xo.env.CLARITY_LOG_DIR||DS(JE(),"logs"),Bp={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:XE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},sa={...Bp},aF=(async()=>{try{let{loadConfig:e}=await YE().then(()=>vp),t=await e({name:"clarity",alias:"logging",defaultConfig:Bp,cwd:Xo.cwd()});if(t)Object.assign(sa,t)}catch{}return sa})();Oe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},z=Oe,cF=Oe.red,QE=Oe.green,lF=Oe.yellow,e0=Oe.blue,uF=Oe.magenta,fF=Oe.cyan,np=Oe.white,hF=Oe.gray,t0=Oe.bgRed,r0=Oe.bgYellow,dF=Oe.bgGray,ip=Oe.bold,mF=Oe.dim,gF=Oe.italic,pF=Oe.underline,yF=Oe.strikethrough,wF=Oe.reset,Au={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},n0={debug:"\uD83D\uDD0D",info:e0("ℹ"),success:QE("✓"),warning:r0(np(ip(" WARN "))),error:t0(np(ip(" ERROR ")))};vF=new da("stacks");Rt=class Rt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};Mp=class Mp extends Rt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};oa=class oa extends Rt{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};_p=class _p extends Rt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};jp=class jp extends Rt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,n){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}};yf=class yf extends Rt{code="ENV_VAR_ERROR";constructor(e,t,r,n){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:n})}};Up=class Up extends Rt{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Kp=class Kp extends Rt{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};aa=class aa extends Rt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Wp=class Wp extends Rt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,n){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:n})}};Vp=class Vp extends Rt{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Fn={configNotFound(e,t,r){return new Mp(e,t,r)},configLoad(e,t,r){return new oa(e,t,r)},configValidation(e,t,r){return new _p(e,t,r)},configMerge(e,t,r,n){return new jp(e,t,r,n)},envVar(e,t,r,n){return new yf(e,t,r,n)},fileSystem(e,t,r){return new Up(e,t,r)},typeGeneration(e,t,r){return new Kp(e,t,r)},schemaValidation(e,t,r){return new aa(e,t,r)},browserConfig(e,t,r,n){return new Wp(e,t,r,n)},plugin(e,t,r){return new Vp(e,t,r)}};u0=/^https?:\/\//;Ft=new da("bunfig",{showTags:!0});Ru=new Jp;bF=wt(ua.cwd(),"config"),$F=wt(ua.cwd(),"src/generated"),ma={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:lu.join(cu.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:lu.join(cu.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:lu.join(cu.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};B=ma,ie={info:(...e)=>console.log(...e),warn:(...e)=>console.warn(...e),success:(...e)=>console.log(...e),error:(...e)=>console.error(...e),debug:(...e)=>console.debug(...e)};g0=m0(d0);p0=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),y0=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;$0=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g;Tf=["macos","ios","windows","debian","rhel","android","linux-nss"],Pf={pem:"application/x-pem-file",der:"application/x-x509-ca-cert",mobileconfig:"application/x-apple-aspen-config"},S0={pem:"pem",der:"cer",mobileconfig:"mobileconfig"};Af=_i(wa,E0);At={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},Ze={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"};Kn={debian:{family:"debian",anchorDir:"/usr/local/share/ca-certificates",updateCommand:"update-ca-certificates",bundles:["/etc/ssl/certs/ca-certificates.crt"]},rhel:{family:"rhel",anchorDir:"/etc/pki/ca-trust/source/anchors",updateCommand:"update-ca-trust",bundles:["/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"]},arch:{family:"arch",anchorDir:"/etc/ca-certificates/trust-source/anchors",updateCommand:"trust extract-compat",bundles:["/etc/ca-certificates/extracted/tls-ca-bundle.pem","/etc/ssl/certs/ca-certificates.crt"]}},G0=new Set(["debian","ubuntu","raspbian","linuxmint","pop","elementary","kali","neon","zorin","alpine"]),q0=new Set(["rhel","fedora","centos","rocky","almalinux","ol","oracle","amzn"]),Y0=new Set(["arch","archarm","manjaro","endeavouros","garuda"]);Z0={platform:"darwin",async addCertificate(e,t){if(await If(e,t?.verbose))return C(S.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),ie.success("Certificate is already trusted in system keychain"),Bn("darwin",[{store:"macos-keychain",location:Ti,status:"already-trusted"}]);return C(S.TRUST,"Adding certificate to macOS keychain",t?.verbose),await it(`sudo security add-trusted-cert -d -r trustRoot -k ${Ti} ${e}`),Bn("darwin",[{store:"macos-keychain",location:Ti,status:"installed"}])},async removeCertificate(e,t,r){let n=r||B.commonName;C(S.TRUST,`Removing certificate ${n} from macOS keychain`,t?.verbose);try{await it(`sudo security delete-certificate -c "${n}" ${Ti}`),C(S.TRUST,`Removed certificate ${n} from macOS keychain`,t?.verbose)}catch(i){throw C(S.TRUST,`Error removing certificate: ${i}`,t?.verbose),i}}},Q0={platform:"win32",async addCertificate(e,t){return C(S.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await it(`certutil -f -v -addstore -enterprise Root ${e}`),Bn("win32",[{store:"windows-root",location:"LocalMachine\\Root",status:"installed"}])},async removeCertificate(e,t,r){let n=r||B.commonName;C(S.TRUST,`Removing certificate ${n} from Windows certificate store`,t?.verbose);try{await it(`certutil -delstore -enterprise Root "${n}"`),C(S.TRUST,`Removed certificate ${n} from Windows certificate store`,t?.verbose)}catch(i){throw C(S.TRUST,`Error removing certificate: ${i}`,t?.verbose),i}}},eT={platform:"linux",async addCertificate(e,t){let r=t?.verbose,n=[];C(S.TRUST,"Adding certificate to the Linux system trust store",r);let i=await Ff(e,{...t?.linux,verbose:r}),s=i.anchorPath??"(no supported anchor directory)";if(i.status==="installed")ie.success(`Root CA installed into the ${i.family} system trust store (${i.anchorPath})`),n.push({store:"linux-system",location:s,status:"installed"});else if(i.status==="already-trusted")ie.success("Root CA is already in the system CA bundle"),n.push({store:"linux-system",location:s,status:"already-trusted"});else if(i.status==="failed")ie.warn(`Could not update the ${i.family} system trust store: ${i.error}`),n.push({store:"linux-system",location:s,status:"failed",detail:i.error});else C(S.TRUST,`System trust store skipped: ${i.error}`,r),n.push({store:"linux-system",location:s,status:"skipped",detail:i.error});let o=i.status==="installed"||i.status==="already-trusted",c=Bt.homedir(),a=lt.LINUX_CERT_DB_FILENAME,l=lt.LINUX_TRUST_ARGS;C(S.TRUST,`Searching for certificate databases in ${c}`,r);let u=Li(c,a);if(u.length===0){if(o)C(S.TRUST,"No NSS certificate databases found; the system store covers this host",r);else ie.warn("No certificate databases found and the system trust store was not updated. Certificate may not be trusted by the system.");return Bn("linux",n)}for(let f of u){C(S.TRUST,`Processing certificate database in ${f}`,r);try{C(S.TRUST,`Attempting to delete existing cert for ${B.commonName}`,r),await it(`certutil -d sql:${f} -D -n ${B.commonName}`)}catch(h){C(S.TRUST,`Warning: Error deleting existing cert: ${h}`,r),console.warn(`Error deleting existing cert: ${h}`)}C(S.TRUST,`Adding new certificate to ${f}`,r);try{await it(`certutil -d sql:${f} -A -t ${l} -n ${B.commonName} -i ${e}`),ie.info(`Cert added to ${f}`),n.push({store:"linux-nss",location:f,status:"installed"})}catch(h){if(!o)throw h;C(S.TRUST,`certutil failed for ${f}: ${h}`,r),n.push({store:"linux-nss",location:f,status:"failed",detail:h instanceof Error?h.message:String(h)})}}return Bn("linux",n)},async removeCertificate(e,t,r){let n=r||B.commonName;C(S.TRUST,`Removing certificate ${n} from Linux certificate store`,t?.verbose);let i=await Lf(n,{...t?.linux,verbose:t?.verbose});if(i.status==="removed")ie.info(`Removed ${i.anchorPath} from the ${i.family} system trust store`);else if(i.status==="failed")ie.warn(`Could not remove the CA from the system trust store: ${i.error}`);else C(S.TRUST,`System trust store removal: ${i.status}`,t?.verbose);let s=Bt.homedir(),o=lt.LINUX_CERT_DB_FILENAME;C(S.TRUST,`Searching for certificate databases in ${s}`,t?.verbose);let c=Li(s,o);if(c.length===0){ie.warn("No certificate databases found. Cannot remove certificate.");return}for(let a of c){C(S.TRUST,`Processing certificate database in ${a}`,t?.verbose);try{await it(`certutil -d sql:${a} -D -n "${n}"`),ie.info(`Cert removed from ${a}`)}catch(l){C(S.TRUST,`Error removing cert from ${a}: ${l}`,t?.verbose),console.warn(`Error removing cert from ${a}: ${l}`)}}}},Wn={darwin:Z0,win32:Q0,linux:eT}});var Mf={};nl(Mf,{AcmeClient:()=>Oi,AcmeError:()=>ki,CERT_CONSTANTS:()=>lt,DEFAULT_PROFILE_IDENTIFIER_PREFIX:()=>wa,DEFAULT_REQUEST_TIMEOUT_MS:()=>ca,EXPORT_MIME_TYPES:()=>Pf,FileHttp01Store:()=>Yu,Http01Store:()=>Wr,LETS_ENCRYPT_PRODUCTION_DIRECTORY:()=>ef,LETS_ENCRYPT_STAGING_DIRECTORY:()=>Qu,LINUX_DISTRO_STORES:()=>Kn,LOG_CATEGORIES:()=>S,PATH_CONSTANTS:()=>mp,PorkbunDnsProvider:()=>qu,TLSX_UUID_NAMESPACE:()=>Af,TRUST_PLATFORMS:()=>Tf,addCertToSystemTrustStore:()=>$y,addCertToSystemTrustStoreAndSaveCert:()=>Ea,base64urlDecode:()=>Ri,base64urlDecodeToString:()=>up,base64urlEncode:()=>Pi,buildCsr:()=>af,buildCsrBase64url:()=>cf,buildMobileConfig:()=>Rf,calculateValidityDates:()=>ba,certFileBase:()=>ey,cleanupTrustStore:()=>xy,config:()=>B,createRootCA:()=>Vi,debugLog:()=>C,defaultConfig:()=>ma,defaultHttp01Store:()=>Ui,derBitString:()=>zo,derContext:()=>Go,derInteger:()=>nf,derNull:()=>fp,derOctetString:()=>sf,derOid:()=>$r,derPrintableString:()=>hp,derSequence:()=>at,derSet:()=>Ho,derUtf8String:()=>of,detectLinuxDistroFamily:()=>Nf,dns01RecordName:()=>rf,exportCA:()=>ly,fetchWithTimeout:()=>kn,findFoldersWithFile:()=>Li,findLinuxCaBundle:()=>Df,generateCertificate:()=>Un,generateCertificateExtensions:()=>hy,generateRandomSerial:()=>fy,generateSubjectAltNames:()=>va,getCertCommonName:()=>_n,getCertSha256Fingerprint:()=>Mn,getCertificateFromCertPemOrPath:()=>nr,getConfig:()=>Xp,getPrimaryDomain:()=>Cf,getSudoPassword:()=>$f,installCA:()=>Ta,installCAIntoLinuxSystemStore:()=>Ff,isCertExpired:()=>iy,isCertTrusted:()=>by,isCertTrustedOnLinux:()=>xa,isCertValidForDomain:()=>ya,jwkFromKey:()=>Ju,jwkThumbprint:()=>Xu,linuxAnchorFileName:()=>Ca,listCertsInDirectory:()=>Qp,log:()=>ie,makeNumberPositive:()=>bf,normalizeCertPaths:()=>In,obtainCertificate:()=>la,parseCertDetails:()=>ny,parseOsRelease:()=>Of,pemBundleHasFingerprint:()=>Sf,pemToDer:()=>ga,readCertFromFile:()=>vf,readLinuxDistroFamily:()=>$a,redactSensitive:()=>Bi,removeCAFromLinuxSystemStore:()=>Lf,removeCertFromSystemTrustStore:()=>Cy,renewalOutputBase:()=>ty,runCommand:()=>it,safeStringify:()=>Wi,sha256FingerprintOfDer:()=>pa,signJws:()=>Zu,splitApexAndSubdomain:()=>Vo,splitPemCertificates:()=>xf,splitPemChain:()=>tf,storeCACertificate:()=>Sa,storeCertificate:()=>Bf,trustInstructions:()=>uy,uninstallCA:()=>Sy,uuidV5:()=>_i,validateBrowserCompatibility:()=>ay,validateCertificate:()=>oy,verifyServerChain:()=>Ef,waitForTxtRecord:()=>Gu,willCertExpireSoon:()=>sy});var Hi=te(()=>{Ey()});function Hr(e){try{return Mn(e)}catch{return null}}function _f(e){try{return _n(e)||null}catch{return null}}function jf(e,t){try{return t.every((r)=>ya(e,r))}catch{return!1}}var Pa=te(()=>{Hi()});import{existsSync as Ty,statSync as Py}from"fs";import{existsSync as sh,mkdirSync as oT,readdirSync as aT,writeFileSync as cT}from"fs";import{homedir as Vn}from"os";import{dirname as Ay,resolve as et}from"path";import zr from"process";import{join as lT,relative as uT,resolve as Ry}from"path";import Va from"process";import{existsSync as fw,mkdirSync as hL,readdirSync as dL,writeFileSync as mL}from"fs";import{homedir as Uf}from"os";import{dirname as yL,resolve as Qe}from"path";import Gi from"process";import{join as fT,relative as hT,resolve as ky}from"path";import Ha from"process";import{existsSync as hw,mkdirSync as CL,readdirSync as xL,writeFileSync as SL}from"fs";import{dirname as TL,resolve as za}from"path";import oh from"process";import{Buffer as xr}from"buffer";import{createCipheriv as dT,createDecipheriv as mT,randomBytes as Kf}from"crypto";import{closeSync as Wf,createReadStream as Oy,createWriteStream as gT,existsSync as Vf,fsyncSync as Ny,openSync as Dy,writeFileSync as pT}from"fs";import{access as yT,constants as Fy,mkdir as wT,readdir as Aa,rename as Ly,stat as Hn,unlink as Ra,writeFile as Hf}from"fs/promises";import{join as zn}from"path";import Ke from"process";import{pipeline as vT}from"stream/promises";import{createGzip as By}from"zlib";import Gn from"process";import or from"process";import{Buffer as ir}from"buffer";import{createCipheriv as bT,createDecipheriv as $T,randomBytes as zf}from"crypto";import{closeSync as Gf,createReadStream as Iy,createWriteStream as CT,existsSync as ka,fsyncSync as My,openSync as _y,writeFileSync as xT}from"fs";import{access as ST,constants as jy,mkdir as ET,readdir as Oa,rename as Uy,stat as qn,unlink as Na,writeFile as qf}from"fs/promises";import{isAbsolute as TT,join as Yn,resolve as PT}from"path";import _ from"process";import{pipeline as AT}from"stream/promises";import{createGzip as Ky}from"zlib";import Jn from"process";import ar from"process";import Da from"process";import{existsSync as Fa}from"fs";import{resolve as Yf}from"path";import{existsSync as RT}from"fs";import{existsSync as kT,readdirSync as OT}from"fs";import{extname as Jf,resolve as Wy}from"path";import NT from"process";import{join as DP,relative as FP,resolve as tw}from"path";import Qa from"process";import{Buffer as sr}from"buffer";import{createCipheriv as IP,createDecipheriv as MP,randomBytes as th}from"crypto";import{closeSync as rh,createReadStream as rw,createWriteStream as _P,existsSync as Ba,fsyncSync as nw,openSync as iw,writeFileSync as jP}from"fs";import{access as UP,constants as sw,mkdir as KP,readdir as Ia,rename as ow,stat as Xn,unlink as Ma,writeFile as nh}from"fs/promises";import{isAbsolute as WP,join as Zn,resolve as VP}from"path";import j from"process";import{pipeline as HP}from"stream/promises";import{createGzip as aw}from"zlib";import Qn from"process";import cr from"process";function nT(e,t){this[e]=rT.bind(null,t)}class ph{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,n){if(!this.options.enabled)return;let i=this.generateKey(e,r),s=n??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(e,t){try{if(!Ty(e))return!0;return Py(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,n){try{let i=Ty(r)?Py(r):null,s=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,n)}catch{this.set(e,t,r,n)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((n,i)=>n+i.size,0),r=e.map((n)=>n.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class yh{metrics=[];maxMetrics=1000;async track(e,t,r={}){let n=performance.now(),i=new Date;try{let s=await t(),o=performance.now()-n;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),s}catch(s){let o=performance.now()-n;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),n=r.reduce((i,s)=>i+s,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function DT(e,t={}){let n=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return n?`${e}:${n}`:e}function FT(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function LT(e){return e.getStats().size*2}function wh(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&le(t[0])&&"id"in t[0]&&t[0].id===3&&le(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(le(t)&&le(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(le(e)&&"arr"in e&&Array.isArray(e.arr)&&le(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&le(t[0])&&le(e[0])){let n=[...t];for(let i of e)if(le(i)&&"name"in i){if(!n.find((o)=>le(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(le(i)&&"path"in i){if(!n.find((o)=>le(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>Ga(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!le(t)||!le(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(le(i)&&le(r[n]))r[n]=wh(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&le(i[0])&&le(r[n][0])){let s=[...i];for(let o of r[n])if(le(o)&&"name"in o){if(!s.find((a)=>le(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(le(o)&&"path"in o){if(!s.find((a)=>le(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Ga(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function Ga(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ga(e[r],t[r]))return!1;return!0}if(le(e)&&le(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Ga(e[i],t[i]))return!1}return!0}return!1}function le(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function BT(e,t){if(!hw(e))return null;try{let r=await import(e),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return wh(t,n)}catch{return null}}catch{return null}}async function IT({name:e="",cwd:t,defaultConfig:r}){let n=t||oh.cwd(),i=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of i){let a=za(n,`${o}${c}`),l=await BT(a,r);if(l!==null)return l}try{let o=za(n,"package.json");if(hw(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return wh(r,a)}catch{}}}catch{}return r}function MT(e,t={}){let r=Ha.cwd();while(r.includes("storage"))r=ky(r,"..");let n=ky(r,e||"");if(t?.relative)return hT(Ha.cwd(),n);return n}async function _T(){try{let e=await IT({name:"clarity",defaultConfig:ja,cwd:Ha.cwd(),endpoint:"",headers:{}});return{...ja,...e}}catch{return ja}}function me(){if(or.env.NODE_ENV==="test"||or.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jT(){if(or.env.NODE_ENV==="test"||or.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof or<"u"){let e=or.type;if(e==="renderer"||e==="worker")return!1;return!!(or.versions&&(or.versions.node||or.versions.bun))}return!1}class dw{async format(e){let t=await jT(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Gn.pid,hostname:t(),environment:Gn.env.NODE_ENV||"development",platform:Gn.platform,version:Gn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Gn.env.NODE_ENV||Gn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qa{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(e,t={}){this.name=e,this.config={...ch},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new dw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Ke.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ua,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ua};return{...Ua,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ch.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await yT(this.config.logDirectory,Fy.F_OK|Fy.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await wT(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:xr.from(e);try{if(!Vf(this.currentLogFile))await Hf(this.currentLogFile,"",{mode:420});if(i=Dy(this.currentLogFile,"a",420),pT(i,a,{flag:"a"}),Ny(i),i!==void 0)Wf(i),i=void 0;if((await Hn(this.currentLogFile)).size===0){if(await Hf(this.currentLogFile,a,{flag:"w",mode:420}),(await Hn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{Wf(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 zn(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 zn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return zn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(me())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Kf(16).toString("hex")}generateKey(){return Kf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Kf(16),n=dT("aes-256-gcm",t,r),i=xr.concat([n.update(e,"utf8"),n.final()]),s=n.getAuthTag();return{encrypted:xr.concat([r,i,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let n=By(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(xr.from(xr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(me())return;let e=await Hn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Aa(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Hn(r).catch(()=>null))try{if(await Ly(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ra(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Hf(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Hn(r).catch(()=>null))await Ly(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Aa(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Ra(zn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Oy(e),n=gT(t),i=By();await vT(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Vf(this.currentLogFile))try{let e=Dy(this.currentLogFile,"r+");Ny(e),Wf(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!me()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Aa(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ra(zn(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?se.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=Ke.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${se.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!me()){let l=xw[e],u=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:se.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:se.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:i,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
191
+ `);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:se.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!me()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
192
+ `;if(c)a+=`${c}
193
+ `;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!me()){let r=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:se.blue(""),tag:r,message:`${se.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
194
+ `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!me()){let u=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:se.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!me())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new qa(t,{...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(r),r}createReadStream(){if(me())throw Error("createReadStream is not supported in browser environments");if(!Vf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Oy(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=xr.isBuffer(e)?e:xr.from(e,"base64"),i=n.slice(0,16),s=n.slice(-16),o=n.slice(16,-16),c=mT("aes-256-gcm",r,i);return c.setAuthTag(s),xr.concat([c.update(o),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return me()}isServerMode(){return!me()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!me()){let s=e.split(`
195
+ `),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:se.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:se.cyan(c)})),l.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:se.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:se.cyan(a),showTimestamp:!1}))}else if(!me())console.error(`${n} ${this.environment}.INFO: [BOX] ${e}`);let i=`${n} ${this.environment}.INFO: [BOX] ${e}
196
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}async prompt(e){if(me())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${se.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();Ke.stdin.removeListener("data",r);try{if(typeof Ke.stdin.setRawMode==="function")Ke.stdin.setRawMode(!1)}catch{}Ke.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof Ke.stdin.setRawMode==="function")Ke.stdin.setRawMode(!0)}catch{}Ke.stdin.resume(),Ke.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!me()){let o=this.options.showTags!==!1&&this.name?se.gray(this.formatTag(this.name)):"",c=se.blue("◐");console.error(`${c} ${o} ${se.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
197
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||me()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||me())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||me())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||me())return;Ke.stdout.write(`${"\r".padEnd(Ke.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||me()||!Ke.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=se.green("━".repeat(n)),o=se.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=t||r===100?se.green("✓"):se.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${se.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=Ke.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,Ke.stdout.write(e.lastRenderedLine),t)Ke.stdout.write(`
198
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||me()||!Ke.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(me()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Aa(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=zn(this.config.logDirectory,n);if(e.before)try{if((await Hn(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ra(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function _a(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Q(t[0])&&"id"in t[0]&&t[0].id===3&&Q(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Q(t)&&Q(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Q(e)&&"arr"in e&&Array.isArray(e.arr)&&Q(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Q(t[0])&&Q(e[0])){let n=[...t];for(let i of e)if(Q(i)&&"name"in i){if(!n.find((o)=>Q(o)&&("name"in o)&&o.name===i.name))n.push(i)}else if(Q(i)&&"path"in i){if(!n.find((o)=>Q(o)&&("path"in o)&&o.path===i.path))n.push(i)}else if(!n.some((s)=>Ya(s,i)))n.push(i);return n}if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}if(!Q(t)||!Q(e))return t;let r={...e};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n];if(i===null||i===void 0)continue;else if(Q(i)&&Q(r[n]))r[n]=_a(r[n],i);else if(Array.isArray(i)&&Array.isArray(r[n]))if(i.length>0&&r[n].length>0&&Q(i[0])&&Q(r[n][0])){let s=[...i];for(let o of r[n])if(Q(o)&&"name"in o){if(!s.find((a)=>Q(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(Q(o)&&"path"in o){if(!s.find((a)=>Q(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Ya(c,o)))s.push(o);r[n]=s}else if(i.every((s)=>typeof s==="string")&&r[n].every((s)=>typeof s==="string")){let s=[...i];for(let o of r[n])if(!s.includes(o))s.push(o);r[n]=s}else r[n]=i;else r[n]=i}return r}function vh(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:_a(e,t);if(Array.isArray(e))return r==="replace"?t:_a(e,t);if(!Q(t)||!Q(e))return t;let n={...e};for(let i of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,i))continue;let s=t[i],o=n[i];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")n[i]=s;else n[i]=_a(o,s);else if(Q(s)&&Q(o))n[i]=vh(o,s,r);else n[i]=s}return n}function Ya(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ya(e[r],t[r]))return!1;return!0}if(Q(e)&&Q(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!Ya(e[i],t[i]))return!1}return!0}return!1}function Q(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function La(e,t,r="replace"){if(!fw(e))return null;try{let n=await import(e),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return vh(t,i,r)}catch{return null}}catch{return null}}function UT(e,t,r=!1){if(!e)return t;let n=e.toUpperCase().replace(/-/g,"_"),i={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${n}_${f.map(h).join("_")}`,y=`${n}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)Ve.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=Gi.env[d]||Gi.env[y];if(g!==void 0){if(r)Ve.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(i)}async function KT({name:e="",alias:t,cwd:r,configDir:n,defaultConfig:i,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof i==="object"&&i!==null&&!Array.isArray(i)?UT(e,i,s):i,l=r||Gi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Ve.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Qe(l,"config"),Qe(l,".config"),n?Qe(l,n):void 0].filter(Boolean)));for(let p of g){if(s)Ve.info(`Searching for configuration in: ${p}`);let v=[Qe(l,"config"),Qe(l,".config")].concat(n?[Qe(l,n)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let P of v)for(let A of u){let R=Qe(p,`${P}${A}`),D=await La(R,a,c);if(D!==null){if(s)Ve.success(`Configuration loaded from: ${R}`);return D}}}if(e){let p=Qe(Uf(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)Ve.info(`Checking user config directory: ${p}`);for(let v of w)for(let P of u){let A=Qe(p,`${v}${P}`),R=await La(A,a,c);if(R!==null){if(s)Ve.success(`Configuration loaded from user config directory: ${A}`);return R}}}if(e){let p=Qe(Uf(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)Ve.info(`Checking user config directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=Qe(p,`${v}${P}`),R=await La(A,a,c);if(R!==null){if(s)Ve.success(`Configuration loaded from user config directory dotfile: ${A}`);return R}}}if(e){let p=Uf(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)Ve.info(`Checking user home directory for dotfile configs: ${p}`);for(let v of w)for(let P of u){let A=Qe(p,`${v}${P}`),R=await La(A,a,c);if(R!==null){if(s)Ve.success(`Configuration loaded from user home directory: ${A}`);return R}}}try{let p=Qe(l,"package.json");if(fw(p)){let w=await import(p),v=w[e];if(!v&&t){if(v=w[t],v&&s)Ve.success(`Using alias "${t}" configuration from package.json`)}if(v&&typeof v==="object"&&!Array.isArray(v))try{if(s)Ve.success(`Configuration loaded from package.json: ${v===w[e]?e:t}`);return vh(a,v,c)}catch(P){if(s)Ve.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)Ve.warn("Failed to load package.json:",p)}if(s)Ve.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function WT(e,t={}){let r=Va.cwd();while(r.includes("storage"))r=Ry(r,"..");let n=Ry(r,e||"");if(t?.relative)return uT(Va.cwd(),n);return n}async function VT(){try{let e=await KT({name:"clarity",alias:"logging",defaultConfig:Ka,cwd:Va.cwd()});return{...Ka,...e||{}}}catch{return Ka}}function Te(){if(ar.env.NODE_ENV==="test"||ar.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function HT(){if(ar.env.NODE_ENV==="test"||ar.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ar<"u"){let e=ar.type;if(e==="renderer"||e==="worker")return!1;return!!(ar.versions&&(ar.versions.node||ar.versions.bun))}return!1}class mw{async format(e){let t=await HT(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Jn.pid,hostname:t(),environment:Jn.env.NODE_ENV||"development",platform:Jn.platform,version:Jn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Jn.env.NODE_ENV||Jn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ja{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(e,t={}){this.name=e,this.config={...lh},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new mw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Wa,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Wa};return{...Wa,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:lh.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Te()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await ST(this.config.logDirectory,jy.F_OK|jy.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await ET(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ir.from(e);try{if(!ka(this.currentLogFile))await qf(this.currentLogFile,"",{mode:420});if(i=_y(this.currentLogFile,"a",420),xT(i,a,{flag:"a"}),My(i),i!==void 0)Gf(i),i=void 0;if((await qn(this.currentLogFile)).size===0){if(await qf(this.currentLogFile,a,{flag:"w",mode:420}),(await qn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{Gf(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 Yn(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 Yn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Yn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Te())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return zf(16).toString("hex")}generateKey(){return zf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=zf(16),n=bT("aes-256-gcm",t,r),i=ir.isBuffer(e)?e:ir.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=ir.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=Ky(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(ir.from(ir.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Te())return;if(!this.shouldWriteToFile())return;let e=await qn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Oa(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await qn(r).catch(()=>null))try{if(await Uy(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Na(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await qf(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await qn(r).catch(()=>null))await Uy(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Oa(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Na(Yn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Iy(e),n=CT(t),i=Ky();await AT(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ka(this.currentLogFile))try{let e=_y(this.currentLogFile,"r+");My(e),Gf(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Te()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Oa(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Na(Yn(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?V.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Te())return!1;let e=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=_.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${V.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=V.underline(V.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>V.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>V.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>V.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>V.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>V.strikethrough(n)),t}supportsHyperlinks(){if(Te())return!1;let e=_.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=_.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(TT(t)||t.startsWith("./")||t.startsWith("../"))t=PT(t);else return null;return ka(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Sw[e],h=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:V.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:V.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
199
+ `);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:V.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!Te()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
200
+ `;if(c)u+=`${c}
201
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Te()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!Te()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!Te()&&_.stdout.isTTY)_.stdout.write(`
202
+ `);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!Te()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":V.blue(""),tag:r,message:`${V.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
203
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":V.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Te())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ja(t,{...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(r),r}createReadStream(){if(Te())throw Error("createReadStream is not supported in browser environments");if(!ka(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Iy(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ir.isBuffer(e)?e:ir.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=$T("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=ir.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Te()}isServerMode(){return!Te()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
204
+ `),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"".repeat(a)}┐`,u=`└${"".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:V.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:V.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:V.cyan(u),showTimestamp:!1}))}else if(!Te())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
205
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Te())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${V.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${V.blue("◐")} `;console.error(`${l}${a} ${V.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
206
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=V.green("".repeat(n)),o=V.gray("".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?V.green(""):V.blue(""),f=this.options.showTags!==!1&&this.name?` ${V.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=_.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,_.stdout.write(e.lastRenderedLine),t)_.stdout.write(`
207
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Te()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Te()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Oa(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=Yn(this.config.logDirectory,n);if(e.before)try{if((await qn(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Na(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function gw(e,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:i=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!i(o))break;if(n>0)await new Promise((l)=>setTimeout(l,n))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function pw(e){return e instanceof ht}function zT(e){return e instanceof Xa}function GT(e){if(pw(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class tc{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:n,useCamelCase:i=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:i,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Ji.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=o.map((u)=>this.formatEnvKey(u,n.useCamelCase)),a=`${r}_${c.join("_")}`,l=n.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,n);else{let u=Da.env[a]||(l?Da.env[l]:void 0);if(u!==void 0){if(n.verbose){let f=Da.env[a]?a:l}try{e[i]=this.parseEnvironmentValue(u,typeof s,a,n.customParsers,n.configName)}catch(f){if(f instanceof Za)throw f;throw Sr.envVar(a,u,typeof s,n.configName)}}}}}parseEnvironmentValue(e,t,r,n,i){for(let[s,o]of Object.entries(n))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Sr.envVar(r,e,`${t} (via ${s.name} parser)`,i)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[n,i]of Object.entries(Da.env))if(n.startsWith(r)&&i!==void 0)t[n]=i;return t}validateEnvironmentVariable(e,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))n.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(i){n.push(`Cannot parse value "${t}" as ${r}: ${i}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(e,t,r={}){let{prefix:n,format:i="text"}=r,s=n||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),i){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,n){for(let[i,s]of Object.entries(e)){let o=[...t,i],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,n);else n.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
150
208
 
151
- `;for(let A of w)Y+=`${A.key}
152
- `,Y+=` Type: ${A.type}
153
- `,Y+=` Description: ${A.description}
154
- `,Y+=` Example: ${A.example}
209
+ `;for(let n of e)r+=`${n.key}
210
+ `,r+=` Type: ${n.type}
211
+ `,r+=` Description: ${n.description}
212
+ `,r+=` Example: ${n.example}
155
213
 
156
- `;return Y}formatAsMarkdown(w,$){let Y=`# Environment Variables for ${$}
214
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
157
215
 
158
- `;Y+=`| Variable | Type | Description | Example |
159
- `,Y+=`|----------|------|-------------|----------|
160
- `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
161
- `;return Y}}function NN(w,$){let Y=p9("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function g9(w,$,Y={}){return d9(w,$,Y,new WeakMap)}function d9(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return n9(w,$,X,A);if(!Fw($)||!Fw(w))return $;return MN(w,$,Y,A)}function n9(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return qN(w,$);case"smart":return HN(w,$,A);default:return $}return $}function qN(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>uW(X,A)))Y.push(A);return Y}function HN(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Fw($[0])&&Fw(w[0]))return RN(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function RN(w,$,Y){let A=[...$];for(let X of w){if(!Fw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Fw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function MN(w,$,Y,A){let X=$;if(Fw(X)&&A.has(X))return A.get(X);let J={...w};if(Fw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Fw(j)&&Fw(W))J[U]=d9(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=n9(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function oW(w,$,Y="replace"){return g9(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function uW(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!uW(w[Y],$[Y]))return!1;return!0}if(Fw(w)&&Fw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!uW(w[X],$[X]))return!1}return!0}return!1}function Fw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class Q8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=k1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!cX(w))return null;try{let Q=`?t=${Date.now()}`,z=await import(w+Q),f=z.default||z,B="default"in z,G=Object.keys(z).length>0;if(!B&&!G)throw new BY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new BY(w,Error("Configuration must export a valid object"),"unknown");let E={config:oW($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)k1.setWithFileCheck("file",E,w,J);return E}catch(Q){throw Q instanceof Error?F$.configLoad(w,Q):F$.configLoad(w,Error(String(Q)))}};if(U)return KY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(LW($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return c9(async()=>{return cX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!cX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=LW(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=LW(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!cX(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class eW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let z=[],f=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return z.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:z,warnings:f}}};if(j)return await KY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!e7($))throw new GY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new GY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:o9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class wj{fileLoader=new Q8;envProcessor=new j8;validator=new eW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||z))throw W;if(f&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Cw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Cw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:z=!1}=w,f=J||P$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,f,U,j,Q,z,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,B,W,A,z);let T=await this.loadHomeConfiguration(A,X,j,Q,z,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,z);let F=await this.loadPackageJsonConfiguration(A,X,f,j,Q,z,W);if(F)return B.push(r0(f,"package.json")),this.finalizeResult(F,B,W,A,z);if(B.push(...this.getAllSearchPaths(A,X,f,U)),$)throw F$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?zY(w,X,U):X,z=this.getLocalDirectories(Y,A);for(let f of z){if(U)Cw.info(`Searching for configuration in: ${f}`);let B=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Cw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?zY(w,Y,X):Y,j=[r0(y1(),".config",w),r0(y1(),".config"),y1()];for(let W of j){if(X)Cw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),z=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(z){if(X)Cw.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?zY(w,A,J):A;try{let W=r0(Y,"package.json");if(!iW(W))return null;let Q=await import(W),z=Q[w],f=w;if(!z&&$)z=Q[$],f=$;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)Cw.success(`Configuration loaded from package.json: ${f}`);return{config:oW(j,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Cw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:zY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw F$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return k1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);k1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,r0(w,"config"),r0(w,".config"),$?r0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(r0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[r0(y1(),".config",w),r0(y1(),".config"),y1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function E9(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function IN(w){return w$.loadConfig({...w,__strictErrorHandling:!0})}async function l9(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await w$.loadConfig(w);else A=await w$.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Cw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await w$.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}async function yN(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await w$.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&E9(Y)))return(await w$.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await w$.loadConfig({...w,cwd:w.cwd||P$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&E9($)))return(await w$.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function CN(w,$,Y="replace"){let A=new Q8;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function zY(w,$,Y=!1){let A=new j8,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,z]of Object.entries(U)){let f=[...j,Q],B=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((F)=>F.toUpperCase()).join("")}`,`${X}_${f.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let F of B)if(G=P$.env[F],G!==void 0){T=F;break}if(G!==void 0&&T)if(typeof z==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof z==="number"){let F=Number(G);if(!Number.isNaN(F))W[Q]=F}else if(Array.isArray(z))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((F)=>F.trim())}else W[Q]=G;else if(z&&typeof z==="object"&&!Array.isArray(z))W[Q]=J(z,f)}return W}return J($)}function VN(w){let $=r0(P$.cwd(),w.configDir),Y=r0(P$.cwd(),w.generatedDir),A=r0(Y,"config-types.ts");if(!iW(w9(A)))_7(w9(A),{recursive:!0,mode:511});let X=iW($)?h7($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${$q}
162
- export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
163
- `;D7(A,J,{mode:438})}function LN(w){let $=null,Y=null,A=()=>{if(!Y)Y=l9(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Cw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function ON(w){let $=F9(YN.cwd(),w?.configDir||"./config");function Y(){if(!wN($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=$N($).filter((W)=>X.has(OW(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let z=OW(Q).toLowerCase(),f=j.get(W);if(!f){j.set(W,Q);continue}let B=OW(f).toLowerCase();if(J.indexOf(z)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((Q)=>Q.base),U=J.length?J.map((Q)=>`'${Q}'`).join(" | "):"string",j=X.length?`{
164
- ${X.map((Q)=>{let z=F9($,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${z}').default`}).join(`,
216
+ `;r+=`| Variable | Type | Description | Example |
217
+ `,r+=`|----------|------|-------------|----------|
218
+ `;for(let n of e)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
219
+ `;return r}}function qT(e,t){let r=$w("process");if(typeof r>"u"||!r.env)return t;let n=r.env[e];return n!==void 0?n:t}function yw(e,t,r={}){return ww(e,t,r,new WeakMap)}function ww(e,t,r,n){let{arrayMergeMode:i="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return vw(e,t,i,n);if(!$t(t)||!$t(e))return t;return ZT(e,t,r,n)}function vw(e,t,r,n){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return YT(e,t);case"smart":return JT(e,t,n);default:return t}return t}function YT(e,t){let r=[...t];for(let n of e)if(!r.some((i)=>ah(i,n)))r.push(n);return r}function JT(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if($t(t[0])&&$t(e[0]))return XT(e,t,r);if(t.every((n)=>typeof n==="string")&&e.every((n)=>typeof n==="string")){let n=[...t];for(let i of e)if(!n.includes(i))n.push(i);return n}return t}function XT(e,t,r){let n=[...t];for(let i of e){if(!$t(i)){n.push(i);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in i){if(n.find((l)=>$t(l)&&(c in l)&&l[c]===i[c])){o=!0;break}}if(!o)n.push(i)}return n}function ZT(e,t,r,n){let i=t;if($t(i)&&n.has(i))return n.get(i);let s={...e};if($t(i))n.set(i,s);for(let o in i){if(!Object.prototype.hasOwnProperty.call(i,o))continue;let c=i[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if($t(c)&&$t(a))s[o]=ww(a,c,r,n);else if(Array.isArray(c)||Array.isArray(a))s[o]=vw(a,c,r.arrayMergeMode||"smart",n);else s[o]=c}return s}function bh(e,t,r="replace"){return yw(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ah(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ah(e[r],t[r]))return!1;return!0}if($t(e)&&$t(t)){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!ah(e[i],t[i]))return!1}return!0}return!1}function $t(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class rc{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:n="replace",useCache:i=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(i){let l=ei.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Fa(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new qi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new qi(e,Error("Configuration must export a valid object"),"unknown");let p={config:bh(t,f,n),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(i)ei.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?Sr.configLoad(e,l):Sr.configLoad(e,Error(String(l)))}};if(o)return Ji.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let n of e)try{let i=await this.loadFromPath(n,t,r);if(i)return i}catch(i){if(i instanceof Error&&i.name==="ConfigLoadError")throw i;if(r.verbose)console.warn(`Failed to load config from ${n}:`,i)}return null}generateConfigPaths(e,t,r){let n=this.generateNamePatterns(e,r),i=[];for(let s of n)for(let o of this.extensions)i.push(Yf(t,`${s}${o}`));return i}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return gw(async()=>Fa(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let n=[];if(!Fa(e))return n;if(t||r){let i=this.generateNamePatterns(t||"",r);for(let s of i)for(let o of this.extensions){let c=Yf(e,`${s}${o}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:i}=await import("fs"),s=i(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=Yf(e,o);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(e){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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Fa(e))return t.push("Configuration file does not exist"),t;let r=await import(e),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:i}=await import("fs"),s=i(e,"utf8");JSON.parse(s)}catch(i){t.push(`Invalid JSON syntax: ${i}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(n)=>{try{let i=await this.loadFromPath(n,{},t);if(i)r.set(n,i.config)}catch(i){if(t.verbose)console.warn(`Failed to preload ${n}:`,i)}})),r}}class $h{async validateConfiguration(e,t,r={}){let{stopOnFirstError:n=!1,validateRequired:i=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:n,validateRequired:i,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await Ji.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!RT(t))throw new Yi(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),i=n.default||n;if(Array.isArray(i))return this.validateWithRules(e,i,r);else return this.validateWithJSONSchema(e,i,r)}catch(n){throw new Yi(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(e,t,r){let n=[],i=[];return this.validateObjectAgainstSchema(e,t,"",n,i,r),{isValid:n.length===0,errors:n,warnings:i}}validateObjectAgainstSchema(e,t,r,n,i,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,n,i,s),s.stopOnFirstError&&n.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,n,i,s),s.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))i.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let n=[],i=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(o){n.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:i}}validateWithRule(e,t,r){let n=[];if(t.required&&(e===void 0||e===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(e===void 0||e===null)return n;if(t.type){let i=Array.isArray(e)?"array":typeof e;if(i!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${i}`,expected:t.type,actual:i,rule:"type"})}if(t.min!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:i,rule:"min"})}if(t.max!==void 0){let i=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(i>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:i,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let i=t.validator(e);if(i)n.push({path:r,message:t.message||i,rule:"custom"})}return n}getValueByPath(e,t){if(!t)return e;let r=t.split("."),n=e;for(let i of r)if(n&&typeof n==="object"&&i in n)n=n[i];else return;return n}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,i,s,o]=n;t.push({path:i,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Tw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ch{fileLoader=new rc;envProcessor=new tc;validator=new $h;async loadConfig(e){let t=Date.now(),{cache:r,performance:n,schema:i,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(i||s)await this.validateConfiguration(c.config,i,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(n?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(a);if(n.slowThreshold&&a.duration>n.slowThreshold)kt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw kt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:n="",alias:i,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||zr.cwd(),h=[],d=await this.loadLocalConfiguration(n,i,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(n,i,f,o)),this.finalizeResult(d,h,a,n,u);let y=await this.loadHomeConfiguration(n,i,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(n,i)),this.finalizeResult(y,h,a,n,u);let g=await this.loadPackageJsonConfiguration(n,i,f,c,l,u,a);if(g)return h.push(et(f,"package.json")),this.finalizeResult(g,h,a,n,u);if(h.push(...this.getAllSearchPaths(n,i,f,o)),t)throw Sr.configNotFound(n,h,i);return{...await this.applyEnvironmentVariables(n,c,a,u),warnings:[`No configuration file found for "${n}"${i?` or alias "${i}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,n,i,s,o,c,a){let l=c?zi(e,i,o):i,u=this.getLocalDirectories(r,n);for(let f of u){if(o)kt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)kt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,n,i,s){if(!e)return null;let o=s?zi(e,r,i):r,c=[et(Vn(),".config",e),et(Vn(),".config"),Vn()];for(let a of c){if(i)kt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:n,verbose:i});if(u){if(i)kt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,n,i,s,o){let c=o?zi(e,n,s):n;try{let a=et(r,"package.json");if(!sh(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)kt.success(`Configuration loaded from package.json: ${f}`);return{config:bh(c,u,i),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)kt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,n){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:zi(e,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,n,i){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,n){let i=[];if(r){let s=r(e);if(s)i.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)i.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(i.length>0)throw Sr.configValidation(n||"unknown",i,n)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ei.get(r)||null}cacheResult(e,t,r,n){let i=this.generateCacheKey(e,n);ei.set(i,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,et(e,"config"),et(e,".config"),t?et(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,n){let i=[];return i.push(...this.getLocalSearchPaths(e,t,r,n)),i.push(...this.getHomeSearchPaths(e,t)),i.push(et(r,"package.json")),i}getLocalSearchPaths(e,t,r,n){let i=this.getLocalDirectories(r,n),s=[];for(let o of i)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[et(Vn(),".config",e),et(Vn(),".config"),Vn()],n=[];for(let i of r)n.push(...this.fileLoader.generateConfigPaths(e,i,t));return n}async loadConfigWithResult(e){return this.loadConfig(e)}}function Vy(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),n=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||n}async function QT(e){return lr.loadConfig({...e,__strictErrorHandling:!0})}async function bw(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let n;if(r)n=await lr.loadConfig(e);else n=await lr.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let i=n instanceof Error?n.name:"UnknownError",s=n instanceof Error?n.message:String(n);if(!(i==="ConfigNotFoundError"||i==="ConfigLoadError"||i==="ConfigValidationError"||s.includes("config"))&&e.verbose)kt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await lr.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function eP(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await lr.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Vy(r)))return(await lr.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await lr.loadConfig({...e,cwd:e.cwd||zr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Vy(t)))return(await lr.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function tP(e,t,r="replace"){let n=new rc;try{let i=await n.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return i?i.config:null}catch{return null}}function zi(e,t,r=!1){let n=new tc,i=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${i}_${f.join("_").toUpperCase()}`,`${i}_${f.map((g)=>g.toUpperCase()).join("")}`,`${i}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=zr.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function rP(e){let t=et(zr.cwd(),e.configDir),r=et(zr.cwd(),e.generatedDir),n=et(r,"config-types.ts");if(!sh(Ay(n)))oT(Ay(n),{recursive:!0,mode:511});let i=sh(t)?aT(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${OP}
220
+ export type ConfigNames = ${i.length?`'${i.join("' | '")}'`:"string"}
221
+ `;cT(n,s,{mode:438})}function nP(e){let t=null,r=null,n=()=>{if(!r)r=bw(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)kt.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},i="defaultConfig"in e?e.defaultConfig:{};return t=i,n(),new Proxy({},{get(s,o){if(t)return t[o];let c=i[o];return n(),c},has(s,o){return o in(t||i)},ownKeys(){return Object.keys(t||i)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||i,o)},set(s,o,c){if(!t)t={...i};return t[o]=c,!0}})}function iP(e){let t=Wy(NT.cwd(),e?.configDir||"./config");function r(){if(!kT(t))return[];let i=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=OT(t).filter((a)=>i.has(Jf(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=Jf(l).toLowerCase(),f=c.get(a);if(!f){c.set(a,l);continue}let h=Jf(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function n(){let i=r(),s=i.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=i.length?`{
222
+ ${i.map((l)=>{let u=Wy(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${u}').default`}).join(`,
165
223
  `)}
166
- }`:"Record<string, any>";return`export type ConfigNames = ${U}
167
- export type ConfigByName = ${j}
224
+ }`:"Record<string, any>";return`export type ConfigNames = ${o}
225
+ export type ConfigByName = ${c}
168
226
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
169
227
  export type ConfigOf = Config
170
- `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function Jq(w,$={}){let Y=U8.cwd();while(Y.includes("storage"))Y=L9(Y,"..");let A=L9(Y,w||"");if($?.relative)return Xq(U8.cwd(),A);return A}function M0(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Eq(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ew<"u"){let w=ew.type;if(w==="renderer"||w==="worker")return!1;return!!(ew.versions&&(ew.versions.node||ew.versions.bun))}return!1}class Y2{async format(w){let $=await Eq(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:x1.pid,hostname:$(),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 FY{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=w,this.config={...W8},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Y2,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...PW,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...PW};return{...PW,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:W8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await fq(this.config.logDirectory,h9.F_OK|h9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await Bq(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:aw.from(w);try{if(!gX(this.currentLogFile))await ZW(this.currentLogFile,"",{mode:420});if(X=_9(this.currentLogFile,"a",420),zq(X,W,{flag:"a"}),S9(X),X!==void 0)kW(X),X=void 0;if((await h1(this.currentLogFile)).size===0){if(await ZW(this.currentLogFile,W,{flag:"w",mode:420}),(await h1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{kW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 D1(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 D1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return D1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return xW(16).toString("hex")}generateKey(){return xW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=xW(16),A=Wq("aes-256-gcm",$,Y),X=aw.isBuffer(w)?w:aw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=aw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=x9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(aw.from(aw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let w=await h1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await dX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await h1(Y).catch(()=>null))try{if(await D9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await nX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await ZW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await h1(Y).catch(()=>null))await D9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await dX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await nX(D1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=O9(w),A=Qq($),X=x9();await Fq(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),gX(this.currentLogFile))try{let w=_9(this.currentLogFile,"r+");S9(w),kW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await dX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await nX(D1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?g.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let w=typeof P.env.NO_COLOR<"u",$=P.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof P.stderr<"u"&&P.stderr.isTTY||typeof P.stdout<"u"&&P.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=P.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${g.cyan(X)}`;if(!U)return Q.trim();let z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),$}supportsHyperlinks(){if(M0())return!1;let w=P.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=P.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(Gq($)||$.startsWith("./")||$.startsWith("../"))$=Kq($);else return null;return gX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Rq[w],B=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:g.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:g.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
171
- `);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:g.gray(` ${F}`),level:w,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}let z=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
172
- `;if(j)z+=`${j}
173
- `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!M0()&&P.stdout.isTTY)P.stdout.write(`
174
- `);if(this[W==="warning"?"warn":W](j),this.activeProgressBar&&this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":g.blue("◐"),tag:Y,message:`${g.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
175
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":g.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new FY($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!gX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return O9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=aw.isBuffer(w)?w:aw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=jq("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),z=W.length+Q.length,f=aw.allocUnsafe(z);return W.copy(f,0),Q.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
176
- `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,f=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:g.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(Q),showTimestamp:!1})),f.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(z),showTimestamp:!1}))}else if(!M0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
177
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(M0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${g.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();P.stdin.removeListener("data",Y);try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!1)}catch{}P.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!0)}catch{}P.stdin.resume(),P.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,Q=0;if(Y=w.replace(W,(z,f)=>{if(f==="%")return"%";if(Q>=$.length)return z;let B=$[Q++];switch(f){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return z}}),Q<$.length)Y+=` ${$.slice(Q).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${g.blue("◐")} `;console.error(`${Q}${W} ${g.cyan(A)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
178
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!P.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=g.green("━".repeat(A)),U=g.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",z=this.options.showIcons===!1?"":$||Y===100?g.green("✓"):g.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",B=`\r${z}${f} ${j} ${W}${Q}`,G=P.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,P.stdout.write(w.lastRenderedLine),$)P.stdout.write(`
179
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await dX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=D1(this.config.logDirectory,A);if(w.before)try{if((await h1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await nX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}var C7,V7=(w)=>w,O7=(w,$)=>{for(var Y in $)C7(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:L7.bind($,Y)})},S7=(w,$)=>()=>(w&&($=w(w=0)),$),P9,p9,k1,KY,r9,SN,_N,T9,pX,vW,k0,w0,hN,N9,DN,q9,xN,kN,SW,ZN,H9,R9,_W,PN,iN,bN,uN,rX,t9,vN,Z0,cN,mN,M9,tX,cW,R0,v,gN,I9,dN,y9,nN,lN,hW,pN,C9,V9,rN,DW,tN,aN,sN,oN,eN,aX,a9,wq,$q="0.15.6",Aw,X8,BY,mW,gW,J8,dW,nW,GY,lW,pW,F$,s9,o9,Cw,w$,e9,w2,Yq,Uq,$2,W8,R3,C0,g,D3,Tq,x3,Nq,k3,Z3,k9,P3,qq,Hq,i3,Z9,b3,u3,v3,c3,m3,PW,Rq,g3;var A2=s(()=>{C7=Object.defineProperty;P9={};O7(P9,{withErrorRecovery:()=>c9,tryLoadConfig:()=>CN,loadConfigWithResult:()=>IN,loadConfig:()=>l9,isRetryableError:()=>TN,isConfigNotFoundError:()=>EN,isBunfigError:()=>m9,globalPerformanceMonitor:()=>KY,globalCache:()=>k1,getEnvOrDefault:()=>NN,generateConfigTypes:()=>VN,defaultGeneratedDir:()=>w2,defaultConfigDir:()=>e9,deepMergeWithArrayStrategy:()=>oW,deepMerge:()=>g9,createLibraryConfig:()=>LN,config:()=>yN,bunfigPlugin:()=>ON,applyEnvVarsToConfig:()=>zY,TypeGenerationError:()=>nW,SchemaValidationError:()=>GY,PluginError:()=>pW,PerformanceMonitor:()=>tW,FileSystemError:()=>dW,ErrorFactory:()=>F$,EnvVarError:()=>J8,EnvProcessor:()=>j8,ConfigValidator:()=>eW,ConfigValidationError:()=>mW,ConfigNotFoundError:()=>X8,ConfigMergeError:()=>gW,ConfigLoader:()=>wj,ConfigLoadError:()=>BY,ConfigFileLoader:()=>Q8,ConfigCache:()=>rW,CacheUtils:()=>r9,BunfigError:()=>Aw,BrowserConfigError:()=>lW,ArrayMergeStrategies:()=>s9});Yq=S7(async()=>{p9=import.meta.require,k1=new rW,KY=new tW,r9={createKey:AN,isEquivalent:XN,estimateMemoryUsage:JN},SN=eX(bW.cwd(),"config"),_N=eX(bW.cwd(),"src/generated"),T9=oX.env.CLARITY_LOG_DIR||Z7(jN(),"logs"),pX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:T9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},vW=await QN(),k0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},w0=k0,hN=k0.red,N9=k0.green,DN=k0.yellow,q9=k0.blue,xN=k0.magenta,kN=k0.cyan,SW=k0.white,ZN=k0.gray,H9=k0.bgRed,R9=k0.bgYellow,_W=k0.bold,PN=k0.dim,iN=k0.italic,bN=k0.underline,uN=k0.reset,rX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},t9={debug:"\uD83D\uDD0D",info:q9("ℹ"),success:N9("✓"),warning:R9(SW(_W(" WARN "))),error:H9(SW(_W(" ERROR ")))},vN=new $8("stacks"),Z0=new $8("bunfig",{showTags:!0}),cN=p0(fY.cwd(),"config"),mN=p0(fY.cwd(),"src/generated"),M9=sX.env.CLARITY_LOG_DIR||x7(GN(),"logs"),tX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:M9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},cW=await KN(),R0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},v=R0,gN=R0.red,I9=R0.green,dN=R0.yellow,y9=R0.blue,nN=R0.magenta,lN=R0.cyan,hW=R0.white,pN=R0.gray,C9=R0.bgRed,V9=R0.bgYellow,rN=R0.bgGray,DW=R0.bold,tN=R0.dim,aN=R0.italic,sN=R0.underline,oN=R0.strikethrough,eN=R0.reset,aX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},a9={debug:"\uD83D\uDD0D",info:y9("ℹ"),success:I9("✓"),warning:V9(hW(DW(" WARN "))),error:C9(hW(DW(" ERROR ")))},wq=new A8("stacks"),Aw=class extends Error{timestamp;context;constructor($,Y={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},X8=class extends Aw{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},BY=class extends Aw{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},mW=class extends Aw{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},gW=class extends Aw{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},J8=class extends Aw{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},dW=class extends Aw{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},nW=class extends Aw{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},GY=class extends Aw{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},lW=class extends Aw{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},pW=class extends Aw{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},F$={configNotFound(w,$,Y){return new X8(w,$,Y)},configLoad(w,$,Y){return new BY(w,$,Y)},configValidation(w,$,Y){return new mW(w,$,Y)},configMerge(w,$,Y,A){return new gW(w,$,Y,A)},envVar(w,$,Y,A){return new J8(w,$,Y,A)},fileSystem(w,$,Y){return new dW(w,$,Y)},typeGeneration(w,$,Y){return new nW(w,$,Y)},schemaValidation(w,$,Y){return new GY(w,$,Y)},browserConfig(w,$,Y,A){return new lW(w,$,Y,A)},plugin(w,$,Y){return new pW(w,$,Y)}},s9={replace:"replace",concat:"concat",smart:"smart"},o9=/^https?:\/\//,Cw=new A8("bunfig",{showTags:!0}),w$=new wj,e9=r0(P$.cwd(),"config"),w2=r0(P$.cwd(),"src/generated")});Uq=U8.env.CLARITY_LOG_DIR||Aq(Jq(),"logs"),$2={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Uq,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},W8={...$2},R3=(async()=>{try{let{loadConfig:w}=await Yq().then(()=>P9),$=await w({name:"clarity",alias:"logging",defaultConfig:$2,cwd:U8.cwd()});if($)Object.assign(W8,$)}catch{}return W8})();C0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},g=C0,D3=C0.red,Tq=C0.green,x3=C0.yellow,Nq=C0.blue,k3=C0.magenta,Z3=C0.cyan,k9=C0.white,P3=C0.gray,qq=C0.bgRed,Hq=C0.bgYellow,i3=C0.bgGray,Z9=C0.bold,b3=C0.dim,u3=C0.italic,v3=C0.underline,c3=C0.strikethrough,m3=C0.reset,PW={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Rq={debug:"\uD83D\uDD0D",info:Nq("ℹ"),success:Tq("✓"),warning:Hq(k9(Z9(" WARN "))),error:qq(k9(Z9(" ERROR ")))};g3=new FY("stacks")});var Z1={};ej(Z1,{shouldReusePort:()=>TY,safeStringify:()=>$$,safeDeleteFile:()=>Aj,resolvePathRewrite:()=>Yj,redactSensitive:()=>f8,isValidRootCA:()=>$j,isSingleProxyOptions:()=>NY,isSingleProxyConfig:()=>Oq,isProcessElevated:()=>EY,isMultiProxyOptions:()=>i$,isMultiProxyConfig:()=>G8,getSudoPassword:()=>E$,getPrimaryDomain:()=>B8,extractHostname:()=>Lq,execSudoSync:()=>T$,debugLog:()=>K,authorizeSystemAccess:()=>Iq});import{execSync as z8}from"node:child_process";import*as J2 from"node:fs/promises";function E$(){return process.env.SUDO_PASSWORD}function EY(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function Iq(w={}){if(process.platform==="win32")return!0;if(EY()||!!E$())return!0;let $=w.exec??z8;try{return $("sudo -n true",{stdio:"ignore"}),!0}catch{if(!w.interactive)return!1}try{return $("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function T$(w){if(EY())return z8(w,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let $=E$(),Y=w.replace(/'/g,"'\\''");if($)return z8(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return z8(`sudo -n sh -c '${Y}'`,{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 K(w,$,Y){if(Y)Mq.debug(`[rpx:${w}] ${$}`)}function TY(){let w=process.env.RPX_REUSE_PORT;return w==="1"||w==="true"}function Vq(w){let $=w.toLowerCase();return yq.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function f8(w){if(Array.isArray(w))return w.map((Y)=>f8(Y));if(typeof w==="string")return Cq.test(w)?X2:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(Vq(Y)){$[Y]=X2;continue}$[Y]=f8(A)}return $}function $$(w,$){return JSON.stringify(f8(w),null,$)}function Lq(w){if(i$(w))return w.proxies.map(($)=>{let Y=$.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(NY(w)){let $=w.to||"stacks.localhost";return[$.startsWith("http")?new URL($).hostname:$]}return["stacks.localhost"]}function $j(w){return typeof w==="object"&&w!==null&&"certificate"in w&&"privateKey"in w&&typeof w.certificate==="string"&&typeof w.privateKey==="string"}function B8(w){if(!w)return"stacks.localhost";if(i$(w)&&w.proxies.length>0)return w.proxies[0].to||"stacks.localhost";if(NY(w))return w.to||"stacks.localhost";return"stacks.localhost"}function G8(w){return!!(w&&("proxies"in w)&&Array.isArray(w.proxies))}function i$(w){return"proxies"in w&&Array.isArray(w.proxies)}function NY(w){return"to"in w&&typeof w.to==="string"}function Oq(w){return!!(w&&("to"in w)&&!("proxies"in w))}function Yj(w,$){if(!$||$.length===0)return null;for(let Y of $)if(w===Y.from||w.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,X=Y.stripPrefix===!0?w.slice(Y.from.length)||"/":w;return{targetHost:A,targetPath:X}}return null}async function Aj(w,$){try{await J2.unlink(w),K("certificates",`Successfully deleted: ${w}`,$)}catch(Y){if(Y.code!=="ENOENT")K("certificates",`Warning: Could not delete ${w}: ${Y}`,$)}}var Mq,X2="[redacted]",yq,Cq;var f0=s(()=>{A2();Mq=new FY("rpx",{showTags:!1});yq=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Cq=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as K8}from"node:child_process";import{homedir as Sq}from"node:os";import{join as _q}from"node:path";function F8(){return _q(Sq(),"Library/Keychains/login.keychain-db")}function Jj(){return[q$,F8()]}function U2(w,$=Xj){let Y=K8(`security find-certificate -a -c "${$}" -Z "${w}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
180
- `)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)A.push(J[1].toUpperCase())}return A}function Uj(w){if(process.platform!=="darwin")return;let $=Z$(w.caPath);if(!$)return;let Y=w.commonName??Xj,A=w.keychains??Jj();for(let X of A)for(let J of U2(X,Y)){if(J===$)continue;try{if(X.startsWith("/Library"))T$(`security delete-certificate -Z ${J} "${X}"`);else K8(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});K("ssl",`Removed stale Root CA ${J} from ${X}`,w.verbose)}catch{}}}function Wj(w,$,Y){if(process.platform!=="darwin")return E8(w,Y);try{let X=K8(`security verify-cert -c "${w}" -s "${$}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return K("ssl",`verify-cert ${$}: ${X?"trusted":"not trusted"}`,Y?.verbose),X}catch{return!1}}function E8(w,$){let Y=Z$(w);if(!Y)return!1;for(let A of Jj())try{let X=K8(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let J of X.split(`
181
- `))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return K("ssl",`Root CA fingerprint found in ${A}`,$?.verbose),!0}}catch{}return!1}var N$="-d -r trustRoot -p ssl -p basic",q$="/Library/Keychains/System.keychain",Xj="rpx.localhost";var jj=s(()=>{kX();f0()});import{execSync as Qj}from"node:child_process";import B0 from"node:fs/promises";import*as zj from"node:os";import{homedir as P1}from"node:os";import*as Q2 from"node:path";import{join as G0}from"node:path";import*as H$ from"node:process";function z2(w,$){return[...new Set(w.filter(Boolean))].map((Y)=>({serverName:Y,cert:$.cert,key:$.key}))}function f2(w,$,Y){let A=G0(P1(),".stacks","ssl"),X=[...new Set([$,...w,"rpx.localhost"])];return{https:{certPath:fj,keyPath:G0(A,"rpx.localhost.key"),caCertPath:G0(A,"rpx.localhost.ca.crt"),commonName:$},verbose:Y,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function B2(w){return{caCertPath:G0(w,Dq),caKeyPath:G0(w,xq)}}async function kq(w,$){try{let[Y,A]=await Promise.all([B0.readFile(w.caCertPath,"utf8"),B0.readFile(w.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return K("ssl",`Root CA files at ${w.caCertPath} look malformed, will regenerate`,$),null;return{certificate:Y,privateKey:A}}catch(Y){return K("ssl",`No existing Root CA at ${w.caCertPath} (${Y.code||Y}), will create one`,$),null}}function W2(w){let $=new Set;$.add(w);let Y=w.split(".");if(Y.length>=3){let A=Y[Y.length-1],X=Y[Y.length-2],J=new Set(["co","com","org","net","ac","gov","edu"]);if(!(Y.length===3&&A.length===2&&J.has(X)))$.add(`*.${Y.slice(1).join(".")}`)}return Array.from($)}function G2(w){let Y=B8(w).replace(/\*/g,"wildcard"),A=G0(P1(),".stacks","ssl"),X=A;if(typeof w?.https==="object")return X=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:A,{caCertPath:w.https.caCertPath||G0(X,`${Y}.ca.crt`),certPath:w.https.certPath||G0(X,`${Y}.crt`),keyPath:w.https.keyPath||G0(X,`${Y}.key`)};return{caCertPath:G0(X,`${Y}.ca.crt`),certPath:G0(X,`${Y}.crt`),keyPath:G0(X,`${Y}.key`)}}function j2(w){let $=new Set;if(i$(w))w.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";W2(A).forEach((X)=>$.add(X))});else if(NY(w)){let Y=w.to||"rpx.localhost";W2(Y).forEach((A)=>$.add(A))}else $.add("rpx.localhost");return $.add("localhost"),$.add("*.localhost"),$}async function qY(w){if(R$&&!w.forceRegenerate){K("ssl","Using cached SSL configuration",w.verbose);return}Bj();let $=i$(w)?w.proxies.map((z)=>z.to):[w.to];K("ssl",`Generating certificate for domains: ${$.join(", ")}`,w.verbose);let Y=HY(w,w.verbose),A=Y.basePath||G0(P1(),".stacks","ssl");await B0.mkdir(A,{recursive:!0});let X=B2(A),J=await kq(X,w.verbose),U=!1;if(!J){if(w.verbose)H.info("Generating Root CA certificate (one-time)...");J=await BW(Y);try{await Promise.all([B0.writeFile(X.caCertPath,J.certificate),B0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,K("ssl",`Persisted Root CA at ${X.caCertPath}`,w.verbose)}catch(z){throw K("ssl",`Error saving Root CA files: ${z}`,w.verbose),Error(`Failed to save Root CA files: ${z}`)}}else K("ssl",`Reusing existing Root CA from ${X.caCertPath}`,w.verbose);if(w.verbose)H.info(`Generating host certificate for: ${$.join(", ")}`);let j=await GW({...Y,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([B0.writeFile(Y.certPath,j.certificate),B0.writeFile(Y.keyPath,j.privateKey),B0.writeFile(Y.caCertPath,J.certificate)]),K("ssl","Certificate files saved successfully",w.verbose)}catch(z){throw K("ssl",`Error saving certificate files: ${z}`,w.verbose),Error(`Failed to save certificate files: ${z}`)}if(U?!1:await F2(X.caCertPath,{verbose:w.verbose,regenerateUntrustedCerts:!0})){if(K("ssl","Root CA already trusted, skipping trust store update",w.verbose),w.verbose)H.success("Root CA is already trusted in system trust store");if(R$={key:j.privateKey,cert:j.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);return}if(w.verbose)H.info("Adding certificate to system trust store (may require sudo permission)...");let Q=!1;if(H$.platform==="darwin")try{Uj({caPath:X.caCertPath,verbose:w.verbose});let z=F8();try{Qj(`security add-trusted-cert ${N$} -k "${z}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(T$(`security add-trusted-cert ${N$} -k ${q$} "${X.caCertPath}"`),w.verbose)H.success("Successfully added Root CA to system trust store");Q=!0;let f=G0(A,"trust-rpx-cert.sh"),B=`#!/bin/bash
228
+ `}return{name:"bunfig-plugin",setup(i){i.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),i.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:n(),loader:"ts"}))}}}function LP(e,t={}){let r=Qa.cwd();while(r.includes("storage"))r=tw(r,"..");let n=tw(r,e||"");if(t?.relative)return FP(Qa.cwd(),n);return n}function Ae(){if(cr.env.NODE_ENV==="test"||cr.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zP(){if(cr.env.NODE_ENV==="test"||cr.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof cr<"u"){let e=cr.type;if(e==="renderer"||e==="worker")return!1;return!!(cr.versions&&(cr.versions.node||cr.versions.bun))}return!1}class kw{async format(e){let t=await zP(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Qn.pid,hostname:t(),environment:Qn.env.NODE_ENV||"development",platform:Qn.platform,version:Qn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qn.env.NODE_ENV||Qn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Xi{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(e,t={}){this.name=e,this.config={...ec},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new kw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??j.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),s=this.generateKey();this.currentKeyId=i,this.keys.set(i,s),this.encryptionKeys.set(i,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ih,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ih};return{...ih,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ec.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ae()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let i,s=0,o=3,c=1000;while(s<o)try{try{try{await UP(this.config.logDirectory,sw.F_OK|sw.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await KP(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:sr.from(e);try{if(!Ba(this.currentLogFile))await nh(this.currentLogFile,"",{mode:420});if(i=iw(this.currentLogFile,"a",420),jP(i,a,{flag:"a"}),nw(i),i!==void 0)rh(i),i=void 0;if((await Xn(this.currentLogFile)).size===0){if(await nh(this.currentLogFile,a,{flag:"w",mode:420}),(await Xn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(i!==void 0)try{rh(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(n,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 Zn(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 Zn(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Zn(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ae())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(i.length>o)for(let[c]of i.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return th(16).toString("hex")}generateKey(){return th(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=th(16),n=IP("aes-256-gcm",t,r),i=sr.isBuffer(e)?e:sr.from(e,"utf8"),s=n.update(i),o=n.final(),c=s.length+o.length,a=n.getAuthTag(),l=sr.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let n=aw(),i=[];n.on("data",(s)=>i.push(s)),n.on("end",()=>t(sr.from(sr.concat(i)))),n.on("error",r),n.write(e),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ae())return;if(!this.shouldWriteToFile())return;let e=await Xn(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await Ia(this.config.logDirectory),s=i.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Xn(r).catch(()=>null))try{if(await ow(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ma(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!i.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await nh(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${i}.log`);if(await Xn(r).catch(()=>null))await ow(r,s)}if(this.currentLogFile=n,t.maxFiles){let s=(await Ia(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Ma(Zn(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=rw(e),n=_P(t),i=aw();await HP(r,i,n)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Ba(this.currentLogFile))try{let e=iw(this.currentLogFile,"r+");nw(e),rh(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ae()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ia(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ma(Zn(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?G.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ae())return!1;let e=typeof j.env.NO_COLOR<"u",t=j.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof j.stderr<"u"&&j.stderr.isTTY||typeof j.stdout<"u"&&j.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:n="",message:i,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)d.push(n.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let a=j.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${i}`;else if(s==="info"||s==="success")l=`${r} ${n} ${i}`;else l=`${r} ${n} ${G.cyan(i)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,n=0,i=e.replace(r,(s,o)=>{if(o==="%")return"%";if(n>=t.length)return s;let c=t[n++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(n<t.length)i+=` ${t.slice(n).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,i)=>{let s=G.underline(G.blue(n)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,n)=>G.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>G.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>G.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>G.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>G.strikethrough(n)),t}supportsHyperlinks(){if(Ae())return!1;let e=j.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=j.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(WP(t)||t.startsWith("./")||t.startsWith("../"))t=VP(t);else return null;return Ba(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let n=new Date,i=this.formatConsoleTimestamp(n),s=this.formatFileTimestamp(n),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":XP[e],h=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:G.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:G.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
229
+ `);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:G.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!Ae()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
230
+ `;if(c)u+=`${c}
231
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Ae()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!Ae()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!Ae()&&j.stdout.isTTY)j.stdout.write(`
232
+ `);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!Ae()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":G.blue("◐"),tag:r,message:`${G.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),i=Math.round(n-t),s=`${e} completed in ${i}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
233
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":G.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ae())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Xi(t,{...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(r),r}createReadStream(){if(Ae())throw Error("createReadStream is not supported in browser environments");if(!Ba(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return rw(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=sr.isBuffer(e)?e:sr.from(e,"base64"),i=n.subarray(0,16),s=n.subarray(n.length-16),o=n.subarray(16,n.length-16),c=MP("aes-256-gcm",r,i);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=sr.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ae()}isServerMode(){return!Ae()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:i,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=i.split(`
234
+ `),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:G.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(u),showTimestamp:!1}))}else if(!Ae())console.error(`${n} ${this.environment}.INFO: [BOX] ${s}`);let o=`${n} ${this.environment}.INFO: [BOX] ${s}
235
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Ae())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${G.cyan("?")} ${e} (y/n) `);let r=(n)=>{let i=n.toString().trim().toLowerCase();j.stdin.removeListener("data",r);try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!1)}catch{}j.stdin.pause(),console.error(""),t(i==="y"||i==="yes")};try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!0)}catch{}j.stdin.resume(),j.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:i}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${G.blue("◐")} `;console.error(`${l}${a} ${G.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${i}
236
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!j.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),n=Math.round(e.barLength*r/100),i=e.barLength-n,s=G.green("━".repeat(n)),o=G.gray("━".repeat(i)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?G.green("✓"):G.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=j.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,j.stdout.write(e.lastRenderedLine),t)j.stdout.write(`
237
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ae()||!j.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ae()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ia(this.config.logDirectory),r=[];for(let n of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let s=Zn(this.config.logDirectory,n);if(e.before)try{if((await Xn(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ma(n),console.warn(`Deleted log file: ${n}`)}catch(i){console.error(`Failed to delete log file ${n}:`,i)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var tT,rT=(e)=>e,iT=(e,t)=>{for(var r in t)tT(e,r,{get:t[r],enumerable:!0,configurable:!0,set:nT.bind(t,r)})},sT=(e,t)=>()=>(e&&(t=e(e=0)),t),uw,$w,ei,Ji,Cw,sP,oP,Hy,ja,ch,We,se,aP,zy,cP,Gy,lP,uP,Xf,fP,qy,Yy,Zf,hP,dP,mP,gP,Ua,xw,pP,Ve,yP,wP,Jy,Ka,lh,Pe,V,vP,Xy,bP,Zy,$P,CP,Qf,xP,Qy,ew,SP,eh,EP,TP,PP,AP,RP,Wa,Sw,kP,OP="0.15.6",ht,Xa,qi,uh,fh,Za,hh,dh,Yi,mh,gh,Sr,Ew,Tw,kt,lr,Pw,Aw,NP,BP,Rw,ec,nB,Ne,G,mB,GP,gB,qP,pB,yB,cw,wB,YP,JP,vB,lw,bB,$B,CB,xB,SB,ih,XP,EB;var Ow=te(()=>{tT=Object.defineProperty;uw={};iT(uw,{withErrorRecovery:()=>gw,tryLoadConfig:()=>tP,loadConfigWithResult:()=>QT,loadConfig:()=>bw,isRetryableError:()=>GT,isConfigNotFoundError:()=>zT,isBunfigError:()=>pw,globalPerformanceMonitor:()=>Ji,globalCache:()=>ei,getEnvOrDefault:()=>qT,generateConfigTypes:()=>rP,defaultGeneratedDir:()=>Aw,defaultConfigDir:()=>Pw,deepMergeWithArrayStrategy:()=>bh,deepMerge:()=>yw,createLibraryConfig:()=>nP,config:()=>eP,bunfigPlugin:()=>iP,applyEnvVarsToConfig:()=>zi,TypeGenerationError:()=>dh,SchemaValidationError:()=>Yi,PluginError:()=>gh,PerformanceMonitor:()=>yh,FileSystemError:()=>hh,ErrorFactory:()=>Sr,EnvVarError:()=>Za,EnvProcessor:()=>tc,ConfigValidator:()=>$h,ConfigValidationError:()=>uh,ConfigNotFoundError:()=>Xa,ConfigMergeError:()=>fh,ConfigLoader:()=>Ch,ConfigLoadError:()=>qi,ConfigFileLoader:()=>rc,ConfigCache:()=>ph,CacheUtils:()=>Cw,BunfigError:()=>ht,BrowserConfigError:()=>mh,ArrayMergeStrategies:()=>Ew});NP=sT(async()=>{$w=import.meta.require,ei=new ph,Ji=new yh,Cw={createKey:DT,isEquivalent:FT,estimateMemoryUsage:LT},sP=za(oh.cwd(),"config"),oP=za(oh.cwd(),"src/generated"),Hy=Ha.env.CLARITY_LOG_DIR||fT(MT(),"logs"),ja={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Hy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},ch=await _T(),We={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},se=We,aP=We.red,zy=We.green,cP=We.yellow,Gy=We.blue,lP=We.magenta,uP=We.cyan,Xf=We.white,fP=We.gray,qy=We.bgRed,Yy=We.bgYellow,Zf=We.bold,hP=We.dim,dP=We.italic,mP=We.underline,gP=We.reset,Ua={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xw={debug:"\uD83D\uDD0D",info:Gy("ℹ"),success:zy("✓"),warning:Yy(Xf(Zf(" WARN "))),error:qy(Xf(Zf(" ERROR ")))},pP=new qa("stacks"),Ve=new qa("bunfig",{showTags:!0}),yP=Qe(Gi.cwd(),"config"),wP=Qe(Gi.cwd(),"src/generated"),Jy=Va.env.CLARITY_LOG_DIR||lT(WT(),"logs"),Ka={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Jy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},lh=await VT(),Pe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},V=Pe,vP=Pe.red,Xy=Pe.green,bP=Pe.yellow,Zy=Pe.blue,$P=Pe.magenta,CP=Pe.cyan,Qf=Pe.white,xP=Pe.gray,Qy=Pe.bgRed,ew=Pe.bgYellow,SP=Pe.bgGray,eh=Pe.bold,EP=Pe.dim,TP=Pe.italic,PP=Pe.underline,AP=Pe.strikethrough,RP=Pe.reset,Wa={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Sw={debug:"\uD83D\uDD0D",info:Zy("ℹ"),success:Xy("✓"),warning:ew(Qf(eh(" WARN "))),error:Qy(Qf(eh(" ERROR ")))},kP=new Ja("stacks"),ht=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,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 t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Xa=class extends ht{code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n?` or alias "${n}"`:"";super(`Configuration "${t}"${i} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},qi=class extends ht{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},uh=class extends ht{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},fh=class extends ht{code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Za=class extends ht{code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}},hh=class extends ht{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},dh=class extends ht{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Yi=class extends ht{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},mh=class extends ht{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}},gh=class extends ht{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Sr={configNotFound(e,t,r){return new Xa(e,t,r)},configLoad(e,t,r){return new qi(e,t,r)},configValidation(e,t,r){return new uh(e,t,r)},configMerge(e,t,r,n){return new fh(e,t,r,n)},envVar(e,t,r,n){return new Za(e,t,r,n)},fileSystem(e,t,r){return new hh(e,t,r)},typeGeneration(e,t,r){return new dh(e,t,r)},schemaValidation(e,t,r){return new Yi(e,t,r)},browserConfig(e,t,r,n){return new mh(e,t,r,n)},plugin(e,t,r){return new gh(e,t,r)}},Ew={replace:"replace",concat:"concat",smart:"smart"},Tw=/^https?:\/\//,kt=new Ja("bunfig",{showTags:!0}),lr=new Ch,Pw=et(zr.cwd(),"config"),Aw=et(zr.cwd(),"src/generated")});BP=Qa.env.CLARITY_LOG_DIR||DP(LP(),"logs"),Rw={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:BP,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ec={...Rw},nB=(async()=>{try{let{loadConfig:e}=await NP().then(()=>uw),t=await e({name:"clarity",alias:"logging",defaultConfig:Rw,cwd:Qa.cwd()});if(t)Object.assign(ec,t)}catch{}return ec})();Ne={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},G=Ne,mB=Ne.red,GP=Ne.green,gB=Ne.yellow,qP=Ne.blue,pB=Ne.magenta,yB=Ne.cyan,cw=Ne.white,wB=Ne.gray,YP=Ne.bgRed,JP=Ne.bgYellow,vB=Ne.bgGray,lw=Ne.bold,bB=Ne.dim,$B=Ne.italic,CB=Ne.underline,xB=Ne.strikethrough,SB=Ne.reset,ih={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},XP={debug:"\uD83D\uDD0D",info:qP("ℹ"),success:GP("✓"),warning:JP(cw(lw(" WARN "))),error:YP(cw(lw(" ERROR ")))};EB=new Xi("stacks")});var ri={};nl(ri,{authorizeSystemAccess:()=>QP,debugLog:()=>m,execSudoSync:()=>Tr,extractHostname:()=>nA,getPrimaryDomain:()=>sc,getSudoPassword:()=>Er,isMultiProxyConfig:()=>oc,isMultiProxyOptions:()=>Gr,isProcessElevated:()=>Zi,isSingleProxyConfig:()=>iA,isSingleProxyOptions:()=>Qi,isValidRootCA:()=>xh,redactSensitive:()=>ic,resolvePathRewrite:()=>Sh,safeDeleteFile:()=>Eh,safeStringify:()=>ur,shouldReusePort:()=>ti});import{execSync as nc}from"node:child_process";import*as Dw from"node:fs/promises";function Er(){return process.env.SUDO_PASSWORD}function Zi(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function QP(e={}){if(process.platform==="win32")return!0;if(Zi()||!!Er())return!0;let t=e.exec??nc;try{return t("sudo -n true",{stdio:"ignore"}),!0}catch{if(!e.interactive)return!1}try{return t("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function Tr(e){if(Zi())return nc(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let t=Er(),r=e.replace(/'/g,"'\\''");if(t)return nc(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return nc(`sudo -n sh -c '${r}'`,{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 m(e,t,r){if(r)ZP.debug(`[rpx:${e}] ${t}`)}function ti(){let e=process.env.RPX_REUSE_PORT;return e==="1"||e==="true"}function rA(e){let t=e.toLowerCase();return eA.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function ic(e){if(Array.isArray(e))return e.map((r)=>ic(r));if(typeof e==="string")return tA.test(e)?Nw:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,n]of Object.entries(e)){if(rA(r)){t[r]=Nw;continue}t[r]=ic(n)}return t}function ur(e,t){return JSON.stringify(ic(e),null,t)}function nA(e){if(Gr(e))return e.proxies.map((t)=>{let r=t.to||"stacks.localhost";return r.startsWith("http")?new URL(r).hostname:r});if(Qi(e)){let t=e.to||"stacks.localhost";return[t.startsWith("http")?new URL(t).hostname:t]}return["stacks.localhost"]}function xh(e){return typeof e==="object"&&e!==null&&"certificate"in e&&"privateKey"in e&&typeof e.certificate==="string"&&typeof e.privateKey==="string"}function sc(e){if(!e)return"stacks.localhost";if(Gr(e)&&e.proxies.length>0)return e.proxies[0].to||"stacks.localhost";if(Qi(e))return e.to||"stacks.localhost";return"stacks.localhost"}function oc(e){return!!(e&&("proxies"in e)&&Array.isArray(e.proxies))}function Gr(e){return"proxies"in e&&Array.isArray(e.proxies)}function Qi(e){return"to"in e&&typeof e.to==="string"}function iA(e){return!!(e&&("to"in e)&&!("proxies"in e))}function Sh(e,t){if(!t||t.length===0)return null;for(let r of t)if(e===r.from||e.startsWith(`${r.from}/`)){let n=r.to.startsWith("http")?new URL(r.to).host:r.to,i=r.stripPrefix===!0?e.slice(r.from.length)||"/":e;return{targetHost:n,targetPath:i}}return null}async function Eh(e,t){try{await Dw.unlink(e),m("certificates",`Successfully deleted: ${e}`,t)}catch(r){if(r.code!=="ENOENT")m("certificates",`Warning: Could not delete ${e}: ${r}`,t)}}var ZP,Nw="[redacted]",eA,tA;var fe=te(()=>{Ow();ZP=new Xi("rpx",{showTags:!1});eA=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),tA=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as ac}from"node:child_process";import{homedir as sA}from"node:os";import{join as oA}from"node:path";function cc(){return oA(sA(),"Library/Keychains/login.keychain-db")}function Ph(){return[Ar,cc()]}function Fw(e,t=Th){let r=ac(`security find-certificate -a -c "${t}" -Z "${e}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let i of r.split(`
238
+ `)){let s=i.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(s)n.push(s[1].toUpperCase())}return n}function Ah(e){if(process.platform!=="darwin")return;let t=Hr(e.caPath);if(!t)return;let r=e.commonName??Th,n=e.keychains??Ph();for(let i of n)for(let s of Fw(i,r)){if(s===t)continue;try{if(i.startsWith("/Library"))Tr(`security delete-certificate -Z ${s} "${i}"`);else ac(`security delete-certificate -Z ${s} "${i}"`,{stdio:"ignore"});m("ssl",`Removed stale Root CA ${s} from ${i}`,e.verbose)}catch{}}}function Rh(e,t,r){if(process.platform!=="darwin")return lc(e,r);try{let i=ac(`security verify-cert -c "${e}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return m("ssl",`verify-cert ${t}: ${i?"trusted":"not trusted"}`,r?.verbose),i}catch{return!1}}function lc(e,t){let r=Hr(e);if(!r)return!1;for(let n of Ph())try{let i=ac(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let s of i.split(`
239
+ `))if(s.toUpperCase().includes("SHA-256")){if(s.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return m("ssl",`Root CA fingerprint found in ${n}`,t?.verbose),!0}}catch{}return!1}var Pr="-d -r trustRoot -p ssl -p basic",Ar="/Library/Keychains/System.keychain",Th="rpx.localhost";var kh=te(()=>{Pa();fe()});import{execSync as Oh}from"node:child_process";import we from"node:fs/promises";import*as Nh from"node:os";import{homedir as ni}from"node:os";import*as Iw from"node:path";import{join as ve}from"node:path";import*as Rr from"node:process";function Mw(e,t){return[...new Set(e.filter(Boolean))].map((r)=>({serverName:r,cert:t.cert,key:t.key}))}function _w(e,t,r){let n=ve(ni(),".stacks","ssl"),i=[...new Set([t,...e,"rpx.localhost"])];return{https:{certPath:Dh,keyPath:ve(n,"rpx.localhost.key"),caCertPath:ve(n,"rpx.localhost.ca.crt"),commonName:t},verbose:r,regenerateUntrustedCerts:!0,proxies:i.map((s)=>({from:"localhost:1",to:s,cleanUrls:!1}))}}function uc(e){return{caCertPath:ve(e,cA),caKeyPath:ve(e,lA)}}async function uA(e,t){try{let[r,n]=await Promise.all([we.readFile(e.caCertPath,"utf8"),we.readFile(e.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return m("ssl",`Root CA files at ${e.caCertPath} look malformed, will regenerate`,t),null;return{certificate:r,privateKey:n}}catch(r){return m("ssl",`No existing Root CA at ${e.caCertPath} (${r.code||r}), will create one`,t),null}}async function Fh(e,t={}){await we.mkdir(e,{recursive:!0});let r=uc(e),n=await uA(r,t.verbose);if(n)return m("ssl",`Reusing existing Root CA from ${r.caCertPath}`,t.verbose),{...n,created:!1,paths:r};if(t.verbose)b.info("Generating Root CA certificate (one-time)...");let i=await Vi(t.caOptions??{});try{await Promise.all([we.writeFile(r.caCertPath,i.certificate),we.writeFile(r.caKeyPath,i.privateKey,{mode:384})]),m("ssl",`Persisted Root CA at ${r.caCertPath}`,t.verbose)}catch(s){throw m("ssl",`Error saving Root CA files: ${s}`,t.verbose),Error(`Failed to save Root CA files: ${s}`)}return{certificate:i.certificate,privateKey:i.privateKey,created:!0,paths:r}}function Lw(e){let t=new Set;t.add(e);let r=e.split(".");if(r.length>=3){let n=r[r.length-1],i=r[r.length-2],s=new Set(["co","com","org","net","ac","gov","edu"]);if(!(r.length===3&&n.length===2&&s.has(i)))t.add(`*.${r.slice(1).join(".")}`)}return Array.from(t)}function jw(e){let r=sc(e).replace(/\*/g,"wildcard"),n=ve(ni(),".stacks","ssl"),i=n;if(typeof e?.https==="object")return i=e.https.basePath&&e.https.basePath.trim()!==""?e.https.basePath:n,{caCertPath:e.https.caCertPath||ve(i,`${r}.ca.crt`),certPath:e.https.certPath||ve(i,`${r}.crt`),keyPath:e.https.keyPath||ve(i,`${r}.key`)};return{caCertPath:ve(i,`${r}.ca.crt`),certPath:ve(i,`${r}.crt`),keyPath:ve(i,`${r}.key`)}}function Bw(e){let t=new Set;if(Gr(e))e.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";Lw(n).forEach((i)=>t.add(i))});else if(Qi(e)){let r=e.to||"rpx.localhost";Lw(r).forEach((n)=>t.add(n))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function es(e){if(kr&&!e.forceRegenerate){m("ssl","Using cached SSL configuration",e.verbose);return}Lh();let t=Gr(e)?e.proxies.map((f)=>f.to):[e.to];m("ssl",`Generating certificate for domains: ${t.join(", ")}`,e.verbose);let r=ts(e,e.verbose),n=r.basePath||ve(ni(),".stacks","ssl"),i=await Fh(n,{caOptions:r,verbose:e.verbose}),s={certificate:i.certificate,privateKey:i.privateKey},o=i.created,c=i.paths;if(e.verbose)b.info(`Generating host certificate for: ${t.join(", ")}`);let a=await Un({...r,rootCA:{certificate:s.certificate,privateKey:s.privateKey}});try{await Promise.all([we.writeFile(r.certPath,a.certificate),we.writeFile(r.keyPath,a.privateKey),we.writeFile(r.caCertPath,s.certificate)]),m("ssl","Certificate files saved successfully",e.verbose)}catch(f){throw m("ssl",`Error saving certificate files: ${f}`,e.verbose),Error(`Failed to save certificate files: ${f}`)}if(o?!1:await fc(c.caCertPath,{verbose:e.verbose,regenerateUntrustedCerts:!0})){if(m("ssl","Root CA already trusted, skipping trust store update",e.verbose),e.verbose)b.success("Root CA is already trusted in system trust store");if(kr={key:a.privateKey,cert:a.certificate,ca:s.certificate},e.verbose)b.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(e.verbose)b.info("Adding certificate to system trust store (may require sudo permission)...");let u=!1;if(Rr.platform==="darwin")try{Ah({caPath:c.caCertPath,verbose:e.verbose});let f=cc();try{Oh(`security add-trusted-cert ${Pr} -k "${f}" "${c.caCertPath}"`,{stdio:"ignore"})}catch{}if(Tr(`security add-trusted-cert ${Pr} -k ${Ar} "${c.caCertPath}"`),e.verbose)b.success("Successfully added Root CA to system trust store");u=!0;let h=ve(n,"trust-rpx-cert.sh"),d=`#!/bin/bash
182
240
  echo "Trusting RPX Root CA"
183
241
  # SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
184
242
  # non-interactive. Without it, fall back to a normal sudo prompt.
185
243
  if [ -n "$SUDO_PASSWORD" ]
186
244
  then
187
245
  printf '%s
188
- ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${N$} -k ${q$} "${X.caCertPath}"
246
+ ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${Pr} -k ${Ar} "${c.caCertPath}"
189
247
  else
190
- sudo security add-trusted-cert ${N$} -k ${q$} "${X.caCertPath}"
248
+ sudo security add-trusted-cert ${Pr} -k ${Ar} "${c.caCertPath}"
191
249
  fi
192
250
  echo "Root CA trusted! Please restart your browser."
193
251
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
194
- `;await B0.writeFile(f,B,{mode:493})}catch(z){if(w.verbose)H.warn(`Could not add Root CA to trust store automatically: ${z}`);let f=G0(A,"trust-rpx-cert.sh"),B=`#!/bin/bash
252
+ `;await we.writeFile(h,d,{mode:493})}catch(f){if(e.verbose)b.warn(`Could not add Root CA to trust store automatically: ${f}`);let h=ve(n,"trust-rpx-cert.sh"),d=`#!/bin/bash
195
253
  echo "Trusting RPX Root CA"
196
254
  # SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
197
255
  # non-interactive. Without it, fall back to a normal sudo prompt.
198
256
  if [ -n "$SUDO_PASSWORD" ]
199
257
  then
200
258
  printf '%s
201
- ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${N$} -k ${q$} "${X.caCertPath}"
259
+ ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${Pr} -k ${Ar} "${c.caCertPath}"
202
260
  else
203
- sudo security add-trusted-cert ${N$} -k ${q$} "${X.caCertPath}"
261
+ sudo security add-trusted-cert ${Pr} -k ${Ar} "${c.caCertPath}"
204
262
  fi
205
263
  echo "Root CA trusted! Please restart your browser."
206
264
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
207
- `;if(await B0.writeFile(f,B,{mode:493}),w.verbose)H.info(`Created a trust helper script at: ${f}`),H.info(`If you're still having certificate issues, run: sh ${f}`)}else if(H$.platform==="linux")try{let{exec:z}=await import("node:child_process"),f="/usr/local/share/ca-certificates/rpx",B=`
265
+ `;if(await we.writeFile(h,d,{mode:493}),e.verbose)b.info(`Created a trust helper script at: ${h}`),b.info(`If you're still having certificate issues, run: sh ${h}`)}else if(Rr.platform==="linux")try{let{exec:f}=await import("node:child_process"),h="/usr/local/share/ca-certificates/rpx",d=`
208
266
  mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
209
- cp "${X.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
267
+ cp "${c.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
210
268
  update-ca-certificates
211
269
  echo "RPX Root CA installed. Please restart your browser."
212
- `,G=G0(zj.tmpdir(),`rpx-trust-${Date.now()}.sh`);await B0.writeFile(G,B,{mode:493}),await new Promise((T)=>{z(`sudo bash "${G}"`,(F)=>{if(F){if(w.verbose)H.warn(`Could not trust certificates: ${F}`);T(!1)}else{if(w.verbose)H.success("Successfully added certificates to system trust store");T(!0)}})}),await B0.unlink(G).catch(()=>{}),Q=!0}catch(z){if(w.verbose)H.warn(`Failed to trust certificates: ${z}`)}else if(H$.platform==="win32")try{let z=`
213
- $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${X.caCertPath.replace(/\//g,"\\")}")
270
+ `,y=ve(Nh.tmpdir(),`rpx-trust-${Date.now()}.sh`);await we.writeFile(y,d,{mode:493}),await new Promise((g)=>{f(`sudo bash "${y}"`,(p)=>{if(p){if(e.verbose)b.warn(`Could not trust certificates: ${p}`);g(!1)}else{if(e.verbose)b.success("Successfully added certificates to system trust store");g(!0)}})}),await we.unlink(y).catch(()=>{}),u=!0}catch(f){if(e.verbose)b.warn(`Failed to trust certificates: ${f}`)}else if(Rr.platform==="win32")try{let f=`
271
+ $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${c.caCertPath.replace(/\//g,"\\")}")
214
272
  $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
215
273
  $store.Open("ReadWrite")
216
274
  $store.Add($cert)
217
275
  $store.Close()
218
276
  Write-Host "Root CA trusted successfully!"
219
- `,f=G0(zj.tmpdir(),"rpx-trust.ps1");if(await B0.writeFile(f,z),Qj(`powershell -ExecutionPolicy Bypass -File "${f}"`),w.verbose)H.success("Successfully added certificate to Windows trust store");Q=!0}catch(z){if(w.verbose)H.warn(`Could not trust certificate: ${z}`)}else try{await EW(j,J.certificate,Y),Q=!0}catch(z){if(w.verbose)H.warn(`Could not add certificate to trust store: ${z}`)}if(R$={key:j.privateKey,cert:j.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);if(!Q&&w.verbose)H.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),H.warn("This will bypass the warning and you should only need to do it once")}function Bj(){R$=null}async function M$(w){if(!w)return null;if(R$)return R$;let $=HY(w);try{let[Y,A,X]=await Promise.all([B0.access($.keyPath).then(()=>!0).catch(()=>!1),B0.access($.certPath).then(()=>!0).catch(()=>!1),$.caCertPath?B0.access($.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return K("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${$.keyPath}, ${$.certPath}`,w.verbose),null;let J="regenerateUntrustedCerts"in w,U=w.regenerateUntrustedCerts,j=J?U!==!1:!0;K("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${j}`,w.verbose);let W=$.basePath||G0(P1(),".stacks","ssl"),Q=B2(W);if(!(j?await F2(Q.caCertPath,w):!0))return K("ssl","Root CA exists but is not trusted, will regenerate",w.verbose),null;let[f,B,G]=await Promise.all([B0.readFile($.keyPath,"utf8"),B0.readFile($.certPath,"utf8"),X&&$.caCertPath?B0.readFile($.caCertPath,"utf8"):Promise.resolve(void 0)]);if(G&&!G.includes("-----BEGIN CERTIFICATE-----"))return K("ssl","Invalid root CA certificate content, will regenerate",w.verbose),null;if(i$(w))try{let{X509Certificate:T}=await import("node:crypto"),E=new T(B).subjectAltName||"",R=w.proxies.map((V)=>V.to).filter((V)=>!E.includes(`DNS:${V}`));if(R.length>0)return K("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,w.verbose),null}catch(T){K("ssl",`Could not verify cert SANs: ${T}`,w.verbose)}return K("ssl","Successfully loaded existing certificates",w.verbose),R$={key:f,cert:B,ca:G},R$}catch(Y){return K("ssl",`Error checking existing certificates: ${Y}`,w.verbose),null}}function HY(w,$){let Y=B8(w);K("ssl",`Primary domain: ${Y}`,$);let A=G2(w),X=G0(P1(),".stacks","ssl");if(typeof w.https==="object"){let J=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:w.https.caCertPath||A.caCertPath,certPath:w.https.certPath||A.certPath,keyPath:w.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:w.https.commonName||Y,organizationName:w.https.organizationName||"Local Development",countryName:w.https.countryName||"US",stateName:w.https.stateName||"California",localityName:w.https.localityName||"Playa Vista",validityDays:w.https.validityDays||825,verbose:$||!1,subjectAltNames:Array.from(j2(w)).map((j)=>({type:2,value:j}))};if($j(w.https.rootCA))U.rootCA=w.https.rootCA;return U}return{domain:Y,hostCertCN:Y,basePath:X,...A,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:Y,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:$||!1,subjectAltNames:Array.from(j2(w)).map((J)=>({type:2,value:J}))}}async function K2(w,$){let Y=G2({to:w,verbose:$}),A=[Y.caCertPath,Y.certPath,Y.keyPath];K("certificates","Attempting to clean up relating certificates",$),await Promise.all(A.map((X)=>Aj(X,$)))}async function F2(w,$){try{if(K("ssl",`Checking if certificate is trusted: ${w}`,$?.verbose),H$.platform==="darwin"){if($?.serverName)return Wj(w,$.serverName,{verbose:$?.verbose});return E8(w,{verbose:$?.verbose})}else if(H$.platform==="win32")try{let Y=TW(w)||"";if(!Y)return K("ssl","Could not extract certificate subject",$?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(Qj(A).toString().includes(Y))return K("ssl","Certificate found in trusted root store",$?.verbose),!0;return K("ssl","Certificate not found in trusted root store",$?.verbose),!1}catch(Y){return K("ssl",`Error checking certificate trust on Windows: ${Y}`,$?.verbose),!1}else if(H$.platform==="linux")try{let Y=Z$(w);if(!Y)return K("ssl","Could not extract certificate fingerprint",$?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await B0.readdir(X)}catch{continue}for(let U of J){let j=Z$(Q2.join(X,U));if(j&&j===Y)return K("ssl",`Certificate fingerprint found in ${X}`,$?.verbose),!0}}return K("ssl","Certificate not found in system trust stores",$?.verbose),!1}catch(Y){return K("ssl",`Error checking certificate trust on Linux: ${Y}`,$?.verbose),!1}return K("ssl",`Platform ${H$.platform} not supported for certificate trust check`,$?.verbose),!1}catch(Y){return K("ssl",`Error checking if certificate is trusted: ${Y}`,$?.verbose),!1}}var R$=null,fj,Dq="rpx-root-ca.crt",xq="rpx-root-ca.key";var Gj=s(()=>{xX();D$();bA();jj();f0();jj();kX();kX();fj=G0(P1(),".stacks","ssl","rpx.localhost.crt")});function Zq(w){return{enabled:w?.enabled??!1,path:w?.path??"/",interval:w?.interval??1e4,timeout:w?.timeout??2000,healthyThreshold:w?.healthyThreshold??2,unhealthyThreshold:w?.unhealthyThreshold??3}}function Pq(w){return(Array.isArray(w)?w:[w]).map((Y)=>{let A=typeof Y==="string"?{url:Y}:Y;return{url:A.url,weight:A.weight&&A.weight>0?A.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function E2(w){return(Array.isArray(w)?w:[w]).map((Y)=>typeof Y==="string"?Y:Y.url)}function b$(w){if(!w)return"localhost:5173";let $=Array.isArray(w)?w[0]:w;if(!$)return"localhost:5173";return typeof $==="string"?$:$.url}function RY(w,$){return{upstreams:Pq(w),strategy:$?.strategy??"round-robin",healthCheck:Zq($?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function iq(w){let $=w.upstreams.filter((Y)=>Y.healthy);if($.length===0&&w.upstreams.length===1)return w.upstreams;return $}function bq(w,$){let Y=w.cursor%$.length;return w.cursor=(w.cursor+1)%$.length,$[Y]}function uq(w,$){if(w.wrrCurrentWeights.length!==$.length)w.wrrCurrentWeights=$.map(()=>0);let Y=$.reduce((X,J)=>X+J.weight,0),A=0;for(let X=0;X<$.length;X++)if(w.wrrCurrentWeights[X]+=$[X].weight,w.wrrCurrentWeights[X]>w.wrrCurrentWeights[A])A=X;return w.wrrCurrentWeights[A]-=Y,$[A]}function vq(w){let $=w[0];for(let Y=1;Y<w.length;Y++)if(w[Y].activeConnections<$.activeConnections)$=w[Y];return $}function T2(w){let $=iq(w);if($.length===0)return;if($.length===1)return $[0];switch(w.strategy){case"weighted-round-robin":return uq(w,$);case"least-connections":return vq($);case"round-robin":default:return bq(w,$)}}function T8(w,$){if($.consecutiveFailures=0,$.consecutiveSuccesses+=1,!$.healthy&&$.consecutiveSuccesses>=w.healthCheck.healthyThreshold)$.healthy=!0}function MY(w,$){if($.consecutiveSuccesses=0,$.consecutiveFailures+=1,$.healthy&&$.consecutiveFailures>=w.healthCheck.unhealthyThreshold)$.healthy=!1}function cq(w){let $=w.lastIndexOf(":");if($===-1)return{hostname:w,port:80};let Y=Number(w.slice($+1));return{hostname:w.slice(0,$),port:Number.isFinite(Y)?Y:80}}async function mq(w,$){let{hostname:Y,port:A}=cq($.url),X=new AbortController,J=setTimeout(()=>X.abort(),w.healthCheck.timeout);try{(await fetch(`http://${Y}:${A}${w.healthCheck.path}`,{signal:X.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),T8(w,$)}catch{MY(w,$)}finally{clearTimeout(J)}}function IY(w){if(!w.healthCheck.enabled||w.healthCheckTimer||w.upstreams.length<2)return;let $=setInterval(()=>{for(let Y of w.upstreams)mq(w,Y)},w.healthCheck.interval);$.unref?.(),w.healthCheckTimer=$}function i1(w){if(w.healthCheckTimer)clearInterval(w.healthCheckTimer),w.healthCheckTimer=null}import{createHash as q2,timingSafeEqual as N2}from"node:crypto";import{readFileSync as gq}from"node:fs";function yY(w,$){let Y=Buffer.from(w,"utf8"),A=Buffer.from($,"utf8");if(Y.length!==A.length)return N2(Y,Y),!1;return N2(Y,A)}function nq(w,$){let Y=(B)=>q2("md5").update(B).digest(),A=Buffer.from(w,"utf8"),X=Buffer.from($,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let B=A.length;B>0;B-=16)U.push(J.subarray(0,Math.min(B,16)));for(let B=A.length;B>0;B>>=1)U.push(B&1?Buffer.from([0]):A.subarray(0,1));let j=Y(Buffer.concat(U));for(let B=0;B<1000;B++){let G=[];if(G.push(B&1?A:j.subarray(0,16)),B%3)G.push(X);if(B%7)G.push(A);G.push(B&1?j.subarray(0,16):A),j=Y(Buffer.concat(G))}let W="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Q=(B,G)=>{let T="",F=B;for(let E=0;E<G;E++)T+=W[F&63],F>>=6;return T},z=j,f="";return f+=Q(z[0]<<16|z[6]<<8|z[12],4),f+=Q(z[1]<<16|z[7]<<8|z[13],4),f+=Q(z[2]<<16|z[8]<<8|z[14],4),f+=Q(z[3]<<16|z[9]<<8|z[15],4),f+=Q(z[4]<<16|z[10]<<8|z[5],4),f+=Q(z[11],2),`$apr1$${$}$${f}`}function lq(w,$){if(/^\$2[aby]?\$/.test($))try{return Bun.password.verifySync(w,$)}catch{return!1}if($.startsWith("$apr1$")){let A=$.split("$")[2]??"";return yY(nq(w,A),$)}if($.startsWith("{SHA}")){let Y=q2("sha1").update(w,"utf8").digest("base64");return yY(`{SHA}${Y}`,$)}return yY(w,$)}function pq(w){let $=new Map;for(let Y of w.split(`
220
- `)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;$.set(A.slice(0,X),A.slice(X+1))}return $}function CY(w){if(!w)return;let $=(w.realm??"").trim()||"Restricted",Y=[];if(w.username)Y.push({username:w.username,password:w.password??""});for(let J of w.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if(w.htpasswdFile)try{A=pq(gq(w.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:$,verify:(J,U)=>{let j=!1;for(let W of Y)if(yY(J,W.username)&&yY(U,W.password))j=!0;if(A){let W=A.get(J);if(W&&lq(U,W))j=!0}return j}}}function H2(w,$,Y){if($.startsWith(dq))return;let A=w.headers.get("authorization")??"",X=A.indexOf(" "),J=X===-1?A:A.slice(0,X),U=X===-1?"":A.slice(X+1).trim();if(J.toLowerCase()==="basic"&&U){let W="";try{W=Buffer.from(U,"base64").toString("utf8")}catch{W=""}let Q=W.indexOf(":");if(Q>=0&&Y.verify(W.slice(0,Q),W.slice(Q+1)))return}let j=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${j}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var dq="/.well-known/acme-challenge/";var N8=()=>{};function aq(w){return tq.has(w.toUpperCase())}function sq(){let w=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(w)&&w>0?w:30000}function oq(w){let $=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite($)&&$>0?$:w*8}function eq(){let w=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(w)&&w>0?w:0}function wH(){let w=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(w)&&w>0?w:0}function $H(){let w=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(w)&&w>0?w:256}class C2{socket=null;buf=new Uint8Array(YH);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(w){let $=this.socket,Y=$.write(w);while(Y<w.length){if(this.closed)throw q8;await new Promise((A)=>{this.drainWaiter=A}),Y+=$.write(w.subarray(Y))}}wakeDrain(){let w=this.drainWaiter;if(w)this.drainWaiter=null,w()}push(w){if(this.bodyQueue){let $=w.length<=this.bodyRemaining?w.length:this.bodyRemaining;if($>0)this.bodyQueue.push(w.slice(0,$)),this.queuedBytes+=$;if(this.bodyRemaining-=$,$<w.length)this.appendToBuf(w.subarray($));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(w),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>AH)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=XH)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(w){let $=this.len+w.length;if($>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,$));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set(w,this.len),this.len=$}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let w=this.waiter;if(w)this.waiter=null,w()}waitForData(w){if(this.len>w||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class V2{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=sq();maxWaiters;checkoutIdleMs=eq();inUse=new Set;constructor(w,$,Y,A=""){this.host=w;this.port=$;this.maxTotal=Y;this.key=A;this.maxWaiters=oq(Y)}trackCheckout(w){if(w.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(w),this.ensureSweeper()}dial(){let w=new C2;return rq({hostname:this.host,port:this.port,socket:{data:($,Y)=>w.push(Y),drain:()=>w.wakeDrain(),close:()=>w.markClosed(),end:()=>w.markClosed(),error:()=>w.markClosed(),connectError:()=>w.markClosed(),timeout:()=>w.markTimedOut()}}).then(($)=>{let Y=$;Y.setNoDelay?.(!0);let A=wH();if(A>0)Y.timeout?.(A);return w.socket=$,w})}acquireIdleSync(){while(this.idle.length){let w=this.idle.pop();if(!w.closed)return w.socket?.ref(),w.pos=0,w.len=0,this.trackCheckout(w),w;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw u$;let w=await this.waitForSlot();if(w===u$)throw u$;if(w)return w.pos=0,w.len=0,this.trackCheckout(w),w}this.open++;try{let w=await this.dial();return this.trackCheckout(w),w}catch(w){throw this.open--,this.wakeWaiter(),w}}waitForSlot(){return new Promise((w)=>{let $=!1,Y=(J)=>{if($)return;$=!0,clearTimeout(X),w(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(u$)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release(w){if(this.inUse.delete(w),w.closed){this.open--,this.wakeWaiter();return}w.clearStreaming(),w.compact(),w.fresh=!1;let $=this.waiters.shift();if($){w.socket?.ref(),this.trackCheckout(w),$(w);return}w.idleSince=Date.now(),w.socket?.unref(),this.idle.push(w),this.ensureSweeper()}destroy(w){this.inUse.delete(w),w.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let w=this.waiters.shift();if(w)w(null)}ensureSweeper(){if(this.sweeper)return;let w=this.checkoutIdleMs>0?Math.min(Kj,this.checkoutIdleMs):Kj;this.sweeper=setInterval(()=>this.sweep(),w),this.sweeper.unref?.()}sweep(){let w=Date.now(),$=w-Kj;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=$)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=w-this.checkoutIdleMs;for(let A of this.inUse)if(!A.closed&&A.lastActivityAt>0&&A.lastActivityAt<=Y)A.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&H8.get(this.key)===this)H8.delete(this.key)}}}function QH(w,$){let Y=H8.get(w);if(!Y){let A=w.lastIndexOf(":"),X=A===-1?w:w.slice(0,A),J=A===-1?80:Number(w.slice(A+1));Y=new V2(X,J,$??$H(),w),H8.set(w,Y)}return Y}function R2(w,$,Y){for(let A=Y+3;A<$;A++)if(w[A]===10&&w[A-1]===13&&w[A-2]===10&&w[A-3]===13)return A-3;return-1}function zH(w,$,Y){let A=y2.decode(w.subarray($,Y)),X=A.indexOf(`\r
221
- `),J=X===-1?A:A.slice(0,X),U=J.indexOf(" "),j=Number.parseInt(J.slice(U+1,U+5),10),W=J.startsWith("HTTP/1.0"),Q=[],z=-1,f=!1,B=W,G=!1,T=!1,F=X===-1?A.length:X+2;while(F<A.length){let E=A.indexOf(`\r
222
- `,F);if(E===-1)E=A.length;let N=A.slice(F,E);if(F=E+2,N==="")continue;let R=N.indexOf(":");if(R===-1)continue;let V=N.slice(0,R),L=N.slice(R+1).trim(),q=V.charCodeAt(0)|32;if(q===99||q===116||q===107){let C=V.toLowerCase();if(C==="content-length"){let M=/^\d+$/.test(L)?Number(L):Number.NaN;if(!Number.isSafeInteger(M)||z>=0&&z!==M)T=!0;else z=M;continue}if(C==="transfer-encoding"){if(L.toLowerCase().includes("chunked"))f=!0;continue}if(C==="connection"){let M=L.toLowerCase();if(M.includes("close"))B=!0;if(M.includes("keep-alive"))G=!0;continue}if(C==="keep-alive")continue}Q.push([V,L])}if(W&&G)B=!1;if(f&&z>=0)z=-1;return{status:j,headerEnd:Y,headers:Q,contentLength:z,chunked:f,closeConn:B,malformed:T}}function fH(w,$){return $||w===204||w===304}async function L2(w){let{hostPort:$,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:j}=w,W=Y==="HEAD",Q=X.get("accept")?.toLowerCase()??"";if(X.get("expect")||X.get("upgrade")||Q.includes("text/event-stream"))throw VY;let z=null;if(j){let T=X.get("content-length"),F=T?Number.parseInt(T,10):Number.NaN;if(Number.isNaN(F)||F>M2)throw VY;if(z=await NH(j),z===null)throw VY}let f=TH(Y,A,X,$,J,U,z),B=f;if(z&&z.length)B=new Uint8Array(f.length+z.length),B.set(f),B.set(z,f.length);let G=QH($,w.maxPerHost);for(let T=0;;T++){if(T>0)await new Promise((E)=>{setTimeout(E,T)});let F;try{F=G.acquireIdleSync()??await G.acquireOrDial()}catch(E){if(E!==u$&&T<4)continue;throw E}try{let E=F.socket.write(B);if(E<B.length)await F.writeAll(B.subarray(E));return await GH(G,F,W,w.signal)}catch(E){let N=E===q8&&T<4&&(F.fresh||aq(Y));if(G.destroy(F),N)continue;if(E===q8)throw Error("upstream closed connection");throw E}}}async function BH(w){let $=R2(w.buf,w.len,w.pos);while($===-1){if(w.closed){if(w.timedOut)throw Fj;if(w.len===w.pos)throw q8;throw Error("upstream closed mid-header")}if(w.len-w.pos>I2)throw Error("upstream header block too large");await w.waitForData(w.len),$=R2(w.buf,w.len,w.pos)}return $}async function GH(w,$,Y,A){let X;for(;;){let U=await BH($);if(X=zH($.buf,$.pos,U),$.pos=U+4,X.status>=100&&X.status<200)continue;break}if(X.malformed)throw w.destroy($),Error("upstream sent malformed response framing");let J=X.headers;if(fH(X.status,Y))return O2(w,$,X.closeConn),new Response(null,{status:X.status,headers:J});if(X.chunked)return new Response(EH(w,$,X.closeConn,A),{status:X.status,headers:J});if(X.contentLength>=0){if($.len-$.pos>=X.contentLength){let j=$.pos+X.contentLength,W=$.len>j,Q=null;if(X.contentLength>=JH)Q=$.buf.subarray($.pos,j),$.buf=new Uint8Array(UH);else if(X.contentLength>0)Q=$.buf.slice($.pos,j);if($.pos=0,$.len=0,X.closeConn||W)w.destroy($);else w.release($);return new Response(Q,{status:X.status,headers:J})}return new Response(KH(w,$,X.contentLength,X.closeConn),{status:X.status,headers:J})}return new Response(FH($),{status:X.status,headers:J})}function O2(w,$,Y){if(Y||$.pos!==$.len)w.destroy($);else w.release($)}function KH(w,$,Y,A){let X=$.len-$.pos,J=X>0?$.buf.slice($.pos,$.len):null;$.pos=0,$.len=0,$.bodyQueue=[],$.bodyRemaining=Y-X,$.queuedBytes=0,$.streamingBody=!0;let U=(j)=>{if($.bodyQueue=null,A||$.len>0)w.destroy($);else w.release($);j.close()};return new ReadableStream({start(j){if(J)j.enqueue(J);if($.bodyRemaining===0&&$.bodyQueue.length===0)U(j)},async pull(j){for(;;){let W=$.bodyQueue;if(W&&W.length>0){let Q=W.shift();if($.queuedBytes-=Q.length,$.resumeIfDrained(),j.enqueue(Q),$.bodyRemaining===0&&W.length===0)U(j);return}if($.bodyRemaining===0){if($.bodyQueue)U(j);return}if($.closed){$.bodyQueue=null,w.destroy($),j.error(Error("upstream closed mid-body"));return}await $.waitForBody()}},cancel(){$.bodyQueue=null,w.destroy($)}})}function FH(w){return w.streamingBody=!0,new ReadableStream({async pull($){for(;;){if(w.len>w.pos){$.enqueue(w.buf.slice(w.pos,w.len)),w.pos=w.len,w.resumeIfDrained();return}if(w.closed){w.destroy(),$.close();return}await w.waitForData(w.len)}},cancel(){w.destroy()}})}function EH(w,$,Y,A){$.streamingBody=!0;let X=0,J=!1,U=!1,j,W=()=>A?.removeEventListener("abort",Q),Q=()=>{if(U)return;U=!0,w.destroy($);try{j?.close()}catch{}};async function z(f=!1){for(;;){for(let B=$.pos;B+1<$.len;B++)if($.buf[B]===13&&$.buf[B+1]===10){let G=y2.decode($.buf.subarray($.pos,B));return $.pos=B+2,G}if($.closed){if(f&&$.pos===$.len)return null;throw Error("upstream closed mid-chunk-header")}if($.len-$.pos>I2)throw Error("upstream chunk header too large");await $.waitForData($.len)}}return new ReadableStream({start(f){if(j=f,A?.aborted)Q();else A?.addEventListener("abort",Q,{once:!0})},async pull(f){try{for(;;){if(X>0){if($.len===$.pos){if($.closed){w.destroy($),f.error(Error("upstream closed mid-chunk"));return}await $.waitForData($.len);continue}let F=Math.min(X,$.len-$.pos);if(f.enqueue($.buf.slice($.pos,$.pos+F)),$.pos+=F,X-=F,$.resumeIfDrained(),X===0)J=!0;return}if(J)await z(),J=!1;let B=await z(!0);if(B===null){w.destroy($),W(),f.close();return}let G=B.indexOf(";"),T=Number.parseInt(G===-1?B:B.slice(0,G),16);if(!Number.isInteger(T)||T<0){w.destroy($),f.error(Error("upstream sent malformed chunk size"));return}if(T===0){for(;;)if(await z()==="")break;O2(w,$,Y),W(),f.close();return}X=T}}catch(B){if(w.destroy($),W(),!U)f.error(B)}},cancel(){U=!0,W(),w.destroy($)}})}function TH(w,$,Y,A,X,J,U){let j=`${w} ${$} HTTP/1.1\r
223
- host: ${A}\r
224
- x-forwarded-for: 127.0.0.1\r
277
+ `,h=ve(Nh.tmpdir(),"rpx-trust.ps1");if(await we.writeFile(h,f),Oh(`powershell -ExecutionPolicy Bypass -File "${h}"`),e.verbose)b.success("Successfully added certificate to Windows trust store");u=!0}catch(f){if(e.verbose)b.warn(`Could not trust certificate: ${f}`)}else try{await Ea(a,s.certificate,r),u=!0}catch(f){if(e.verbose)b.warn(`Could not add certificate to trust store: ${f}`)}if(kr={key:a.privateKey,cert:a.certificate,ca:s.certificate},e.verbose)b.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!u&&e.verbose)b.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),b.warn("This will bypass the warning and you should only need to do it once")}function Lh(){kr=null}async function Or(e){if(!e)return null;if(kr)return kr;let t=ts(e);try{let[r,n,i]=await Promise.all([we.access(t.keyPath).then(()=>!0).catch(()=>!1),we.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?we.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return m("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${t.keyPath}, ${t.certPath}`,e.verbose),null;let s="regenerateUntrustedCerts"in e,o=e.regenerateUntrustedCerts,c=s?o!==!1:!0;m("ssl",`Trust check: hasFlag=${s}, flagValue=${o}, shouldCheckTrust=${c}`,e.verbose);let a=t.basePath||ve(ni(),".stacks","ssl"),l=uc(a);if(!(c?await fc(l.caCertPath,e):!0))return m("ssl","Root CA exists but is not trusted, will regenerate",e.verbose),null;let[f,h,d]=await Promise.all([we.readFile(t.keyPath,"utf8"),we.readFile(t.certPath,"utf8"),i&&t.caCertPath?we.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(d&&!d.includes("-----BEGIN CERTIFICATE-----"))return m("ssl","Invalid root CA certificate content, will regenerate",e.verbose),null;if(Gr(e))try{let{X509Certificate:y}=await import("node:crypto"),p=new y(h).subjectAltName||"",v=e.proxies.map((P)=>P.to).filter((P)=>!p.includes(`DNS:${P}`));if(v.length>0)return m("ssl",`Certificate missing SANs for: ${v.join(", ")}, will regenerate`,e.verbose),null}catch(y){m("ssl",`Could not verify cert SANs: ${y}`,e.verbose)}return m("ssl","Successfully loaded existing certificates",e.verbose),kr={key:f,cert:h,ca:d},kr}catch(r){return m("ssl",`Error checking existing certificates: ${r}`,e.verbose),null}}function ts(e,t){let r=sc(e);m("ssl",`Primary domain: ${r}`,t);let n=jw(e),i=ve(ni(),".stacks","ssl");if(typeof e.https==="object"){let s=e.https.basePath&&e.https.basePath.trim()!==""?e.https.basePath:i,o=e.https.altNameIPs?.filter((a)=>typeof a==="string"&&a.length>0),c={domain:r,hostCertCN:r,basePath:s,caCertPath:e.https.caCertPath||n.caCertPath,certPath:e.https.certPath||n.certPath,keyPath:e.https.keyPath||n.keyPath,altNameIPs:o&&o.length>0?o:["127.0.0.1","::1"],altNameURIs:[],commonName:e.https.commonName||r,organizationName:e.https.organizationName||"Local Development",countryName:e.https.countryName||"US",stateName:e.https.stateName||"California",localityName:e.https.localityName||"Playa Vista",validityDays:e.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(Bw(e)).map((a)=>({type:2,value:a}))};if(xh(e.https.rootCA))c.rootCA=e.https.rootCA;return c}return{domain:r,hostCertCN:r,basePath:i,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(Bw(e)).map((s)=>({type:2,value:s}))}}async function Uw(e,t){let r=jw({to:e,verbose:t}),n=[r.caCertPath,r.certPath,r.keyPath];m("certificates","Attempting to clean up relating certificates",t),await Promise.all(n.map((i)=>Eh(i,t)))}async function fc(e,t){try{if(m("ssl",`Checking if certificate is trusted: ${e}`,t?.verbose),Rr.platform==="darwin"){if(t?.serverName)return Rh(e,t.serverName,{verbose:t?.verbose});return lc(e,{verbose:t?.verbose})}else if(Rr.platform==="win32")try{let r=_f(e)||"";if(!r)return m("ssl","Could not extract certificate subject",t?.verbose),!1;let n=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(Oh(n).toString().includes(r))return m("ssl","Certificate found in trusted root store",t?.verbose),!0;return m("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Windows: ${r}`,t?.verbose),!1}else if(Rr.platform==="linux")try{let r=Hr(e);if(!r)return m("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let n=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let i of n){let s;try{s=await we.readdir(i)}catch{continue}for(let o of s){let c=Hr(Iw.join(i,o));if(c&&c===r)return m("ssl",`Certificate fingerprint found in ${i}`,t?.verbose),!0}}return m("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Linux: ${r}`,t?.verbose),!1}return m("ssl",`Platform ${Rr.platform} not supported for certificate trust check`,t?.verbose),!1}catch(r){return m("ssl",`Error checking if certificate is trusted: ${r}`,t?.verbose),!1}}var kr=null,Dh,cA="rpx-root-ca.crt",lA="rpx-root-ca.key";var hc=te(()=>{Hi();qt();Co();kh();fe();kh();Pa();Pa();Dh=ve(ni(),".stacks","ssl","rpx.localhost.crt")});function fA(e){return{enabled:e?.enabled??!1,path:e?.path??"/",interval:e?.interval??1e4,timeout:e?.timeout??2000,healthyThreshold:e?.healthyThreshold??2,unhealthyThreshold:e?.unhealthyThreshold??3}}function hA(e){return(Array.isArray(e)?e:[e]).map((r)=>{let n=typeof r==="string"?{url:r}:r;return{url:n.url,weight:n.weight&&n.weight>0?n.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function Kw(e){return(Array.isArray(e)?e:[e]).map((r)=>typeof r==="string"?r:r.url)}function qr(e){if(!e)return"localhost:5173";let t=Array.isArray(e)?e[0]:e;if(!t)return"localhost:5173";return typeof t==="string"?t:t.url}function rs(e,t){return{upstreams:hA(e),strategy:t?.strategy??"round-robin",healthCheck:fA(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function dA(e){let t=e.upstreams.filter((r)=>r.healthy);if(t.length===0&&e.upstreams.length===1)return e.upstreams;return t}function mA(e,t){let r=e.cursor%t.length;return e.cursor=(e.cursor+1)%t.length,t[r]}function gA(e,t){if(e.wrrCurrentWeights.length!==t.length)e.wrrCurrentWeights=t.map(()=>0);let r=t.reduce((i,s)=>i+s.weight,0),n=0;for(let i=0;i<t.length;i++)if(e.wrrCurrentWeights[i]+=t[i].weight,e.wrrCurrentWeights[i]>e.wrrCurrentWeights[n])n=i;return e.wrrCurrentWeights[n]-=r,t[n]}function pA(e){let t=e[0];for(let r=1;r<e.length;r++)if(e[r].activeConnections<t.activeConnections)t=e[r];return t}function Ww(e){let t=dA(e);if(t.length===0)return;if(t.length===1)return t[0];switch(e.strategy){case"weighted-round-robin":return gA(e,t);case"least-connections":return pA(t);case"round-robin":default:return mA(e,t)}}function dc(e,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=e.healthCheck.healthyThreshold)t.healthy=!0}function ns(e,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=e.healthCheck.unhealthyThreshold)t.healthy=!1}function yA(e){let t=e.lastIndexOf(":");if(t===-1)return{hostname:e,port:80};let r=Number(e.slice(t+1));return{hostname:e.slice(0,t),port:Number.isFinite(r)?r:80}}async function wA(e,t){let{hostname:r,port:n}=yA(t.url),i=new AbortController,s=setTimeout(()=>i.abort(),e.healthCheck.timeout);try{(await fetch(`http://${r}:${n}${e.healthCheck.path}`,{signal:i.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),dc(e,t)}catch{ns(e,t)}finally{clearTimeout(s)}}function is(e){if(!e.healthCheck.enabled||e.healthCheckTimer||e.upstreams.length<2)return;let t=setInterval(()=>{for(let r of e.upstreams)wA(e,r)},e.healthCheck.interval);t.unref?.(),e.healthCheckTimer=t}function ii(e){if(e.healthCheckTimer)clearInterval(e.healthCheckTimer),e.healthCheckTimer=null}import{createHash as Hw,timingSafeEqual as Vw}from"node:crypto";import{readFileSync as vA}from"node:fs";function ss(e,t){let r=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8");if(r.length!==n.length)return Vw(r,r),!1;return Vw(r,n)}function $A(e,t){let r=(h)=>Hw("md5").update(h).digest(),n=Buffer.from(e,"utf8"),i=Buffer.from(t,"utf8"),s=r(Buffer.concat([n,i,n])),o=[n,Buffer.from("$apr1$","utf8"),i];for(let h=n.length;h>0;h-=16)o.push(s.subarray(0,Math.min(h,16)));for(let h=n.length;h>0;h>>=1)o.push(h&1?Buffer.from([0]):n.subarray(0,1));let c=r(Buffer.concat(o));for(let h=0;h<1000;h++){let d=[];if(d.push(h&1?n:c.subarray(0,16)),h%3)d.push(i);if(h%7)d.push(n);d.push(h&1?c.subarray(0,16):n),c=r(Buffer.concat(d))}let a="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",l=(h,d)=>{let y="",g=h;for(let p=0;p<d;p++)y+=a[g&63],g>>=6;return y},u=c,f="";return f+=l(u[0]<<16|u[6]<<8|u[12],4),f+=l(u[1]<<16|u[7]<<8|u[13],4),f+=l(u[2]<<16|u[8]<<8|u[14],4),f+=l(u[3]<<16|u[9]<<8|u[15],4),f+=l(u[4]<<16|u[10]<<8|u[5],4),f+=l(u[11],2),`$apr1$${t}$${f}`}function CA(e,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(e,t)}catch{return!1}if(t.startsWith("$apr1$")){let n=t.split("$")[2]??"";return ss($A(e,n),t)}if(t.startsWith("{SHA}")){let r=Hw("sha1").update(e,"utf8").digest("base64");return ss(`{SHA}${r}`,t)}return ss(e,t)}function xA(e){let t=new Map;for(let r of e.split(`
278
+ `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let i=n.indexOf(":");if(i<=0)continue;t.set(n.slice(0,i),n.slice(i+1))}return t}function os(e){if(!e)return;let t=(e.realm??"").trim()||"Restricted",r=[];if(e.username)r.push({username:e.username,password:e.password??""});for(let s of e.users??[])if(s?.username)r.push({username:s.username,password:s.password??""});let n;if(e.htpasswdFile)try{n=xA(vA(e.htpasswdFile,"utf8"))}catch{n=void 0}if(r.length===0&&(!n||n.size===0))return;return{realm:t,verify:(s,o)=>{let c=!1;for(let a of r)if(ss(s,a.username)&&ss(o,a.password))c=!0;if(n){let a=n.get(s);if(a&&CA(o,a))c=!0}return c}}}function zw(e,t,r){if(t.startsWith(bA))return;let n=e.headers.get("authorization")??"",i=n.indexOf(" "),s=i===-1?n:n.slice(0,i),o=i===-1?"":n.slice(i+1).trim();if(s.toLowerCase()==="basic"&&o){let a="";try{a=Buffer.from(o,"base64").toString("utf8")}catch{a=""}let l=a.indexOf(":");if(l>=0&&r.verify(a.slice(0,l),a.slice(l+1)))return}let c=r.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${c}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var bA="/.well-known/acme-challenge/";var mc=()=>{};function TA(e){return EA.has(e.toUpperCase())}function PA(){let e=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(e)&&e>0?e:30000}function AA(e){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:e*8}function RA(){let e=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(e)&&e>0?e:0}function kA(){let e=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(e)&&e>0?e:0}function OA(){let e=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(e)&&e>0?e:256}class Xw{socket=null;buf=new Uint8Array(NA);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(e){let t=this.socket,r=t.write(e);while(r<e.length){if(this.closed)throw gc;await new Promise((n)=>{this.drainWaiter=n}),r+=t.write(e.subarray(r))}}wakeDrain(){let e=this.drainWaiter;if(e)this.drainWaiter=null,e()}push(e){if(this.bodyQueue){let t=e.length<=this.bodyRemaining?e.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(e.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<e.length)this.appendToBuf(e.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(e),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>DA)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=FA)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(e){let t=this.len+e.length;if(t>this.buf.length){let r=new Uint8Array(Math.max(this.buf.length*2,t));r.set(this.buf.subarray(0,this.len)),this.buf=r}this.buf.set(e,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let e=this.waiter;if(e)this.waiter=null,e()}waitForData(e){if(this.len>e||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((e)=>{this.waiter=e})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class Zw{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=PA();maxWaiters;checkoutIdleMs=RA();inUse=new Set;constructor(e,t,r,n=""){this.host=e;this.port=t;this.maxTotal=r;this.key=n;this.maxWaiters=AA(r)}trackCheckout(e){if(e.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(e),this.ensureSweeper()}dial(){let e=new Xw;return SA({hostname:this.host,port:this.port,socket:{data:(t,r)=>e.push(r),drain:()=>e.wakeDrain(),close:()=>e.markClosed(),end:()=>e.markClosed(),error:()=>e.markClosed(),connectError:()=>e.markClosed(),timeout:()=>e.markTimedOut()}}).then((t)=>{let r=t;r.setNoDelay?.(!0);let n=kA();if(n>0)r.timeout?.(n);return e.socket=t,e})}acquireIdleSync(){while(this.idle.length){let e=this.idle.pop();if(!e.closed)return e.socket?.ref(),e.pos=0,e.len=0,this.trackCheckout(e),e;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw Yr;let e=await this.waitForSlot();if(e===Yr)throw Yr;if(e)return e.pos=0,e.len=0,this.trackCheckout(e),e}this.open++;try{let e=await this.dial();return this.trackCheckout(e),e}catch(e){throw this.open--,this.wakeWaiter(),e}}waitForSlot(){return new Promise((e)=>{let t=!1,r=(s)=>{if(t)return;t=!0,clearTimeout(i),e(s)},n=(s)=>r(s),i=setTimeout(()=>{let s=this.waiters.indexOf(n);if(s!==-1)this.waiters.splice(s,1);r(Yr)},this.queueWaitMs);i.unref?.(),this.waiters.push(n)})}release(e){if(this.inUse.delete(e),e.closed){this.open--,this.wakeWaiter();return}e.clearStreaming(),e.compact(),e.fresh=!1;let t=this.waiters.shift();if(t){e.socket?.ref(),this.trackCheckout(e),t(e);return}e.idleSince=Date.now(),e.socket?.unref(),this.idle.push(e),this.ensureSweeper()}destroy(e){this.inUse.delete(e),e.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let e=this.waiters.shift();if(e)e(null)}ensureSweeper(){if(this.sweeper)return;let e=this.checkoutIdleMs>0?Math.min(Bh,this.checkoutIdleMs):Bh;this.sweeper=setInterval(()=>this.sweep(),e),this.sweeper.unref?.()}sweep(){let e=Date.now(),t=e-Bh;if(this.idle.length){let r=[];for(let n of this.idle)if(n.closed||n.idleSince<=t)n.destroy(),this.open--;else r.push(n);this.idle=r}if(this.checkoutIdleMs>0&&this.inUse.size){let r=e-this.checkoutIdleMs;for(let n of this.inUse)if(!n.closed&&n.lastActivityAt>0&&n.lastActivityAt<=r)n.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&pc.get(this.key)===this)pc.delete(this.key)}}}function _A(e,t){let r=pc.get(e);if(!r){let n=e.lastIndexOf(":"),i=n===-1?e:e.slice(0,n),s=n===-1?80:Number(e.slice(n+1));r=new Zw(i,s,t??OA(),e),pc.set(e,r)}return r}function Gw(e,t,r){for(let n=r+3;n<t;n++)if(e[n]===10&&e[n-1]===13&&e[n-2]===10&&e[n-3]===13)return n-3;return-1}function jA(e,t,r){let n=Jw.decode(e.subarray(t,r)),i=n.indexOf(`\r
279
+ `),s=i===-1?n:n.slice(0,i),o=s.indexOf(" "),c=Number.parseInt(s.slice(o+1,o+5),10),a=s.startsWith("HTTP/1.0"),l=[],u=-1,f=!1,h=a,d=!1,y=!1,g=i===-1?n.length:i+2;while(g<n.length){let p=n.indexOf(`\r
280
+ `,g);if(p===-1)p=n.length;let w=n.slice(g,p);if(g=p+2,w==="")continue;let v=w.indexOf(":");if(v===-1)continue;let P=w.slice(0,v),A=w.slice(v+1).trim(),R=P.charCodeAt(0)|32;if(R===99||R===116||R===107){let D=P.toLowerCase();if(D==="content-length"){let F=/^\d+$/.test(A)?Number(A):Number.NaN;if(!Number.isSafeInteger(F)||u>=0&&u!==F)y=!0;else u=F;continue}if(D==="transfer-encoding"){if(A.toLowerCase().includes("chunked"))f=!0;continue}if(D==="connection"){let F=A.toLowerCase();if(F.includes("close"))h=!0;if(F.includes("keep-alive"))d=!0;continue}if(D==="keep-alive")continue}l.push([P,A])}if(a&&d)h=!1;if(f&&u>=0)u=-1;return{status:c,headerEnd:r,headers:l,contentLength:u,chunked:f,closeConn:h,malformed:y}}function UA(e,t){return t||e===204||e===304}async function Qw(e){let{hostPort:t,method:r,path:n,reqHeaders:i,forwardedHost:s,clientIp:o,originOverride:c,body:a}=e,l=r==="HEAD",u=i.get("accept")?.toLowerCase()??"";if(i.get("expect")||i.get("upgrade")||u.includes("text/event-stream"))throw as;let f=null;if(a){let g=i.get("content-length"),p=g?Number.parseInt(g,10):Number.NaN;if(Number.isNaN(p)||p>qw)throw as;if(f=await qA(a),f===null)throw as}let h=GA(r,n,i,t,s,o,c,f),d=h;if(f&&f.length)d=new Uint8Array(h.length+f.length),d.set(h),d.set(f,h.length);let y=_A(t,e.maxPerHost);for(let g=0;;g++){if(g>0)await new Promise((w)=>{setTimeout(w,g)});let p;try{p=y.acquireIdleSync()??await y.acquireOrDial()}catch(w){if(w!==Yr&&g<4)continue;throw w}try{let w=p.socket.write(d);if(w<d.length)await p.writeAll(d.subarray(w));return await WA(y,p,l,e.signal)}catch(w){let v=w===gc&&g<4&&(p.fresh||TA(r));if(y.destroy(p),v)continue;if(w===gc)throw Error("upstream closed connection");throw w}}}async function KA(e){let t=Gw(e.buf,e.len,e.pos);while(t===-1){if(e.closed){if(e.timedOut)throw Ih;if(e.len===e.pos)throw gc;throw Error("upstream closed mid-header")}if(e.len-e.pos>Yw)throw Error("upstream header block too large");await e.waitForData(e.len),t=Gw(e.buf,e.len,e.pos)}return t}async function WA(e,t,r,n){let i;for(;;){let o=await KA(t);if(i=jA(t.buf,t.pos,o),t.pos=o+4,i.status>=100&&i.status<200)continue;break}if(i.malformed)throw e.destroy(t),Error("upstream sent malformed response framing");let s=i.headers;if(UA(i.status,r))return ev(e,t,i.closeConn),new Response(null,{status:i.status,headers:s});if(i.chunked)return new Response(zA(e,t,i.closeConn,n),{status:i.status,headers:s});if(i.contentLength>=0){if(t.len-t.pos>=i.contentLength){let c=t.pos+i.contentLength,a=t.len>c,l=null;if(i.contentLength>=LA)l=t.buf.subarray(t.pos,c),t.buf=new Uint8Array(BA);else if(i.contentLength>0)l=t.buf.slice(t.pos,c);if(t.pos=0,t.len=0,i.closeConn||a)e.destroy(t);else e.release(t);return new Response(l,{status:i.status,headers:s})}return new Response(VA(e,t,i.contentLength,i.closeConn),{status:i.status,headers:s})}return new Response(HA(t),{status:i.status,headers:s})}function ev(e,t,r){if(r||t.pos!==t.len)e.destroy(t);else e.release(t)}function VA(e,t,r,n){let i=t.len-t.pos,s=i>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=r-i,t.queuedBytes=0,t.streamingBody=!0;let o=(c)=>{if(t.bodyQueue=null,n||t.len>0)e.destroy(t);else e.release(t);c.close()};return new ReadableStream({start(c){if(s)c.enqueue(s);if(t.bodyRemaining===0&&t.bodyQueue.length===0)o(c)},async pull(c){for(;;){let a=t.bodyQueue;if(a&&a.length>0){let l=a.shift();if(t.queuedBytes-=l.length,t.resumeIfDrained(),c.enqueue(l),t.bodyRemaining===0&&a.length===0)o(c);return}if(t.bodyRemaining===0){if(t.bodyQueue)o(c);return}if(t.closed){t.bodyQueue=null,e.destroy(t),c.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,e.destroy(t)}})}function HA(e){return e.streamingBody=!0,new ReadableStream({async pull(t){for(;;){if(e.len>e.pos){t.enqueue(e.buf.slice(e.pos,e.len)),e.pos=e.len,e.resumeIfDrained();return}if(e.closed){e.destroy(),t.close();return}await e.waitForData(e.len)}},cancel(){e.destroy()}})}function zA(e,t,r,n){t.streamingBody=!0;let i=0,s=!1,o=!1,c,a=()=>n?.removeEventListener("abort",l),l=()=>{if(o)return;o=!0,e.destroy(t);try{c?.close()}catch{}};async function u(f=!1){for(;;){for(let h=t.pos;h+1<t.len;h++)if(t.buf[h]===13&&t.buf[h+1]===10){let d=Jw.decode(t.buf.subarray(t.pos,h));return t.pos=h+2,d}if(t.closed){if(f&&t.pos===t.len)return null;throw Error("upstream closed mid-chunk-header")}if(t.len-t.pos>Yw)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({start(f){if(c=f,n?.aborted)l();else n?.addEventListener("abort",l,{once:!0})},async pull(f){try{for(;;){if(i>0){if(t.len===t.pos){if(t.closed){e.destroy(t),f.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let g=Math.min(i,t.len-t.pos);if(f.enqueue(t.buf.slice(t.pos,t.pos+g)),t.pos+=g,i-=g,t.resumeIfDrained(),i===0)s=!0;return}if(s)await u(),s=!1;let h=await u(!0);if(h===null){e.destroy(t),a(),f.close();return}let d=h.indexOf(";"),y=Number.parseInt(d===-1?h:h.slice(0,d),16);if(!Number.isInteger(y)||y<0){e.destroy(t),f.error(Error("upstream sent malformed chunk size"));return}if(y===0){for(;;)if(await u()==="")break;ev(e,t,r),a(),f.close();return}i=y}}catch(h){if(e.destroy(t),a(),!o)f.error(h)}},cancel(){o=!0,a(),e.destroy(t)}})}function GA(e,t,r,n,i,s,o,c){let a=s||"127.0.0.1",l=`${e} ${t} HTTP/1.1\r
281
+ host: ${n}\r
282
+ x-forwarded-for: ${a}\r
283
+ x-real-ip: ${a}\r
225
284
  x-forwarded-proto: https\r
226
- x-forwarded-host: ${X}\r
227
- `;if(J!==void 0)j+=`origin: ${J}\r
228
- `;let W=!1;for(let[Q,z]of Y){let f=Q.toLowerCase();if(jH.has(f))continue;if(J!==void 0&&f==="origin")continue;if(f==="content-length")W=!0;j+=`${Q}: ${z}\r
229
- `}if(j+=`connection: keep-alive\r
230
- `,U&&!W)j+=`content-length: ${U.length}\r
231
- `;return j+=`\r
232
- `,WH.encode(j)}async function NH(w){let $=w.getReader(),Y=[],A=0;for(;;){let{done:U,value:j}=await $.read();if(U)break;if(j){if(A+=j.length,A>M2)return $.cancel().catch(()=>{}),null;Y.push(j)}}if(Y.length===1)return Y[0];let X=new Uint8Array(A),J=0;for(let U of Y)X.set(U,J),J+=U.length;return X}var rq,VY,q8,tq,Fj,u$,M2=1048576,Kj=30000,YH=16384,I2=262144,AH=2097152,XH=524288,JH=8192,UH=4096,WH,y2,jH,H8;var S2=s(()=>{({connect:rq}=Bun),VY=Symbol("rpx.pool.fallback"),q8=Symbol("rpx.pool.stale"),tq=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);Fj=Symbol("rpx.pool.timeout"),u$=Symbol("rpx.pool.busy");WH=new TextEncoder,y2=new TextDecoder,jH=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);H8=new Map});function _2(w){let $=typeof w==="string"?{to:w}:w,Y=($.to??"").trim();if(Y&&!/^[a-z][\w+.-]*:\/\//i.test(Y))Y=`https://${Y}`;return Y=Y.replace(/\/+$/,""),{to:Y,status:$.status??301,preservePath:$.preservePath??!0}}function h2(w,$,Y){if(!w.preservePath)return w.to||"/";let A=`${$}${Y}`;return A==="/"?`${w.to}/`:`${w.to}${A}`}import*as Ew from"node:path";function R8(w,$){if(typeof w==="string")return{dir:w,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:$};return{dir:w.dir,spa:w.spa??!1,pathRewriteStyle:w.pathRewriteStyle??"directory",maxAge:w.maxAge??0,cleanUrls:$}}function HH(w){let $=Ew.extname(w).toLowerCase();return qH[$]??"application/octet-stream"}function RH(w){let $;try{$=decodeURIComponent(w)}catch{return null}if($.includes("\x00")||$.includes("\\"))return null;let Y=Ew.posix.normalize(`/${$}`);if(Y.split("/").includes(".."))return null;return Y.replace(/^\/+/,"")}function MH(w,$){let Y=RH(w);if(Y===null)return null;let A=Ew.posix.extname(Y);if($.cleanUrls&&A===".html"){let X=w.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ew.join($.dir,Y),redirectTo:X||"/"}}if(Y===""||w.endsWith("/"))return{filePath:Ew.join($.dir,Y,"index.html")};if(A!=="")return{filePath:Ew.join($.dir,Y)};if($.pathRewriteStyle==="flat")return{filePath:Ew.join($.dir,`${Y}.html`)};return{filePath:Ew.join($.dir,Y,"index.html")}}async function D2(w,$){let Y=MH(w,$);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=$.maxAge>0?`public, max-age=${$.maxAge}`:"no-cache",X=Bun.file(Y.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":HH(Y.filePath),"Cache-Control":A}});if($.spa){let J=Ew.join($.dir,"index.html"),U=Bun.file(J);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 qH;var M8=s(()=>{qH={".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 IH(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function LH(w){if(!w)return!1;let $=null;for(let Y of w.split(",")){let[A,...X]=Y.trim().split(";"),J=A.trim().toLowerCase();if(J!=="gzip"&&J!=="*")continue;let U=1;for(let j of X){let W=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(j);if(W)U=Number.parseFloat(W[1])}if(J==="gzip")return Number.isFinite(U)&&U>0;$=U}return $!==null&&Number.isFinite($)&&$>0}function OH(w){let $=w.get("vary");if(!$){w.set("vary","Accept-Encoding");return}if(!$.split(",").some((Y)=>Y.trim().toLowerCase()==="accept-encoding"))w.set("vary",`${$}, Accept-Encoding`)}function SH(w,$){if(w.method==="HEAD"||$.status===204||$.status===206||$.status===304||!$.body||$.headers.has("content-encoding")||$.headers.get("cache-control")?.toLowerCase().includes("no-transform")||w.headers.has("range")||!LH(w.headers.get("accept-encoding")))return $;let Y=$.headers.get("content-type")?.toLowerCase()??"";if(!CH.some((J)=>Y.startsWith(J)))return $;let A=$.headers.get("content-length");if(A!==null){let J=Number.parseInt(A,10);if(Number.isFinite(J)&&J<VH)return $}let X=new Headers($.headers);return X.set("content-encoding","gzip"),OH(X),X.delete("content-length"),X.delete("content-md5"),X.delete("content-digest"),X.delete("accept-ranges"),X.delete("etag"),new Response($.body.pipeThrough(new CompressionStream("gzip")),{status:$.status,statusText:$.statusText,headers:X})}function _H(w){let $=w.headers.get("host")||"",Y=$.indexOf(":");return Y===-1?$:$.slice(0,Y)}function Z2(w,$){if(!$||$==="/")return w;if(w===$)return"/";if(w.startsWith(`${$}/`)){let Y=w.slice($.length);return Y===""?"/":Y}return w}function x2(w){if(w.upstreamPool)return T2(w.upstreamPool);if(w.sourceHost)return{url:w.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function k2(w,$,Y,A){let X=Y?.url??$.sourceHost??"",U=$.stripBasePathPrefix??!1?Z2(w,$.basePath):w,j=Yj(U,$.pathRewrites);if(j)X=j.targetHost,U=j.targetPath,K("request",`Path rewrite: ${w} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function hH(w){let $=w.indexOf("://"),Y=$===-1?w.indexOf("/"):w.indexOf("/",$+3);if(Y===-1)return{pathname:"/",search:""};let A=w.indexOf("?",Y);if(A===-1)return{pathname:w.slice(Y),search:""};return{pathname:w.slice(Y,A),search:w.slice(A)}}function LY(w,$,Y){let A=async(X,J)=>{let{pathname:U,search:j}=hH(X.url),W=_H(X),Q=w(W,U);if(!Q&&Y){let E=await Y(W,U,X);if(E instanceof Response)return E;if(E&&E.retry)Q=w(W,U)}if(!Q)return K("request",`No route found for host: ${W}`,$),new Response(`No proxy configured for ${W}`,{status:404});if(Q.auth){let E=H2(X,U,Q.auth);if(E)return K("request",`401 challenge for ${W}${U}`,$),E}if(Q.redirect){let E=h2(Q.redirect,U,j);return K("request",`${Q.redirect.status} redirect ${W}${U} → ${E}`,$),new Response(null,{status:Q.redirect.status,headers:{location:E}})}if(Q.static){let N=Q.stripBasePathPrefix??!0?Z2(U,Q.basePath):U;return D2(N,Q.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let E=x2(Q);if(!J||!E)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:N,targetPath:R}=k2(U,Q,E,$),V=`ws://${N}${R}${j}`,L={};for(let[M,D]of X.headers)if(!yH.has(M.toLowerCase())&&M.toLowerCase()!=="host")L[M]=D;L.host=N,L["x-forwarded-for"]="127.0.0.1",L["x-forwarded-proto"]="https",L["x-forwarded-host"]=W;let q={targetUrl:V,forwardHeaders:L};if(J.upgrade(X,{data:q})){K("ws",`upgraded ${W}${R} → ${V}`,$);return}return new Response("WebSocket upgrade failed",{status:400})}let z=x2(Q);if(!z)return new Response(`No upstream configured for ${W}`,{status:502});if(Q.cleanUrls&&U.endsWith(".html")){let E=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:E}})}let{targetHost:f,targetPath:B}=k2(U,Q,z,$),G=Q.changeOrigin?`http://${f}`:void 0,T=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",F=Q.upstreamPool;if(F)z.activeConnections++;try{let E=await L2({hostPort:f,method:X.method,path:`${B}${j}`,reqHeaders:X.headers,forwardedHost:W,originOverride:G,body:X.body,signal:X.signal});if(F)T8(F,z);return E}catch(E){if(E===Fj){if(K("request",`Upstream timeout for ${W}`,$),F)MY(F,z);return new Response("Gateway Timeout",{status:504})}if(E===u$)return K("request",`Upstream pool saturated for ${W}`,$),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(E===VY||!T)try{let N=new Headers(X.headers);if(N.set("host",f),N.set("x-forwarded-for","127.0.0.1"),N.set("x-forwarded-proto","https"),N.set("x-forwarded-host",W),G!==void 0)N.set("origin",G);let R=await fetch(`http://${f}${B}${j}`,{method:X.method,headers:N,body:X.body,redirect:"manual"});if(F)T8(F,z);return R}catch(N){if(K("request",`Proxy error for ${W}: ${N}`,$),F)MY(F,z);return new Response(`Proxy Error: ${N}`,{status:502})}if(K("request",`Proxy error for ${W}: ${E}`,$),F)MY(F,z);return new Response(`Proxy Error: ${E}`,{status:502})}finally{if(F)z.activeConnections--}};return async(X,J)=>{try{let U=await A(X,J);return U?SH(X,U):U}catch(U){return K("request",`Unhandled proxy handler error: ${U}`,$),new Response("Bad Gateway",{status:502})}}}function OY(w){let $=new WeakMap,Y=IH();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(W){K("ws",`failed to open upstream ${X}: ${W}`,w),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let j={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};$.set(A,j),U.addEventListener("open",()=>{j.upstreamOpen=!0;for(let W of j.pending)U.send(W);j.pending=[],j.pendingBytes=0}),U.addEventListener("message",(W)=>{A.send(W.data)}),U.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),U.addEventListener("error",()=>{K("ws",`upstream error for ${X}`,w);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=$.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let j=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+j>Y){K("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,w);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}$.delete(A);return}J.pending.push(U),J.pendingBytes+=j},close(A,X,J){let U=$.get(A);if(!U)return;$.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var yH,CH,VH=1024;var Ej=s(()=>{N8();S2();M8();f0();yH=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]),CH=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"]});import*as i2 from"node:fs";import*as b2 from"node:path";function I8(w,$){if(!w||!$.startsWith(P2))return null;let Y=$.slice(P2.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return i2.readFileSync(b2.join(w,Y),"utf8")}catch{return null}}var P2="/.well-known/acme-challenge/";var Tj=()=>{};function Y$(w){if(!w||w==="/")return"/";let $=w.trim();if(!$.startsWith("/"))$=`/${$}`;return $=$.replace(/\/+$/,""),$===""?"/":$}function DH(w,$){if($==="/")return!0;if(w===$)return!0;return w.startsWith(`${$}/`)}function SY(w){let $=new Map;for(let A of w){let X=Y$(A.path),J=$.get(A.host);if(!J)J=new Map,$.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of $){let J=[];for(let[U,j]of X)J.push({path:U,route:j});J.sort((U,j)=>j.path.length-U.path.length),Y.set(A,J)}return Y}function Nj(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!W1(J))continue;if(h$($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}function _Y(w,$,Y){let A=Nj(w,$);if(!A)return;for(let X of A)if(DH(Y,X.path))return X.route;return}var y8=()=>{};import*as hY from"node:fs/promises";import*as qj from"node:path";function v$(w){if(Array.isArray(w))return w.map(($)=>({...$,lowMemoryMode:!0}));return{...w,lowMemoryMode:!0}}function xH(w){if(!w.endsWith(".crt"))return null;let $=w.slice(0,-4);if($.length===0)return null;if($.startsWith("_wildcard."))return`*.${$.slice(10)}`;return $}async function kH(w,$,Y,A){try{let[X,J]=await Promise.all([hY.readFile($,"utf8"),hY.readFile(Y,"utf8")]);return{serverName:w,cert:X,key:J}}catch(X){return K("sni",`skipping ${w}: ${X.message}`,A),null}}async function DY(w,$){let Y=new Map,A=w.certsDirServerNames?new Set(w.certsDirServerNames):void 0;if(w.certsDir){let J=[];try{J=await hY.readdir(w.certsDir)}catch(U){K("sni",`certsDir read failed (${w.certsDir}): ${U.message}`,$)}for(let U of J){let j=xH(U);if(!j)continue;if(A&&!A.has(j))continue;let W=U.slice(0,-4);Y.set(j,{certPath:qj.join(w.certsDir,U),keyPath:qj.join(w.certsDir,`${W}.key`)})}}if(w.domains)for(let[J,U]of Object.entries(w.domains))Y.set(J,U);let X=[];for(let[J,U]of Y){let j=await kH(J,U.certPath,U.keyPath,$);if(j)X.push(j)}return X}var Hj=s(()=>{f0()});import*as Vw from"node:fs/promises";import*as C8 from"node:path";function xY(w=process.env){let $=w.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if($==="restart"||$==="rebind")return $;return w.INVOCATION_ID?"restart":"rebind"}function iH(w,$){if(!$||$.length===0)return!1;return $.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return w===A||w.endsWith(`.${A}`)})}function v2(w){if(!w||w.length>253)return!1;if(w.includes("/")||w.includes(":")||w.includes(" "))return!1;if(w.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(w)}class b1{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(w){this.config=w.config,this.certsDir=w.certsDir,this.onCertAdded=w.onCertAdded,this.http01Store=w.http01Store??CX,this.issuer=w.issuer??oU,this.verbose=w.verbose??!1,this.negativeCacheMs=w.negativeCacheMs??PH;for(let $ of w.initial??[])this.certs.set($.serverName,$)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(w){return this.certs.has(w)}async isApproved(w){if(!v2(w))return!1;if(iH(w,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(w)}catch($){return K("on-demand",`ask(${w}) threw: ${$.message}`,this.verbose),!1}return!1}async ensureCert(w){if(!this.config.enabled)return!1;if(this.certs.has(w))return!0;if(!v2(w))return!1;let $=this.inFlight.get(w);if($)return $;let Y=this.negativeCache.get(w);if(Y!==void 0&&Date.now()<Y){if(await this.loadFromDisk(w))return this.negativeCache.delete(w),!0;return K("on-demand",`${w} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1}let A=this.issue(w).finally(()=>{this.inFlight.delete(w)});return this.inFlight.set(w,A),A}async issue(w){if(this.certs.has(w))return!0;if(await this.loadFromDisk(w))return!0;if(!await this.isApproved(w))return K("on-demand",`refused issuance for ${w} (not approved)`,this.verbose),this.cacheNegative(w),!1;try{K("on-demand",`issuing cert for ${w} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let $=await this.issuer({domains:[w],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey($.accountKeyPem),await this.persist(w,$.fullChainPem,$.keyPem);let Y={serverName:w,cert:$.fullChainPem,key:$.keyPem};return this.certs.set(w,Y),this.negativeCache.delete(w),K("on-demand",`issued + installed cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch($){return this.cacheNegative(w),K("on-demand",`issuance for ${w} failed: ${$.message}`,this.verbose),!1}}cacheNegative(w){if(this.negativeCache.size>=u2){let $=Date.now();for(let[Y,A]of this.negativeCache)if(A<=$)this.negativeCache.delete(Y);if(this.negativeCache.size>=u2){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set(w,Date.now()+this.negativeCacheMs)}async loadFromDisk(w){let{certPath:$,keyPath:Y}=this.pathsFor(w);try{let[A,X]=await Promise.all([Vw.readFile($,"utf8"),Vw.readFile(Y,"utf8")]),J={serverName:w,cert:A,key:X};return this.certs.set(w,J),K("on-demand",`adopted existing on-disk cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(w){return{certPath:C8.join(this.certsDir,`${w}.crt`),keyPath:C8.join(this.certsDir,`${w}.key`)}}async persist(w,$,Y){await Vw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor(w);await Promise.all([Vw.writeFile(A,$,"utf8"),Vw.writeFile(X,Y,{encoding:"utf8",mode:384})])}get accountKeyPath(){return C8.join(this.certsDir,ZH)}async loadAccountKey(){try{return await Vw.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(w){if(!w||this.accountKeyPem===w)return;this.accountKeyPem=w,await Vw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Vw.writeFile(this.accountKeyPath,w,{encoding:"utf8",mode:384}).catch(()=>{})}}var ZH="acme-account.key",PH=60000,u2=4096;var Rj=s(()=>{xX();f0()});import*as V8 from"node:net";function I$(w,$,Y){return K("port",`Checking if port ${w} is in use on ${$}`,Y),new Promise((A)=>{let X=V8.createServer(),J=setTimeout(()=>{K("port",`Checking port ${w} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")K("port",`Port ${w} is in use`,Y),A(!0);else K("port",`Error checking port ${w}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),K("port",`Port ${w} is available`,Y),X.close(),A(!1)});try{X.listen(w,$)}catch(U){clearTimeout(J),K("port",`Exception checking port ${w}: ${U}`,Y),A(!0)}})}async function Mj(w,$,Y,A=50){K("port",`Finding available port starting from ${w} (max attempts: ${A})`,Y);let X=w,J=0;while(J<A){if(J++,!await I$(X,$,Y))return K("port",`Found available port: ${X} after ${J} attempts`,Y),X;K("port",`Port ${X} is in use, trying ${X+1} (attempt ${J}/${A})`,Y),X++}throw Error(`Unable to find available port after ${A} attempts starting from ${w}`)}function c2(w,$,Y=5000,A){return K("port",`Testing connection to ${$}:${w}`,A),new Promise((X)=>{let J=V8.connect({host:$,port:w,timeout:Y});J.once("connect",()=>{K("port",`Successfully connected to ${$}:${w}`,A),J.end(),X(!0)}),J.once("timeout",()=>{K("port",`Connection to ${$}:${w} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{K("port",`Failed to connect to ${$}:${w}: ${U.message}`,A),J.destroy(),X(!1)})})}class L8{usedPorts=new Set;hostname;verbose;maxRetries;constructor(w="0.0.0.0",$,Y=50){this.hostname=w,this.verbose=$,this.maxRetries=Y}async getNextAvailablePort(w,$=!1){if(this.usedPorts.has(w))return this.findNextAvailablePort(w+1,$);if(await I$(w,this.hostname,this.verbose))return this.findNextAvailablePort(w+1,$);if($){if(!await c2(w,this.hostname,3000,this.verbose))return K("port",`Port ${w} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(w+1,$)}return this.usedPorts.add(w),w}async findNextAvailablePort(w,$=!1){let Y=await Mj(w,this.hostname,this.verbose,this.maxRetries);if($){if(!await c2(Y,this.hostname,3000,this.verbose))if(Y<w+this.maxRetries)return this.findNextAvailablePort(Y+1,$);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort(w){K("port",`Releasing port ${w}`,this.verbose),this.usedPorts.delete(w)}}var bL;var Ij=s(()=>{f0();bL=new L8});import*as O8 from"node:fs";import*as t0 from"node:fs/promises";import{homedir as bH}from"node:os";import*as yj from"node:path";import*as S8 from"node:process";function Xw(){return yj.join(bH(),".stacks","rpx","registry.d")}function y$(w){return typeof w==="string"&&w.length>0&&w.length<=128&&uH.test(w)}function Cj(w,$){if(!y$($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return yj.join(w,`${$}.json`)}function Jw(w){if(!Number.isInteger(w)||w<=0)return!1;try{return S8.kill(w,0),!0}catch($){return $.code==="EPERM"}}function m2(w){if(!w||typeof w!=="object")return!1;let $=w,Y=$.pid===void 0||typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0,A=typeof $.from==="string"&&$.from.length>0||Array.isArray($.from)&&$.from.length>0,X=typeof $.static==="string"||!!$.static&&typeof $.static==="object"&&typeof $.static.dir==="string",J=$.path===void 0||typeof $.path==="string";return typeof $.id==="string"&&y$($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function vH(w){await t0.mkdir(w,{recursive:!0})}async function u1(w,$=Xw(),Y){if(!m2(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await vH($);let A=Cj($,w.id),X=`${A}.tmp.${S8.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await t0.writeFile(X,J,{encoding:"utf8",mode:420}),await t0.rename(X,A),K("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await t0.unlink(X).catch(()=>{}),U}}async function c$(w,$=Xw(),Y){let A=Cj($,w);try{await t0.unlink(A),K("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function Vj(w,$=Xw(),Y){let A=Cj($,w);try{let X=await t0.readFile(A,"utf8"),J=JSON.parse(X);if(!m2(J))return K("registry",`entry ${w} failed validation, removing`,Y),await t0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return K("registry",`entry ${w} has invalid JSON, removing`,Y),await t0.unlink(A).catch(()=>{}),null;throw X}}async function Tw(w=Xw(),$){let Y;try{Y=await t0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!y$(J))continue;let U=await Vj(J,w,$);if(U)A.push(U)}return A}async function kY(w=Xw(),$){let Y=await Tw(w,$),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!Jw(X.pid))K("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,$),await c$(X.id,w,$).catch(()=>{}),A++}return A}function _8(w,$={}){let Y=$.dir??Xw(),A=$.debounceMs??100,X=$.pollMs??Math.max(A*2,250),J=$.verbose;O8.mkdirSync(Y,{recursive:!0});let U=null,j=!1,W=null,Q=!1,z=(E)=>{return JSON.stringify(E.map((N)=>({id:N.id,from:N.from,to:N.to,path:N.path,pid:N.pid,pathRewrites:N.pathRewrites,cleanUrls:N.cleanUrls,changeOrigin:N.changeOrigin,static:N.static,loadBalancer:N.loadBalancer})).sort((N,R)=>N.id.localeCompare(R.id)))},f=()=>{if(U=null,j)return;Tw(Y,J).then((E)=>{return W=z(E),w(E)}).catch((E)=>{K("registry",`watcher onChange failed: ${E}`,J)})},B=()=>{if(j)return;if(U)clearTimeout(U);U=setTimeout(f,A)},T=setInterval(()=>{if(j||Q)return;Q=!0,Tw(Y,J).then((E)=>{if(z(E)!==W)B()}).catch((E)=>{K("registry",`watcher poll failed: ${E}`,J)}).finally(()=>{Q=!1})},X),F=O8.watch(Y,{persistent:!0},(E,N)=>{if(N&&/\.tmp\.\d+\.\d+$/.test(N))return;B()});return F.on("error",(E)=>{K("registry",`watcher error: ${E}`,J)}),B(),{close:()=>{if(j=!0,U)clearTimeout(U);clearInterval(T),F.close()}}}var uH;var m$=s(()=>{f0();uH=/^[a-zA-Z0-9._-]+$/});import{closeSync as g2,openSync as cH,readFileSync as mH}from"node:fs";import*as d2 from"node:fs/promises";import{spawn as gH}from"node:child_process";import{homedir as dH}from"node:os";import*as ZY from"node:path";import*as Lw from"node:process";class Oj{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(w){this.resolver=w.resolver,this.registryDir=w.registryDir??Xw(),this.rpxDir=w.rpxDir??ZY.join(dH(),".stacks","rpx"),this.verbose=w.verbose??!1,this.startupTimeoutMs=w.startupTimeoutMs??nH,this.pollIntervalMs=w.pollIntervalMs??lH,this.restartDelayMs=w.restartDelayMs??rH,this.killGraceMs=w.killGraceMs??tH,this.launch=w.launcher??sH(this.verbose),this.probePort=w.probePort??aH,this.pickPort=w.pickPort??((Y)=>Mj(Y,"127.0.0.1")),this.isHostRoutable=w.isHostRoutable??(()=>!1),this.onSiteActivating=w.onSiteActivating,this.now=w.now??Date.now,this.writeEntry=w.writeEntry??u1,this.removeEntry=w.removeEntry??c$;let $=w.reapIntervalMs??pH;if(this.reaper=setInterval(()=>{this.reapIdle()},$),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(w){if(this.stopped)return{kind:"unknown"};let $=this.sites.get(w);if($&&$.status==="failed"&&this.now()-$.failedAt>=this.restartDelayMs)this.sites.delete(w),$=void 0;if(!$){let Y=this.resolver.resolve(w);if(!Y)return{kind:"unknown"};$=await this.start(Y)}if($.lastAccess=this.now(),$.status==="ready")return{kind:"ready",host:w};if($.status==="failed")return{kind:"failed",host:w,error:$.error??"failed to start",logTail:this.readLogTail($)};return{kind:"starting",host:w,sinceMs:this.now()-$.startedAt,source:$.site.source,logTail:this.readLogTail($,16)}}async start(w){try{this.onSiteActivating?.(w.host)}catch{}let $=new Map;if(!w.selfRegisters)for(let j of w.routes){if($.has(j.portEnv))continue;let W=await this.pickPort(j.defaultPort??3000);$.set(j.portEnv,W)}let Y=ZY.join(this.rpxDir,"sites",`${w.id}.log`);await d2.mkdir(ZY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv(w,$),X=null,J;try{X=this.launch({command:w.command,cwd:w.dir,env:A,logPath:Y})}catch(j){J=`failed to spawn: ${j.message}`}let U={site:w,status:J?"failed":"starting",handle:X,ports:$,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:J?this.now():0,error:J,logPath:Y,exited:!1,ready:Promise.resolve()};if(this.sites.set(w.host,U),J)return H.warn(`rpx: site ${w.host} ${J}`),U;return H.info(`rpx: booting ${w.host} → ${w.command} (${w.dir})`),X.exited.then((j)=>this.onProcessExit(U,j)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((j)=>{K("sites",`readiness loop for ${w.host} threw: ${j}`,this.verbose)}),U}async onProcessExit(w,$){if(w.exited=!0,this.stopped||this.sites.get(w.site.host)!==w)return;if(w.status==="ready"){H.warn(`rpx: ${w.site.host} exited${$!==null?` (code ${$})`:""} — will reboot on next request`),this.sites.delete(w.site.host);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if(w.status==="starting")this.fail(w,`process exited${$!==null?` with code ${$}`:""} before becoming ready`)}async driveReadiness(w){let{site:$}=w,Y=this.now()+this.startupTimeoutMs,A=$.selfRegisters?()=>this.isHostRoutable($.host):await this.makeGateProbe($,w.ports);while(this.now()<Y&&!this.stopped){if(w.status!=="starting"||w.exited)return;if(await A()){if(await this.publishRoutes(w),w.status==="starting")w.status="ready",H.success(`rpx: ${$.host} ready`);return}await Lj(this.pollIntervalMs)}if(w.status==="starting")this.fail(w,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(w,$){let Y=w.routes.filter((X)=>X.readyGate??Y$(X.path)==="/").map((X)=>$.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...$.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes(w){let{site:$,ports:Y}=w;if($.selfRegisters||$.routes.length===0)return;let A=$.routes.find((W)=>Y$(W.path)==="/")??$.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let W of $.routes){if(W===A)continue;let Q=Y.get(W.portEnv);if(Q===void 0)continue;J.push({from:Y$(W.path),to:`localhost:${Q}`,stripPrefix:W.stripPrefix??!1})}let U={id:$.id,from:`localhost:${X}`,to:$.host,cwd:$.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:w.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),w.routeIds=[$.id];let j=this.now()+2000;while(this.now()<j&&!this.isHostRoutable($.host))await Lj(50)}fail(w,$){w.status="failed",w.error=$,w.failedAt=this.now(),H.warn(`rpx: site ${w.site.host} failed — ${$}`),this.killProcess(w)}buildEnv(w,$){let Y={};for(let[A,X]of Object.entries(Lw.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,w.env);for(let[A,X]of $)Y[A]=String(X);return Y.RPX_SITE_HOST=w.host,Y.RPX_SITE_URL=`https://${w.host}`,Y}readLogTail(w,$=40){try{return mH(w.logPath,"utf8").split(`
233
- `).slice(-$).join(`
234
- `).trim()}catch{return""}}async stop(w){let $=this.sites.get(w);if(!$)return;this.sites.delete(w);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{});await this.killProcess($),H.info(`rpx: stopped ${w}`)}async killProcess(w){let $=w.handle;if(!$)return;w.handle=null;try{$.stop("SIGTERM")}catch{}let Y=setTimeout(()=>{try{$.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof Y.unref==="function")Y.unref();await Promise.race([$.exited.catch(()=>{}),Lj(this.killGraceMs+500)]),clearTimeout(Y)}async reapIdle(){if(this.stopped)return;let w=this.now();for(let[$,Y]of this.sites){let A=Y.site.idleTimeoutMs;if(A<=0)continue;let X=w-Y.lastAccess;if((Y.status==="ready"||w-Y.startedAt>this.startupTimeoutMs)&&X>A)K("sites",`reaping ${$} (idle ${Math.round(X/1000)}s)`,this.verbose),await this.stop($)}}list(){let w=this.now();return[...this.sites.values()].map(($)=>({host:$.site.host,dir:$.site.dir,status:$.status,pid:$.handle?.pid??null,ports:Object.fromEntries($.ports),uptimeMs:w-$.startedAt,idleMs:w-$.lastAccess,error:$.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((w)=>this.stop(w)))}}function Lj(w){return new Promise(($)=>setTimeout($,w))}async function aH(w){let $=new AbortController,Y=setTimeout(()=>$.abort(),2000);try{return await fetch(`http://127.0.0.1:${w}/`,{signal:$.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(Y)}}function sH(w){let $=oH();return({command:Y,cwd:A,env:X,logPath:J})=>{let U=cH(J,"a");try{let j=gH("sh",["-c",Y],{cwd:A,env:X,detached:!0,stdio:["ignore",U,U],...$?{uid:$.uid,gid:$.gid}:{}}),W=j.pid;if(W===void 0)throw Error("spawn returned no pid");let Q=new Promise((z)=>{j.once("exit",(f)=>{z(f)}),j.once("error",()=>{z(null)})}).finally(()=>{try{g2(U)}catch{}});return K("sites",`spawned pid ${W}: sh -c ${Y} (cwd ${A})`,w),{pid:W,exited:Q,stop:(z="SIGTERM")=>{try{Lw.kill(-W,z)}catch{try{j.kill(z)}catch{}}}}}catch(j){try{g2(U)}catch{}throw j}}}function oH(){if(Lw.platform==="win32")return null;if(!(typeof Lw.getuid==="function"&&Lw.getuid()===0))return null;let $=Number.parseInt(Lw.env.SUDO_UID??"",10),Y=Number.parseInt(Lw.env.SUDO_GID??"",10);if(!Number.isInteger($)||$<=0||!Number.isInteger(Y)||Y<=0)return null;return{uid:$,gid:Y}}var nH=120000,lH=200,pH=30000,rH=3000,tH=4000;var n2=s(()=>{y8();Ij();m$();f0();D$()});function v1(w){return w.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function l2(w,$,Y){return`<!doctype html>
285
+ x-forwarded-host: ${i}\r
286
+ `;if(o!==void 0)l+=`origin: ${o}\r
287
+ `;let u=!1;for(let[f,h]of r){let d=f.toLowerCase();if(MA.has(d))continue;if(o!==void 0&&d==="origin")continue;if(d==="content-length")u=!0;l+=`${f}: ${h}\r
288
+ `}if(l+=`connection: keep-alive\r
289
+ `,c&&!u)l+=`content-length: ${c.length}\r
290
+ `;return l+=`\r
291
+ `,IA.encode(l)}async function qA(e){let t=e.getReader(),r=[],n=0;for(;;){let{done:o,value:c}=await t.read();if(o)break;if(c){if(n+=c.length,n>qw)return t.cancel().catch(()=>{}),null;r.push(c)}}if(r.length===1)return r[0];let i=new Uint8Array(n),s=0;for(let o of r)i.set(o,s),s+=o.length;return i}var SA,as,gc,EA,Ih,Yr,qw=1048576,Bh=30000,NA=16384,Yw=262144,DA=2097152,FA=524288,LA=8192,BA=4096,IA,Jw,MA,pc;var tv=te(()=>{({connect:SA}=Bun),as=Symbol("rpx.pool.fallback"),gc=Symbol("rpx.pool.stale"),EA=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);Ih=Symbol("rpx.pool.timeout"),Yr=Symbol("rpx.pool.busy");IA=new TextEncoder,Jw=new TextDecoder,MA=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host","x-real-ip"]);pc=new Map});function rv(e){let t=typeof e==="string"?{to:e}:e,r=(t.to??"").trim();if(r&&!/^[a-z][\w+.-]*:\/\//i.test(r))r=`https://${r}`;return r=r.replace(/\/+$/,""),{to:r,status:t.status??301,preservePath:t.preservePath??!0}}function nv(e,t,r){if(!e.preservePath)return e.to||"/";let n=`${t}${r}`;return n==="/"?`${e.to}/`:`${e.to}${n}`}import*as Ct from"node:path";function yc(e,t){if(typeof e==="string")return{dir:e,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:e.dir,spa:e.spa??!1,pathRewriteStyle:e.pathRewriteStyle??"directory",maxAge:e.maxAge??0,cleanUrls:t}}function JA(e){let t=Ct.extname(e).toLowerCase();return YA[t]??"application/octet-stream"}function XA(e){let t;try{t=decodeURIComponent(e)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=Ct.posix.normalize(`/${t}`);if(r.split("/").includes(".."))return null;return r.replace(/^\/+/,"")}function ZA(e,t){let r=XA(e);if(r===null)return null;let n=Ct.posix.extname(r);if(t.cleanUrls&&n===".html"){let i=e.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ct.join(t.dir,r),redirectTo:i||"/"}}if(r===""||e.endsWith("/"))return{filePath:Ct.join(t.dir,r,"index.html")};if(n!=="")return{filePath:Ct.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:Ct.join(t.dir,`${r}.html`)};return{filePath:Ct.join(t.dir,r,"index.html")}}async function iv(e,t){let r=ZA(e,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",i=Bun.file(r.filePath);if(await i.exists())return new Response(i,{status:200,headers:{"Content-Type":JA(r.filePath),"Cache-Control":n}});if(t.spa){let s=Ct.join(t.dir,"index.html"),o=Bun.file(s);if(await o.exists())return new Response(o,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var YA;var wc=te(()=>{YA={".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 QA(e,t){let r;try{r=t?.requestIP?.(e)?.address}catch{return Mh}if(!r)return Mh;return/^[0-9a-f.:]{1,45}$/i.test(r)?r:Mh}function eR(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function iR(e){if(!e)return!1;let t=null;for(let r of e.split(",")){let[n,...i]=r.trim().split(";"),s=n.trim().toLowerCase();if(s!=="gzip"&&s!=="*")continue;let o=1;for(let c of i){let a=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(c);if(a)o=Number.parseFloat(a[1])}if(s==="gzip")return Number.isFinite(o)&&o>0;t=o}return t!==null&&Number.isFinite(t)&&t>0}function sR(e){let t=e.get("vary");if(!t){e.set("vary","Accept-Encoding");return}if(!t.split(",").some((r)=>r.trim().toLowerCase()==="accept-encoding"))e.set("vary",`${t}, Accept-Encoding`)}function oR(e,t){if(e.method==="HEAD"||t.status===204||t.status===206||t.status===304||!t.body||t.headers.has("content-encoding")||t.headers.get("cache-control")?.toLowerCase().includes("no-transform")||e.headers.has("range")||!iR(e.headers.get("accept-encoding")))return t;let r=t.headers.get("content-type")?.toLowerCase()??"";if(!rR.some((s)=>r.startsWith(s)))return t;let n=t.headers.get("content-length");if(n!==null){let s=Number.parseInt(n,10);if(Number.isFinite(s)&&s<nR)return t}let i=new Headers(t.headers);return i.set("content-encoding","gzip"),sR(i),i.delete("content-length"),i.delete("content-md5"),i.delete("content-digest"),i.delete("accept-ranges"),i.delete("etag"),new Response(t.body.pipeThrough(new CompressionStream("gzip")),{status:t.status,statusText:t.statusText,headers:i})}function aR(e){let t=e.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function av(e,t){if(!t||t==="/")return e;if(e===t)return"/";if(e.startsWith(`${t}/`)){let r=e.slice(t.length);return r===""?"/":r}return e}function sv(e){if(e.upstreamPool)return Ww(e.upstreamPool);if(e.sourceHost)return{url:e.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function ov(e,t,r,n){let i=r?.url??t.sourceHost??"",o=t.stripBasePathPrefix??!1?av(e,t.basePath):e,c=Sh(o,t.pathRewrites);if(c)i=c.targetHost,o=c.targetPath,m("request",`Path rewrite: ${e} → ${i}${o}`,n);return{targetHost:i,targetPath:o}}function cR(e){let t=e.indexOf("://"),r=t===-1?e.indexOf("/"):e.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let n=e.indexOf("?",r);if(n===-1)return{pathname:e.slice(r),search:""};return{pathname:e.slice(r,n),search:e.slice(n)}}function cs(e,t,r){let n=async(i,s)=>{let{pathname:o,search:c}=cR(i.url),a=aR(i),l=QA(i,s),u=e(a,o);if(!u&&r){let w=await r(a,o,i);if(w instanceof Response)return w;if(w&&w.retry)u=e(a,o)}if(!u)return m("request",`No route found for host: ${a}`,t),new Response(`No proxy configured for ${a}`,{status:404});if(u.auth){let w=zw(i,o,u.auth);if(w)return m("request",`401 challenge for ${a}${o}`,t),w}if(u.redirect){let w=nv(u.redirect,o,c);return m("request",`${u.redirect.status} redirect ${a}${o} → ${w}`,t),new Response(null,{status:u.redirect.status,headers:{location:w}})}if(u.static){let v=u.stripBasePathPrefix??!0?av(o,u.basePath):o;return iv(v,u.static)}if(i.headers.get("upgrade")?.toLowerCase()==="websocket"){let w=sv(u);if(!s||!w)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:v,targetPath:P}=ov(o,u,w,t),A=`ws://${v}${P}${c}`,R={};for(let[x,k]of i.headers)if(!tR.has(x.toLowerCase())&&x.toLowerCase()!=="host")R[x]=k;R.host=v,R["x-forwarded-for"]=l,R["x-real-ip"]=l,R["x-forwarded-proto"]="https",R["x-forwarded-host"]=a;let D={targetUrl:A,forwardHeaders:R};if(s.upgrade(i,{data:D})){m("ws",`upgraded ${a}${P} → ${A}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let f=sv(u);if(!f)return new Response(`No upstream configured for ${a}`,{status:502});if(u.cleanUrls&&o.endsWith(".html")){let w=o.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:w}})}let{targetHost:h,targetPath:d}=ov(o,u,f,t),y=u.changeOrigin?`http://${h}`:void 0,g=i.body!=null&&i.method!=="GET"&&i.method!=="HEAD",p=u.upstreamPool;if(p)f.activeConnections++;try{let w=await Qw({hostPort:h,method:i.method,path:`${d}${c}`,reqHeaders:i.headers,forwardedHost:a,clientIp:l,originOverride:y,body:i.body,signal:i.signal});if(p)dc(p,f);return w}catch(w){if(w===Ih){if(m("request",`Upstream timeout for ${a}`,t),p)ns(p,f);return new Response("Gateway Timeout",{status:504})}if(w===Yr)return m("request",`Upstream pool saturated for ${a}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(w===as||!g)try{let v=new Headers(i.headers);if(v.set("host",h),v.set("x-forwarded-for",l),v.set("x-real-ip",l),v.set("x-forwarded-proto","https"),v.set("x-forwarded-host",a),y!==void 0)v.set("origin",y);let P=await fetch(`http://${h}${d}${c}`,{method:i.method,headers:v,body:i.body,redirect:"manual"});if(p)dc(p,f);return P}catch(v){if(m("request",`Proxy error for ${a}: ${v}`,t),p)ns(p,f);return new Response(`Proxy Error: ${v}`,{status:502})}if(m("request",`Proxy error for ${a}: ${w}`,t),p)ns(p,f);return new Response(`Proxy Error: ${w}`,{status:502})}finally{if(p)f.activeConnections--}};return async(i,s)=>{try{let o=await n(i,s);return o?oR(i,o):o}catch(o){return m("request",`Unhandled proxy handler error: ${o}`,t),new Response("Bad Gateway",{status:502})}}}function ls(e){let t=new WeakMap,r=eR();return{open(n){let{targetUrl:i,forwardHeaders:s}=n.data,o;try{o=new WebSocket(i,{headers:s})}catch(a){m("ws",`failed to open upstream ${i}: ${a}`,e),n.close(1011,"upstream connect failed");return}o.binaryType="arraybuffer";let c={upstream:o,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(n,c),o.addEventListener("open",()=>{c.upstreamOpen=!0;for(let a of c.pending)o.send(a);c.pending=[],c.pendingBytes=0}),o.addEventListener("message",(a)=>{n.send(a.data)}),o.addEventListener("close",(a)=>{try{n.close(a.code||1000,a.reason||"")}catch{}}),o.addEventListener("error",()=>{m("ws",`upstream error for ${i}`,e);try{n.close(1011,"upstream error")}catch{}})},message(n,i){let s=t.get(n);if(!s)return;let o=typeof i==="string"?i:new Uint8Array(i);if(s.upstreamOpen){s.upstream.send(o);return}let c=typeof o==="string"?Buffer.byteLength(o):o.byteLength;if(s.pendingBytes+c>r){m("ws",`pending buffer would exceed ${r}B before upstream open; closing socket`,e);try{n.close(1009,"buffer limit")}catch{}try{s.upstream.close(1011,"client buffer overflow")}catch{}t.delete(n);return}s.pending.push(o),s.pendingBytes+=c},close(n,i,s){let o=t.get(n);if(!o)return;t.delete(n);try{o.upstream.close(i||1000,s||"")}catch{}}}}var Mh="127.0.0.1",tR,rR,nR=1024;var _h=te(()=>{mc();tv();wc();fe();tR=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]),rR=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"]});import*as lv from"node:fs";import*as uv from"node:path";function vc(e,t){if(!e||!t.startsWith(cv))return null;let r=t.slice(cv.length);if(!r||!/^[A-Za-z0-9_-]+$/.test(r))return null;try{return lv.readFileSync(uv.join(e,r),"utf8")}catch{return null}}var cv="/.well-known/acme-challenge/";var jh=()=>{};function fr(e){if(!e||e==="/")return"/";let t=e.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function lR(e,t){if(t==="/")return!0;if(e===t)return!0;return e.startsWith(`${t}/`)}function us(e){let t=new Map;for(let n of e){let i=fr(n.path),s=t.get(n.host);if(!s)s=new Map,t.set(n.host,s);s.set(i,n.route)}let r=new Map;for(let[n,i]of t){let s=[];for(let[o,c]of i)s.push({path:o,route:c});s.sort((o,c)=>c.path.length-o.path.length),r.set(n,s)}return r}function Uh(e,t){let r=e.get(t);if(r!==void 0)return r;let n,i=-1;for(let[s,o]of e){if(!yn(s))continue;if(Ur(t,s)){let c=s.length-1;if(c>i)i=c,n=o}}return n}function fs(e,t,r){let n=Uh(e,t);if(!n)return;for(let i of n)if(lR(r,i.path))return i.route;return}var bc=()=>{};import*as hs from"node:fs/promises";import*as Kh from"node:path";function $c(e,t=fv,r){let n=Number.isFinite(t)&&t>0?Math.floor(t):fv;if(e.length<=n)return e;let i=e.slice(0,n),s=e.slice(n).map((o)=>o.serverName);return b.warn(`rpx: ${e.length} TLS contexts exceed maxTlsContexts=${n}; keeping the first ${n} and dropping ${s.length} host(s): ${s.join(", ")}`),m("sni",`capped SNI set to ${n} of ${e.length}`,r),i}function ds(e){let r=$c(e.sni,e.maxTlsContexts,e.verbose).map((i)=>({serverName:i.serverName,cert:i.cert,key:i.key})),n=e.defaultTls?[{cert:e.defaultTls.cert,key:e.defaultTls.key},...r]:r;return si(n)}function si(e){if(Array.isArray(e))return e.map((t)=>({...t,lowMemoryMode:!0}));return{...e,lowMemoryMode:!0}}function uR(e){if(!e.endsWith(".crt"))return null;let t=e.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function fR(e,t,r,n){try{let[i,s]=await Promise.all([hs.readFile(t,"utf8"),hs.readFile(r,"utf8")]);return{serverName:e,cert:i,key:s}}catch(i){return m("sni",`skipping ${e}: ${i.message}`,n),null}}async function ms(e,t){let r=new Map,n=e.certsDirServerNames?new Set(e.certsDirServerNames):void 0;if(e.certsDir){let s=[];try{s=await hs.readdir(e.certsDir)}catch(o){m("sni",`certsDir read failed (${e.certsDir}): ${o.message}`,t)}for(let o of s){let c=uR(o);if(!c)continue;if(n&&!n.has(c))continue;let a=o.slice(0,-4);r.set(c,{certPath:Kh.join(e.certsDir,o),keyPath:Kh.join(e.certsDir,`${a}.key`)})}}if(e.domains)for(let[s,o]of Object.entries(e.domains))r.set(s,o);let i=[];for(let[s,o]of r){let c=await fR(s,o.certPath,o.keyPath,t);if(c)i.push(c)}return i}var fv=256;var Wh=te(()=>{qt();fe()});import*as Ot from"node:fs/promises";import*as Cc from"node:path";function gs(e=process.env){let t=e.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if(t==="restart"||t==="rebind")return t;return e.INVOCATION_ID?"restart":"rebind"}function Vh(e,t){if(!t||t.length===0)return!1;return t.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return e===n||e.endsWith(`.${n}`)})}function dv(e){if(!e||e.length>253)return!1;if(e.includes("/")||e.includes(":")||e.includes(" "))return!1;if(e.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(e)}class oi{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(e){this.config=e.config,this.certsDir=e.certsDir,this.onCertAdded=e.onCertAdded,this.http01Store=e.http01Store??Ui,this.issuer=e.issuer??la,this.verbose=e.verbose??!1,this.negativeCacheMs=e.negativeCacheMs??dR;for(let t of e.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(e){return this.certs.has(e)}async isApproved(e){if(!dv(e))return!1;if(Vh(e,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(e)}catch(t){return m("on-demand",`ask(${e}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(e){if(!this.config.enabled)return!1;if(this.certs.has(e))return!0;if(!dv(e))return!1;let t=this.inFlight.get(e);if(t)return t;let r=this.negativeCache.get(e);if(r!==void 0&&Date.now()<r){if(await this.loadFromDisk(e))return this.negativeCache.delete(e),!0;return m("on-demand",`${e} negatively cached for ${r-Date.now()}ms`,this.verbose),!1}let n=this.issue(e).finally(()=>{this.inFlight.delete(e)});return this.inFlight.set(e,n),n}async issue(e){if(this.certs.has(e))return!0;if(await this.loadFromDisk(e))return!0;if(!await this.isApproved(e))return m("on-demand",`refused issuance for ${e} (not approved)`,this.verbose),this.cacheNegative(e),!1;try{m("on-demand",`issuing cert for ${e} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[e],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(e,t.fullChainPem,t.keyPem);let r={serverName:e,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(e,r),this.negativeCache.delete(e),m("on-demand",`issued + installed cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(e),m("on-demand",`issuance for ${e} failed: ${t.message}`,this.verbose),!1}}cacheNegative(e){if(this.negativeCache.size>=hv){let t=Date.now();for(let[r,n]of this.negativeCache)if(n<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=hv){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(e,Date.now()+this.negativeCacheMs)}async loadFromDisk(e){let{certPath:t,keyPath:r}=this.pathsFor(e);try{let[n,i]=await Promise.all([Ot.readFile(t,"utf8"),Ot.readFile(r,"utf8")]),s={serverName:e,cert:n,key:i};return this.certs.set(e,s),m("on-demand",`adopted existing on-disk cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(e){return{certPath:Cc.join(this.certsDir,`${e}.crt`),keyPath:Cc.join(this.certsDir,`${e}.key`)}}async persist(e,t,r){await Ot.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:i}=this.pathsFor(e);await Promise.all([Ot.writeFile(n,t,"utf8"),Ot.writeFile(i,r,{encoding:"utf8",mode:384})])}get accountKeyPath(){return Cc.join(this.certsDir,hR)}async loadAccountKey(){try{return await Ot.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(e){if(!e||this.accountKeyPem===e)return;this.accountKeyPem=e,await Ot.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Ot.writeFile(this.accountKeyPath,e,{encoding:"utf8",mode:384}).catch(()=>{})}}var hR="acme-account.key",dR=60000,hv=4096;var xc=te(()=>{Hi();fe()});import{X509Certificate as Hh,createPrivateKey as mR}from"node:crypto";import*as ps from"node:fs/promises";import{isIP as zh}from"node:net";import*as ys from"node:path";function $R(e){let t=uc(e);return{caCertPath:t.caCertPath,caKeyPath:t.caKeyPath,certPath:ys.join(e,gR),keyPath:ys.join(e,pR)}}function ws(e,t){if(!e||typeof e.dir!=="string"||e.dir.trim()==="")throw Error("localCa.dir is required");let r=[...new Set((e.hosts??[]).map((o)=>String(o).trim().toLowerCase()).filter(Boolean))];if(r.length===0)throw Error("localCa.hosts must name at least one host");for(let o of r)if(o.startsWith("*")||o.includes("/")||o.includes(":")||o.includes(" ")||zh(o)!==0)throw Error(`localCa.hosts entry ${JSON.stringify(o)} is not a hostname (wildcards are not supported; put IP addresses in localCa.ips)`);let n=[...new Set((e.ips??[]).map((o)=>String(o).trim()).filter(Boolean))];for(let o of n)if(zh(o)===0)throw Error(`localCa.ips entry ${JSON.stringify(o)} is not an IP address`);if(t?.enabled){let o=r.filter((c)=>Vh(c,t.allowedSuffixes));if(o.length>0)throw Error(`localCa.hosts and onDemandTls.allowedSuffixes overlap on ${o.join(", ")}; a host is either LAN-only (local CA) or public (ACME), never both`)}let i=e.validityDays??wR,s=e.renewBeforeDays??vR;if(!(i>0))throw Error("localCa.validityDays must be a positive number of days");if(!(s>=0)||s>=i)throw Error("localCa.renewBeforeDays must be between 0 and localCa.validityDays");return{dir:e.dir,hosts:r,ips:n,installTrust:e.installTrust===!0,validityDays:i,renewBeforeDays:s}}function gv(e){let t=zh(e);if(t===4)return e;if(t!==6)return e.toLowerCase();let r=[],n=[],[i,s]=e.split("::");r=i?i.split(":"):[],n=s?s.split(":"):[];let o=(l)=>l.flatMap((u)=>{if(!u.includes("."))return[u];let f=u.split(".").map((h)=>Number.parseInt(h,10));return[(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16)]});r=o(r),n=o(n);let c=e.includes("::")?8-r.length-n.length:0;return[...r,...Array.from({length:Math.max(0,c)},()=>"0"),...n].map((l)=>Number.parseInt(l||"0",16).toString(16)).join(":")}function CR(e){let t=new Set,r=new Set;for(let n of(e??"").split(",")){let i=n.trim();if(i.startsWith("DNS:"))t.add(i.slice(4).toLowerCase());else if(i.startsWith("IP Address:"))r.add(gv(i.slice(11)))}return{dns:t,ips:r}}function xR(e,t,r=new Date){let n,i;try{n=new Hh(e.cert),i=new Hh(e.caCert)}catch(h){return`unreadable certificate (${h.message})`}try{if(!n.checkPrivateKey(mR(e.key)))return"private key does not match the certificate"}catch(h){return`unreadable private key (${h.message})`}let s=!1;try{s=n.verify(i.publicKey)}catch{s=!1}if(!s)return"not issued by the current Root CA";let o=CR(n.subjectAltName),c=t.hosts.filter((h)=>!o.dns.has(h));if(c.length>0)return`missing DNS SAN(s): ${c.join(", ")}`;let a=t.ips.filter((h)=>!o.ips.has(gv(h)));if(a.length>0)return`missing IP SAN(s): ${a.join(", ")}`;let l=new Date(n.validTo).getTime(),u=new Date(n.validFrom).getTime();if(Number.isNaN(l)||Number.isNaN(u))return"unreadable validity period";if(u>r.getTime())return"not valid yet";let f=(l-r.getTime())/bR;if(f<t.renewBeforeDays)return f<=0?"expired":`${Math.floor(f)} day(s) left, under renewBeforeDays=${t.renewBeforeDays}`;return null}async function SR(e,t){let r=Reflect.get(Mf,"isCertTrusted");if(typeof r==="function")try{return await r(e,{verbose:t})}catch(n){m("local-ca",`tlsx isCertTrusted failed (${n.message}); using rpx's own check`,t)}return fc(e,{verbose:t,regenerateUntrustedCerts:!0})}async function ER(e,t){if(await SR(e.caCertPath,t))return m("local-ca",`Root CA ${e.caCertPath} already trusted; skipping installCA`,t),{alreadyTrusted:!0,installed:!1};try{let r=await Ta({basePath:ys.dirname(e.caCertPath),caCertPath:e.caCertPath,verbose:t});if(t)b.success(`Root CA ${r.alreadyTrusted?"already trusted":"installed"} in the system trust store (${e.caCertPath})`);return{alreadyTrusted:r.alreadyTrusted,installed:r.trustInstalled}}catch(r){return b.warn(`rpx: could not install the local Root CA into the system trust store: ${r.message}`),b.warn(`rpx: trust it manually: ${e.caCertPath}`),{alreadyTrusted:!1,installed:!1}}}async function mv(e){try{return await ps.readFile(e,"utf8")}catch{return null}}async function vs(e,t={}){let r=t.verbose,n=ws(e,t.onDemandTls),i=t.now??(()=>new Date),s=$R(n.dir),o=await Fh(n.dir,{verbose:r,caOptions:{commonName:yR,organization:"rpx",verbose:r}});if(o.created&&r)b.info(`Created local Root CA at ${s.caCertPath}`);let[c,a]=await Promise.all([mv(s.certPath),mv(s.keyPath)]),l;if(c&&a)l=xR({cert:c,key:a,caCert:o.certificate},n,i());else l="no leaf on disk";let u,f;if(l===null&&c&&a)u=c,f=a,m("local-ca",`reusing leaf ${s.certPath}`,r);else{m("local-ca",`minting leaf for ${[...n.hosts,...n.ips].join(", ")} (${l})`,r);let y={domain:n.hosts[0],domains:n.hosts,altNameIPs:n.ips,commonName:n.hosts[0],organizationName:"rpx",validityDays:n.validityDays,rootCA:{certificate:o.certificate,privateKey:o.privateKey},verbose:r},g=await Un(y);if(u=g.certificate,f=g.privateKey,await ps.writeFile(s.keyPath,f,{mode:384}),await ps.writeFile(s.certPath,u),r)b.success(`Minted local certificate for ${[...n.hosts,...n.ips].join(", ")} (${l})`)}let h=new Date(new Hh(u).validTo),d={paths:s,caCert:o.certificate,cert:u,key:f,caCreated:o.created,leafMinted:l!==null,renewalReason:l,notAfter:h,entries:n.hosts.map((y)=>({serverName:y,cert:u,key:f})),defaultTls:{cert:u,key:f}};if(n.installTrust)d.trust=await ER(s,r);return d}var gR="rpx-local-host.crt",pR="rpx-local-host.key",yR="rpx Local CA",wR=825,vR=30,bR=86400000;var Gh=te(()=>{Hi();hc();qt();xc();fe()});import*as Sc from"node:net";function Nr(e,t,r){return m("port",`Checking if port ${e} is in use on ${t}`,r),new Promise((n)=>{let i=Sc.createServer(),s=setTimeout(()=>{m("port",`Checking port ${e} timed out, assuming it's in use`,r),i.close(),n(!0)},3000);i.once("error",(o)=>{if(clearTimeout(s),o.code==="EADDRINUSE")m("port",`Port ${e} is in use`,r),n(!0);else m("port",`Error checking port ${e}: ${o.message}`,r),n(!0)}),i.once("listening",()=>{clearTimeout(s),m("port",`Port ${e} is available`,r),i.close(),n(!1)});try{i.listen(e,t)}catch(o){clearTimeout(s),m("port",`Exception checking port ${e}: ${o}`,r),n(!0)}})}async function qh(e,t,r,n=50){m("port",`Finding available port starting from ${e} (max attempts: ${n})`,r);let i=e,s=0;while(s<n){if(s++,!await Nr(i,t,r))return m("port",`Found available port: ${i} after ${s} attempts`,r),i;m("port",`Port ${i} is in use, trying ${i+1} (attempt ${s}/${n})`,r),i++}throw Error(`Unable to find available port after ${n} attempts starting from ${e}`)}function pv(e,t,r=5000,n){return m("port",`Testing connection to ${t}:${e}`,n),new Promise((i)=>{let s=Sc.connect({host:t,port:e,timeout:r});s.once("connect",()=>{m("port",`Successfully connected to ${t}:${e}`,n),s.end(),i(!0)}),s.once("timeout",()=>{m("port",`Connection to ${t}:${e} timed out`,n),s.destroy(),i(!1)}),s.once("error",(o)=>{m("port",`Failed to connect to ${t}:${e}: ${o.message}`,n),s.destroy(),i(!1)})})}class Ec{usedPorts=new Set;hostname;verbose;maxRetries;constructor(e="0.0.0.0",t,r=50){this.hostname=e,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(e,t=!1){if(this.usedPorts.has(e))return this.findNextAvailablePort(e+1,t);if(await Nr(e,this.hostname,this.verbose))return this.findNextAvailablePort(e+1,t);if(t){if(!await pv(e,this.hostname,3000,this.verbose))return m("port",`Port ${e} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(e+1,t)}return this.usedPorts.add(e),e}async findNextAvailablePort(e,t=!1){let r=await qh(e,this.hostname,this.verbose,this.maxRetries);if(t){if(!await pv(r,this.hostname,3000,this.verbose))if(r<e+this.maxRetries)return this.findNextAvailablePort(r+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(r),r}releasePort(e){m("port",`Releasing port ${e}`,this.verbose),this.usedPorts.delete(e)}}var AI;var Yh=te(()=>{fe();AI=new Ec});import*as Tc from"node:fs";import*as tt from"node:fs/promises";import{homedir as TR}from"node:os";import*as Jh from"node:path";import*as Pc from"node:process";function dt(){return Jh.join(TR(),".stacks","rpx","registry.d")}function Dr(e){return typeof e==="string"&&e.length>0&&e.length<=128&&PR.test(e)}function Xh(e,t){if(!Dr(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return Jh.join(e,`${t}.json`)}function mt(e){if(!Number.isInteger(e)||e<=0)return!1;try{return Pc.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function yv(e){if(!e||typeof e!=="object")return!1;let t=e,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,n=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,i=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",s=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&Dr(t.id)&&(n||i)&&typeof t.to==="string"&&t.to.length>0&&s&&r&&typeof t.createdAt==="string"}async function AR(e){await tt.mkdir(e,{recursive:!0})}async function ai(e,t=dt(),r){if(!yv(e))throw Error(`invalid registry entry: ${JSON.stringify(e)}`);await AR(t);let n=Xh(t,e.id),i=`${n}.tmp.${Pc.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{await tt.writeFile(i,s,{encoding:"utf8",mode:420}),await tt.rename(i,n),m("registry",`wrote entry ${e.id} → ${n}`,r)}catch(o){throw await tt.unlink(i).catch(()=>{}),o}}async function Jr(e,t=dt(),r){let n=Xh(t,e);try{await tt.unlink(n),m("registry",`removed entry ${e}`,r)}catch(i){if(i.code!=="ENOENT")throw i}}async function Zh(e,t=dt(),r){let n=Xh(t,e);try{let i=await tt.readFile(n,"utf8"),s=JSON.parse(i);if(!yv(s))return m("registry",`entry ${e} failed validation, removing`,r),await tt.unlink(n).catch(()=>{}),null;return s}catch(i){if(i.code==="ENOENT")return null;if(i instanceof SyntaxError)return m("registry",`entry ${e} has invalid JSON, removing`,r),await tt.unlink(n).catch(()=>{}),null;throw i}}async function xt(e=dt(),t){let r;try{r=await tt.readdir(e)}catch(i){if(i.code==="ENOENT")return[];throw i}let n=[];for(let i of r){if(!i.endsWith(".json"))continue;let s=i.slice(0,-5);if(!Dr(s))continue;let o=await Zh(s,e,t);if(o)n.push(o)}return n}async function bs(e=dt(),t){let r=await xt(e,t),n=0;for(let i of r){if(i.pid===void 0)continue;if(!mt(i.pid))m("registry",`GC: pid ${i.pid} for ${i.id} is dead, removing`,t),await Jr(i.id,e,t).catch(()=>{}),n++}return n}function Ac(e,t={}){let r=t.dir??dt(),n=t.debounceMs??100,i=t.pollMs??Math.max(n*2,250),s=t.verbose;Tc.mkdirSync(r,{recursive:!0});let o=null,c=!1,a=null,l=!1,u=(p)=>JSON.stringify(p.map((w)=>({id:w.id,from:w.from,to:w.to,path:w.path,pid:w.pid,pathRewrites:w.pathRewrites,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,static:w.static,loadBalancer:w.loadBalancer})).sort((w,v)=>w.id.localeCompare(v.id))),f=()=>{if(o=null,c)return;xt(r,s).then((p)=>(a=u(p),e(p))).catch((p)=>{m("registry",`watcher onChange failed: ${p}`,s)})},h=()=>{if(c)return;if(o)clearTimeout(o);o=setTimeout(f,n)},y=setInterval(()=>{if(c||l)return;l=!0,xt(r,s).then((p)=>{if(u(p)!==a)h()}).catch((p)=>{m("registry",`watcher poll failed: ${p}`,s)}).finally(()=>{l=!1})},i),g=Tc.watch(r,{persistent:!0},(p,w)=>{if(w&&/\.tmp\.\d+\.\d+$/.test(w))return;h()});return g.on("error",(p)=>{m("registry",`watcher error: ${p}`,s)}),h(),{close:()=>{if(c=!0,o)clearTimeout(o);clearInterval(y),g.close()}}}var PR;var Xr=te(()=>{fe();PR=/^[a-zA-Z0-9._-]+$/});import{closeSync as wv,openSync as RR,readFileSync as kR}from"node:fs";import*as vv from"node:fs/promises";import{spawn as OR}from"node:child_process";import{homedir as NR}from"node:os";import*as $s from"node:path";import*as Nt from"node:process";class ed{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(e){this.resolver=e.resolver,this.registryDir=e.registryDir??dt(),this.rpxDir=e.rpxDir??$s.join(NR(),".stacks","rpx"),this.verbose=e.verbose??!1,this.startupTimeoutMs=e.startupTimeoutMs??DR,this.pollIntervalMs=e.pollIntervalMs??FR,this.restartDelayMs=e.restartDelayMs??BR,this.killGraceMs=e.killGraceMs??IR,this.launch=e.launcher??_R(this.verbose),this.probePort=e.probePort??MR,this.pickPort=e.pickPort??((r)=>qh(r,"127.0.0.1")),this.isHostRoutable=e.isHostRoutable??(()=>!1),this.onSiteActivating=e.onSiteActivating,this.now=e.now??Date.now,this.writeEntry=e.writeEntry??ai,this.removeEntry=e.removeEntry??Jr;let t=e.reapIntervalMs??LR;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(e){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(e);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(e),t=void 0;if(!t){let r=this.resolver.resolve(e);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:e};if(t.status==="failed")return{kind:"failed",host:e,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:e,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(e){try{this.onSiteActivating?.(e.host)}catch{}let t=new Map;if(!e.selfRegisters)for(let c of e.routes){if(t.has(c.portEnv))continue;let a=await this.pickPort(c.defaultPort??3000);t.set(c.portEnv,a)}let r=$s.join(this.rpxDir,"sites",`${e.id}.log`);await vv.mkdir($s.dirname(r),{recursive:!0}).catch(()=>{});let n=this.buildEnv(e,t),i=null,s;try{i=this.launch({command:e.command,cwd:e.dir,env:n,logPath:r})}catch(c){s=`failed to spawn: ${c.message}`}let o={site:e,status:s?"failed":"starting",handle:i,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:s?this.now():0,error:s,logPath:r,exited:!1,ready:Promise.resolve()};if(this.sites.set(e.host,o),s)return b.warn(`rpx: site ${e.host} ${s}`),o;return b.info(`rpx: booting ${e.host} → ${e.command} (${e.dir})`),i.exited.then((c)=>this.onProcessExit(o,c)).catch(()=>{}),o.ready=this.driveReadiness(o).catch((c)=>{m("sites",`readiness loop for ${e.host} threw: ${c}`,this.verbose)}),o}async onProcessExit(e,t){if(e.exited=!0,this.stopped||this.sites.get(e.site.host)!==e)return;if(e.status==="ready"){b.warn(`rpx: ${e.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(e.site.host);for(let r of e.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(e.status==="starting")this.fail(e,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(e){let{site:t}=e,r=this.now()+this.startupTimeoutMs,n=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,e.ports);while(this.now()<r&&!this.stopped){if(e.status!=="starting"||e.exited)return;if(await n()){if(await this.publishRoutes(e),e.status==="starting")e.status="ready",b.success(`rpx: ${t.host} ready`);return}await Qh(this.pollIntervalMs)}if(e.status==="starting")this.fail(e,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(e,t){let r=e.routes.filter((i)=>i.readyGate??fr(i.path)==="/").map((i)=>t.get(i.portEnv)).filter((i)=>typeof i==="number"),n=r.length>0?r:[...t.values()];return async()=>{for(let i of n)if(!await this.probePort(i))return!1;return n.length>0}}async publishRoutes(e){let{site:t,ports:r}=e;if(t.selfRegisters||t.routes.length===0)return;let n=t.routes.find((a)=>fr(a.path)==="/")??t.routes[0],i=r.get(n.portEnv);if(i===void 0)return;let s=[];for(let a of t.routes){if(a===n)continue;let l=r.get(a.portEnv);if(l===void 0)continue;s.push({from:fr(a.path),to:`localhost:${l}`,stripPrefix:a.stripPrefix??!1})}let o={id:t.id,from:`localhost:${i}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:s.length>0?s:void 0,pid:e.handle?.pid};await this.writeEntry(o,this.registryDir,this.verbose),e.routeIds=[t.id];let c=this.now()+2000;while(this.now()<c&&!this.isHostRoutable(t.host))await Qh(50)}fail(e,t){e.status="failed",e.error=t,e.failedAt=this.now(),b.warn(`rpx: site ${e.site.host} failed — ${t}`),this.killProcess(e)}buildEnv(e,t){let r={};for(let[n,i]of Object.entries(Nt.env))if(typeof i==="string")r[n]=i;Object.assign(r,e.env);for(let[n,i]of t)r[n]=String(i);return r.RPX_SITE_HOST=e.host,r.RPX_SITE_URL=`https://${e.host}`,r}readLogTail(e,t=40){try{return kR(e.logPath,"utf8").split(`
292
+ `).slice(-t).join(`
293
+ `).trim()}catch{return""}}async stop(e){let t=this.sites.get(e);if(!t)return;this.sites.delete(e);for(let r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),b.info(`rpx: stopped ${e}`)}async killProcess(e){let t=e.handle;if(!t)return;e.handle=null;try{t.stop("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof r.unref==="function")r.unref();await Promise.race([t.exited.catch(()=>{}),Qh(this.killGraceMs+500)]),clearTimeout(r)}async reapIdle(){if(this.stopped)return;let e=this.now();for(let[t,r]of this.sites){let n=r.site.idleTimeoutMs;if(n<=0)continue;let i=e-r.lastAccess;if((r.status==="ready"||e-r.startedAt>this.startupTimeoutMs)&&i>n)m("sites",`reaping ${t} (idle ${Math.round(i/1000)}s)`,this.verbose),await this.stop(t)}}list(){let e=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:e-t.startedAt,idleMs:e-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((e)=>this.stop(e)))}}function Qh(e){return new Promise((t)=>setTimeout(t,e))}async function MR(e){let t=new AbortController,r=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${e}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(r)}}function _R(e){let t=jR();return({command:r,cwd:n,env:i,logPath:s})=>{let o=RR(s,"a");try{let c=OR("sh",["-c",r],{cwd:n,env:i,detached:!0,stdio:["ignore",o,o],...t?{uid:t.uid,gid:t.gid}:{}}),a=c.pid;if(a===void 0)throw Error("spawn returned no pid");let l=new Promise((u)=>{c.once("exit",(f)=>{u(f)}),c.once("error",()=>{u(null)})}).finally(()=>{try{wv(o)}catch{}});return m("sites",`spawned pid ${a}: sh -c ${r} (cwd ${n})`,e),{pid:a,exited:l,stop:(u="SIGTERM")=>{try{Nt.kill(-a,u)}catch{try{c.kill(u)}catch{}}}}}catch(c){try{wv(o)}catch{}throw c}}}function jR(){if(Nt.platform==="win32")return null;if(!(typeof Nt.getuid==="function"&&Nt.getuid()===0))return null;let t=Number.parseInt(Nt.env.SUDO_UID??"",10),r=Number.parseInt(Nt.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(r)||r<=0)return null;return{uid:t,gid:r}}var DR=120000,FR=200,LR=30000,BR=3000,IR=4000;var bv=te(()=>{bc();Yh();Xr();fe();qt()});function ci(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function $v(e,t,r){return`<!doctype html>
235
294
  <html lang="en">
236
295
  <head>
237
296
  <meta charset="utf-8">
238
297
  <meta name="viewport" content="width=device-width, initial-scale=1">
239
- ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
240
- <title>${v1(w)}</title>
241
- <style>${eH}</style>
298
+ ${r>0?`<meta http-equiv="refresh" content="${r}">`:""}
299
+ <title>${ci(e)}</title>
300
+ <style>${UR}</style>
242
301
  </head>
243
- <body><main class="card">${$}</main></body>
244
- </html>`}function p2(w){let $=Math.max(1,Math.round(w.sinceMs/1000)),Y=w.logTail?`<pre>${v1(w.logTail)}</pre>`:"",A=`
245
- <div class="row"><div class="spinner"></div><h1>Starting ${v1(w.host)}…</h1></div>
302
+ <body><main class="card">${t}</main></body>
303
+ </html>`}function Cv(e){let t=Math.max(1,Math.round(e.sinceMs/1000)),r=e.logTail?`<pre>${ci(e.logTail)}</pre>`:"",n=`
304
+ <div class="row"><div class="spinner"></div><h1>Starting ${ci(e.host)}…</h1></div>
246
305
  <p>rpx is booting this site's dev server on demand. This page reloads itself —
247
306
  it'll switch to the app as soon as it's ready (usually a few seconds).</p>
248
- <p>Booting for ${$}s.</p>
249
- ${Y}`;return new Response(l2(`Starting ${w.host}`,A,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function r2(w){let $=w.logTail?`<pre>${v1(w.logTail)}</pre>`:"<p>No output was captured.</p>",Y=`
250
- <div class="row"><div class="dot"></div><h1>${v1(w.host)} failed to start</h1></div>
251
- <p>${v1(w.error)}</p>
252
- ${$}
253
- <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(l2(`${w.host} failed`,Y,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var eH=`
307
+ <p>Booting for ${t}s.</p>
308
+ ${r}`;return new Response($v(`Starting ${e.host}`,n,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function xv(e){let t=e.logTail?`<pre>${ci(e.logTail)}</pre>`:"<p>No output was captured.</p>",r=`
309
+ <div class="row"><div class="dot"></div><h1>${ci(e.host)} failed to start</h1></div>
310
+ <p>${ci(e.error)}</p>
311
+ ${t}
312
+ <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response($v(`${e.host} failed`,r,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var UR=`
254
313
  :root { color-scheme: light dark }
255
314
  * { box-sizing: border-box }
256
315
  body {
@@ -276,63 +335,54 @@ ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
276
335
  }
277
336
  .dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
278
337
  @keyframes spin { to { transform: rotate(360deg) } }
279
- `;import{exec as wR}from"node:child_process";import h8 from"node:fs";import $R from"node:os";import s2 from"node:path";import*as g$ from"node:process";import{promisify as YR}from"node:util";function t2(w){let $=w.trim().toLowerCase();return $==="localhost"||$.endsWith(".localhost")||$.endsWith(".localhost.")}async function o2(w){if(g$.platform==="win32")throw Error("Administrator privileges required on Windows");if(EY()){let{stdout:A}=await PY(w);return A}let $=E$(),Y=w.replace(/'/g,"'\\''");try{if($){let{stdout:A}=await PY(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`);return Sj=!0,A}if(Sj)try{let{stdout:A}=await PY(`sudo -n sh -c '${Y}'`);return A}catch(A){K("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await PY(`sudo -n sh -c '${Y}'`);return Sj=!0,A}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(A){throw Error(`Failed to execute sudo command: ${A.message}`)}}function x8(w){let $=w.indexOf("#"),Y=($===-1?w:w.slice(0,$)).trim();if(!Y)return null;let A=$===-1?"":w.slice($+1).trim(),[X,...J]=Y.split(/\s+/);if(!X||J.length===0)return null;let U=/^rpx(?::pid=(\d+))?$/.exec(A);return{address:X,names:J,comment:A,rpxPid:U?.[1]?Number.parseInt(U[1],10):null,rpxManaged:U!==null}}function e2(w,$){let Y=x8(w);return Y!==null&&D8.has(Y.address)&&Y.names.includes($)}function XR(w,$){let Y=new Set($),A=new Set,X=w.split(`
280
- `),J=[],U=0;while(U<X.length){let j=X[U];if(j.trim()===AR){let Q=[],z=U+1;while(z<X.length){let B=X[z];if(B.trim()===""||B.trim().startsWith("#"))break;Q.push(B),z++}let f=Q.filter((B)=>{let G=x8(B),T=G!==null&&D8.has(G.address)&&G.names.some((F)=>Y.has(F));if(T){for(let F of G.names)if(Y.has(F))A.add(F)}return!T});if(f.length>0||Q.length===0)J.push(j,...f);U=z;continue}let W=x8(j);if(W?.rpxManaged&&D8.has(W.address)&&W.names.some((Q)=>Y.has(Q))){for(let Q of W.names)if(Y.has(Q))A.add(Q);U++;continue}J.push(j),U++}while(J.length>0&&J[J.length-1].trim()==="")J.pop();return{content:`${J.join(`
338
+ `;import{exec as KR}from"node:child_process";import Rc from"node:fs";import WR from"node:os";import Tv from"node:path";import*as Zr from"node:process";import{promisify as VR}from"node:util";function Sv(e){let t=e.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}async function Pv(e){if(Zr.platform==="win32")throw Error("Administrator privileges required on Windows");if(Zi()){let{stdout:n}=await Cs(e);return n}let t=Er(),r=e.replace(/'/g,"'\\''");try{if(t){let{stdout:n}=await Cs(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`);return td=!0,n}if(td)try{let{stdout:n}=await Cs(`sudo -n sh -c '${r}'`);return n}catch(n){m("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:n}=await Cs(`sudo -n sh -c '${r}'`);return td=!0,n}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(n){throw Error(`Failed to execute sudo command: ${n.message}`)}}function Oc(e){let t=e.indexOf("#"),r=(t===-1?e:e.slice(0,t)).trim();if(!r)return null;let n=t===-1?"":e.slice(t+1).trim(),[i,...s]=r.split(/\s+/);if(!i||s.length===0)return null;let o=/^rpx(?::pid=(\d+))?$/.exec(n);return{address:i,names:s,comment:n,rpxPid:o?.[1]?Number.parseInt(o[1],10):null,rpxManaged:o!==null}}function Av(e,t){let r=Oc(e);return r!==null&&kc.has(r.address)&&r.names.includes(t)}function zR(e,t){let r=new Set(t),n=new Set,i=e.split(`
339
+ `),s=[],o=0;while(o<i.length){let c=i[o];if(c.trim()===HR){let l=[],u=o+1;while(u<i.length){let h=i[u];if(h.trim()===""||h.trim().startsWith("#"))break;l.push(h),u++}let f=l.filter((h)=>{let d=Oc(h),y=d!==null&&kc.has(d.address)&&d.names.some((g)=>r.has(g));if(y){for(let g of d.names)if(r.has(g))n.add(g)}return!y});if(f.length>0||l.length===0)s.push(c,...f);o=u;continue}let a=Oc(c);if(a?.rpxManaged&&kc.has(a.address)&&a.names.some((l)=>r.has(l))){for(let l of a.names)if(r.has(l))n.add(l);o++;continue}s.push(c),o++}while(s.length>0&&s[s.length-1].trim()==="")s.pop();return{content:`${s.join(`
281
340
  `)}
282
- `,removed:[...A]}}function JR(w,$){let Y=[],A=new Set,X=[];for(let J of w.split(`
283
- `)){let U=x8(J);if(U?.rpxManaged&&U.rpxPid!==null&&D8.has(U.address)&&!$(U.rpxPid)){Y.push(...U.names),A.add(U.rpxPid);continue}X.push(J)}while(X.length>0&&X[X.length-1].trim()==="")X.pop();return{content:`${X.join(`
341
+ `,removed:[...n]}}function GR(e,t){let r=[],n=new Set,i=[];for(let s of e.split(`
342
+ `)){let o=Oc(s);if(o?.rpxManaged&&o.rpxPid!==null&&kc.has(o.address)&&!t(o.rpxPid)){r.push(...o.names),n.add(o.rpxPid);continue}i.push(s)}while(i.length>0&&i[i.length-1].trim()==="")i.pop();return{content:`${i.join(`
284
343
  `)}
285
- `,removed:Y,stalePids:[...A]}}async function _j(w){try{return await h8.promises.readFile(A$,"utf-8")}catch{return K("hosts","Reading hosts file requires elevated permissions, using sudo",w),o2(`cat "${A$}"`)}}async function hj(w,$){let Y=s2.join($R.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await h8.promises.writeFile(Y,w,"utf8"),await o2(`cat "${Y}" | tee "${A$}" > /dev/null`)}finally{await h8.promises.unlink(Y).catch((A)=>{K("hosts",`Failed to remove temporary file: ${A}`,$)})}}async function iY(w,$){let Y=w.filter((X)=>!t2(X)),A=w.filter((X)=>t2(X));if(A.length>0)K("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,$);if(Y.length===0)return;K("hosts",`Adding hosts: ${Y.join(", ")}`,$),K("hosts",`Using hosts file at: ${A$}`,$);try{let X;try{X=await _j($)}catch(Q){throw console.log(" Could not read hosts file — skipping hosts setup"),K("hosts",`sudo read also failed: ${Q}`,$),Error(`Cannot read hosts file: ${Q}`)}let J=X.split(`
286
- `),U=Y.filter((Q)=>!J.some((z)=>e2(z,Q)));if(U.length===0){K("hosts","All hosts already exist in hosts file",$);return}let j=g$.pid,W=U.map((Q)=>`
287
- 127.0.0.1 ${Q} ${a2}:pid=${j}
288
- ::1 ${Q} ${a2}:pid=${j}`).join(`
289
- `);try{await hj(X+W,$),console.log(` Hosts updated: ${U.join(", ")}`)}catch(Q){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),U.forEach((z)=>{console.log(` 127.0.0.1 ${z}`),console.log(` ::1 ${z}`)}),console.log(` Or run: sudo nano ${A$}`)}}catch(X){K("hosts",`Failed to manage hosts file: ${X.message}`,$)}}async function w6(w,$){K("hosts",`Removing hosts: ${w.join(", ")}`,$);try{let Y;try{Y=await _j($)}catch(J){throw K("hosts",`sudo read also failed: ${J}`,$),Error(`Cannot read hosts file: ${J}`)}let{content:A,removed:X}=XR(Y,w);if(X.length===0){K("hosts","No matching rpx-managed hosts found to remove",$);return}try{await hj(A,$),K("hosts",`Hosts removed successfully: ${X.join(", ")}`,$)}catch(J){K("hosts","Could not clean up hosts file automatically",$)}}catch(Y){K("hosts",`Failed to clean up hosts file: ${Y.message}`,$)}}async function bY(w,$){K("hosts",`Checking hosts: ${w}`,$);let Y;try{Y=await h8.promises.readFile(A$,"utf-8")}catch(X){K("hosts",`Error reading hosts file: ${X}`,$);try{let J=E$(),U;if(J)U=`echo '${J}' | sudo -S cat "${A$}" 2>/dev/null`;else U=`sudo -n cat "${A$}" 2>/dev/null || cat "${A$}" 2>/dev/null || echo ""`;let{stdout:j}=await PY(U);Y=j}catch(J){return K("hosts",`Cannot read hosts file, assuming entries don't exist: ${J}`,$),w.map(()=>!1)}}let A=Y.split(`
290
- `);return w.map((X)=>A.some((J)=>e2(J,X)))}async function uY(w={}){let $=w.isAlive??Jw,Y;try{Y=await _j(w.verbose)}catch(U){return K("hosts",`stale hosts GC: cannot read hosts file: ${U}`,w.verbose),[]}let{content:A,removed:X,stalePids:J}=JR(Y,$);if(X.length===0)return[];try{return await hj(A,w.verbose),K("hosts",`stale hosts GC: removed ${X.join(", ")} (dead pid(s): ${J.join(", ")})`,w.verbose),[...new Set(X)]}catch(U){return K("hosts",`stale hosts GC: write failed: ${U}`,w.verbose),[]}}var PY,A$,a2="# rpx",AR="# Added by rpx",D8,Sj=!1;var Dj=s(()=>{m$();f0();PY=YR(wR);A$=g$.platform==="win32"?s2.join(g$.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",D8=new Set(["127.0.0.1","::1"])});import*as C$ from"node:fs/promises";import{homedir as UR}from"node:os";import*as xj from"node:path";function Y6(){return xj.join(UR(),".stacks","rpx")}function kj(w=Y6()){return xj.join(w,WR)}async function Z8(w=Y6()){try{let $=await C$.readFile(kj(w),"utf8"),Y=JSON.parse($);if(Y.version!==k8||!Array.isArray(Y.resolvers))return null;return{version:k8,resolvers:Y.resolvers.filter((A)=>typeof A==="string"),domains:Array.isArray(Y.domains)?Y.domains.filter((A)=>typeof A==="string"):[],ownerPid:typeof Y.ownerPid==="number"?Y.ownerPid:null,updatedAt:typeof Y.updatedAt==="string"?Y.updatedAt:""}}catch($){if($.code==="ENOENT")return null;throw $}}async function A6(w,$){await C$.mkdir(w,{recursive:!0}),await C$.writeFile(kj(w),`${JSON.stringify($,null,2)}
291
- `,"utf8")}async function Zj(w){await C$.rm(kj(w),{force:!0})}function X6(w){let $=w.trim().toLowerCase().replace(/\.$/,"");if(!$||$.includes("127.0.0.1"))return null;if($==="localhost"||$.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test($))return null;if(!/^[a-z0-9.-]+$/.test($))return null;return $}function QR(w){let $=X6(w);if(!$)return null;let Y=$.split(".");if(Y.length<2)return null;let A=Y[Y.length-1];if(jR.has(A))return Y.slice(-2).join(".");return $}function Pj(w){let $=new Set;for(let Y of w){let A=QR(Y);if(A)$.add(A)}return Array.from($).sort()}function ij(w){let $=new Set;for(let Y of w){let A=X6(Y);if(A)$.add(A)}return Array.from($).sort()}var k8=1,WR="dns-state.json",$6,jR;var J6=s(()=>{$6=["com","test","dev","app","page","local","localhost","example","invalid"];jR=new Set(["test","localhost","local","example","invalid","internal","home","lan"])});var i8={};ej(i8,{tearDownDevelopmentDns:()=>d$,syncDevelopmentDnsFromRegistry:()=>m1,stopDnsServer:()=>bj,startDnsServer:()=>G6,setupResolver:()=>qR,setupDevelopmentDns:()=>mj,resolverFilePath:()=>c1,removeResolver:()=>RR,removeLegacyTldResolvers:()=>cj,reconcileStaleDevelopmentDns:()=>n$,isRpxDevelopmentDnsAnswering:()=>K6,isDnsServerRunning:()=>GR,contentLooksLikeRpxResolver:()=>F6,RPX_RESOLVER_MARKER:()=>Q6,DNS_PORT:()=>cY});import U6 from"node:dgram";import*as W6 from"node:fs/promises";import*as j6 from"node:path";import*as X$ from"node:process";function f6(w){return{id:w.readUInt16BE(0),flags:w.readUInt16BE(2),qdcount:w.readUInt16BE(4),ancount:w.readUInt16BE(6),nscount:w.readUInt16BE(8),arcount:w.readUInt16BE(10)}}function B6(w,$,Y=0){let A=[],X=$,J=0;while(!0){if(X>=w.length||++J>128)break;let U=w[X];if(U===0){X++;break}if((U&192)===192){if(X+1>=w.length||Y>=10)break;let j=w.readUInt16BE(X)&16383,{name:W}=B6(w,j,Y+1);if(W)A.push(W);X+=2;break}if(X++,X+U>w.length)break;A.push(w.subarray(X,X+U).toString("ascii")),X+=U}return{name:A.join("."),newOffset:X}}function zR(w,$){let{name:Y,newOffset:A}=B6(w,$),X=w.readUInt16BE(A),J=w.readUInt16BE(A+2);return{question:{name:Y,type:X,class:J},newOffset:A+4}}function vY(w){let $=w.split("."),Y=[];for(let A of $)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function fR(w,$,Y){let A=[],X=Buffer.alloc(12);X.writeUInt16BE(w,0),X.writeUInt16BE(33152,2),X.writeUInt16BE(1,4),X.writeUInt16BE(1,6),X.writeUInt16BE(0,8),X.writeUInt16BE(0,10),A.push(X),A.push(vY($.name));let J=Buffer.alloc(4);J.writeUInt16BE($.type,0),J.writeUInt16BE($.class,2),A.push(J),A.push(vY($.name));let U=Buffer.alloc(10);if(U.writeUInt16BE($.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),$.type===1){U.writeUInt16BE(4,8),A.push(U);let j=Y.split(".").map((W)=>Number.parseInt(W,10));A.push(Buffer.from(j))}else if($.type===28)U.writeUInt16BE(16,8),A.push(U),A.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return X.writeUInt16BE(33155,2),X.writeUInt16BE(0,6),Buffer.concat([X,vY($.name),J]);return Buffer.concat(A)}function BR(w,$){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE(w,0),A.writeUInt16BE(33155,2),A.writeUInt16BE(1,4),A.writeUInt16BE(0,6),A.writeUInt16BE(0,8),A.writeUInt16BE(0,10),Y.push(A),Y.push(vY($.name));let X=Buffer.alloc(4);return X.writeUInt16BE($.type,0),X.writeUInt16BE($.class,2),Y.push(X),Buffer.concat(Y)}async function G6(w,$){if(X$.platform!=="darwin")return!1;let Y=ij(w);if(Y.length===0)return!1;if(s0){for(let A of Y)P8.add(A);return K("dns","DNS server already running — merged domains",$),!0}return P8=new Set(Y),new Promise((A)=>{s0=U6.createSocket("udp4"),s0.on("error",(X)=>{K("dns",`DNS server error: ${X.message}`,$),s0?.close(),s0=null,A(!1)}),s0.on("message",(X,J)=>{try{let U=f6(X),{question:j}=zR(X,12);K("dns",`Query for ${j.name} type ${j.type} from ${J.address}`,$);let W=j.name.toLowerCase(),Q=!1;for(let f of P8)if(W===f||W.endsWith(`.${f}`)){Q=!0;break}let z;if(Q&&(j.type===1||j.type===28))z=fR(U.id,j,"127.0.0.1"),K("dns",`Responding with localhost for ${j.name}`,$);else z=BR(U.id,j),K("dns",`NXDOMAIN for ${j.name}`,$);s0?.send(z,J.port,J.address)}catch(U){K("dns",`Error processing DNS query: ${U}`,$)}}),s0.on("listening",()=>{let X=s0?.address();K("dns",`DNS server listening on ${X?.address}:${X?.port}`,$),A(!0)});try{s0.bind(cY,"127.0.0.1")}catch(X){K("dns",`Failed to bind DNS server: ${X}`,$),A(!1)}})}function bj(w){if(s0)K("dns","Stopping DNS server",w),s0.close(),s0=null,P8=new Set}function GR(){return s0!==null}async function K6(w,$=500){let Y=w.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let X=U6.createSocket("udp4"),J=setTimeout(()=>{X.close(),A(!1)},$);X.on("message",(j)=>{clearTimeout(J),X.close();try{let W=f6(j);A(W.ancount>0)}catch{A(!1)}}),X.on("error",()=>{clearTimeout(J),X.close(),A(!1)});let U=KR(Y,1);X.send(U,cY,"127.0.0.1",(j)=>{if(j)clearTimeout(J),X.close(),A(!1)})})}function KR(w,$){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([vY(w),Buffer.from([0,$,0,1])]);return Buffer.concat([Y,A])}function FR(){return`${Q6}
344
+ `,removed:r,stalePids:[...n]}}async function rd(e){try{return await Rc.promises.readFile(hr,"utf-8")}catch{return m("hosts","Reading hosts file requires elevated permissions, using sudo",e),Pv(`cat "${hr}"`)}}async function nd(e,t){let r=Tv.join(WR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Rc.promises.writeFile(r,e,"utf8"),await Pv(`cat "${r}" | tee "${hr}" > /dev/null`)}finally{await Rc.promises.unlink(r).catch((n)=>{m("hosts",`Failed to remove temporary file: ${n}`,t)})}}async function xs(e,t){let r=e.filter((i)=>!Sv(i)),n=e.filter((i)=>Sv(i));if(n.length>0)m("hosts",`Skipping /etc/hosts for loopback dev names: ${n.join(", ")}`,t);if(r.length===0)return;m("hosts",`Adding hosts: ${r.join(", ")}`,t),m("hosts",`Using hosts file at: ${hr}`,t);try{let i;try{i=await rd(t)}catch(l){throw console.log(" Could not read hosts file — skipping hosts setup"),m("hosts",`sudo read also failed: ${l}`,t),Error(`Cannot read hosts file: ${l}`)}let s=i.split(`
345
+ `),o=r.filter((l)=>!s.some((u)=>Av(u,l)));if(o.length===0){m("hosts","All hosts already exist in hosts file",t);return}let c=Zr.pid,a=o.map((l)=>`
346
+ 127.0.0.1 ${l} ${Ev}:pid=${c}
347
+ ::1 ${l} ${Ev}:pid=${c}`).join(`
348
+ `);try{await nd(i+a,t),console.log(` Hosts updated: ${o.join(", ")}`)}catch(l){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),o.forEach((u)=>{console.log(` 127.0.0.1 ${u}`),console.log(` ::1 ${u}`)}),console.log(` Or run: sudo nano ${hr}`)}}catch(i){m("hosts",`Failed to manage hosts file: ${i.message}`,t)}}async function Rv(e,t){m("hosts",`Removing hosts: ${e.join(", ")}`,t);try{let r;try{r=await rd(t)}catch(s){throw m("hosts",`sudo read also failed: ${s}`,t),Error(`Cannot read hosts file: ${s}`)}let{content:n,removed:i}=zR(r,e);if(i.length===0){m("hosts","No matching rpx-managed hosts found to remove",t);return}try{await nd(n,t),m("hosts",`Hosts removed successfully: ${i.join(", ")}`,t)}catch(s){m("hosts","Could not clean up hosts file automatically",t)}}catch(r){m("hosts",`Failed to clean up hosts file: ${r.message}`,t)}}async function Ss(e,t){m("hosts",`Checking hosts: ${e}`,t);let r;try{r=await Rc.promises.readFile(hr,"utf-8")}catch(i){m("hosts",`Error reading hosts file: ${i}`,t);try{let s=Er(),o;if(s)o=`echo '${s}' | sudo -S cat "${hr}" 2>/dev/null`;else o=`sudo -n cat "${hr}" 2>/dev/null || cat "${hr}" 2>/dev/null || echo ""`;let{stdout:c}=await Cs(o);r=c}catch(s){return m("hosts",`Cannot read hosts file, assuming entries don't exist: ${s}`,t),e.map(()=>!1)}}let n=r.split(`
349
+ `);return e.map((i)=>n.some((s)=>Av(s,i)))}async function Es(e={}){let t=e.isAlive??mt,r;try{r=await rd(e.verbose)}catch(o){return m("hosts",`stale hosts GC: cannot read hosts file: ${o}`,e.verbose),[]}let{content:n,removed:i,stalePids:s}=GR(r,t);if(i.length===0)return[];try{return await nd(n,e.verbose),m("hosts",`stale hosts GC: removed ${i.join(", ")} (dead pid(s): ${s.join(", ")})`,e.verbose),[...new Set(i)]}catch(o){return m("hosts",`stale hosts GC: write failed: ${o}`,e.verbose),[]}}var Cs,hr,Ev="# rpx",HR="# Added by rpx",kc,td=!1;var id=te(()=>{Xr();fe();Cs=VR(KR);hr=Zr.platform==="win32"?Tv.join(Zr.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",kc=new Set(["127.0.0.1","::1"])});import*as Fr from"node:fs/promises";import{homedir as qR}from"node:os";import*as sd from"node:path";function Ov(){return sd.join(qR(),".stacks","rpx")}function od(e=Ov()){return sd.join(e,YR)}async function Dc(e=Ov()){try{let t=await Fr.readFile(od(e),"utf8"),r=JSON.parse(t);if(r.version!==Nc||!Array.isArray(r.resolvers))return null;return{version:Nc,resolvers:r.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(r.domains)?r.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Nv(e,t){await Fr.mkdir(e,{recursive:!0}),await Fr.writeFile(od(e),`${JSON.stringify(t,null,2)}
350
+ `,"utf8")}async function ad(e){await Fr.rm(od(e),{force:!0})}function Dv(e){let t=e.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function XR(e){let t=Dv(e);if(!t)return null;let r=t.split(".");if(r.length<2)return null;let n=r[r.length-1];if(JR.has(n))return r.slice(-2).join(".");return t}function cd(e){let t=new Set;for(let r of e){let n=XR(r);if(n)t.add(n)}return Array.from(t).sort()}function ld(e){let t=new Set;for(let r of e){let n=Dv(r);if(n)t.add(n)}return Array.from(t).sort()}var Nc=1,YR="dns-state.json",kv,JR;var Fv=te(()=>{kv=["com","test","dev","app","page","local","localhost","example","invalid"];JR=new Set(["test","localhost","local","example","invalid","internal","home","lan"])});var Lc={};nl(Lc,{DNS_PORT:()=>Ps,RPX_RESOLVER_MARKER:()=>Mv,contentLooksLikeRpxResolver:()=>Vv,isDnsServerRunning:()=>tk,isRpxDevelopmentDnsAnswering:()=>Wv,reconcileStaleDevelopmentDns:()=>en,removeLegacyTldResolvers:()=>dd,removeResolver:()=>lk,resolverFilePath:()=>li,setupDevelopmentDns:()=>md,setupResolver:()=>ak,startDnsServer:()=>Kv,stopDnsServer:()=>ud,syncDevelopmentDnsFromRegistry:()=>ui,tearDownDevelopmentDns:()=>Qr});import Lv from"node:dgram";import*as Bv from"node:fs/promises";import*as Iv from"node:path";import*as dr from"node:process";function jv(e){return{id:e.readUInt16BE(0),flags:e.readUInt16BE(2),qdcount:e.readUInt16BE(4),ancount:e.readUInt16BE(6),nscount:e.readUInt16BE(8),arcount:e.readUInt16BE(10)}}function Uv(e,t,r=0){let n=[],i=t,s=0;while(!0){if(i>=e.length||++s>128)break;let o=e[i];if(o===0){i++;break}if((o&192)===192){if(i+1>=e.length||r>=10)break;let c=e.readUInt16BE(i)&16383,{name:a}=Uv(e,c,r+1);if(a)n.push(a);i+=2;break}if(i++,i+o>e.length)break;n.push(e.subarray(i,i+o).toString("ascii")),i+=o}return{name:n.join("."),newOffset:i}}function ZR(e,t){let{name:r,newOffset:n}=Uv(e,t),i=e.readUInt16BE(n),s=e.readUInt16BE(n+2);return{question:{name:r,type:i,class:s},newOffset:n+4}}function Ts(e){let t=e.split("."),r=[];for(let n of t)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function QR(e,t,r){let n=[],i=Buffer.alloc(12);i.writeUInt16BE(e,0),i.writeUInt16BE(33152,2),i.writeUInt16BE(1,4),i.writeUInt16BE(1,6),i.writeUInt16BE(0,8),i.writeUInt16BE(0,10),n.push(i),n.push(Ts(t.name));let s=Buffer.alloc(4);s.writeUInt16BE(t.type,0),s.writeUInt16BE(t.class,2),n.push(s),n.push(Ts(t.name));let o=Buffer.alloc(10);if(o.writeUInt16BE(t.type,0),o.writeUInt16BE(1,2),o.writeUInt32BE(300,4),t.type===1){o.writeUInt16BE(4,8),n.push(o);let c=r.split(".").map((a)=>Number.parseInt(a,10));n.push(Buffer.from(c))}else if(t.type===28)o.writeUInt16BE(16,8),n.push(o),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return i.writeUInt16BE(33155,2),i.writeUInt16BE(0,6),Buffer.concat([i,Ts(t.name),s]);return Buffer.concat(n)}function ek(e,t){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(e,0),n.writeUInt16BE(33155,2),n.writeUInt16BE(1,4),n.writeUInt16BE(0,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),r.push(n),r.push(Ts(t.name));let i=Buffer.alloc(4);return i.writeUInt16BE(t.type,0),i.writeUInt16BE(t.class,2),r.push(i),Buffer.concat(r)}async function Kv(e,t){if(dr.platform!=="darwin")return!1;let r=ld(e);if(r.length===0)return!1;if(st){for(let n of r)Fc.add(n);return m("dns","DNS server already running — merged domains",t),!0}return Fc=new Set(r),new Promise((n)=>{st=Lv.createSocket("udp4"),st.on("error",(i)=>{m("dns",`DNS server error: ${i.message}`,t),st?.close(),st=null,n(!1)}),st.on("message",(i,s)=>{try{let o=jv(i),{question:c}=ZR(i,12);m("dns",`Query for ${c.name} type ${c.type} from ${s.address}`,t);let a=c.name.toLowerCase(),l=!1;for(let f of Fc)if(a===f||a.endsWith(`.${f}`)){l=!0;break}let u;if(l&&(c.type===1||c.type===28))u=QR(o.id,c,"127.0.0.1"),m("dns",`Responding with localhost for ${c.name}`,t);else u=ek(o.id,c),m("dns",`NXDOMAIN for ${c.name}`,t);st?.send(u,s.port,s.address)}catch(o){m("dns",`Error processing DNS query: ${o}`,t)}}),st.on("listening",()=>{let i=st?.address();m("dns",`DNS server listening on ${i?.address}:${i?.port}`,t),n(!0)});try{st.bind(Ps,"127.0.0.1")}catch(i){m("dns",`Failed to bind DNS server: ${i}`,t),n(!1)}})}function ud(e){if(st)m("dns","Stopping DNS server",e),st.close(),st=null,Fc=new Set}function tk(){return st!==null}async function Wv(e,t=500){let r=e.trim().toLowerCase().replace(/\.$/,"");if(!r)return!1;return new Promise((n)=>{let i=Lv.createSocket("udp4"),s=setTimeout(()=>{i.close(),n(!1)},t);i.on("message",(c)=>{clearTimeout(s),i.close();try{let a=jv(c);n(a.ancount>0)}catch{n(!1)}}),i.on("error",()=>{clearTimeout(s),i.close(),n(!1)});let o=rk(r,1);i.send(o,Ps,"127.0.0.1",(c)=>{if(c)clearTimeout(s),i.close(),n(!1)})})}function rk(e,t){let r=Buffer.alloc(12);r.writeUInt16BE(1,0),r.writeUInt16BE(256,2),r.writeUInt16BE(1,4);let n=Buffer.concat([Ts(e),Buffer.from([0,t,0,1])]);return Buffer.concat([r,n])}function nk(){return`${Mv}
292
351
  nameserver 127.0.0.1
293
- port ${cY}
294
- `}function c1(w){return j6.join(z6,w)}function F6(w){return w.includes("127.0.0.1")&&w.includes(String(cY))}async function ER(w){try{return await W6.readFile(c1(w),"utf8")}catch($){if($.code==="ENOENT")return null;throw $}}async function uj(w){if(X$.platform!=="darwin")return;let{execSudoSync:$,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),Z1));if(!A()&&!Y()){K("dns","Cannot flush DNS cache without SUDO_PASSWORD",w);return}try{$("dscacheutil -flushcache"),$("killall -HUP mDNSResponder 2>/dev/null || true"),K("dns","DNS cache flushed",w)}catch(X){K("dns",`Could not flush DNS cache: ${X}`,w)}}function E6(w){if(!/^[a-z0-9.-]+$/.test(w))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(w)}`)}async function TR(w,$){E6(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (f0(),Z1)),A=FR().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${z6} && printf "%b" "${A}" > ${c1(w)}'`;Y(X),K("dns",`Created ${c1(w)}`,$)}async function NR(w,$){E6(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (f0(),Z1));Y(`rm -f ${c1(w)}`),K("dns",`Removed ${c1(w)}`,$)}async function qR(w,$){return mj({domains:$??[],verbose:w})}async function HR(w,$){if(X$.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),Z1));if(!A()&&!Y())return K("dns","SUDO_PASSWORD not set, cannot create resolver files",$),!1;try{for(let X of w)await TR(X,$);return await uj($),!0}catch(X){return K("dns",`Failed to create resolver file: ${X}`,$),!1}}async function vj(w,$){if(X$.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),Z1));if(!A()&&!Y())return;try{for(let X of w)await NR(X,$);await uj($)}catch(X){K("dns",`Failed to remove resolver files: ${X}`,$)}}async function cj(w){if(X$.platform!=="darwin")return[];let $=[];for(let Y of $6){let A=await ER(Y);if(A&&F6(A))await vj([Y],w),$.push(Y)}return $}async function mj(w){let $=w.rpxDir??V0(),Y=ij(w.domains);if(Y.length===0)return!1;let A=Pj(Y),X=await G6(Y,w.verbose);if(!X){let j=Y[0];if(j&&await K6(j))X=!0;else K("dns","Dev DNS server not available on 127.0.0.1:15353",w.verbose)}if(!X)return!1;if(!await HR(A,w.verbose))return!1;let U={version:k8,resolvers:A,domains:Y,ownerPid:w.ownerPid??X$.pid,updatedAt:new Date().toISOString()};return await A6($,U),!0}async function m1(w,$={}){let Y=w.map((W)=>W.to).filter(Boolean),A=$.rpxDir??V0(),X=Pj(Y),j=((await Z8(A))?.resolvers??[]).filter((W)=>!X.includes(W));if(j.length>0)await vj(j,$.verbose);if(X.length===0){bj($.verbose),await Zj(A);return}await mj({domains:Y,rpxDir:A,verbose:$.verbose,ownerPid:$.ownerPid??X$.pid})}async function d$(w={}){let $=w.rpxDir??V0();bj(w.verbose);let A=(await Z8($))?.resolvers??[];await vj(A,w.verbose),await cj(w.verbose),await Zj($)}async function RR(w){await d$({verbose:w})}async function n$(w={}){let $=w.rpxDir??V0(),Y=await Z8($),A=Y?.ownerPid!=null&&Jw(Y.ownerPid);if(Y&&!A){K("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,w.verbose),await d$(w);return}let X=await cj(w.verbose);if(X.length>0)K("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,w.verbose);await uj(w.verbose)}var cY=15353,Q6="# managed-by: rpx",z6="/etc/resolver",s0=null,P8;var mY=s(()=>{b8();J6();m$();f0();P8=new Set});import{spawn as H6}from"node:child_process";import*as b0 from"node:fs/promises";import{homedir as R6}from"node:os";import*as _w from"node:path";import*as y from"node:process";function V0(){return _w.join(R6(),".stacks","rpx")}function L$(w=V0()){return _w.join(w,"daemon.pid")}async function V$(w=V0()){try{let $=await b0.readFile(L$(w),"utf8"),Y=Number.parseInt($.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch($){if($.code==="ENOENT")return null;throw $}}async function m8(w=V0()){let $=await V$(w);return $!==null&&Jw($)}async function M6(w=V0()){await b0.mkdir(w,{recursive:!0});let $=L$(w);while(!0){try{let A=await b0.open($,"wx");try{await A.write(`${y.pid}
295
- `)}finally{await A.close()}return $}catch(A){if(A.code!=="EEXIST")throw A}let Y=await V$(w);if(Y!==null&&Jw(Y))throw Error(`rpx daemon already running (pid=${Y})`);await b0.unlink($).catch(()=>{})}}async function g1(w=V0()){await b0.unlink(L$(w)).catch(()=>{})}function c8(w){for(let[$,Y]of v8)if(!w.has($))i1(Y),v8.delete($)}function IR(w,$){let Y=E2($??"localhost:1");if(w.upstreams.length!==Y.length)return!1;return w.upstreams.every((A,X)=>A.url===Y[X])}function I6(w){let $=w.cleanUrls??!1,Y=Y$(w.path),A=CY(w.auth);if(w.static)return{static:R8(w.static,$),cleanUrls:$,basePath:Y,auth:A};let X=w.from??"localhost:1",J=b$(X),U=new URL(J.startsWith("http")?J:`http://${J}`),j=v8.get(w.id);if(j&&!IR(j,X))i1(j),j=void 0;if(!j)j=RY(X,w.loadBalancer),IY(j),v8.set(w.id,j);return{sourceHost:U.host,upstreamPool:j,cleanUrls:$,changeOrigin:w.changeOrigin??!1,pathRewrites:w.pathRewrites,basePath:Y,auth:A}}function yR(w){return w.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??w[0]??"rpx.localhost"}async function u8(w,$,Y=[],A=!1){let X=await Tw($,w.verbose),J=[...new Set([...X.map((z)=>z.to).filter(Boolean),...Y])],U=yR(J),j=[...new Set([U,...J,"rpx.localhost"])],W=f2(J,U,w.verbose);if(typeof w.https==="object"&&typeof W.https==="object")W.https={...W.https,...w.https};let Q=await M$(W);if(Q&&(A||!NW(fj,j)))K("daemon",`regenerating shared cert for host(s): ${j.join(", ")}`,w.verbose),Bj(),Q=null;if(!Q)K("daemon","no usable cert on disk, generating one via tlsx",w.verbose),await qY({...W,forceRegenerate:!0}),Q=await M$(W);if(!Q)throw Error("failed to bootstrap TLS for rpx daemon");return Q}async function CR(w,$,Y,A){let X=y.env.SUDO_PASSWORD,J=y.env.HOME??R6(),U=[y.execPath,...y.argv.slice(1)],j=[`HOME=${J}`,`PATH=${y.env.PATH??""}`];if(A)j.push("RPX_VERBOSE=1");for(let[T,F]of Object.entries(y.env))if(F!==void 0&&T!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(T))j.push(`${T}=${F}`);let W=X?["-S","-p","","env",...j,...U]:["-n","env",...j,...U];K("daemon",`elevating daemon via sudo for privileged ports ${$}/${Y}`,A);let Q=H6("sudo",W,{detached:!0,stdio:["pipe","ignore","ignore"]}),z=null,f=null;if(Q.once("error",(T)=>{z=T}),Q.once("exit",(T)=>{f=T??0}),X&&Q.stdin)Q.stdin.write(`${X}
296
- `),Q.stdin.end();Q.unref();let B=L$(w),G=Date.now()+15000;while(Date.now()<G){if(z)throw z;let T=await V$(w);if(T!==null&&Jw(T)){if(A)H.success(`rpx daemon elevated to root (pid=${T}, https on :${$})`);return{httpsPort:$,httpPort:Y,pidPath:B,done:Promise.resolve(),stop:async()=>{try{y.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(f!==null&&f!==0)throw Error(`rpx daemon could not elevate to bind :${$} (sudo exited ${f}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((F)=>setTimeout(F,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${w})`)}function gj(){if(T6)return;T6=!0,y.on("uncaughtException",(w)=>{H.error(`rpx daemon: uncaught exception (continuing): ${w?.stack??w}`)}),y.on("unhandledRejection",(w)=>{H.error(`rpx daemon: unhandled rejection (continuing): ${w}`)})}function y6(w,$,Y){let A;try{A=new URL(w.url)}catch{return new Response("Bad Request",{status:400})}let X=(w.headers.get("host")??A.hostname).split(":")[0];if(A.pathname.startsWith("/.well-known/acme-challenge/")){if($){let J=$.challengeStore.handlePath(A.pathname);if(J!==void 0)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if(Y){let J=I8(Y,A.pathname);if(J!=null)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if($)return new Response("challenge not found",{status:404})}if($&&!$.hasCert(X))$.ensureCert(X).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${X}${A.pathname}${A.search}`}})}async function C6(w={}){gj();let $=w.verbose??!1,Y=w.rpxDir??V0(),A=w.registryDir??_w.join(Y,"registry.d"),X=w.httpsPort??443,J=w.httpPort??80,U=w.hostname??"::",j=w.hostname==null,W=w.gcIntervalMs??MR;if(y.env.RPX_DAEMON_WORKER==="1")return OR({rpxDir:y.env.RPX_WORKER_RPXDIR??Y,registryDir:y.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(y.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:y.env.RPX_WORKER_HOSTNAME??U,verbose:y.env.RPX_WORKER_VERBOSE==="1"||$});let Q=X>0&&X<1024||J>0&&J<1024,z=typeof y.getuid==="function"&&y.getuid()===0;if(y.platform!=="win32"&&Q&&!z)return CR(Y,X,J,$);let f=Math.max(1,w.workers??(Number.parseInt(y.env.RPX_WORKERS??"",10)||1));if(f>1){if(w.onDemandSites?.enabled)H.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return SR(w,{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:$,gcIntervalMs:W,workers:f})}let B=await M6(Y),G=new Map,T=(I,h)=>_Y(G,I,h);function F(I){G=SY(I.map((o0)=>({host:o0.to,path:o0.path,route:I6(o0)}))),c8(new Set(I.map((o0)=>o0.id)));let h=Array.from(G.keys());K("daemon",`routing table now covers ${h.length} host(s): ${h.join(", ")||"<empty>"}`,$)}await kY(A,$).catch((I)=>{K("daemon",`initial gc failed: ${I}`,$)}),await uY({verbose:$}).catch((I)=>{K("daemon",`stale hosts GC on start failed: ${I}`,$)});let E=await Tw(A,$);F(E),await n$({rpxDir:Y,verbose:$}).catch((I)=>{K("daemon",`DNS reconcile on start failed: ${I}`,$)}),await m1(E,{rpxDir:Y,verbose:$,ownerPid:y.pid}).catch((I)=>{K("daemon",`DNS setup on start failed: ${I}`,$)});let N=[];if(w.productionCerts){if(N=await DY(w.productionCerts,$),$&&N.length>0)H.info(`SNI: serving ${N.length} real cert(s): ${N.map((I)=>I.serverName).join(", ")}`)}let R=new Set,V=null,L;if(w.onDemandSites?.enabled){if(V=new Oj({resolver:jU(w.onDemandSites),registryDir:A,rpxDir:Y,verbose:$,startupTimeoutMs:w.onDemandSites.startupTimeoutMs,isHostRoutable:(I)=>Nj(G,I)!==void 0,onSiteActivating:(I)=>{pY(I)}}),L=async(I)=>{let h=await V.onRequest(I);switch(h.kind){case"ready":return{retry:!0};case"starting":return p2({host:h.host,sinceMs:h.sinceMs,logTail:h.logTail});case"failed":return r2({host:h.host,error:h.error,logTail:h.logTail});case"unknown":default:return}},$)H.info("rpx: on-demand sites enabled")}let q=LY(T,$,L),C=OY($),M=null;if(N.length===0)M=await u8(w,A);let D=w.onDemandTls,n=D?.enabled?new b1({config:D,certsDir:D.certsDir??w.productionCerts?.certsDir??_w.join(Y,"on-demand-certs"),initial:N,verbose:$,onCertAdded:(I)=>{if(xY()==="restart")K("on-demand","certificate installed; restarting supervised gateway to reload TLS",$),setTimeout(()=>y.kill(y.pid,"SIGTERM"),10).unref();else _(I)}}):null;function a0(I){if(I.length>0)return v$(I.map((h)=>({serverName:h.serverName,cert:h.cert,key:h.key})));return v$({key:M.key,cert:M.cert,ca:M.ca,requestCert:!1,rejectUnauthorized:!1})}function Uw(I){try{return Bun.serve(I)}catch(h){let o0=h instanceof Error?h.message:String(h),l1=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test(o0);if(!j||I.hostname!=="::"||!l1)throw h;return K("daemon",`no IPv6 on this host (${o0}); binding 0.0.0.0`,w.verbose),Bun.serve({...I,hostname:"0.0.0.0"})}}function l$(I){return Uw({port:X,hostname:U,reusePort:TY(),tls:a0(I),fetch(h,o0){return q(h,o0)},websocket:C,error(h){return K("daemon",`https server error: ${h}`,$),new Response(`Server Error: ${h.message}`,{status:500})}})}let d1=(I)=>[...new Set(I.map((h)=>h.to).filter(Boolean))],J$=(I)=>{if(!M)return N;return z2([...d1(I),...R,"rpx.localhost"],M)},i0=l$(n?n.sniEntries():N.length>0?N:J$(E)),Ww=null,v0=!1;async function _(I){if(Ow)return;if(Ww=I,v0)return;v0=!0;try{while(!Ow&&Ww){let h=Ww;Ww=null,K("daemon",`rebuilding :443 with ${h.length} SNI cert(s)`,$),i0.stop(!1);let o0,l1=!1,oj=60,m6=500;for(let XJ=0;!Ow&&!l1;XJ++)try{i0=l$(h),l1=!0;break}catch(g6){if(o0=g6,XJ>=oj)break;await new Promise((d6)=>setTimeout(d6,Math.min(25*2**Math.min(XJ,4),m6)))}if(!l1)H.error(`rpx: CRITICAL — could not rebind :443 after ${oj} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${o0?.message}`)}}finally{v0=!1}}let c0=null;if(J>0)c0=Uw({port:J,hostname:U,fetch(I){return y6(I,n,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if($)H.success(`rpx daemon listening on https://${U}:${X}${c0?` (http→https on :${J})`:""}`),H.info(`pid file: ${B}`),H.info(`registry: ${A}`);async function n1(I){if(Ow||N.length>0||n||!M)return;try{M=await u8(w,A,[...R]),await _(J$(I))}catch(h){K("daemon",`TLS sync on registry change failed: ${h}`,$)}}async function pY(I){if(Ow||N.length>0||n||!M||!I)return;if(R.has(I))return;R.add(I);try{M=await u8(w,A,[...R],!0);let h=await Tw(A,$);await _(J$(h))}catch(h){K("daemon",`dev cert refresh for ${I} failed: ${h}`,$)}}let rY=_8((I)=>{F(I),n1(I),m1(I,{rpxDir:Y,verbose:$,ownerPid:y.pid}).catch((h)=>{K("daemon",`DNS sync on registry change failed: ${h}`,$)})},{dir:A,verbose:$}),p$=setInterval(()=>{kY(A,$).then((I)=>{if(I>0)K("daemon",`gc reaped ${I} stale entries`,$)}).catch((I)=>{K("daemon",`periodic gc failed: ${I}`,$)}),uY({verbose:$}).then((I)=>{if(I.length>0)K("daemon",`gc reaped stale hosts entries: ${I.join(", ")}`,$)}).catch((I)=>{K("daemon",`periodic hosts gc failed: ${I}`,$)})},W);if(typeof p$.unref==="function")p$.unref();let Ow=!1,YJ,AJ=new Promise((I)=>{YJ=I});async function aj(){if(Ow)return AJ;if(Ow=!0,clearInterval(p$),rY.close(),await V?.stopAll().catch((I)=>{K("daemon",`site supervisor stopAll failed: ${I}`,$)}),i0.stop(!1),c0?.stop(!1),await d$({rpxDir:Y,verbose:$}).catch((I)=>{K("daemon",`DNS teardown failed: ${I}`,$)}),c8(new Set),await g1(Y),$)H.info("rpx daemon stopped");return YJ(),AJ}let sj=(I)=>{K("daemon",`received ${I}, shutting down`,$),aj().catch(()=>{})};return y.once("SIGINT",sj),y.once("SIGTERM",sj),{stop:aj,done:AJ,httpsPort:typeof i0.port==="number"?i0.port:X,httpPort:c0&&typeof c0.port==="number"?c0.port:J,pidPath:B,ensureCert:(I)=>n?n.ensureCert(I):Promise.resolve(!1),listSites:()=>V?.list()??[]}}function dj(w){return _w.join(w,"cluster-sni.json")}async function N6(w,$,Y){let A=dj(w),X=`${A}.${y.pid}.tmp`;await b0.writeFile(X,JSON.stringify({sni:$,dev:Y}),"utf8"),await b0.rename(X,A)}async function q6(w){try{return JSON.parse(await b0.readFile(dj(w),"utf8"))}catch{return{sni:[],dev:null}}}function VR(w){if(w.sni.length>0)return v$(w.sni.map(($)=>({serverName:$.serverName,cert:$.cert,key:$.key})));if(w.dev)return v$({key:w.dev.key,cert:w.dev.cert,ca:w.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function LR(){let w=y.execPath,$=y.env.RPX_WORKER_BIN;if($)return[w,$,"daemon:start"];let Y=_w.basename(w).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&y.argv[1])return[w,y.argv[1],"daemon:start"];return[w,"daemon:start"]}async function OR(w){gj();let{rpxDir:$,registryDir:Y,httpsPort:A,hostname:X,verbose:J}=w,U=new Map,j=(C,M)=>_Y(U,C,M),W=(C)=>{U=SY(C.map((M)=>({host:M.to,path:M.path,route:I6(M)}))),c8(new Set(C.map((M)=>M.id)))};W(await Tw(Y,J));let Q=LY(j,J),z=OY(J),f=!1,B=(C)=>Bun.serve({port:A,hostname:X,reusePort:!0,tls:VR(C),fetch(M,D){return Q(M,D)},websocket:z,error(M){return K("daemon",`worker https error: ${M}`,J),new Response(`Server Error: ${M.message}`,{status:500})}}),G=B(await q6($));async function T(){if(f)return;let C=await q6($),M=null;for(let n=0;n<20&&!f;n++)try{M=B(C);break}catch{await new Promise((a0)=>setTimeout(a0,25))}if(!M){K("daemon","worker reloadTls: could not bind new listener; keeping current",J);return}let D=G;G=M,D.stop(!1)}let F=_8((C)=>W(C),{dir:Y,verbose:J}),E=()=>{T().catch(()=>{})};y.on("SIGHUP",E);let N=()=>{let C=y.removeListener??y.off;if(typeof C==="function")C.call(y,"SIGHUP",E)},R,V=new Promise((C)=>{R=C});async function L(){if(f)return V;return f=!0,N(),F.close(),G.stop(!1),c8(new Set),R(),V}let q=()=>{L().then(()=>y.exit(0)).catch(()=>y.exit(0))};if(y.once("SIGTERM",q),y.once("SIGINT",q),J)H.success(`rpx worker (pid ${y.pid}) serving :${A}`);return{stop:L,done:V,httpsPort:typeof G.port==="number"?G.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function SR(w,$){gj();let{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:j,gcIntervalMs:W,workers:Q}=$,z=await M6(Y),f=[];if(w.productionCerts)f=await DY(w.productionCerts,j);let B=null;if(f.length===0)B=await u8(w,A);let G=B?{key:B.key,cert:B.cert,ca:Array.isArray(B.ca)?B.ca.join(`
297
- `):B.ca}:null,T=!1,F=[];function E(_){for(let c0 of F)try{c0.kill(_)}catch{}}async function N(_){await N6(Y,_,G),E("SIGHUP")}let R=w.onDemandTls,V=R?.enabled?new b1({config:R,certsDir:R.certsDir??w.productionCerts?.certsDir??_w.join(Y,"on-demand-certs"),initial:f,verbose:j,onCertAdded:(_)=>{if(xY()==="restart")K("on-demand","certificate installed; restarting supervised gateway to reload TLS",j),setTimeout(()=>y.kill(y.pid,"SIGTERM"),10).unref();else N(_)}}):null;await N6(Y,V?V.sniEntries():f,G);let L=await Tw(A,j);await n$({rpxDir:Y,verbose:j}).catch((_)=>{K("daemon",`DNS reconcile on start failed: ${_}`,j)}),await m1(L,{rpxDir:Y,verbose:j,ownerPid:y.pid}).catch((_)=>{K("daemon",`DNS setup on start failed: ${_}`,j)}),await kY(A,j).catch(()=>{}),await uY({verbose:j}).catch(()=>{});let q=_8((_)=>{m1(_,{rpxDir:Y,verbose:j,ownerPid:y.pid}).catch((c0)=>{K("daemon",`DNS sync on registry change failed: ${c0}`,j)})},{dir:A,verbose:j}),C=setInterval(()=>{kY(A,j).catch(()=>{}),uY({verbose:j}).catch(()=>{})},W);C.unref?.();let M=null;if(J>0)M=Bun.serve({port:J,hostname:U,fetch(_){return y6(_,V,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let D=10,n=60000,a0=30000,Uw=0,l$=Date.now();function d1(){if(T)return;let _={...y.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:j?"1":"0"},c0=Bun.spawn(LR(),{env:_,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(n1,pY){if(T)return;let rY=F.indexOf(n1);if(rY!==-1)F.splice(rY,1);let p$=Date.now();if(p$-l$>n)l$=p$,Uw=0;if(Uw++,Uw>D){H.error(`rpx: worker keeps exiting (code ${pY}); giving up after ${D} restarts in ${Math.round(n/1000)}s`);return}let Ow=Math.min(a0,100*2**Math.min(Uw,8));K("daemon",`worker exited (code ${pY}); respawning in ${Ow}ms (restart ${Uw}/${D})`,j),setTimeout(d1,Ow).unref?.()}});F.push(c0)}for(let _=0;_<Q;_++)d1();if(j)H.success(`rpx coordinator listening on https://${U}:${X} via ${Q} worker(s)${M?` (http→https on :${J})`:""}`),H.info(`pid file: ${z}`);let J$,i0=new Promise((_)=>{J$=_});async function Ww(){if(T)return i0;if(T=!0,clearInterval(C),q.close(),M?.stop(!1),E("SIGTERM"),await Promise.race([Promise.all(F.map((_)=>_.exited)),new Promise((_)=>setTimeout(_,3000))]),E("SIGKILL"),await d$({rpxDir:Y,verbose:j}).catch((_)=>{K("daemon",`DNS teardown failed: ${_}`,j)}),await g1(Y),await b0.unlink(dj(Y)).catch(()=>{}),j)H.info("rpx coordinator stopped");return J$(),i0}let v0=(_)=>{K("daemon",`coordinator received ${_}, shutting down`,j),Ww().catch(()=>{})};return y.once("SIGINT",v0),y.once("SIGTERM",v0),{stop:Ww,done:i0,httpsPort:X,httpPort:J,pidPath:z,ensureCert:(_)=>V?V.ensureCert(_):Promise.resolve(!1),listSites:()=>[]}}function _R(){let w=y.execPath,$=_w.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&y.argv[1])return[w,y.argv[1],"daemon:start"];return[w,"daemon:start"]}async function g8(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1;await n$({rpxDir:$,verbose:Y}).catch((z)=>{K("daemon",`DNS reconcile before ensureDaemonRunning: ${z}`,Y)});let A=await V$($);if(A!==null&&Jw(A))return K("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)K("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await g1($);await b0.mkdir($,{recursive:!0});let X=w.spawnCommand??_R();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");K("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=H6(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??y.cwd(),env:w.spawnEnv?{...y.env,...w.spawnEnv}:y.env});J.unref();let U=null;J.once("error",(z)=>{U=z});let j=w.startupTimeoutMs??5000,W=w.pollIntervalMs??50,Q=Date.now()+j;while(Date.now()<Q){if(U)throw U;let z=await V$($);if(z!==null&&Jw(z))return K("daemon",`daemon registered with pid=${z}`,Y),{pid:z,spawned:!0};await new Promise((f)=>setTimeout(f,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${j}ms (rpxDir=${$})`)}async function V6(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1,A=w.timeoutMs??5000,X=w.pollIntervalMs??50,J=w.forceAfterTimeout??!0,U=await V$($);if(U===null||!Jw(U)){if(U!==null)await g1($);return await n$({rpxDir:$,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{y.kill(U,"SIGTERM")}catch(W){let Q=W.code;if(Q==="ESRCH")return await g1($),{stopped:!1,pid:U,forced:!1};if(Q==="EPERM")T$(`kill -TERM ${U}`);else throw W}let j=Date.now()+A;while(Date.now()<j){if(!Jw(U))return K("daemon",`daemon pid=${U} stopped cleanly`,Y),{stopped:!0,pid:U,forced:!1};await new Promise((W)=>setTimeout(W,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${A}ms`);K("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{y.kill(U,"SIGKILL")}catch(W){let Q=W.code;if(Q==="EPERM")T$(`kill -KILL ${U}`);else if(Q!=="ESRCH")throw W}return await g1($),await d$({rpxDir:$,verbose:Y}).catch((W)=>{K("daemon",`DNS teardown after SIGKILL: ${W}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function L6(w={}){let $=w.rpxDir??V0();if(await m8($))return;await n$({rpxDir:$,verbose:w.verbose})}var MR=5000,v8,T6=!1;var b8=s(()=>{D$();Gj();Ej();Tj();y8();Hj();Rj();QU();n2();M8();N8();m$();Dj();mY();f0();v8=new Map});import{dirname as dR,join as nR}from"node:path";import*as P0 from"node:process";import{fileURLToPath as lR}from"node:url";import{existsSync as t6}from"node:fs";import JJ from"node:fs/promises";import wQ from"node:os";import UJ from"node:path";import O$ from"node:process";import{EventEmitter as a6}from"node:events";import U$ from"node:process";import $Q from"node:process";import zJ from"node:process";import sY from"node:process";import t1 from"node:process";import XQ from"node:tty";import iG,{stdin as BM,stdout as GM}from"node:process";import UQ,{stdin as vG,stdout as cG}from"node:process";import mG from"node:readline";class jQ{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let w=wQ.homedir(),$=UJ.join(w,".config","clapp");this.configPath=UJ.join($,"telemetry.json")}async isEnabled(){if(O$.env.DO_NOT_TRACK==="1"||O$.env.DO_NOT_TRACK==="true")return!1;if(O$.env.NO_TELEMETRY==="1"||O$.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let w=await this.loadConfig();if(w.enabled=!0,!w.userId)w.userId=this.generateUserId();await this.saveConfig(w)}async disable(){let w=await this.loadConfig();w.enabled=!1,await this.saveConfig(w)}async track(w,$){if(!await this.isEnabled())return;let A={event:w,...$,timestamp:Date.now(),platform:wQ.platform(),nodeVersion:O$.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand(w,$){await this.track("command",{command:w,duration:$})}async trackError(w,$){await this.track("error",{error:w,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(w){return new Promise(($)=>setTimeout($,w))}async status(){let w=await this.loadConfig();return{enabled:w.enabled,doNotTrack:O$.env.DO_NOT_TRACK==="1"||O$.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:w.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(t6(this.configPath)){let w=await JJ.readFile(this.configPath,"utf-8");return this.config=JSON.parse(w),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(w){this.config=w;try{let $=UJ.dirname(this.configPath);await JJ.mkdir($,{recursive:!0}),await JJ.writeFile(this.configPath,JSON.stringify(w,null,2),"utf-8")}catch{}}generateUserId(){let w=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${w}-${$}`}}var wM=new jQ;function s6(w,$={}){let Y={_:[]},A=$.alias||{},X=new Set($.boolean||[]),J={};for(let j of Object.keys(A))for(let W of A[j])J[W]=j;for(let j of X)if(A[j])for(let W of A[j])X.add(W);function U(j,W){let Q=J[j]||j;if(Y[Q]=W,A[Q])for(let z of A[Q])Y[z]=W;if(J[j]&&A[J[j]])for(let z of A[J[j]])Y[z]=W;Y[j]=W}for(let j=0;j<w.length;j++){let W=w[j];if(W==="--"){Y._.push(...w.slice(j+1));break}if(W.startsWith("--")){let Q=W.indexOf("=");if(Q!==-1){let z=W.slice(2,Q),f=W.slice(Q+1);U(z,f)}else{let z=W.slice(2);if(z.startsWith("no-")){let B=z.slice(3);U(B,!1);continue}let f=J[z]||z;if(X.has(f)||X.has(z))U(z,!0);else{let B=w[j+1];if(B!==void 0&&!B.startsWith("-"))U(z,B),j++;else U(z,!0)}}}else if(W.startsWith("-")&&W.length>1){let Q=W.slice(1);for(let z=0;z<Q.length;z++){let f=Q[z],B=J[f]||f;if(z===Q.length-1&&!X.has(B)&&!X.has(f)){let G=w[j+1];if(G!==void 0&&!G.startsWith("-"))U(f,G),j++;else U(f,!0)}else U(f,!0)}}else Y._.push(W)}return Y}function QJ(w){return w.replace(/[<[].+/,"").trim()}function o6(w){let $=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(j)=>{let W=!1,Q=j[1];if(Q.startsWith("..."))Q=Q.slice(3),W=!0;return{required:j[0].startsWith("<"),value:Q,variadic:W}},J;while(J=$.exec(w))A.push(X(J));let U;while(U=Y.exec(w))A.push(X(U));return A}function e6(w){let $={alias:{},boolean:[]};for(let[Y,A]of w.entries()){if(A.names.length>1)$.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!w.some((J,U)=>{return U!==Y&&J.names.some((j)=>A.names.includes(j))&&typeof J.required==="boolean"}))$.boolean.push(A.names[0])}else $.boolean.push(A.names[0])}return $}function YQ(w){return w.reduce(($,Y)=>$.length>=Y.length?$:Y,"")}function WJ(w,$){return w.length>=$?w:`${w}${" ".repeat($-w.length)}`}function wG(w){return w.replace(/([a-z])-([a-z])/g,($,Y,A)=>{return Y+A.toUpperCase()})}function $G(w,$,Y){let A=0,X=$.length,J=w,U;for(;A<X;++A)U=J[$[A]],J=J[$[A]]=A===X-1?Y:U!=null?U:!!~$[A+1].indexOf(".")||!(+$[A+1]>-1)?{}:[]}function YG(w,$){for(let Y of Object.keys($)){let A=$[Y];if(A.shouldTransform){if(w[Y]=Array.prototype.concat.call([],w[Y]),typeof A.transformFunction==="function")w[Y]=w[Y].map(A.transformFunction)}}}function AG(w){let $=/([^\\/]+)$/.exec(w);return $?$[1]:""}function QQ(w){return w.split(".").map(($,Y)=>{return Y===0?wG($):$}).join(".")}class aY extends Error{exitCode=2;isUsageError=!0;constructor(w){super(w);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(w).stack}format(w=!1){if(w&&this.stack)return`${this.message}
352
+ port ${Ps}
353
+ `}function li(e){return Iv.join(_v,e)}function Vv(e){return e.includes("127.0.0.1")&&e.includes(String(Ps))}async function ik(e){try{return await Bv.readFile(li(e),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function fd(e){if(dr.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:r,isProcessElevated:n}=await Promise.resolve().then(() => (fe(),ri));if(!n()&&!r()){m("dns","Cannot flush DNS cache without SUDO_PASSWORD",e);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),m("dns","DNS cache flushed",e)}catch(i){m("dns",`Could not flush DNS cache: ${i}`,e)}}function Hv(e){if(!/^[a-z0-9.-]+$/.test(e))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(e)}`)}async function sk(e,t){Hv(e);let{execSudoSync:r}=await Promise.resolve().then(() => (fe(),ri)),n=nk().replace(/\n/g,"\\n"),i=`bash -c 'mkdir -p ${_v} && printf "%b" "${n}" > ${li(e)}'`;r(i),m("dns",`Created ${li(e)}`,t)}async function ok(e,t){Hv(e);let{execSudoSync:r}=await Promise.resolve().then(() => (fe(),ri));r(`rm -f ${li(e)}`),m("dns",`Removed ${li(e)}`,t)}async function ak(e,t){return md({domains:t??[],verbose:e})}async function ck(e,t){if(dr.platform!=="darwin")return!0;let{getSudoPassword:r,isProcessElevated:n}=await Promise.resolve().then(() => (fe(),ri));if(!n()&&!r())return m("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let i of e)await sk(i,t);return await fd(t),!0}catch(i){return m("dns",`Failed to create resolver file: ${i}`,t),!1}}async function hd(e,t){if(dr.platform!=="darwin")return;let{getSudoPassword:r,isProcessElevated:n}=await Promise.resolve().then(() => (fe(),ri));if(!n()&&!r())return;try{for(let i of e)await ok(i,t);await fd(t)}catch(i){m("dns",`Failed to remove resolver files: ${i}`,t)}}async function dd(e){if(dr.platform!=="darwin")return[];let t=[];for(let r of kv){let n=await ik(r);if(n&&Vv(n))await hd([r],e),t.push(r)}return t}async function md(e){let t=e.rpxDir??De(),r=ld(e.domains);if(r.length===0)return!1;let n=cd(r),i=await Kv(r,e.verbose);if(!i){let c=r[0];if(c&&await Wv(c))i=!0;else m("dns","Dev DNS server not available on 127.0.0.1:15353",e.verbose)}if(!i)return!1;if(!await ck(n,e.verbose))return!1;let o={version:Nc,resolvers:n,domains:r,ownerPid:e.ownerPid??dr.pid,updatedAt:new Date().toISOString()};return await Nv(t,o),!0}async function ui(e,t={}){let r=e.map((a)=>a.to).filter(Boolean),n=t.rpxDir??De(),i=cd(r),c=((await Dc(n))?.resolvers??[]).filter((a)=>!i.includes(a));if(c.length>0)await hd(c,t.verbose);if(i.length===0){ud(t.verbose),await ad(n);return}await md({domains:r,rpxDir:n,verbose:t.verbose,ownerPid:t.ownerPid??dr.pid})}async function Qr(e={}){let t=e.rpxDir??De();ud(e.verbose);let n=(await Dc(t))?.resolvers??[];await hd(n,e.verbose),await dd(e.verbose),await ad(t)}async function lk(e){await Qr({verbose:e})}async function en(e={}){let t=e.rpxDir??De(),r=await Dc(t),n=r?.ownerPid!=null&&mt(r.ownerPid);if(r&&!n){m("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,e.verbose),await Qr(e);return}let i=await dd(e.verbose);if(i.length>0)m("dns",`reconcile: removed legacy TLD resolvers: ${i.join(", ")}`,e.verbose);await fd(e.verbose)}var Ps=15353,Mv="# managed-by: rpx",_v="/etc/resolver",st=null,Fc;var As=te(()=>{Bc();Fv();Xr();fe();Fc=new Set});import{spawn as Yv}from"node:child_process";import*as ze from"node:fs/promises";import{homedir as Jv}from"node:os";import*as It from"node:path";import*as T from"node:process";function De(){return It.join(Jv(),".stacks","rpx")}function Br(e=De()){return It.join(e,"daemon.pid")}async function Lr(e=De()){try{let t=await ze.readFile(Br(e),"utf8"),r=Number.parseInt(t.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(t){if(t.code==="ENOENT")return null;throw t}}async function jc(e=De()){let t=await Lr(e);return t!==null&&mt(t)}async function Xv(e=De()){await ze.mkdir(e,{recursive:!0});let t=Br(e);while(!0){try{let n=await ze.open(t,"wx");try{await n.write(`${T.pid}
354
+ `)}finally{await n.close()}return t}catch(n){if(n.code!=="EEXIST")throw n}let r=await Lr(e);if(r!==null&&mt(r))throw Error(`rpx daemon already running (pid=${r})`);await ze.unlink(t).catch(()=>{})}}async function fi(e=De()){await ze.unlink(Br(e)).catch(()=>{})}function _c(e){for(let[t,r]of Mc)if(!e.has(t))ii(r),Mc.delete(t)}function fk(e,t){let r=Kw(t??"localhost:1");if(e.upstreams.length!==r.length)return!1;return e.upstreams.every((n,i)=>n.url===r[i])}function Zv(e){let t=e.cleanUrls??!1,r=fr(e.path),n=os(e.auth);if(e.static)return{static:yc(e.static,t),cleanUrls:t,basePath:r,auth:n};let i=e.from??"localhost:1",s=qr(i),o=new URL(s.startsWith("http")?s:`http://${s}`),c=Mc.get(e.id);if(c&&!fk(c,i))ii(c),c=void 0;if(!c)c=rs(i,e.loadBalancer),is(c),Mc.set(e.id,c);return{sourceHost:o.host,upstreamPool:c,cleanUrls:t,changeOrigin:e.changeOrigin??!1,pathRewrites:e.pathRewrites,basePath:r,auth:n}}function hk(e){return e.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??e[0]??"rpx.localhost"}async function Ic(e,t,r=[],n=!1){let i=await xt(t,e.verbose),s=[...new Set([...i.map((u)=>u.to).filter(Boolean),...r])],o=hk(s),c=[...new Set([o,...s,"rpx.localhost"])],a=_w(s,o,e.verbose);if(typeof e.https==="object"&&typeof a.https==="object")a.https={...a.https,...e.https};let l=await Or(a);if(l&&(n||!jf(Dh,c)))m("daemon",`regenerating shared cert for host(s): ${c.join(", ")}`,e.verbose),Lh(),l=null;if(!l)m("daemon","no usable cert on disk, generating one via tlsx",e.verbose),await es({...a,forceRegenerate:!0}),l=await Or(a);if(!l)throw Error("failed to bootstrap TLS for rpx daemon");return l}async function dk(e,t,r,n){let i=T.env.SUDO_PASSWORD,s=T.env.HOME??Jv(),o=[T.execPath,...T.argv.slice(1)],c=[`HOME=${s}`,`PATH=${T.env.PATH??""}`];if(n)c.push("RPX_VERBOSE=1");for(let[y,g]of Object.entries(T.env))if(g!==void 0&&y!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(y))c.push(`${y}=${g}`);let a=i?["-S","-p","","env",...c,...o]:["-n","env",...c,...o];m("daemon",`elevating daemon via sudo for privileged ports ${t}/${r}`,n);let l=Yv("sudo",a,{detached:!0,stdio:["pipe","ignore","ignore"]}),u=null,f=null;if(l.once("error",(y)=>{u=y}),l.once("exit",(y)=>{f=y??0}),i&&l.stdin)l.stdin.write(`${i}
355
+ `),l.stdin.end();l.unref();let h=Br(e),d=Date.now()+15000;while(Date.now()<d){if(u)throw u;let y=await Lr(e);if(y!==null&&mt(y)){if(n)b.success(`rpx daemon elevated to root (pid=${y}, https on :${t})`);return{httpsPort:t,httpPort:r,pidPath:h,done:Promise.resolve(),stop:async()=>{try{T.kill(y,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(f!==null&&f!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${f}). 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=${e})`)}function gd(){if(zv)return;zv=!0,T.on("uncaughtException",(e)=>{b.error(`rpx daemon: uncaught exception (continuing): ${e?.stack??e}`)}),T.on("unhandledRejection",(e)=>{b.error(`rpx daemon: unhandled rejection (continuing): ${e}`)})}function Qv(e,t,r){let n;try{n=new URL(e.url)}catch{return new Response("Bad Request",{status:400})}let i=(e.headers.get("host")??n.hostname).split(":")[0];if(n.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let s=t.challengeStore.handlePath(n.pathname);if(s!==void 0)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(r){let s=vc(r,n.pathname);if(s!=null)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(i))t.ensureCert(i).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${i}${n.pathname}${n.search}`}})}async function eb(e={}){gd();let t=e.verbose??!1,r=e.rpxDir??De(),n=e.registryDir??It.join(r,"registry.d"),i=e.httpsPort??443,s=e.httpPort??80,o=e.https===!1;if(e.localCa)ws(e.localCa,e.onDemandTls);let c=e.hostname??"::",a=e.hostname==null,l=e.gcIntervalMs??uk;if(T.env.RPX_DAEMON_WORKER==="1")return pk({rpxDir:T.env.RPX_WORKER_RPXDIR??r,registryDir:T.env.RPX_WORKER_REGISTRYDIR??n,httpsPort:Number.parseInt(T.env.RPX_WORKER_HTTPSPORT??"",10)||i,hostname:T.env.RPX_WORKER_HOSTNAME??c,verbose:T.env.RPX_WORKER_VERBOSE==="1"||t});let u=!o&&i>0&&i<1024||s>0&&s<1024,f=typeof T.getuid==="function"&&T.getuid()===0;if(T.platform!=="win32"&&u&&!f)return dk(r,i,s,t);let h=Math.max(1,e.workers??(Number.parseInt(T.env.RPX_WORKERS??"",10)||1));if(h>1){if(o)throw Error("rpx daemon: https: false is not supported with workers > 1 (the cluster shares the HTTPS port only); run a single process");if(e.onDemandSites?.enabled)b.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return yk(e,{rpxDir:r,registryDir:n,httpsPort:i,httpPort:s,hostname:c,verbose:t,gcIntervalMs:l,workers:h})}let d=await Xv(r),y=new Map,g=(E,N)=>fs(y,E,N);function p(E){y=us(E.map((Le)=>({host:Le.to,path:Le.path,route:Zv(Le)}))),_c(new Set(E.map((Le)=>Le.id)));let N=Array.from(y.keys());m("daemon",`routing table now covers ${N.length} host(s): ${N.join(", ")||"<empty>"}`,t)}await bs(n,t).catch((E)=>{m("daemon",`initial gc failed: ${E}`,t)}),await Es({verbose:t}).catch((E)=>{m("daemon",`stale hosts GC on start failed: ${E}`,t)});let w=await xt(n,t);p(w),await en({rpxDir:r,verbose:t}).catch((E)=>{m("daemon",`DNS reconcile on start failed: ${E}`,t)}),await ui(w,{rpxDir:r,verbose:t,ownerPid:T.pid}).catch((E)=>{m("daemon",`DNS setup on start failed: ${E}`,t)});let v=[];if(e.productionCerts&&!o){if(v=await ms(e.productionCerts,t),t&&v.length>0)b.info(`SNI: serving ${v.length} real cert(s): ${v.map((E)=>E.serverName).join(", ")}`)}let P=null;if(e.localCa&&!o){let E=await vs(e.localCa,{verbose:t,onDemandTls:e.onDemandTls}),N=new Set(E.entries.map((Le)=>Le.serverName));if(v=[...E.entries,...v.filter((Le)=>!N.has(Le.serverName))],P=E.defaultTls,t)b.info(`Local CA: ${E.leafMinted?`minted leaf (${E.renewalReason})`:"reusing leaf"} for ${[...N].join(", ")}; valid until ${E.notAfter.toISOString()}`)}let A=new Set,R=null,D;if(e.onDemandSites?.enabled){if(R=new ed({resolver:su(e.onDemandSites),registryDir:n,rpxDir:r,verbose:t,startupTimeoutMs:e.onDemandSites.startupTimeoutMs,isHostRoutable:(E)=>Uh(y,E)!==void 0,onSiteActivating:(E)=>{tn(E)}}),D=async(E)=>{let N=await R.onRequest(E);switch(N.kind){case"ready":return{retry:!0};case"starting":return Cv({host:N.host,sinceMs:N.sinceMs,logTail:N.logTail});case"failed":return xv({host:N.host,error:N.error,logTail:N.logTail});case"unknown":default:return}},t)b.info("rpx: on-demand sites enabled")}let F=cs(g,t,D),x=ls(t),k=null;if(!o&&v.length===0)k=await Ic(e,n);let L=e.onDemandTls,ee=L?.enabled&&!o?new oi({config:L,certsDir:L.certsDir??e.productionCerts?.certsDir??It.join(r,"on-demand-certs"),initial:v,verbose:t,onCertAdded:(E)=>{if(gs()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",t),setTimeout(()=>T.kill(T.pid,"SIGTERM"),10).unref();else pe(E)}}):null;function Re(E){if(E.length>0)return ds({sni:E,defaultTls:P,maxTlsContexts:e.maxTlsContexts,verbose:t});return si({key:k.key,cert:k.cert,ca:k.ca,requestCert:!1,rejectUnauthorized:!1})}function Ge(E){try{return Bun.serve(E)}catch(N){let Le=N instanceof Error?N.message:String(N),di=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test(Le);if(!a||E.hostname!=="::"||!di)throw N;return m("daemon",`no IPv6 on this host (${Le}); binding 0.0.0.0`,e.verbose),Bun.serve({...E,hostname:"0.0.0.0"})}}function jt(E){return Ge({port:i,hostname:c,reusePort:ti(),tls:Re(E),fetch(N,Le){return F(N,Le)},websocket:x,error(N){return m("daemon",`https server error: ${N}`,t),new Response(`Server Error: ${N.message}`,{status:500})}})}let hi=(E)=>[...new Set(E.map((N)=>N.to).filter(Boolean))],mr=(E)=>{if(!k)return v;return Mw([...hi(E),...A,"rpx.localhost"],k)},St=o?null:jt(ee?ee.sniEntries():v.length>0?v:mr(w)),rt=null,O=!1;async function pe(E){if(gr||o)return;if(rt=E,O)return;O=!0;try{while(!gr&&rt){let N=rt;rt=null,m("daemon",`rebuilding :443 with ${N.length} SNI cert(s)`,t),St?.stop(!1);let Le,di=!1,Td=60,$b=500;for(let rl=0;!gr&&!di;rl++)try{St=jt(N),di=!0;break}catch(Cb){if(Le=Cb,rl>=Td)break;await new Promise((xb)=>setTimeout(xb,Math.min(25*2**Math.min(rl,4),$b)))}if(!di)b.error(`rpx: CRITICAL — could not rebind :443 after ${Td} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Le?.message}`)}}finally{O=!1}}let ye=null;if(o)ye=Ge({port:s,hostname:c,reusePort:ti(),fetch(E,N){return F(E,N)},websocket:x,error(E){return m("daemon",`http server error: ${E}`,t),new Response(`Server Error: ${E.message}`,{status:500})}});else if(s>0)ye=Ge({port:s,hostname:c,fetch(E){return Qv(E,ee,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t){if(o)b.success(`rpx daemon listening on http://${c}:${ye?.port??s} (https disabled)`);else b.success(`rpx daemon listening on https://${c}:${i}${ye?` (http→https on :${s})`:""}`);b.info(`pid file: ${d}`),b.info(`registry: ${n}`)}async function Ir(E){if(gr||v.length>0||ee||!k)return;try{k=await Ic(e,n,[...A]),await pe(mr(E))}catch(N){m("daemon",`TLS sync on registry change failed: ${N}`,t)}}async function tn(E){if(gr||v.length>0||ee||!k||!E)return;if(A.has(E))return;A.add(E);try{k=await Ic(e,n,[...A],!0);let N=await xt(n,t);await pe(mr(N))}catch(N){m("daemon",`dev cert refresh for ${E} failed: ${N}`,t)}}let Fs=Ac((E)=>{p(E),Ir(E),ui(E,{rpxDir:r,verbose:t,ownerPid:T.pid}).catch((N)=>{m("daemon",`DNS sync on registry change failed: ${N}`,t)})},{dir:n,verbose:t}),rn=setInterval(()=>{bs(n,t).then((E)=>{if(E>0)m("daemon",`gc reaped ${E} stale entries`,t)}).catch((E)=>{m("daemon",`periodic gc failed: ${E}`,t)}),Es({verbose:t}).then((E)=>{if(E.length>0)m("daemon",`gc reaped stale hosts entries: ${E.join(", ")}`,t)}).catch((E)=>{m("daemon",`periodic hosts gc failed: ${E}`,t)})},l);if(typeof rn.unref==="function")rn.unref();let gr=!1,xd,tl=new Promise((E)=>{xd=E});async function Sd(){if(gr)return tl;if(gr=!0,clearInterval(rn),Fs.close(),await R?.stopAll().catch((E)=>{m("daemon",`site supervisor stopAll failed: ${E}`,t)}),St?.stop(!1),ye?.stop(!1),await Qr({rpxDir:r,verbose:t}).catch((E)=>{m("daemon",`DNS teardown failed: ${E}`,t)}),_c(new Set),await fi(r),t)b.info("rpx daemon stopped");return xd(),tl}let Ed=(E)=>{m("daemon",`received ${E}, shutting down`,t),Sd().catch(()=>{})};return T.once("SIGINT",Ed),T.once("SIGTERM",Ed),{stop:Sd,done:tl,httpsPort:St&&typeof St.port==="number"?St.port:o?0:i,httpPort:ye&&typeof ye.port==="number"?ye.port:s,pidPath:d,ensureCert:(E)=>ee?ee.ensureCert(E):Promise.resolve(!1),listSites:()=>R?.list()??[]}}function pd(e){return It.join(e,"cluster-sni.json")}async function Gv(e,t,r,n=null){let i=pd(e),s=`${i}.${T.pid}.tmp`;await ze.writeFile(s,JSON.stringify({sni:t,dev:r,defaultTls:n}),"utf8"),await ze.rename(s,i)}async function qv(e){try{return JSON.parse(await ze.readFile(pd(e),"utf8"))}catch{return{sni:[],dev:null}}}function mk(e){if(e.sni.length>0)return ds({sni:e.sni,defaultTls:e.defaultTls??null});if(e.dev)return si({key:e.dev.key,cert:e.dev.cert,ca:e.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function gk(){let e=T.execPath,t=T.env.RPX_WORKER_BIN;if(t)return[e,t,"daemon:start"];let r=It.basename(e).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&T.argv[1])return[e,T.argv[1],"daemon:start"];return[e,"daemon:start"]}async function pk(e){gd();let{rpxDir:t,registryDir:r,httpsPort:n,hostname:i,verbose:s}=e,o=new Map,c=(D,F)=>fs(o,D,F),a=(D)=>{o=us(D.map((F)=>({host:F.to,path:F.path,route:Zv(F)}))),_c(new Set(D.map((F)=>F.id)))};a(await xt(r,s));let l=cs(c,s),u=ls(s),f=!1,h=(D)=>Bun.serve({port:n,hostname:i,reusePort:!0,tls:mk(D),fetch(F,x){return l(F,x)},websocket:u,error(F){return m("daemon",`worker https error: ${F}`,s),new Response(`Server Error: ${F.message}`,{status:500})}}),d=h(await qv(t));async function y(){if(f)return;let D=await qv(t),F=null;for(let k=0;k<20&&!f;k++)try{F=h(D);break}catch{await new Promise((L)=>setTimeout(L,25))}if(!F){m("daemon","worker reloadTls: could not bind new listener; keeping current",s);return}let x=d;d=F,x.stop(!1)}let g=Ac((D)=>a(D),{dir:r,verbose:s}),p=()=>{y().catch(()=>{})};T.on("SIGHUP",p);let w=()=>{let D=T.removeListener??T.off;if(typeof D==="function")D.call(T,"SIGHUP",p)},v,P=new Promise((D)=>{v=D});async function A(){if(f)return P;return f=!0,w(),g.close(),d.stop(!1),_c(new Set),v(),P}let R=()=>{A().then(()=>T.exit(0)).catch(()=>T.exit(0))};if(T.once("SIGTERM",R),T.once("SIGINT",R),s)b.success(`rpx worker (pid ${T.pid}) serving :${n}`);return{stop:A,done:P,httpsPort:typeof d.port==="number"?d.port:n,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function yk(e,t){gd();let{rpxDir:r,registryDir:n,httpsPort:i,httpPort:s,hostname:o,verbose:c,gcIntervalMs:a,workers:l}=t,u=await Xv(r),f=[];if(e.productionCerts)f=await ms(e.productionCerts,c);let h=null;if(e.localCa){let O=await vs(e.localCa,{verbose:c,onDemandTls:e.onDemandTls}),pe=new Set(O.entries.map((ye)=>ye.serverName));f=[...O.entries,...f.filter((ye)=>!pe.has(ye.serverName))],h=O.defaultTls}let d=null;if(f.length===0)d=await Ic(e,n);let y=d?{key:d.key,cert:d.cert,ca:Array.isArray(d.ca)?d.ca.join(`
356
+ `):d.ca}:null,g=!1,p=[];function w(O){for(let pe of p)try{pe.kill(O)}catch{}}async function v(O){await Gv(r,$c(O,e.maxTlsContexts,c),y,h),w("SIGHUP")}let P=e.onDemandTls,A=P?.enabled?new oi({config:P,certsDir:P.certsDir??e.productionCerts?.certsDir??It.join(r,"on-demand-certs"),initial:f,verbose:c,onCertAdded:(O)=>{if(gs()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",c),setTimeout(()=>T.kill(T.pid,"SIGTERM"),10).unref();else v(O)}}):null;await Gv(r,$c(A?A.sniEntries():f,e.maxTlsContexts,c),y,h);let R=await xt(n,c);await en({rpxDir:r,verbose:c}).catch((O)=>{m("daemon",`DNS reconcile on start failed: ${O}`,c)}),await ui(R,{rpxDir:r,verbose:c,ownerPid:T.pid}).catch((O)=>{m("daemon",`DNS setup on start failed: ${O}`,c)}),await bs(n,c).catch(()=>{}),await Es({verbose:c}).catch(()=>{});let D=Ac((O)=>{ui(O,{rpxDir:r,verbose:c,ownerPid:T.pid}).catch((pe)=>{m("daemon",`DNS sync on registry change failed: ${pe}`,c)})},{dir:n,verbose:c}),F=setInterval(()=>{bs(n,c).catch(()=>{}),Es({verbose:c}).catch(()=>{})},a);F.unref?.();let x=null;if(s>0)x=Bun.serve({port:s,hostname:o,fetch(O){return Qv(O,A,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let k=10,L=60000,ee=30000,Re=0,Ge=Date.now();function jt(){if(g)return;let O={...T.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:n,RPX_WORKER_HTTPSPORT:String(i),RPX_WORKER_HOSTNAME:o,RPX_WORKER_VERBOSE:c?"1":"0"},pe=Bun.spawn(gk(),{env:O,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(ye,Ir){if(g)return;let tn=p.indexOf(ye);if(tn!==-1)p.splice(tn,1);let Fs=Date.now();if(Fs-Ge>L)Ge=Fs,Re=0;if(Re++,Re>k){b.error(`rpx: worker keeps exiting (code ${Ir}); giving up after ${k} restarts in ${Math.round(L/1000)}s`);return}let rn=Math.min(ee,100*2**Math.min(Re,8));m("daemon",`worker exited (code ${Ir}); respawning in ${rn}ms (restart ${Re}/${k})`,c),setTimeout(jt,rn).unref?.()}});p.push(pe)}for(let O=0;O<l;O++)jt();if(c)b.success(`rpx coordinator listening on https://${o}:${i} via ${l} worker(s)${x?` (http→https on :${s})`:""}`),b.info(`pid file: ${u}`);let hi,mr=new Promise((O)=>{hi=O});async function St(){if(g)return mr;if(g=!0,clearInterval(F),D.close(),x?.stop(!1),w("SIGTERM"),await Promise.race([Promise.all(p.map((O)=>O.exited)),new Promise((O)=>setTimeout(O,3000))]),w("SIGKILL"),await Qr({rpxDir:r,verbose:c}).catch((O)=>{m("daemon",`DNS teardown failed: ${O}`,c)}),await fi(r),await ze.unlink(pd(r)).catch(()=>{}),c)b.info("rpx coordinator stopped");return hi(),mr}let rt=(O)=>{m("daemon",`coordinator received ${O}, shutting down`,c),St().catch(()=>{})};return T.once("SIGINT",rt),T.once("SIGTERM",rt),{stop:St,done:mr,httpsPort:i,httpPort:s,pidPath:u,ensureCert:(O)=>A?A.ensureCert(O):Promise.resolve(!1),listSites:()=>[]}}function wk(){let e=T.execPath,t=It.basename(e).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&T.argv[1])return[e,T.argv[1],"daemon:start"];return[e,"daemon:start"]}async function Uc(e={}){let t=e.rpxDir??De(),r=e.verbose??!1;await en({rpxDir:t,verbose:r}).catch((u)=>{m("daemon",`DNS reconcile before ensureDaemonRunning: ${u}`,r)});let n=await Lr(t);if(n!==null&&mt(n))return m("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)m("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await fi(t);await ze.mkdir(t,{recursive:!0});let i=e.spawnCommand??wk();if(i.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");m("daemon",`spawning daemon: ${i.join(" ")}`,r);let s=Yv(i[0],i.slice(1),{detached:!0,stdio:"ignore",cwd:e.spawnCwd??T.cwd(),env:e.spawnEnv?{...T.env,...e.spawnEnv}:T.env});s.unref();let o=null;s.once("error",(u)=>{o=u});let c=e.startupTimeoutMs??5000,a=e.pollIntervalMs??50,l=Date.now()+c;while(Date.now()<l){if(o)throw o;let u=await Lr(t);if(u!==null&&mt(u))return m("daemon",`daemon registered with pid=${u}`,r),{pid:u,spawned:!0};await new Promise((f)=>setTimeout(f,a))}if(o)throw o;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${t})`)}async function tb(e={}){let t=e.rpxDir??De(),r=e.verbose??!1,n=e.timeoutMs??5000,i=e.pollIntervalMs??50,s=e.forceAfterTimeout??!0,o=await Lr(t);if(o===null||!mt(o)){if(o!==null)await fi(t);return await en({rpxDir:t,verbose:r}).catch(()=>{}),{stopped:!1,pid:o,forced:!1}}try{T.kill(o,"SIGTERM")}catch(a){let l=a.code;if(l==="ESRCH")return await fi(t),{stopped:!1,pid:o,forced:!1};if(l==="EPERM")Tr(`kill -TERM ${o}`);else throw a}let c=Date.now()+n;while(Date.now()<c){if(!mt(o))return m("daemon",`daemon pid=${o} stopped cleanly`,r),{stopped:!0,pid:o,forced:!1};await new Promise((a)=>setTimeout(a,i))}if(!s)throw Error(`rpx daemon (pid=${o}) did not exit within ${n}ms`);m("daemon",`daemon pid=${o} did not exit, escalating to SIGKILL`,r);try{T.kill(o,"SIGKILL")}catch(a){let l=a.code;if(l==="EPERM")Tr(`kill -KILL ${o}`);else if(l!=="ESRCH")throw a}return await fi(t),await Qr({rpxDir:t,verbose:r}).catch((a)=>{m("daemon",`DNS teardown after SIGKILL: ${a}`,r)}),{stopped:!0,pid:o,forced:!0}}async function rb(e={}){let t=e.rpxDir??De();if(await jc(t))return;await en({rpxDir:t,verbose:e.verbose})}var uk=5000,Mc,zv=!1;var Bc=te(()=>{qt();hc();_h();jh();bc();Wh();Gh();xc();ou();bv();wc();mc();Xr();id();As();fe();Mc=new Map});import{dirname as Mk,join as _k}from"node:path";import*as Fe from"node:process";import{fileURLToPath as jk}from"node:url";import{existsSync as Ab}from"node:fs";import il from"node:fs/promises";import Pd from"node:os";import sl from"node:path";import Mr from"node:process";import{EventEmitter as Rb}from"node:events";import pr from"node:process";import Ad from"node:process";import cl from"node:process";import Bs from"node:process";import pi from"node:process";import Nd from"node:tty";import y$,{stdin as a1,stdout as c1}from"node:process";class Dd{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Pd.homedir(),t=sl.join(e,".config","clapp");this.configPath=sl.join(t,"telemetry.json")}async isEnabled(){if(Mr.env.DO_NOT_TRACK==="1"||Mr.env.DO_NOT_TRACK==="true")return!1;if(Mr.env.NO_TELEMETRY==="1"||Mr.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let n={event:e,...t,timestamp:Date.now(),platform:Pd.platform(),nodeVersion:Mr.version};if(this.events.push(n),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:Mr.env.DO_NOT_TRACK==="1"||Mr.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Ab(this.configPath)){let e=await il.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=sl.dirname(this.configPath);await il.mkdir(t,{recursive:!0}),await il.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var qk=new Dd;function kb(e,t={}){let r={_:[]},n=t.alias||{},i=new Set(t.boolean||[]),s={};for(let c of Object.keys(n))for(let a of n[c])s[a]=c;for(let c of i)if(n[c])for(let a of n[c])i.add(a);function o(c,a){let l=s[c]||c;if(r[l]=a,n[l])for(let u of n[l])r[u]=a;if(s[c]&&n[s[c]])for(let u of n[s[c]])r[u]=a;r[c]=a}for(let c=0;c<e.length;c++){let a=e[c];if(a==="--"){r._.push(...e.slice(c+1));break}if(a.startsWith("--")){let l=a.indexOf("=");if(l!==-1){let u=a.slice(2,l),f=a.slice(l+1);o(u,f)}else{let u=a.slice(2);if(u.startsWith("no-")){let h=u.slice(3);o(h,!1);continue}let f=s[u]||u;if(i.has(f)||i.has(u))o(u,!0);else{let h=e[c+1];if(h!==void 0&&!h.startsWith("-"))o(u,h),c++;else o(u,!0)}}}else if(a.startsWith("-")&&a.length>1){let l=a.slice(1);for(let u=0;u<l.length;u++){let f=l[u],h=s[f]||f;if(u===l.length-1&&!i.has(h)&&!i.has(f)){let d=e[c+1];if(d!==void 0&&!d.startsWith("-"))o(f,d),c++;else o(f,!0)}else o(f,!0)}}else r._.push(a)}return r}function al(e){return e.replace(/[<[].+/,"").trim()}function Ob(e){let t=/<([^>]+)>/g,r=/\[([^\]]+)\]/g,n=[],i=(c)=>{let a=!1,l=c[1];if(l.startsWith("..."))l=l.slice(3),a=!0;return{required:c[0].startsWith("<"),value:l,variadic:a}},s;while(s=t.exec(e))n.push(i(s));let o;while(o=r.exec(e))n.push(i(o));return n}function Nb(e){let t={alias:{},boolean:[]};for(let[r,n]of e.entries()){if(n.names.length>1)t.alias[n.names[0]]=n.names.slice(1);if(n.isBoolean)if(n.negated){if(!e.some((s,o)=>o!==r&&s.names.some((c)=>n.names.includes(c))&&typeof s.required==="boolean"))t.boolean.push(n.names[0])}else t.boolean.push(n.names[0])}return t}function Rd(e){return e.reduce((t,r)=>t.length>=r.length?t:r,"")}function ol(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function Db(e){return e.replace(/([a-z])-([a-z])/g,(t,r,n)=>r+n.toUpperCase())}function Fb(e,t,r){let n=0,i=t.length,s=e,o;for(;n<i;++n)o=s[t[n]],s=s[t[n]]=n===i-1?r:o!=null?o:!!~t[n+1].indexOf(".")||!(+t[n+1]>-1)?{}:[]}function Lb(e,t){for(let r of Object.keys(t)){let n=t[r];if(n.shouldTransform){if(e[r]=Array.prototype.concat.call([],e[r]),typeof n.transformFunction==="function")e[r]=e[r].map(n.transformFunction)}}}function Bb(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function Fd(e){return e.split(".").map((t,r)=>r===0?Db(t):t).join(".")}class Ls extends Error{exitCode=2;isUsageError=!0;constructor(e){super(e);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
298
357
 
299
358
  Stack trace:
300
- ${this.stack}`;return this.message}}function XG(){let{env:w}=$Q,{TERM:$,TERM_PROGRAM:Y}=w;if($Q.platform!=="win32")return $!=="linux";return Boolean(w.WT_SESSION)||Boolean(w.TERMINUS_SUBLIME)||w.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||$==="xterm-256color"||$==="alacritty"||$==="rxvt-unicode"||$==="rxvt-unicode-256color"||w.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var wA="\x1B",Q0=`${wA}[`;var xw={to(w,$){if(!$)return`${Q0}${w+1}G`;return`${Q0}${$+1};${w+1}H`},move(w,$){let Y="";if(w<0)Y+=`${Q0}${-w}D`;else if(w>0)Y+=`${Q0}${w}C`;if($<0)Y+=`${Q0}${-$}A`;else if($>0)Y+=`${Q0}${$}B`;return Y},up:(w=1)=>`${Q0}${w}A`,down:(w=1)=>`${Q0}${w}B`,forward:(w=1)=>`${Q0}${w}C`,backward:(w=1)=>`${Q0}${w}D`,nextLine:(w=1)=>`${Q0}E`.repeat(w),prevLine:(w=1)=>`${Q0}F`.repeat(w),left:`${Q0}G`,hide:`${Q0}?25l`,show:`${Q0}?25h`,save:`${wA}7`,restore:`${wA}8`};var jJ={screen:`${Q0}2J`,up:(w=1)=>`${Q0}1J`.repeat(w),down:(w=1)=>`${Q0}J`.repeat(w),line:`${Q0}2K`,lineEnd:`${Q0}K`,lineStart:`${Q0}1K`,lines(w){let $="";for(let Y=0;Y<w;Y++)$+=this.line+(Y<w-1?xw.up():"");if(w)$+=xw.left;return $}},XM={screen:`${wA}c`};function JG(w,$){let Y=[];for(let A=0;A<=$.length;A++)Y[A]=[A];for(let A=0;A<=w.length;A++)Y[0][A]=A;for(let A=1;A<=$.length;A++)for(let X=1;X<=w.length;X++)if($.charAt(A-1)===w.charAt(X-1))Y[A][X]=Y[A-1][X-1];else Y[A][X]=Math.min(Y[A-1][X-1]+1,Y[A][X-1]+1,Y[A-1][X]+1);return Y[$.length][w.length]}function zQ(w,$,Y=2,A=3){return $.map((X)=>({cmd:X,distance:JG(w,X)})).filter(({distance:X})=>X<=Y).sort((X,J)=>X.distance-J.distance).slice(0,A).map(({cmd:X})=>X)}class fQ{rawName;description;name;names;isBoolean;required;config;negated;constructor(w,$,Y){if(this.rawName=w,this.description=$,this.config=Object.assign({},Y),w=w.replace(/\.\*/g,""),this.negated=!1,this.names=QJ(w).split(",").map((A)=>{let X=A.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return QQ(X)}).sort((A,X)=>A.length>X.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(w.includes("<"))this.required=!0;else if(w.includes("["))this.required=!1;else this.isBoolean=!0}}var UM=zJ.argv,UG=`${zJ.platform}-${zJ.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,AQ=sY.argv,WG=`${sY.platform}-${sY.arch} node-${sY.version}`;class fJ{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(w,$,Y,A){this.rawName=w,this.description=$,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=QJ(w);let X=QJ(w),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=o6(w),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage(w){return this.usageText=w,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(w,$="-v, --version"){return this.versionNumber=w,this.option($,"Display version number"),this}example(w){return this.examples.push(w),this}option(w,$,Y){let A=new fQ(w,$,Y);return this.options.push(A),this}alias(w){return this.aliasNames.push(w),this}action(w){return this.commandAction=w,this}before(w){return this.beforeHooks.push(w),this}after(w){return this.afterHooks.push(w),this}use(w){return this.middleware.push(w),this}isMatched(w){if(this.aliasNames.includes(w))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===w;return this.name===w}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof BJ}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(w){return w=w.split(".")[0],!!this.options.find(($)=>{return $.names.includes(w)})}outputHelp(){let{name:w,commands:$}=this.cli,{versionNumber:Y,options:A,helpCallback:X}=this.cli.globalCommand,J=[{body:`${w}${Y?`/${Y}`:""}`}];if(J.push({title:"Usage",body:` $ ${w} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let W=YQ($.map((G)=>G.rawName)),Q=new Map,z=[];for(let G of $)if(G.namespace){if(!Q.has(G.namespace))Q.set(G.namespace,[]);Q.get(G.namespace).push(G)}else z.push(G);let f="";if(z.length>0)f+=z.map((G)=>{return` ${WJ(G.rawName,W.length)} ${G.description}`}).join(`
301
- `);let B=Array.from(Q.keys()).sort();for(let G of B){let T=Q.get(G);if(f.length>0)f+=`
359
+ ${this.stack}`;return this.message}}function Ib(){let{env:e}=Ad,{TERM:t,TERM_PROGRAM:r}=e;if(Ad.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||r==="Terminus-Sublime"||r==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Is="\x1B",ge=`${Is}[`;var kd={to(e,t){if(!t)return`${ge}${e+1}G`;return`${ge}${t+1};${e+1}H`},move(e,t){let r="";if(e<0)r+=`${ge}${-e}D`;else if(e>0)r+=`${ge}${e}C`;if(t<0)r+=`${ge}${-t}A`;else if(t>0)r+=`${ge}${t}B`;return r},up:(e=1)=>`${ge}${e}A`,down:(e=1)=>`${ge}${e}B`,forward:(e=1)=>`${ge}${e}C`,backward:(e=1)=>`${ge}${e}D`,nextLine:(e=1)=>`${ge}E`.repeat(e),prevLine:(e=1)=>`${ge}F`.repeat(e),left:`${ge}G`,hide:`${ge}?25l`,show:`${ge}?25h`,save:`${Is}7`,restore:`${Is}8`};var Zk={screen:`${ge}2J`,up:(e=1)=>`${ge}1J`.repeat(e),down:(e=1)=>`${ge}J`.repeat(e),line:`${ge}2K`,lineEnd:`${ge}K`,lineStart:`${ge}1K`,lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?kd.up():"");if(e)t+=kd.left;return t}},Qk={screen:`${Is}c`};function Mb(e,t){let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=t.length;n++)for(let i=1;i<=e.length;i++)if(t.charAt(n-1)===e.charAt(i-1))r[n][i]=r[n-1][i-1];else r[n][i]=Math.min(r[n-1][i-1]+1,r[n][i-1]+1,r[n-1][i]+1);return r[t.length][e.length]}function Ld(e,t,r=2,n=3){return t.map((i)=>({cmd:i,distance:Mb(e,i)})).filter(({distance:i})=>i<=r).sort((i,s)=>i.distance-s.distance).slice(0,n).map(({cmd:i})=>i)}class Bd{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,r){if(this.rawName=e,this.description=t,this.config=Object.assign({},r),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=al(e).split(",").map((n)=>{let i=n.trim().replace(/^-{1,2}/,"");if(i.startsWith("no-"))this.negated=!0,i=i.replace(/^no-/,"");return Fd(i)}).sort((n,i)=>n.length>i.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var t1=cl.argv,_b=`${cl.platform}-${cl.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,Od=Bs.argv,jb=`${Bs.platform}-${Bs.arch} node-${Bs.version}`;class ll{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,r,n){this.rawName=e,this.description=t,this.config=r,this.cli=n,this.options=[],this.aliasNames=[],this.name=al(e);let i=al(e),s=i.indexOf(":");if(s>0)this.namespace=i.substring(0,s),this.name=i.substring(s+1);if(this.args=Ob(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!r)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,r){let n=new Bd(e,t,r);return this.options.push(n),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof ul}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){return e=e.split(".")[0],!!this.options.find((t)=>t.names.includes(e))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:r,options:n,helpCallback:i}=this.cli.globalCommand,s=[{body:`${e}${r?`/${r}`:""}`}];if(s.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let a=Rd(t.map((d)=>d.rawName)),l=new Map,u=[];for(let d of t)if(d.namespace){if(!l.has(d.namespace))l.set(d.namespace,[]);l.get(d.namespace).push(d)}else u.push(d);let f="";if(u.length>0)f+=u.map((d)=>` ${ol(d.rawName,a.length)} ${d.description}`).join(`
360
+ `);let h=Array.from(l.keys()).sort();for(let d of h){let y=l.get(d);if(f.length>0)f+=`
302
361
 
303
- `;f+=` ${G}:
304
- `,f+=T.map((F)=>{return` ${WJ(F.rawName,W.length-2)} ${F.description}`}).join(`
305
- `)}J.push({title:"Commands",body:f}),J.push({title:"For more info, run any command with the `--help` flag",body:$.map((G)=>` $ ${w}${G.displayName===""?"":` ${G.displayName}`} --help`).join(`
306
- `)})}let j=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)j=j.filter((W)=>W.name!=="version");if(j.length>0){let W=YQ(j.map((Q)=>Q.rawName));J.push({title:"Options",body:j.map((Q)=>{return` ${WJ(Q.rawName,W.length)} ${Q.description} ${Q.config.default===void 0?"":`(default: ${Q.config.default})`}`}).join(`
307
- `)})}if(this.examples.length>0)J.push({title:"Examples",body:this.examples.map((W)=>{if(typeof W==="function")return W(w);return W}).join(`
308
- `)});if(X)J=X(J)||J;console.log(J.map((W)=>{return W.title?`${W.title}:
309
- ${W.body}`:W.body}).join(`
362
+ `;f+=` ${d}:
363
+ `,f+=y.map((g)=>` ${ol(g.rawName,a.length-2)} ${g.description}`).join(`
364
+ `)}s.push({title:"Commands",body:f}),s.push({title:"For more info, run any command with the `--help` flag",body:t.map((d)=>` $ ${e}${d.displayName===""?"":` ${d.displayName}`} --help`).join(`
365
+ `)})}let c=this.isGlobalCommand?n:[...this.options,...n||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)c=c.filter((a)=>a.name!=="version");if(c.length>0){let a=Rd(c.map((l)=>l.rawName));s.push({title:"Options",body:c.map((l)=>` ${ol(l.rawName,a.length)} ${l.description} ${l.config.default===void 0?"":`(default: ${l.config.default})`}`).join(`
366
+ `)})}if(this.examples.length>0)s.push({title:"Examples",body:this.examples.map((a)=>{if(typeof a==="function")return a(e);return a}).join(`
367
+ `)});if(i)s=i(s)||s;console.log(s.map((a)=>a.title?`${a.title}:
368
+ ${a.body}`:a.body).join(`
310
369
 
311
- `))}outputVersion(){let{name:w}=this.cli,{versionNumber:$}=this.cli.globalCommand;if($)console.log(`${w}/${$} ${typeof Bun<"u"?UG:WG}`)}checkRequiredArgs(){let w=this.args.filter(($)=>$.required).length;if(this.cli.args.length<w){let Y=this.args.filter((X)=>X.required).slice(this.cli.args.length),A=Y.map((X)=>`<${X.value}>`).join(" ");throw new aY(`Missing required argument${Y.length>1?"s":""}: ${A}
370
+ `))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;if(t)console.log(`${e}/${t} ${typeof Bun<"u"?_b:jb}`)}checkRequiredArgs(){let e=this.args.filter((t)=>t.required).length;if(this.cli.args.length<e){let r=this.args.filter((i)=>i.required).slice(this.cli.args.length),n=r.map((i)=>`<${i.value}>`).join(" ");throw new Ls(`Missing required argument${r.length>1?"s":""}: ${n}
312
371
 
313
- Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:w,globalCommand:$}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys(w))if(Y!=="--"&&!this.hasOption(Y)&&!$.hasOption(Y)){let X=[...$.options,...this.options].flatMap((W)=>W.names),J=Y.length>1?`--${Y}`:`-${Y}`,U=zQ(Y,X),j=`Unknown option \`${J}\``;if(U.length>0)j+=`
372
+ Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let r of Object.keys(e))if(r!=="--"&&!this.hasOption(r)&&!t.hasOption(r)){let i=[...t.options,...this.options].flatMap((a)=>a.names),s=r.length>1?`--${r}`:`-${r}`,o=Ld(r,i),c=`Unknown option \`${s}\``;if(o.length>0)c+=`
314
373
 
315
- Did you mean one of these?`,U.forEach((W)=>{let Q=W.length>1?`--${W}`:`-${W}`;j+=`
316
- • ${Q}`});throw j+=`
374
+ Did you mean one of these?`,o.forEach((a)=>{let l=a.length>1?`--${a}`:`-${a}`;c+=`
375
+ • ${l}`});throw c+=`
317
376
 
318
- Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new aY(j)}}}checkOptionValue(){let{options:w,globalCommand:$}=this.cli,Y=[...$.options,...this.options];for(let A of Y){let X=w[A.name.split(".")[0]];if(A.required){let J=Y.some((U)=>U.negated&&U.names.includes(A.name));if(X===!0||X===!1&&!J)throw new aY(`Option \`${A.rawName}\` requires a value.
377
+ Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new Ls(c)}}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,r=[...t.options,...this.options];for(let n of r){let i=e[n.name.split(".")[0]];if(n.required){let s=r.some((o)=>o.negated&&o.names.includes(n.name));if(i===!0||i===!1&&!s)throw new Ls(`Option \`${n.rawName}\` requires a value.
319
378
 
320
- Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class BJ extends fJ{constructor(w){super("@@global@@","",{},w)}}var jG=fJ,W$={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 p1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function QG(){return!0}function zG(){let w={};w.supportsColor=QG();function $(A,X=[]){let J=A===""?[]:[...X,A],U=function(W){if(!w.supportsColor)return W;let Q="",z="";for(let f of J)if(f in p1&&p1[f]in W$){let B=p1[f];Q+=W$[B][0],z=W$[B][1]+z}else if(f in W$)Q+=W$[f][0],z=W$[f][1]+z;return Q+W+z},j=[...Object.keys(W$),...Object.keys(p1)];for(let W of j)if(!(W in U))Object.defineProperty(U,W,{get(){return $(W,J)}});return U}let Y=[...Object.keys(W$),...Object.keys(p1)];for(let A of Y)if(!(A in w))Object.defineProperty(w,A,{get(){return $(A)}});return w}var r1=zG();class GJ extends a6{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(w=""){super();this.name=w,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new BJ(this),this.globalCommand.usage("<command> [options]")}handleSignals(w){if(this.signalHandlersSet)return this;let $=async(Y)=>{if(console.log(`
379
+ Example: ${this.cli.name} ${this.rawName} ${n.rawName} <value>`)}}}}class ul extends ll{constructor(e){super("@@global@@","",{},e)}}var Ub=ll,yr={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 mi={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function Kb(){return!0}function Wb(){let e={};e.supportsColor=Kb();function t(n,i=[]){let s=n===""?[]:[...i,n],o=function(a){if(!e.supportsColor)return a;let l="",u="";for(let f of s)if(f in mi&&mi[f]in yr){let h=mi[f];l+=yr[h][0],u=yr[h][1]+u}else if(f in yr)l+=yr[f][0],u=yr[f][1]+u;return l+a+u},c=[...Object.keys(yr),...Object.keys(mi)];for(let a of c)if(!(a in o))Object.defineProperty(o,a,{get(){return t(a,s)}});return o}let r=[...Object.keys(yr),...Object.keys(mi)];for(let n of r)if(!(n in e))Object.defineProperty(e,n,{get(){return t(n)}});return e}var gi=Wb();class fl extends Rb{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(e=""){super();this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new ul(this),this.globalCommand.usage("<command> [options]")}handleSignals(e){if(this.signalHandlersSet)return this;let t=async(r)=>{if(console.log(`
321
380
 
322
- Received ${Y}, cleaning up...`),w)try{await w()}catch(A){console.error("Error during cleanup:",A)}U$.exit(0)};return U$.on("SIGINT",()=>$("SIGINT")),U$.on("SIGTERM",()=>$("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(w=!0){return this.enableDidYouMean=w,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(w){return this.globalCommand.usage(w),this}command(w,$,Y){if(!Y)Y={};let A=new jG(w,$||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option(w,$,Y){return this.globalCommand.option(w,$,Y),this}help(w){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=w,this.showHelpOnExit=!0,this}version(w,$="-v, --version"){return this.globalCommand.version(w,$),this.showVersionOnExit=!0,this}example(w){return this.globalCommand.example(w),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:w,options:$},Y,A){if(this.args=w,this.options=$,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(w){if(console.log(r1.red(`
323
- ✗ Command "${w}" not found.
324
- `)),this.enableDidYouMean){let $=[];for(let A of this.commands){if(A.displayName)$.push(A.displayName);if(A.aliasNames)$.push(...A.aliasNames)}let Y=zQ(w,$);if(Y.length>0)console.log(r1.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${r1.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(r1.dim("Run"),`${this.name} --help`,r1.dim("to see all available commands")),U$.exit(1)}async parse(w=AQ,$={}){let{run:Y=!0,exitOnError:A=!1}=$;if(A)try{return await this.parse(w,{run:Y})}catch(W){throw this.handleUsageError(W),W}if(this.rawArgs=w,!this.name)this.name=w[1]?AG(w[1]):"cli";let X=!0,J=w.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let W of this.commands)if(W.isMatched(U)){let Q=this.mri(J,W);X=!1;let z={...Q,args:Q.args.slice(1)};this.setParsedInfo(z,W,U),this.emit(`command:${U}`,W);break}}if(X){for(let W of this.commands)if(W.name===""){X=!1;let Q=this.mri(J,W);this.setParsedInfo(Q,W),this.emit("command:!",W);break}}if(X){let W=this.mri(w.slice(2));this.setParsedInfo(W)}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(),Y=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),Y=!1,this.unsetMatchedCommand();let j={args:this.args,options:this.options};if(Y)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return j}mri(w,$){let Y=[...this.globalCommand.options,...$?$.options:[]],A=e6(Y),X=[],J=w.indexOf("--");if(J>-1)X=w.slice(J+1),w=w.slice(0,J);let U=s6(w,A),j={_:U._};for(let B of Object.keys(U))if(B!=="_")j[QQ(B)]=U[B];let W=j._,Q={"--":X},z=$&&$.config.ignoreOptionDefaultValue?$.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,f=Object.create(null);for(let B of Y){if(!z&&B.config.default!==void 0)for(let G of B.names)Q[G]=B.config.default;if(Array.isArray(B.config.type)){if(f[B.name]===void 0)f[B.name]={shouldTransform:!0,transformFunction:B.config.type[0]}}}for(let B of Object.keys(j))if(B!=="_"){let G=B.split(".");$G(Q,G,j[B]),YG(Q,f)}return{args:W,options:Q}}async run(w=AQ){return this.parse(w,{run:!0,exitOnError:!0})}handleUsageError(w){if(!(!!w&&typeof w==="object"&&w.name==="ClappError"&&w.isUsageError!==!1))return;let A=w,X=A.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
325
- Run \`${this.name??"cli"} --help\` for usage.`;U$.stderr.write(`${J}${X}${U}
326
- `),U$.exit(A.exitCode??2)}async runMatchedCommand(){let{args:w,options:$,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((j,W)=>{if(j.variadic)A.push(w.slice(W));else A.push(w[W])}),A.push($);let X={command:Y,args:A,options:$};for(let j of Y.beforeHooks)await j(X);let J,U=async()=>{let j=Y.commandAction.apply(this,A);if(j instanceof Promise)J=await j;else J=j;return J};if(Y.middleware.length>0){let j=0,W=async()=>{if(j<Y.middleware.length){let Q=Y.middleware[j++];await Q({...X,next:W})}else await U()};await W()}else await U();for(let j of Y.afterHooks)await j(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return U$.removeAllListeners("SIGINT"),U$.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 BQ{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(w){if(!this.enabled){this.misses++;return}let $=this.cache.get(w);if(!$){this.misses++;return}if(Date.now()-$.timestamp>$.ttl){this.cache.delete(w),this.misses++;return}return this.hits++,$.value}set(w,$,Y=5000){if(!this.enabled)return;this.cache.set(w,{value:$,timestamp:Date.now(),ttl:Y})}has(w){if(!this.enabled)return!1;let $=this.cache.get(w);if(!$)return!1;if(Date.now()-$.timestamp>$.ttl)return this.cache.delete(w),!1;return!0}delete(w){this.cache.delete(w)}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 w=Date.now();for(let[$,Y]of this.cache.entries())if(w-Y.timestamp>Y.ttl)this.cache.delete($)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var jM=new BQ;function fG(){if("FORCE_COLOR"in t1.env)return t1.env.FORCE_COLOR!=="0";if("NO_COLOR"in t1.env||t1.env.TERM==="dumb")return!1;if(t1.platform==="win32")return!0;return XQ.isatty(1)&&XQ.isatty(2)}var GQ=fG();function J0(w,$){if(!GQ)return(Y)=>Y;return(Y)=>w+Y+$}var BG=J0("\x1B[0m","\x1B[0m"),GG=J0("\x1B[31m","\x1B[39m"),KG=J0("\x1B[32m","\x1B[39m"),FG=J0("\x1B[33m","\x1B[39m"),EG=J0("\x1B[34m","\x1B[39m"),TG=J0("\x1B[35m","\x1B[39m"),NG=J0("\x1B[36m","\x1B[39m"),qG=J0("\x1B[37m","\x1B[39m"),HG=J0("\x1B[90m","\x1B[39m"),RG=J0("\x1B[1m","\x1B[22m"),MG=J0("\x1B[3m","\x1B[23m"),IG=J0("\x1B[4m","\x1B[24m"),yG=J0("\x1B[2m","\x1B[22m"),CG=J0("\x1B[7m","\x1B[27m"),VG=J0("\x1B[8m","\x1B[28m"),LG=J0("\x1B[9m","\x1B[29m"),OG=J0("\x1B[41m","\x1B[49m"),SG=J0("\x1B[42m","\x1B[49m"),_G=J0("\x1B[43m","\x1B[49m"),hG=J0("\x1B[44m","\x1B[49m"),DG=J0("\x1B[45m","\x1B[49m"),xG=J0("\x1B[46m","\x1B[49m"),kG=J0("\x1B[47m","\x1B[49m"),ZG=GQ,PG={reset:BG,red:GG,green:KG,yellow:FG,blue:EG,magenta:TG,cyan:NG,white:qG,gray:HG,bold:RG,italic:MG,underline:IG,dim:yG,inverse:CG,hidden:VG,strikethrough:LG,bgRed:OG,bgGreen:SG,bgYellow:_G,bgBlue:hG,bgMagenta:DG,bgCyan:xG,bgWhite:kG,isColorSupported:ZG},oY=PG,bG=["up","down","left","right","space","enter","cancel"],eY={actions:new Set(bG),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function KQ(w,$){if(typeof w==="string")return eY.aliases.get(w)===$;for(let Y of w){if(Y===void 0)continue;if(KQ(Y,$))return!0}return!1}function uG(w,$){if(w===$)return[];let Y=w.split(`
327
- `),A=$.split(`
328
- `),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var KM=iG.platform.startsWith("win"),JQ=Symbol("clapp:cancel");function tY(w,$){let Y=w;if(Y.isTTY)Y.setRawMode($)}function gG(w){return w.replace(/\x1b\[[0-9;]*m/g,"")}function dG(w){return gG(w).length}function WQ(w,$,Y){if(!$||$<1)return w;let A=Y?.hard??!1,X=Y?.trim??!0,J=w.split(`
329
- `),U=[];for(let j of J){if(dG(j)<=$){U.push(X?j.trimEnd():j);continue}if(A){let W="",Q=0,z=0;while(z<j.length){let f=j.slice(z).match(/^\x1b\[[0-9;]*m/);if(f){W+=f[0],z+=f[0].length;continue}if(Q>=$)U.push(X?W.trimEnd():W),W="",Q=0;W+=j[z],Q++,z++}if(W)U.push(X?W.trimEnd():W)}else U.push(X?j.trimEnd():j)}return U.join(`
330
- `)}class KJ{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:Y=vG,output:A=cG,render:X,signal:J,...U}=w;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=$,this._abortSignal=J,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber(w,$){let Y=this._subscribers.get(w)??[];Y.push($),this._subscribers.set(w,Y)}on(w,$){return this.setSubscriber(w,{cb:$}),this}once(w,$){return this.setSubscriber(w,{cb:$,once:!0}),this}emit(w,...$){let Y=this._subscribers.get(w)??[],A=[];for(let X of Y)if(X.cb(...$),X.once)A.push(()=>Y.splice(Y.indexOf(X),1));for(let X of A)X();return this}prompt(){return new Promise((w)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),w(JQ);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=mG.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),tY(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(xw.show),this.output.off("resize",this.render),tY(this.input,!1),w(this.value)}),this.once("cancel",()=>{this.output.write(xw.show),this.output.off("resize",this.render),tY(this.input,!1),w(JQ)})})}_isActionKey(w,$){return w==="\t"}_setValue(w){this.value=w,this.emit("value",this.value)}_setUserInput(w,$){if(this.userInput=w??"",this.emit("userInput",this.userInput),$&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(w,$){if(this._track&&$.name!=="return"){if($.name&&this._isActionKey(w,$))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=$.name==="tab"||$.name==="escape"||$.name==="backspace"||$.name==="delete"||$.name==="enter"||$.name==="return"||$.name&&["up","down","left","right"].includes($.name);if(w&&!Y&&w.length===1&&w>=" ")this._manualLine+=w;else if($.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let A=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(A)}if(this.state==="error")this.state="active",this.error="";if($?.name){if(!this._track&&eY.aliases.has($.name))this.emit("cursor",eY.aliases.get($.name));if(eY.actions.has($.name))this.emit("cursor",$.name)}if(w&&(w.toLowerCase()==="y"||w.toLowerCase()==="n"))this.emit("confirm",w.toLowerCase()==="y");if(this.emit("key",w?.toLowerCase(),$),$?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(KQ([w,$?.name,$?.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(`
331
- `),tY(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 w=WQ(this._prevFrame,UQ.stdout.columns,{hard:!0,trim:!1}).split(`
332
- `).length-1;this.output.write(xw.move(-999,w*-1))}render(){let w=WQ(this._render(this)??"",UQ.stdout.columns,{hard:!0,trim:!1});if(w===this._prevFrame)return;if(this.state==="initial")this.output.write(xw.hide);else{let $=uG(this._prevFrame,w);if(this.restoreCursor(),$&&$?.length===1){let Y=$[0];this.output.write(xw.move(0,Y)),this.output.write(jJ.lines(1));let A=w.split(`
333
- `);this.output.write(A[Y]),this._prevFrame=w,this.output.write(xw.move(0,A.length-Y-1));return}if($&&$?.length>1){let Y=$[0];this.output.write(xw.move(0,Y)),this.output.write(jJ.down());let X=w.split(`
334
- `).slice(Y);this.output.write(X.join(`
335
- `)),this._prevFrame=w;return}this.output.write(jJ.down())}if(this.output.write(w),this.state==="initial")this.state="active";this._prevFrame=w}}function nG(w,$){if(w===void 0)return 0;if($.length===0)return 0;let A=$.findIndex((X)=>X.value===w);return A!==-1?A:0}function lG(w,$){return($.label??String($.value)).toLowerCase().includes(w.toLowerCase())}function pG(w,$){if(!$)return;if(w)return $;return $[0]}class rG extends KJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#w=0;#Y="";#A;#$;get cursor(){return this.#w}get userInputWithCursor(){if(!this.userInput)return oY.inverse(oY.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let w=this.userInput.slice(0,this._cursor),[$,...Y]=this.userInput.slice(this._cursor);return`${w}${oY.inverse($)}${Y.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(w){super(w);this.#$=w.options;let $=this.options;this.filteredOptions=[...$],this.multiple=w.multiple===!0,this.#A=w.filter??lG;let Y;if(w.initialValue&&Array.isArray(w.initialValue))if(this.multiple)Y=w.initialValue;else Y=w.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let A of Y){let X=$.findIndex((J)=>J.value===A);if(X!==-1)this.toggleSelected(A),this.#w=X}this.focusedValue=this.options[this.#w]?.value,this.on("key",(A,X)=>this.#X(A,X)),this.on("userInput",(A)=>this.#J(A))}_isActionKey(w,$){return w==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&w!==void 0&&w!==""}#X(w,$){let Y=$.name==="up",A=$.name==="down",X=$.name==="return";if(Y||A){if(this.#w=Math.max(0,Math.min(this.#w+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(X)this.value=pG(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.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(w){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(w))this.selectedValues=this.selectedValues.filter(($)=>$!==w);else this.selectedValues=[...this.selectedValues,w];else this.selectedValues=[w]}#J(w){if(w!==this.#Y){this.#Y=w;let $=this.options;if(w)this.filteredOptions=$.filter((Y)=>this.#A(w,Y));else this.filteredOptions=[...$];if(this.#w=nG(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class tG extends KJ{options;cursor=0;#w;getGroupItems(w){return this.options.filter(($)=>$.group===w)}isGroupSelected(w){let $=this.getGroupItems(w),Y=this.value;if(Y===void 0)return!1;return $.every((A)=>Y.includes(A.value))}toggleValue(){let w=this.options[this.cursor];if(this.value===void 0)this.value=[];if(w.group===!0){let $=String(w.value),Y=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((A)=>Y.findIndex((X)=>X.value===A)===-1);else this.value=[...this.value,...Y.map((A)=>A.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(w.value);this.value=$?this.value.filter((Y)=>Y!==w.value):[...this.value,w.value]}}constructor(w){super(w,!1);let{options:$}=w;this.#w=w.selectableGroups!==!1,this.options=Object.entries($).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((X)=>({...X,group:Y}))]),this.value=[...w.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===w.cursorAt),this.#w?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let A=this.options[this.cursor]?.group===!0;if(!this.#w&&A)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 A=this.options[this.cursor]?.group===!0;if(!this.#w&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var aG=XG();var $0=(w,$)=>aG?w:$,TM=$0("◆","*"),NM=$0("■","x"),qM=$0("▲","x"),HM=$0("◇","o"),RM=$0("┌","T"),sG=$0("│","|"),MM=$0("└","—"),IM=$0("●",">"),yM=$0("○"," "),CM=$0("◻","[•]"),VM=$0("◼","[+]"),LM=$0("◻","[ ]"),OM=$0("▪","•"),SM=$0("─","-"),_M=$0("╮","+"),hM=$0("├","+"),DM=$0("╯","+"),xM=$0("●","•"),kM=$0("◆","*"),ZM=$0("▲","!"),PM=$0("■","x");var iM={light:$0("─","-"),heavy:$0("━","="),block:$0("█","#")};function oG(){return`${oY.gray(sG)} `}var bM=oG();bA();QU();b8();D$();f0();import{spawn as hR}from"node:child_process";import*as d8 from"node:process";class n8{processes=new Map;isShuttingDown=!1;async startProcess(w,$,Y){if(this.processes.has(w)){K("start",`Process ${w} is already running`,Y);return}let[A,...X]=$.command.split(" "),J=$.cwd||d8.cwd();K("start",`Starting process ${w}:`,Y),K("start",` Command: ${A} ${X.join(" ")}`,Y),K("start",` Working directory: ${J}`,Y),K("start",` Environment variables: ${$$($.env)}`,Y);let U=hR(A,X,{cwd:J,env:{...d8.env,...$.env},shell:!0,stdio:"inherit"});return this.processes.set(w,{command:$.command,cwd:J,process:U,env:$.env}),new Promise((j,W)=>{if(U.on("error",(Q)=>{if(!this.isShuttingDown)K("start",`Process ${w} failed to start: ${Q}`,Y),this.processes.delete(w),W(Q)}),U.on("exit",(Q)=>{if(!this.isShuttingDown&&Q!==null&&Q!==0)K("start",`Process ${w} exited with code ${Q}; leaving the proxy running`,Y),this.processes.delete(w),W(Error(`Process ${w} exited with code ${Q}`))}),Y)U.stdout?.on("data",(Q)=>{K("process",`[${w}] ${Q.toString().trim()}`,!0)}),U.stderr?.on("data",(Q)=>{K("process",`[${w}] ERR: ${Q.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete(w),W(Error(`Process ${w} was killed during startup`));else K("start",`Process ${w} started successfully`,Y),j()},1000)})}async stopProcess(w,$){let Y=this.processes.get(w);if(!Y?.process){K("start",`No process found for ${w}`,$);return}return K("start",`Stopping process ${w}`,$),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete(w),K("start",`Process ${w} stopped`,$),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){K("start",`Force killing process ${w}`,$);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){K("start",`Error stopping process ${w}: ${X}`,$),this.processes.delete(w),A()}})}async stopAll(w){if(this.isShuttingDown){K("start","Already shutting down, skipping duplicate stopAll call",w);return}this.isShuttingDown=!0,K("start","Stopping all processes",w);let $=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,w).catch((A)=>{H.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled($),this.processes.clear(),this.isShuttingDown=!1}isRunning(w){let $=this.processes.get(w);return!!$?.process&&!$.process.killed}}var l8=new n8;m$();D$();import{execSync as bR}from"node:child_process";import*as e8 from"node:http";import*as x6 from"node:net";import*as wJ from"node:os";import*as k6 from"node:path";import*as d from"node:process";var p8=(w,$)=>(Y)=>`\x1B[${w}m${Y}\x1B[${$}m`,hw={bold:p8(1,22),dim:p8(2,22),green:p8(32,39),cyan:p8(36,39)};bA();b8();D$();m$();f0();import*as O6 from"node:fs";import*as S6 from"node:path";import*as Dw from"node:process";function DR(w,$){let A=($&&$!=="/"?`${w}${$}`:w).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function nj(w){if(w.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let $=w.verbose??!1,Y=w.registryDir,A=new Set,X=w.proxies.map((B)=>{let G=B.id??DR(B.to,B.path);if(!y$(G))throw Error(`invalid registry id "${G}" derived from to="${B.to}"`);if(A.has(G))throw Error(`duplicate registry id "${G}" — set an explicit \`id\` on one of the proxies`);return A.add(G),{...B,id:G}}),J=new Date().toISOString();for(let B of X)await u1({id:B.id,from:B.from,to:B.to,path:B.path,pid:w.persistent?void 0:Dw.pid,cwd:Dw.cwd(),createdAt:J,cleanUrls:B.cleanUrls,changeOrigin:B.changeOrigin,pathRewrites:B.pathRewrites,static:B.static,loadBalancer:B.loadBalancer},Y,$);let U=await g8({rpxDir:w.rpxDir,verbose:$,spawnCommand:w.spawnCommand,startupTimeoutMs:w.startupTimeoutMs,spawnEnv:w.spawnEnv});for(let B of X){let G=B.static?`static ${typeof B.static==="string"?B.static:B.static.dir}`:B.from;H.success(`https://${B.to} → ${G}`)}if(H.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),w.detached)return;let j=!1,W=Y??Xw(),Q=X.map((B)=>B.id),z=async()=>{if(j)return;j=!0;for(let B of Q)await c$(B,Y,$).catch((G)=>{K("runner",`removeEntry(${B}) failed: ${G}`,$)})},f=(B)=>{K("runner",`received ${B}, unregistering ${Q.length} entries`,$),z().finally(()=>Dw.exit(0))};Dw.once("SIGINT",f),Dw.once("SIGTERM",f),Dw.once("exit",()=>{if(j)return;for(let B of Q)try{O6.unlinkSync(S6.join(W,`${B}.json`))}catch{}}),await new Promise(()=>{})}Dj();Gj();Ij();import{timingSafeEqual as xR}from"node:crypto";function kR(w,$){if(w==null)return!1;let Y=Buffer.from(w),A=Buffer.from($);if(Y.length!==A.length)return!1;return xR(Y,A)}function r8(w){return w.toLowerCase().replace(/\.$/,"")}var ZR=["/.well-known/acme-challenge/"];function PR(w){let $=w.headers.get("host");if($)return r8($.split(":")[0]);try{return r8(new URL(w.url).hostname)}catch{return""}}function _6(w){let $=w.header.toLowerCase(),Y=new Set,A=[];for(let W of w.hosts){let Q=r8(W);if(Q.startsWith("*."))A.push(Q);else Y.add(Q)}let X=w.exemptPaths??ZR,J=w.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
336
- `,U=(W)=>{let Q=r8(W);return Y.has(Q)||A.some((z)=>h$(Q,z))},j=(W)=>{let Q=PR(W);if(!U(Q))return;let z="/";try{z=new URL(W.url).pathname}catch{}if(X.some((f)=>z.startsWith(f)))return;if(kR(W.headers.get($),w.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return j.protects=U,j}Ej();Tj();N8();y8();Hj();Rj();M8();f0();var h6={name:"@stacksjs/rpx",type:"module",version:"0.11.45",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build --production ./bin/cli.ts --compile --outfile bin/rpx",compile:"bun build --production ./bin/cli.ts --compile --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build --production ./bin/cli.ts --compile --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build --production ./bin/cli.ts --compile --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build --production ./bin/cli.ts --compile --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build --production ./bin/cli.ts --compile --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build --production ./bin/cli.ts --compile --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.13"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var gY=h6.version;var a8=new n8,uR=new L8("0.0.0.0"),nY=new Set,o8=new Set,lj=!1,t8=null,pj=null;async function $J(w){if(lj)return K("cleanup","Cleanup already in progress, skipping",w?.verbose),pj||Promise.resolve();lj=!0,K("cleanup","Starting cleanup process",w?.verbose),pj=new Promise(($)=>{t8=$});try{await a8.stopAll(w?.verbose),H.info("Shutting down proxy servers...");let $=[],Y=Array.from(nY).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),K("cleanup","Bun server stopped",w?.verbose),X();else if(typeof J.close==="function")J.close(()=>{K("cleanup","Server closed successfully",w?.verbose),X()});else X()}catch(U){K("cleanup",`Error stopping server: ${U}`,w?.verbose),X()}}));$.push(...Y),nY.clear();for(let A of o8)i1(A);if(o8.clear(),w?.hosts&&w.domains?.length){K("cleanup","Cleaning up hosts file entries",w?.verbose),K("cleanup",`Original domains for cleanup: ${JSON.stringify(w.domains)}`,w?.verbose);let A=w.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(K("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,w?.verbose),A.length>0)H.info("Cleaning up hosts file entries..."),$.push(w6(A,w?.verbose).then(()=>{K("cleanup",`Removed hosts entries for ${A.join(", ")}`,w?.verbose)}).catch((X)=>{K("cleanup",`Failed to remove hosts entries: ${X}`,w?.verbose),H.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if(w?.certs&&w.domains?.length){K("cleanup","Cleaning up SSL certificates",w?.verbose),H.info("Cleaning up SSL certificates...");let A=w.domains.map(async(X)=>{try{await K2(X,w?.verbose),K("cleanup",`Removed certificates for ${X}`,w?.verbose)}catch(J){K("cleanup",`Failed to remove certificates for ${X}: ${J}`,w?.verbose),H.warn(`Failed to clean up certificates for ${X}:`,J)}});$.push(...A)}await Promise.allSettled($),K("cleanup","All cleanup tasks completed successfully",w?.verbose),H.success("All cleanup tasks completed successfully")}catch($){K("cleanup",`Error during cleanup: ${$}`,w?.verbose),H.error("Error during cleanup:",$)}finally{if(t8)t8();t8=null,lj=!1;let $=w&&"vitePluginUsage"in w&&w.vitePluginUsage===!0;if(d.env.NODE_ENV!=="test"&&d.env.BUN_ENV!=="test"&&!$)d.exit(0)}return pj}var rj=!1;function Z6(w){if(rj){K("signal",`Received second ${w} signal, forcing exit`,!0),d.exit(1);return}rj=!0,K("signal",`Received ${w} signal, initiating cleanup`,!0),$J().catch(($)=>{K("signal",`Cleanup failed after ${w}: ${$}`,!0),d.exit(1)}).finally(()=>{rj=!1})}d.once("SIGINT",()=>Z6("SIGINT"));d.once("SIGTERM",()=>Z6("SIGTERM"));d.on("uncaughtException",(w)=>{H.error("Uncaught exception (continuing):",w)});d.on("unhandledRejection",(w)=>{H.error("Unhandled rejection (continuing):",w)});async function lY(w,$,Y,A=5){K("connection",`Testing connection to ${w}:${$} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(d.env.RPX_BYPASS_CONNECTION_TEST==="true"){K("connection",`Bypassing connection test for ${w}:${$} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((j,W)=>{let Q=x6.connect({host:w,port:$,timeout:3000});Q.once("connect",()=>{K("connection",`Successfully connected to ${w}:${$}`,Y),Q.end(),j()}),Q.once("timeout",()=>{K("connection",`Connection to ${w}:${$} timed out`,Y),Q.destroy(),W(Error("Connection timed out"))}),Q.once("error",(z)=>{K("connection",`Failed to connect to ${w}:${$}: ${z}`,Y),Q.destroy(),W(z)})});try{await U()}catch(j){let W=j;if(Date.now()-J>X){K("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),H.warn(`Connection test to ${w}:${$} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&A>0)return K("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),lY(w,$,Y,A-1);if(A>0)try{K("connection",`Trying HTTP request to ${w}:${$}`,Y),await new Promise((z,f)=>{let B=e8.request({hostname:w,port:$,path:"/",method:"HEAD",timeout:5000},(G)=>{K("connection",`Received HTTP response with status: ${G.statusCode}`,Y),z()});B.on("error",(G)=>f(G)),B.on("timeout",()=>{B.destroy(),f(Error("HTTP request timed out"))}),B.end()}),K("connection",`HTTP request to ${w}:${$} succeeded`,Y);return}catch(z){return K("connection",`HTTP request to ${w}:${$} failed: ${z}`,Y),K("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((f)=>setTimeout(f,2000)),lY(w,$,Y,A-1)}let Q=`Failed to connect to ${w}:${$} after ${5-A} attempts: ${W.message}`;K("connection",`${Q}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),H.warn(Q),H.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 P6(w){K("server",`Starting server with options: ${$$(w)}`,w.verbose);let $=b$(w.from),Y=new URL($.startsWith("http")?$:`http://${$}`),A=new URL((w.to?.startsWith("http")?w.to:`http://${w.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(tj(w)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){K("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,w?.verbose);try{if(!(await bY(J,w.verbose))[0]){H.info(`Adding ${A.hostname} to hosts file...`),H.info("This may require sudo/administrator privileges");try{await iY(J,w.verbose)}catch(W){if(H.error("Failed to add hosts entry:",W.message),H.warn("You can manually add this entry to your hosts file:"),H.warn(`127.0.0.1 ${A.hostname}`),H.warn(`::1 ${A.hostname}`),d.platform==="win32")H.warn("On Windows:"),H.warn("1. Run notepad as administrator"),H.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else H.warn("On Unix systems:"),H.warn("sudo nano /etc/hosts")}}else K("hosts",`Host entry already exists for ${A.hostname}`,w.verbose)}catch(j){H.error("Failed to check hosts file:",j.message)}}try{await lY(Y.hostname,X,w.verbose)}catch(j){K("server",`Connection test failed: ${j}`,w.verbose),H.error(j.message),H.warn("Continuing with proxy setup despite connection test failure..."),H.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=w._cachedSSLConfig||null;if(w.https)try{if(w.https===!0)w.https=HY({...w,to:A.hostname});if(U=await M$({...w,to:A.hostname,https:w.https}),!U){if(K("ssl",`Generating new certificates for ${A.hostname}`,w.verbose),await qY({...w,from:Y.toString(),to:A.hostname,https:w.https}),U=await M$({...w,to:A.hostname,https:w.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(j){throw K("server",`SSL setup failed: ${j}`,w.verbose),j}K("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,w.verbose),await cR({...w,from:$,originalFrom:w.from||$,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function vR(w,$,Y,A,X,J,U,j,W,Q,z,f){K("proxy",`Creating proxy server ${w} -> ${$} with cleanUrls: ${j}`,U);let B=RY(z??A.host,f);IY(B);let G=[{host:$,route:{sourceHost:A.host,upstreamPool:B,cleanUrls:j||!1,changeOrigin:W||!1,basePath:"/",auth:Q}}];if(!s8({routeEntries:G,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw i1(B),Error(`Failed to start proxy server for ${$} on port ${Y}`);o8.add(B),gR({from:w,to:$,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:j,verbose:U})}async function cR(w){K("setup",`Setting up reverse proxy: ${$$(w)}`,w.verbose);let{from:$,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:j,vitePluginUsage:W,changeOrigin:Q,cleanUrls:z}=w,f=80,B=443,G=v6(),T=w.portManager||uR,F=tj(w);try{if(F&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await bY([A],U))[0]){H.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await iY([A],U),H.success(`Added ${A} to your hosts file.`)}catch(L){H.error(`Failed to add ${A} to your hosts file: ${L}`),H.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(F&&d.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await bY([A],U))[0]){K("hosts",`${A} not found in hosts file, adding...`,U);try{await iY([A],U)}catch(L){K("hosts",`Failed to add ${A} to hosts file: ${L}`,U)}}}if(J&&!T.usedPorts.has(f)){if(!await I$(f,G,U))K("setup","Starting HTTP redirect server",U),i6(U),T.usedPorts.add(f);else if(K("setup","Port 80 is in use, skipping HTTP redirect",U),U)H.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let E=J?B:f,N=await I$(E,G,U),R;if(N){if(K("setup",`Port ${E} is already in use`,U),U)H.warn(`Port ${E} is already in use. This may be another instance of rpx or another service.`);if(E===443){if(R=await T.getNextAvailablePort(3443,!0),K("setup",`Using port ${R} instead of ${E}`,U),U)H.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await T.getNextAvailablePort(E+1000,!0),K("setup",`Using port ${R} instead of ${E}`,U),U)H.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=E,T.usedPorts.add(R),K("setup",`Using standard ${E===443?"HTTPS":"HTTP"} port ${E} for ${A}`,U);await vR($,A,R,X,J,W,U,z,Q,CY(w.auth),Y,w.loadBalancer)}catch(E){K("setup",`Setup failed: ${E}`,U),H.error(`Failed to setup reverse proxy: ${E.message}`),$J({domains:[A],hosts:typeof j==="boolean"?j:j?.hosts,certs:typeof j==="boolean"?j:j?.certs,verbose:U,vitePluginUsage:W})}}function i6(w,$=80,Y=443,A,X,J){K("redirect",`Starting HTTP redirect server on port ${$}`,w);let U=e8.createServer((j,W)=>{let Q=j.url?j.url.split("?",1)[0]:"";if(Q.startsWith("/.well-known/acme-challenge/")){if(X){let G=X.challengeStore.handlePath(Q);if(G!==void 0){K("redirect",`Serving on-demand ACME challenge ${Q}`,w),W.writeHead(200,{"content-type":"text/plain"}),W.end(G);return}}if(A){let G=I8(A,Q);if(G!=null){K("redirect",`Serving ACME challenge ${Q}`,w),W.writeHead(200,{"content-type":"text/plain"}),W.end(G);return}}if(X){W.writeHead(404,{"content-type":"text/plain"}),W.end("challenge not found");return}}let z=j.headers.host||"",f=z.includes(":")?z.slice(0,z.indexOf(":")):z;if(X&&f&&!X.hasCert(f)&&(!J||J(f)))X.ensureCert(f).catch(()=>{});let B=Y===443?f:`${f}:${Y}`;K("redirect",`Redirecting request from ${z}${j.url} to https://${B}`,w),W.writeHead(301,{Location:`https://${B}${j.url}`}),W.end()}).listen($);nY.add(U),K("redirect","HTTP redirect server started",w)}function b6(w){let $={...vw,...w};if(K("proxy",`Starting proxy with options: ${$$($)}`,$?.verbose),$.viaDaemon){if(!$.from||!$.to){H.error("viaDaemon mode requires both `from` and `to`");return}nj({proxies:[{id:$.id,from:$.from,to:$.to,path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}],verbose:$.verbose}).catch((W)=>{H.error(`Failed to register with rpx daemon: ${W.message}`),d.exit(1)});return}let Y=$.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=d.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(A)&&$?.verbose)H.warn(`The .${A} TLD may not work reliably for local development`),H.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),H.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (mY(),i8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:$.verbose}).then((Q)=>{if(Q)Promise.resolve().then(()=>{if($.verbose)if(U.includes(A))H.success(`DNS server started for .${A} domains`);else H.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else K("dns",`Could not start DNS server - ${Y} may not resolve in browser`,$.verbose)})}).catch((W)=>{K("dns",`Failed to start DNS server: ${W}`,$.verbose)});let j={from:$.from,to:$.to,cleanUrls:$.cleanUrls,https:HY($),cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,changeOrigin:$.changeOrigin,verbose:$.verbose,regenerateUntrustedCerts:$.regenerateUntrustedCerts};K("proxy",`Server options: ${$$(j)}`,$.verbose),P6(j).catch((W)=>{K("proxy",`Failed to start proxy: ${W}`,$.verbose),H.error(`Failed to start proxy: ${W.message}`),$J({domains:[$.to],hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose})})}function mR(w){return w?.verbose||!1}function tj(w){if(w?.hostsManagement===!1)return!1;let $=w?.cleanup;if($===!1)return!1;if($&&typeof $==="object"&&$.hosts===!1)return!1;return!0}async function u6(w){let $={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 Y=mR($),A=tj($);if(K("config",`Starting with config: ${$$($,2)}`,Y),K("config",`Is multi-proxy? ${"proxies"in $}`,Y),K("config",`Hosts management enabled? ${A}`,Y),$.viaDaemon){let C="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((M)=>({id:M.id,from:M.from,to:M.to,path:M.path,cleanUrls:M.cleanUrls??$.cleanUrls,changeOrigin:M.changeOrigin??$.changeOrigin,pathRewrites:M.pathRewrites})):[{id:$.id,from:$.from,to:$.to??"rpx.localhost",path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}];await nj({proxies:C,verbose:Y});return}if("proxies"in $&&Array.isArray($.proxies)){K("servers",`Found ${$.proxies.length} proxies in config`,Y);for(let q of $.proxies)if(q.start){let C=`${q.from}-${q.to}`;try{K("watch",`Starting command for ${C} with command: ${q.start.command}`,Y),H.info(`Starting command for ${C}...`),await a8.startProcess(C,q.start,Y);let M=b$(q.from),D=new URL(M.startsWith("http")?M:`http://${M}`),n=D.hostname||"localhost",a0=Number(D.port)||80;try{await lY(n,a0,Y),K("watch",`Dev server is ready at ${n}:${a0}`,Y)}catch(Uw){K("watch",`Connection check failed, but continuing with proxy setup: ${Uw}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw K("watch",`Failed to start command for ${C}: ${M}`,Y),Error(`Failed to start command for ${C}: ${M}`)}}else K("watch",`No start command for proxy ${q.from} -> ${q.to}`,Y)}else if("start"in $&&$.start){K("watch","Found start command in single proxy config",Y);let q=`${$.from}-${$.to}`;try{if($.start)K("watch",`Starting command: ${$.start.command}`,Y),await a8.startProcess(q,$.start,Y);let C=b$($.from),M=new URL(C.startsWith("http")?C:`http://${C}`),D=M.hostname||"localhost",n=Number(M.port)||80;try{await lY(D,n,Y),K("watch",`Dev server is ready at ${D}:${n}`,Y)}catch(a0){K("watch",`Connection check failed, but continuing with proxy setup: ${a0}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(C){throw K("watch",`Failed to run start command: ${C}`,Y),Error(`Failed to run start command: ${C}`)}}else K("watch","No start command found in config",Y);let X="proxies"in $&&Array.isArray($.proxies)?$.proxies[0]?.to:("to"in $)?$.to:"rpx.localhost";if(d.platform!=="win32"&&($.https||A)){if(!E$())try{K("sudo","Pre-acquiring sudo credentials for privileged operations",Y),bR("sudo -v",{stdio:"inherit"})}catch{K("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if($.productionCerts){if(J=await DY($.productionCerts,Y),J.length>0)K("ssl",`Using ${J.length} production SNI cert(s): ${J.map((q)=>q.serverName).join(", ")}`,Y)}if($.https){let q=J.length>0?null:await M$($);if(!q&&J.length===0){if(K("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,$.verbose),await qY($),q=await M$($),!q)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else K("ssl",`Using existing and trusted certificates for ${X}`,$.verbose);$._cachedSSLConfig=q}let U="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((q)=>({...q,https:$.https,cleanup:$.cleanup,cleanUrls:q.cleanUrls??("cleanUrls"in $?$.cleanUrls:!1),vitePluginUsage:$.vitePluginUsage,changeOrigin:q.changeOrigin??$.changeOrigin,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig})):[{from:"from"in $?$.from:"localhost:5173",to:"to"in $?$.to:"rpx.localhost",cleanUrls:"cleanUrls"in $?$.cleanUrls:!1,https:$.https,cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,start:"start"in $?$.start:void 0,changeOrigin:$.changeOrigin,auth:"auth"in $?$.auth:void 0,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig}],j=U.map((q)=>q.to||"rpx.localhost"),W=J.length>0?J:$._cachedSSLConfig??null,Q=j.filter((q)=>q&&!q.includes("localhost")&&!q.includes("127.0.0.1")),z=["dev","app","page","new","day","foo"],f=["test","localhost","local","example","invalid"],B=[...new Set(Q.map((q)=>q.split(".").pop()?.toLowerCase()))],G=B.filter((q)=>!!q&&z.includes(q));if(G.length>0&&Y)H.warn(`The following TLDs may not work reliably for local development: ${G.map((q)=>`.${q}`).join(", ")}`),H.info(" These TLDs have HSTS preloading which can bypass local DNS"),H.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&d.platform==="darwin"&&Q.length>0){let{setupDevelopmentDns:q}=await Promise.resolve().then(() => (mY(),i8));if(await q({domains:Q,verbose:Y})){if(Y)if(B.every((D)=>!!D&&f.includes(D)))H.success(`DNS server started for ${B.map((D)=>`.${D}`).join(", ")} domains`);else H.success(`DNS server started for ${B.map((D)=>`.${D}`).join(", ")} domains (hosts file entries also added)`)}else K("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{K("cleanup","Starting cleanup handler",$.verbose);try{let{tearDownDevelopmentDns:q}=await Promise.resolve().then(() => (mY(),i8));await q({verbose:$.verbose})}catch(q){K("cleanup",`Error stopping DNS server: ${q}`,$.verbose)}try{await a8.stopAll($.verbose)}catch(q){K("cleanup",`Error stopping processes: ${q}`,$.verbose)}await $J({domains:j,hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose||!1})};d.on("SIGINT",T),d.on("SIGTERM",T);let F=$.singlePortMode===!0,E=$.httpsPort??443,N=$.httpPort??80,R=$.originGuard?_6($.originGuard):null,V=!!W&&(U.length>1||F||J.length>0),L=!W&&F&&U.length>0;if(V&&W){K("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${E}`,Y);let q=await D6(U,A,Y),C=null,M=$.onDemandTls,D=M?.enabled?new b1({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??k6.join(wJ.homedir(),".stacks","rpx","on-demand-certs"),initial:J,verbose:Y,onCertAdded:(i0)=>{if(xY()==="restart")K("on-demand","certificate installed; restarting supervised gateway to reload TLS",Y),setTimeout(()=>d.kill(d.pid,"SIGTERM"),10).unref();else Uw(i0)}}):null,n=null,a0=!1;async function Uw(i0){if(n=i0,a0)return;a0=!0;try{while(n){let Ww=n;if(n=null,K("proxies",`rebuilding :${E} with ${Ww.length} SNI cert(s)`,Y),C)nY.delete(C),C.stop(!1);let v0=!1;for(let _=0;!v0&&_<60;_++){let c0=s8({routeEntries:q,listenPort:E,sslConfig:Ww,originGuard:R,verbose:Y});if(c0){C=c0,v0=!0;break}await new Promise((n1)=>setTimeout(n1,Math.min(25*2**Math.min(_,4),500)))}if(!v0)H.error(`rpx: CRITICAL — could not rebind :${E} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{a0=!1}}if(!await I$(N,"0.0.0.0",Y)){let i0=new Set(q.map((v0)=>v0.host)),Ww=(v0)=>i0.has(v0)||[...i0].some((_)=>h$(v0,_));i6(Y,N,E,$.acmeChallengeWebroot,D,Ww)}if(await I$(E,"0.0.0.0",Y)){if(K("proxies",`Port ${E} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${E} is in use. Shared HTTPS proxy cannot start.`);return}let J$=D&&D.sniEntries().length>0?D.sniEntries():W;if(C=s8({routeEntries:q,listenPort:E,sslConfig:J$,originGuard:R,verbose:Y}),!C){H.error(`Shared HTTPS proxy failed to bind :${E}; not exiting`);return}}else if(L){K("proxies",`Creating shared HTTP server for ${U.length} domains on port ${N}`,Y);let q=await D6(U,A,Y);if(await I$(N,"0.0.0.0",Y)){if(K("proxies",`Port ${N} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${N} is in use. Shared HTTP proxy cannot start.`);return}if(!s8({routeEntries:q,listenPort:N,sslConfig:null,originGuard:R,verbose:Y})){H.error(`Shared HTTP proxy failed to bind :${N}; not exiting`);return}}else for(let q of U)try{let C=q.to||"rpx.localhost";K("proxy",`Starting proxy for ${C} with SSL config: ${!!W}`,q.verbose),await P6({from:q.from||"localhost:5173",to:C,cleanUrls:q.cleanUrls||!1,https:q.https||!1,cleanup:q.cleanup||!1,vitePluginUsage:q.vitePluginUsage||!1,verbose:q.verbose||!1,_cachedSSLConfig:$._cachedSSLConfig,changeOrigin:q.changeOrigin||!1,loadBalancer:q.loadBalancer,auth:q.auth,path:q.path,pathRewrites:q.pathRewrites})}catch(C){K("proxies",`Failed to start proxy for ${q.to}: ${C}`,q.verbose),H.error(`Failed to start proxy for ${q.to}:`,C)}}async function D6(w,$,Y){let A=[],X=new Set;for(let J of w){let U=J.to||"rpx.localhost",j=J.cleanUrls||!1,W=J.path,Q=Y$(W),z=CY(J.auth);if(J.redirect){let f=_2(J.redirect);A.push({host:U,path:W,route:{redirect:f,basePath:Q,auth:z}}),K("proxies",`Route: ${U}${W??""} → redirect ${f.status} ${f.to}${z?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:R8(J.static,j),cleanUrls:j,basePath:Q,auth:z}}),K("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${z?" (auth)":""}`,Y);else{let f=b$(J.from),B=new URL(f.startsWith("http")?f:`http://${f}`),G=RY(J.from??B.host,J.loadBalancer);IY(G),o8.add(G),A.push({host:U,path:W,route:{sourceHost:B.host,upstreamPool:G,cleanUrls:j,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:Q,auth:z}}),K("proxies",`Route: ${U}${W??""} → ${B.host}${z?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),$&&!W1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await bY([U],Y))[0])await iY([U],Y)}catch{K("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}var dY=null;function v6(){if(d.env.RPX_BIND_HOSTNAME)return d.env.RPX_BIND_HOSTNAME;if(dY)return dY;try{dY=Object.values(wJ.networkInterfaces()).flat().some((Y)=>Y&&Y.family==="IPv6")?"::":"0.0.0.0"}catch{dY="0.0.0.0"}return dY}function s8(w){let{routeEntries:$,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=w,U=SY($),j=LY((z,f)=>_Y(U,z,f),J),W=X?(z,f)=>X(z)??j(z,f):j,Q=OY(J);try{let z=Bun.serve({port:Y,hostname:v6(),reusePort:TY(),...A?{tls:v$(Array.isArray(A)?A.map((f)=>({serverName:f.serverName,key:f.key,cert:f.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(f,B){return W(f,B)},websocket:Q,error(f){return K("server",`Shared proxy server error: ${f}`,J),new Response(`Server Error: ${f.message}`,{status:500})}});return nY.add(z),K("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),z}catch(z){return K("proxies",`Failed to start shared proxy: ${z}`,J),console.error("Failed to start shared proxy:",z),null}}function gR(w){if(w?.vitePluginUsage||!w?.verbose)return;if(console.log(""),console.log(` ${hw.green(hw.bold("rpx"))} ${hw.green(`v${gY}`)}`),console.log(` ${hw.green("➜")} ${hw.dim(w?.from??"")} ${hw.dim("➜")} ${hw.cyan(w?.ssl?`https://${w?.to}`:`http://${w?.to}`)}`),w?.listenPort!==(w?.ssl?443:80))console.log(` ${hw.green("➜")} Listening on port ${w?.listenPort}`);if(w?.cleanUrls)console.log(` ${hw.green("➜")} Clean URLs enabled`)}f0();P0.chdir(nR(dR(lR(import.meta.url)),".."));var u0=new GJ("rpx");u0.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("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").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").example("rpx start --single-port-mode --https-port 8443").action(async(w)=>{if(!w?.from||!w.to)return u6(vw);let $={from:w.from,to:w.to,https:{keyPath:w.keyPath,certPath:w.certPath,caCertPath:w.caCertPath},cleanup:{certs:w.certsCleanup||!1,hosts:w.hostsCleanup||!1},verbose:w.verbose||!1,changeOrigin:w.changeOrigin||!1,singlePortMode:w.singlePortMode||!1,httpPort:w.httpPort!==void 0?Number(w.httpPort):void 0,httpsPort:w.httpsPort!==void 0?Number(w.httpsPort):void 0,viaDaemon:w.viaDaemon||!1,id:w.id};if(w.startCommand){let Y={command:w.startCommand};if(w.startCwd)Y.cwd=w.startCwd;if(w.startEnv)try{Y.env=JSON.parse(w.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),P0.exit(1)}$.start=Y}return b6($)});u0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{let Y=G8(vw)?vw.proxies.find((A)=>A.to===w||`${A.from}-${A.to}`===w):vw.to===w?vw:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${w}`),P0.exit(1);try{await l8.startProcess(w,Y.start,$.verbose),console.log(`Started dev server for ${w}`)}catch(A){console.error(`Failed to start dev server for ${w}:`,A),P0.exit(1)}});u0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{try{await l8.stopProcess(w,$.verbose),console.log(`Stopped dev server for ${w}`)}catch(Y){console.error(`Failed to stop dev server for ${w}:`,Y),P0.exit(1)}});u0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(w)=>{try{await l8.stopAll(w.verbose),console.log("Stopped all dev servers")}catch($){console.error("Failed to stop all dev servers:",$),P0.exit(1)}});async function c6(w){let Y={...(await vz().catch(()=>null))?.onDemand??{},enabled:!0};if(w){let A=w.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}u0.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("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(w)=>{try{let $=w.onDemand?await c6(w.roots):void 0;await(await C6({rpxDir:w.rpxDir,registryDir:w.registryDir,httpsPort:typeof w.httpsPort==="string"?Number.parseInt(w.httpsPort,10):w.httpsPort,httpPort:typeof w.httpPort==="string"?Number.parseInt(w.httpPort,10):w.httpPort,hostname:w.hostname,productionCerts:w.certsDir?{certsDir:w.certsDir}:void 0,workers:w.workers===void 0?void 0:typeof w.workers==="string"?Number.parseInt(w.workers,10):w.workers,onDemandSites:$,verbose:w.verbose??!0})).done,P0.exit(0)}catch($){console.error(`Failed to start rpx daemon: ${$.message}`),P0.exit(1)}});u0.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(w)=>{let $=typeof w.timeout==="string"?Number.parseInt(w.timeout,10):w.timeout,Y=await V6({rpxDir:w.rpxDir,timeoutMs:$,forceAfterTimeout:w.force!==!1,verbose:w.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});u0.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(w)=>{let $=w.rpxDir??V0(),Y=await V$($),A=await m8($),X=w.registryDir,J=await Tw(X).catch(()=>[]);if(w.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:L$($),rpxDir:$,registryDir:X??Xw(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${L$($)} → pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${L$($)}`);if(console.log(`registry: ${X??Xw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let j=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} → ${U.from} (id=${U.id}${j})`)}});u0.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(w)=>{if(!w.id||!w.from||!w.to)console.error("rpx register requires --id, --from, and --to"),P0.exit(1);if(!y$(w.id))console.error(`invalid id: ${JSON.stringify(w.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),P0.exit(1);try{await u1({id:w.id,from:w.from,to:w.to,cwd:w.cwd,createdAt:new Date().toISOString(),cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin},w.registryDir,w.verbose)}catch($){console.error(`failed to write registry entry: ${$.message}`),P0.exit(1)}if(w.skipSpawn){console.log(`registered ${w.to} → ${w.from} (daemon spawn skipped)`);return}try{let $=await g8({rpxDir:w.rpxDir,verbose:w.verbose}),Y=$.spawned?"spawned":"attached to";console.log(`registered https://${w.to} → ${w.from} (${Y} daemon pid=${$.pid})`)}catch($){console.error(`registered entry but daemon spawn failed: ${$.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),P0.exit(1)}});u0.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(!y$(w))console.error(`invalid id: ${JSON.stringify(w)}`),P0.exit(1);let Y=await Vj(w,$.registryDir,$.verbose);if(!Y){console.log(`no registry entry for id=${w}`);return}await c$(w,$.registryDir,$.verbose),console.log(`unregistered ${Y.to} (id=${w})`)});u0.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(w)=>{let $=w.rpxDir??V0();if(await m8($)){console.log("rpx daemon is running — DNS overrides are managed by the daemon");return}await L6({rpxDir:$,verbose:w.verbose}),console.log("DNS reconcile complete")});u0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(w)=>{let $=await c6(w.roots),Y=lz($),A=await Tw(w.registryDir).catch(()=>[]),X=new Set(A.map((j)=>j.to)),J=Y.map((j)=>({host:j.host,dir:j.dir,command:j.command,source:j.source,live:X.has(j.host)}));if(w.json){console.log(JSON.stringify(J,null,2));return}let U=$.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) — scanned ${U.join(", ")}:`);for(let j of J)console.log(` ${j.live?"●":"○"} https://${j.host} ${j.live?"(live)":"(idle)"}`),console.log(` ${j.command} ${j.dir}`)});u0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(w,$)=>{let{readFile:Y}=await import("node:fs/promises"),{join:A}=await import("node:path"),X=$.rpxDir??V0(),J=A(X,"sites",`${uA(w.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${w} (it may not have been booted yet) — looked in ${J}`);return}let j=$.lines===void 0?void 0:typeof $.lines==="string"?Number.parseInt($.lines,10):$.lines,W=U.split(`
337
- `);P0.stdout.write((j&&j>0?W.slice(-j):W).join(`
338
- `))});u0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(gY)});u0.version(gY);u0.help();u0.run();
381
+ Received ${r}, cleaning up...`),e)try{await e()}catch(n){console.error("Error during cleanup:",n)}pr.exit(0)};return pr.on("SIGINT",()=>t("SIGINT")),pr.on("SIGTERM",()=>t("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(e=!0){return this.enableDidYouMean=e,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(e){return this.globalCommand.usage(e),this}command(e,t,r){if(!r)r={};let n=new Ub(e,t||"",r,this);return n.globalCommand=this.globalCommand,this.commands.push(n),n}option(e,t,r){return this.globalCommand.option(e,t,r),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t="-v, --version"){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},r,n){if(this.args=e,this.options=t,r)this.matchedCommand=r;if(n)this.matchedCommandName=n;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(e){if(console.log(gi.red(`
382
+ ✗ Command "${e}" not found.
383
+ `)),this.enableDidYouMean){let t=[];for(let n of this.commands){if(n.displayName)t.push(n.displayName);if(n.aliasNames)t.push(...n.aliasNames)}let r=Ld(e,t);if(r.length>0)console.log(gi.yellow("Did you mean one of these?")),r.forEach((n)=>console.log(` ${gi.dim("•")} ${this.name} ${n}`)),console.log("")}console.log(gi.dim("Run"),`${this.name} --help`,gi.dim("to see all available commands")),pr.exit(1)}async parse(e=Od,t={}){let{run:r=!0,exitOnError:n=!1}=t;if(n)try{return await this.parse(e,{run:r})}catch(a){throw this.handleUsageError(a),a}if(this.rawArgs=e,!this.name)this.name=e[1]?Bb(e[1]):"cli";let i=!0,s=e.slice(2),o=s[0];if(o&&!o.startsWith("-")){for(let a of this.commands)if(a.isMatched(o)){let l=this.mri(s,a);i=!1;let u={...l,args:l.args.slice(1)};this.setParsedInfo(u,a,o),this.emit(`command:${o}`,a);break}}if(i){for(let a of this.commands)if(a.name===""){i=!1;let l=this.mri(s,a);this.setParsedInfo(l,a),this.emit("command:!",a);break}}if(i){let a=this.mri(e.slice(2));this.setParsedInfo(a)}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(),r=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),r=!1,this.unsetMatchedCommand();let c={args:this.args,options:this.options};if(r)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return c}mri(e,t){let r=[...this.globalCommand.options,...t?t.options:[]],n=Nb(r),i=[],s=e.indexOf("--");if(s>-1)i=e.slice(s+1),e=e.slice(0,s);let o=kb(e,n),c={_:o._};for(let h of Object.keys(o))if(h!=="_")c[Fd(h)]=o[h];let a=c._,l={"--":i},u=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,f=Object.create(null);for(let h of r){if(!u&&h.config.default!==void 0)for(let d of h.names)l[d]=h.config.default;if(Array.isArray(h.config.type)){if(f[h.name]===void 0)f[h.name]={shouldTransform:!0,transformFunction:h.config.type[0]}}}for(let h of Object.keys(c))if(h!=="_"){let d=h.split(".");Fb(l,d,c[h]),Lb(l,f)}return{args:a,options:l}}async run(e=Od){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!(!!e&&typeof e==="object"&&e.name==="ClappError"&&e.isUsageError!==!1))return;let n=e,i=n.message??"command-line error",s=this.name?`${this.name}: `:"",o=/--help/.test(i)?"":`
384
+ Run \`${this.name??"cli"} --help\` for usage.`;pr.stderr.write(`${s}${i}${o}
385
+ `),pr.exit(n.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:r}=this;if(!r||!r.commandAction)return;r.checkUnknownOptions(),r.checkOptionValue(),r.checkRequiredArgs();let n=[];r.args.forEach((c,a)=>{if(c.variadic)n.push(e.slice(a));else n.push(e[a])}),n.push(t);let i={command:r,args:n,options:t};for(let c of r.beforeHooks)await c(i);let s,o=async()=>{let c=r.commandAction.apply(this,n);if(c instanceof Promise)s=await c;else s=c;return s};if(r.middleware.length>0){let c=0,a=async()=>{if(c<r.middleware.length){let l=r.middleware[c++];await l({...i,next:a})}else await o()};await a()}else await o();for(let c of r.afterHooks)await c(i);return s}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return pr.removeAllListeners("SIGINT"),pr.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 Id{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(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,r=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:r})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}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 e=Date.now();for(let[t,r]of this.cache.entries())if(e-r.timestamp>r.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var n1=new Id;function Vb(){if("FORCE_COLOR"in pi.env)return pi.env.FORCE_COLOR!=="0";if("NO_COLOR"in pi.env||pi.env.TERM==="dumb")return!1;if(pi.platform==="win32")return!0;return Nd.isatty(1)&&Nd.isatty(2)}var Md=Vb();function ue(e,t){if(!Md)return(r)=>r;return(r)=>e+r+t}var Hb=ue("\x1B[0m","\x1B[0m"),zb=ue("\x1B[31m","\x1B[39m"),Gb=ue("\x1B[32m","\x1B[39m"),qb=ue("\x1B[33m","\x1B[39m"),Yb=ue("\x1B[34m","\x1B[39m"),Jb=ue("\x1B[35m","\x1B[39m"),Xb=ue("\x1B[36m","\x1B[39m"),Zb=ue("\x1B[37m","\x1B[39m"),Qb=ue("\x1B[90m","\x1B[39m"),e$=ue("\x1B[1m","\x1B[22m"),t$=ue("\x1B[3m","\x1B[23m"),r$=ue("\x1B[4m","\x1B[24m"),n$=ue("\x1B[2m","\x1B[22m"),i$=ue("\x1B[7m","\x1B[27m"),s$=ue("\x1B[8m","\x1B[28m"),o$=ue("\x1B[9m","\x1B[29m"),a$=ue("\x1B[41m","\x1B[49m"),c$=ue("\x1B[42m","\x1B[49m"),l$=ue("\x1B[43m","\x1B[49m"),u$=ue("\x1B[44m","\x1B[49m"),f$=ue("\x1B[45m","\x1B[49m"),h$=ue("\x1B[46m","\x1B[49m"),d$=ue("\x1B[47m","\x1B[49m"),m$=Md,g$={reset:Hb,red:zb,green:Gb,yellow:qb,blue:Yb,magenta:Jb,cyan:Xb,white:Zb,gray:Qb,bold:e$,italic:t$,underline:r$,dim:n$,inverse:i$,hidden:s$,strikethrough:o$,bgRed:a$,bgGreen:c$,bgYellow:l$,bgBlue:u$,bgMagenta:f$,bgCyan:h$,bgWhite:d$,isColorSupported:m$},p$=g$,w$=["up","down","left","right","space","enter","cancel"],l1={actions:new Set(w$),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var u1=y$.platform.startsWith("win"),f1=Symbol("clapp:cancel");var v$=Ib();var oe=(e,t)=>v$?e:t,h1=oe("◆","*"),d1=oe("■","x"),m1=oe("▲","x"),g1=oe("◇","o"),p1=oe("┌","T"),b$=oe("│","|"),y1=oe("└","—"),w1=oe("●",">"),v1=oe("○"," "),b1=oe("◻","[•]"),$1=oe("◼","[+]"),C1=oe("◻","[ ]"),x1=oe("▪","•"),S1=oe("─","-"),E1=oe("╮","+"),T1=oe("├","+"),P1=oe("╯","+"),A1=oe("●","•"),R1=oe("◆","*"),k1=oe("▲","!"),O1=oe("■","x");var N1={light:oe("─","-"),heavy:oe("━","="),block:oe("█","#")};function $$(){return`${p$.gray(b$)} `}var D1=$$();Co();ou();Bc();qt();fe();import{spawn as vk}from"node:child_process";import*as Kc from"node:process";class Wc{processes=new Map;isShuttingDown=!1;async startProcess(e,t,r){if(this.processes.has(e)){m("start",`Process ${e} is already running`,r);return}let[n,...i]=t.command.split(" "),s=t.cwd||Kc.cwd();m("start",`Starting process ${e}:`,r),m("start",` Command: ${n} ${i.join(" ")}`,r),m("start",` Working directory: ${s}`,r),m("start",` Environment variables: ${ur(t.env)}`,r);let o=vk(n,i,{cwd:s,env:{...Kc.env,...t.env},shell:!0,stdio:"inherit"});return this.processes.set(e,{command:t.command,cwd:s,process:o,env:t.env}),new Promise((c,a)=>{if(o.on("error",(l)=>{if(!this.isShuttingDown)m("start",`Process ${e} failed to start: ${l}`,r),this.processes.delete(e),a(l)}),o.on("exit",(l)=>{if(!this.isShuttingDown&&l!==null&&l!==0)m("start",`Process ${e} exited with code ${l}; leaving the proxy running`,r),this.processes.delete(e),a(Error(`Process ${e} exited with code ${l}`))}),r)o.stdout?.on("data",(l)=>{m("process",`[${e}] ${l.toString().trim()}`,!0)}),o.stderr?.on("data",(l)=>{m("process",`[${e}] ERR: ${l.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&o.killed)this.processes.delete(e),a(Error(`Process ${e} was killed during startup`));else m("start",`Process ${e} started successfully`,r),c()},1000)})}async stopProcess(e,t){let r=this.processes.get(e);if(!r?.process){m("start",`No process found for ${e}`,t);return}return m("start",`Stopping process ${e}`,t),new Promise((n)=>{if(!r.process){n();return}r.process.once("exit",()=>{this.processes.delete(e),m("start",`Process ${e} stopped`,t),n()});try{r.process.kill("SIGTERM"),setTimeout(()=>{if(r.process){m("start",`Force killing process ${e}`,t);try{r.process.kill("SIGKILL")}catch(i){}}},3000)}catch(i){m("start",`Error stopping process ${e}: ${i}`,t),this.processes.delete(e),n()}})}async stopAll(e){if(this.isShuttingDown){m("start","Already shutting down, skipping duplicate stopAll call",e);return}this.isShuttingDown=!0,m("start","Stopping all processes",e);let t=Array.from(this.processes.keys()).map((r)=>this.stopProcess(r,e).catch((n)=>{b.error(`Failed to stop process ${r}:`,n)}));await Promise.allSettled(t),this.processes.clear(),this.isShuttingDown=!1}isRunning(e){let t=this.processes.get(e);return!!t?.process&&!t.process.killed}}var Vc=new Wc;Xr();import{readdir as Nk,readFile as Dk}from"node:fs/promises";import*as gb from"node:path";import*as pb from"node:process";qt();import{execSync as Tk}from"node:child_process";import*as Xc from"node:http";import*as cb from"node:net";import*as Zc from"node:os";import*as lb from"node:path";import*as q from"node:process";var Hc=(e,t)=>(r)=>`\x1B[${e}m${r}\x1B[${t}m`,Mt={bold:Hc(1,22),dim:Hc(2,22),green:Hc(32,39),cyan:Hc(36,39)};Co();Bc();qt();Xr();fe();import*as nb from"node:fs";import*as ib from"node:path";import*as _t from"node:process";function bk(e,t){let n=(t&&t!=="/"?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}async function yd(e){if(e.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let t=e.verbose??!1,r=e.registryDir,n=new Set,i=e.proxies.map((h)=>{let d=h.id??bk(h.to,h.path);if(!Dr(d))throw Error(`invalid registry id "${d}" derived from to="${h.to}"`);if(n.has(d))throw Error(`duplicate registry id "${d}" — set an explicit \`id\` on one of the proxies`);return n.add(d),{...h,id:d}}),s=new Date().toISOString();for(let h of i)await ai({id:h.id,from:h.from,to:h.to,path:h.path,pid:e.persistent?void 0:_t.pid,cwd:_t.cwd(),createdAt:s,cleanUrls:h.cleanUrls,changeOrigin:h.changeOrigin,pathRewrites:h.pathRewrites,static:h.static,loadBalancer:h.loadBalancer},r,t);let o=await Uc({rpxDir:e.rpxDir,verbose:t,spawnCommand:e.spawnCommand,startupTimeoutMs:e.startupTimeoutMs,spawnEnv:e.spawnEnv});for(let h of i){let d=h.static?`static ${typeof h.static==="string"?h.static:h.static.dir}`:h.from;b.success(`https://${h.to} → ${d}`)}if(b.info(`(via rpx daemon pid=${o.pid}; \`rpx daemon:status\` to inspect)`),e.detached)return;let c=!1,a=r??dt(),l=i.map((h)=>h.id),u=async()=>{if(c)return;c=!0;for(let h of l)await Jr(h,r,t).catch((d)=>{m("runner",`removeEntry(${h}) failed: ${d}`,t)})},f=(h)=>{m("runner",`received ${h}, unregistering ${l.length} entries`,t),u().finally(()=>_t.exit(0))};_t.once("SIGINT",f),_t.once("SIGTERM",f),_t.once("exit",()=>{if(c)return;for(let h of l)try{nb.unlinkSync(ib.join(a,`${h}.json`))}catch{}}),await new Promise(()=>{})}id();hc();Yh();import{timingSafeEqual as $k}from"node:crypto";function Ck(e,t){if(e==null)return!1;let r=Buffer.from(e),n=Buffer.from(t);if(r.length!==n.length)return!1;return $k(r,n)}function zc(e){return e.toLowerCase().replace(/\.$/,"")}var xk=["/.well-known/acme-challenge/"];function Sk(e){let t=e.headers.get("host");if(t)return zc(t.split(":")[0]);try{return zc(new URL(e.url).hostname)}catch{return""}}function sb(e){let t=e.header.toLowerCase(),r=new Set,n=[];for(let a of e.hosts){let l=zc(a);if(l.startsWith("*."))n.push(l);else r.add(l)}let i=e.exemptPaths??xk,s=e.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
386
+ `,o=(a)=>{let l=zc(a);return r.has(l)||n.some((u)=>Ur(l,u))},c=(a)=>{let l=Sk(a);if(!o(l))return;let u="/";try{u=new URL(a.url).pathname}catch{}if(i.some((f)=>u.startsWith(f)))return;if(Ck(a.headers.get(t),e.value))return;return new Response(s,{status:403,headers:{"content-type":"text/plain"}})};return c.protects=o,c}_h();jh();mc();bc();Wh();Gh();xc();wc();fe();var ob={name:"@stacksjs/rpx",type:"module",version:"0.11.47",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build --production ./bin/cli.ts --compile --outfile bin/rpx",compile:"bun build --production ./bin/cli.ts --compile --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build --production ./bin/cli.ts --compile --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build --production ./bin/cli.ts --compile --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build --production ./bin/cli.ts --compile --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build --production ./bin/cli.ts --compile --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build --production ./bin/cli.ts --compile --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.19"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var Rs=ob.version;var qc=new Wc,Pk=new Ec("0.0.0.0"),Os=new Set,Jc=new Set,wd=!1,Gc=null,vd=null;async function Qc(e){if(wd)return m("cleanup","Cleanup already in progress, skipping",e?.verbose),vd||Promise.resolve();wd=!0,m("cleanup","Starting cleanup process",e?.verbose),vd=new Promise((t)=>{Gc=t});try{await qc.stopAll(e?.verbose),b.info("Shutting down proxy servers...");let t=[],r=Array.from(Os).map((n)=>new Promise((i)=>{let s=n;try{if(typeof s.stop==="function")s.stop(!0),m("cleanup","Bun server stopped",e?.verbose),i();else if(typeof s.close==="function")s.close(()=>{m("cleanup","Server closed successfully",e?.verbose),i()});else i()}catch(o){m("cleanup",`Error stopping server: ${o}`,e?.verbose),i()}}));t.push(...r),Os.clear();for(let n of Jc)ii(n);if(Jc.clear(),e?.hosts&&e.domains?.length){m("cleanup","Cleaning up hosts file entries",e?.verbose),m("cleanup",`Original domains for cleanup: ${JSON.stringify(e.domains)}`,e?.verbose);let n=e.domains.filter((i)=>{if(i==="test.local")return!0;return i!=="localhost"&&!i.startsWith("localhost.")&&i!=="127.0.0.1"});if(m("cleanup",`Filtered domains for cleanup: ${JSON.stringify(n)}`,e?.verbose),n.length>0)b.info("Cleaning up hosts file entries..."),t.push(Rv(n,e?.verbose).then(()=>{m("cleanup",`Removed hosts entries for ${n.join(", ")}`,e?.verbose)}).catch((i)=>{m("cleanup",`Failed to remove hosts entries: ${i}`,e?.verbose),b.warn(`Failed to clean up hosts file entries for ${n.join(", ")}:`,i)}))}if(e?.certs&&e.domains?.length){m("cleanup","Cleaning up SSL certificates",e?.verbose),b.info("Cleaning up SSL certificates...");let n=e.domains.map(async(i)=>{try{await Uw(i,e?.verbose),m("cleanup",`Removed certificates for ${i}`,e?.verbose)}catch(s){m("cleanup",`Failed to remove certificates for ${i}: ${s}`,e?.verbose),b.warn(`Failed to clean up certificates for ${i}:`,s)}});t.push(...n)}await Promise.allSettled(t),m("cleanup","All cleanup tasks completed successfully",e?.verbose),b.success("All cleanup tasks completed successfully")}catch(t){m("cleanup",`Error during cleanup: ${t}`,e?.verbose),b.error("Error during cleanup:",t)}finally{if(Gc)Gc();Gc=null,wd=!1;let t=e&&"vitePluginUsage"in e&&e.vitePluginUsage===!0;if(q.env.NODE_ENV!=="test"&&q.env.BUN_ENV!=="test"&&!t)q.exit(0)}return vd}var bd=!1;function ub(e){if(bd){m("signal",`Received second ${e} signal, forcing exit`,!0),q.exit(1);return}bd=!0,m("signal",`Received ${e} signal, initiating cleanup`,!0),Qc().catch((t)=>{m("signal",`Cleanup failed after ${e}: ${t}`,!0),q.exit(1)}).finally(()=>{bd=!1})}q.once("SIGINT",()=>ub("SIGINT"));q.once("SIGTERM",()=>ub("SIGTERM"));q.on("uncaughtException",(e)=>{b.error("Uncaught exception (continuing):",e)});q.on("unhandledRejection",(e)=>{b.error("Unhandled rejection (continuing):",e)});async function Ns(e,t,r,n=5){m("connection",`Testing connection to ${e}:${t} (retries left: ${n})`,r);let i=15000,s=Date.now();if(q.env.RPX_BYPASS_CONNECTION_TEST==="true"){m("connection",`Bypassing connection test for ${e}:${t} due to RPX_BYPASS_CONNECTION_TEST flag`,r);return}let o=()=>new Promise((c,a)=>{let l=cb.connect({host:e,port:t,timeout:3000});l.once("connect",()=>{m("connection",`Successfully connected to ${e}:${t}`,r),l.end(),c()}),l.once("timeout",()=>{m("connection",`Connection to ${e}:${t} timed out`,r),l.destroy(),a(Error("Connection timed out"))}),l.once("error",(u)=>{m("connection",`Failed to connect to ${e}:${t}: ${u}`,r),l.destroy(),a(u)})});try{await o()}catch(c){let a=c;if(Date.now()-s>i){m("connection",`Connection test timed out after ${i}ms, but continuing anyway`,r),b.warn(`Connection test to ${e}:${t} timed out, but RPX will try to proceed anyway.`);return}if(a.code==="ECONNREFUSED"&&n>0)return m("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${n} retries left)`,r),await new Promise((u)=>setTimeout(u,2000)),Ns(e,t,r,n-1);if(n>0)try{m("connection",`Trying HTTP request to ${e}:${t}`,r),await new Promise((u,f)=>{let h=Xc.request({hostname:e,port:t,path:"/",method:"HEAD",timeout:5000},(d)=>{m("connection",`Received HTTP response with status: ${d.statusCode}`,r),u()});h.on("error",(d)=>f(d)),h.on("timeout",()=>{h.destroy(),f(Error("HTTP request timed out"))}),h.end()}),m("connection",`HTTP request to ${e}:${t} succeeded`,r);return}catch(u){return m("connection",`HTTP request to ${e}:${t} failed: ${u}`,r),m("connection",`Retrying socket connection in 2 seconds... (${n} retries left)`,r),await new Promise((f)=>setTimeout(f,2000)),Ns(e,t,r,n-1)}let l=`Failed to connect to ${e}:${t} after ${5-n} attempts: ${a.message}`;m("connection",`${l}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,r),b.warn(l),b.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 fb(e){m("server",`Starting server with options: ${ur(e)}`,e.verbose);let t=qr(e.from),r=new URL(t.startsWith("http")?t:`http://${t}`),n=new URL((e.to?.startsWith("http")?e.to:`http://${e.to}`)||"rpx.localhost"),i=Number.parseInt(r.port)||(r.protocol.includes("https:")?443:80),s=[n.hostname];if($d(e)&&!n.hostname.includes("localhost")&&!n.hostname.includes("127.0.0.1")){m("hosts",`Checking if hosts file entry exists for: ${n.hostname}`,e?.verbose);try{if(!(await Ss(s,e.verbose))[0]){b.info(`Adding ${n.hostname} to hosts file...`),b.info("This may require sudo/administrator privileges");try{await xs(s,e.verbose)}catch(a){if(b.error("Failed to add hosts entry:",a.message),b.warn("You can manually add this entry to your hosts file:"),b.warn(`127.0.0.1 ${n.hostname}`),b.warn(`::1 ${n.hostname}`),q.platform==="win32")b.warn("On Windows:"),b.warn("1. Run notepad as administrator"),b.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else b.warn("On Unix systems:"),b.warn("sudo nano /etc/hosts")}}else m("hosts",`Host entry already exists for ${n.hostname}`,e.verbose)}catch(c){b.error("Failed to check hosts file:",c.message)}}try{await Ns(r.hostname,i,e.verbose)}catch(c){m("server",`Connection test failed: ${c}`,e.verbose),b.error(c.message),b.warn("Continuing with proxy setup despite connection test failure..."),b.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let o=e._cachedSSLConfig||null;if(e.https)try{if(e.https===!0)e.https=ts({...e,to:n.hostname});if(o=await Or({...e,to:n.hostname,https:e.https}),!o){if(m("ssl",`Generating new certificates for ${n.hostname}`,e.verbose),await es({...e,from:r.toString(),to:n.hostname,https:e.https}),o=await Or({...e,to:n.hostname,https:e.https}),!o)throw Error(`Failed to load SSL configuration after generating certificates for ${n.hostname}`)}}catch(c){throw m("server",`SSL setup failed: ${c}`,e.verbose),c}m("server",`Setting up reverse proxy with SSL config for ${n.hostname}`,e.verbose),await Rk({...e,from:t,originalFrom:e.from||t,to:n.hostname,fromPort:i,sourceUrl:{hostname:r.hostname,host:r.host},ssl:o})}async function Ak(e,t,r,n,i,s,o,c,a,l,u,f){m("proxy",`Creating proxy server ${e} -> ${t} with cleanUrls: ${c}`,o);let h=rs(u??n.host,f);is(h);let d=[{host:t,route:{sourceHost:n.host,upstreamPool:h,cleanUrls:c||!1,changeOrigin:a||!1,basePath:"/",auth:l}}];if(!Yc({routeEntries:d,listenPort:r,sslConfig:i,originGuard:null,verbose:o??!1}))throw ii(h),Error(`Failed to start proxy server for ${t} on port ${r}`);Jc.add(h),Ok({from:e,to:t,vitePluginUsage:s,listenPort:r,ssl:!!i,cleanUrls:c,verbose:o})}async function Rk(e){m("setup",`Setting up reverse proxy: ${ur(e)}`,e.verbose);let{from:t,originalFrom:r,to:n,sourceUrl:i,ssl:s,verbose:o,cleanup:c,vitePluginUsage:a,changeOrigin:l,cleanUrls:u}=e,f=e.httpPort??80,h=e.httpsPort??443,d=mb(),y=e.portManager||Pk,g=$d(e);try{if(g&&n&&!n.includes("localhost")&&!n.includes("127.0.0.1")){if(!(await Ss([n],o))[0]){b.warn(`The hostname ${n} isn't in your hosts file. Adding it now...`);try{await xs([n],o),b.success(`Added ${n} to your hosts file.`)}catch(A){b.error(`Failed to add ${n} to your hosts file: ${A}`),b.info(`You may need to manually add '127.0.0.1 ${n}' to your /etc/hosts file.`)}}}else if(g&&q.platform!=="darwin"&&n&&n.includes("localhost")&&!n.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await Ss([n],o))[0]){m("hosts",`${n} not found in hosts file, adding...`,o);try{await xs([n],o)}catch(A){m("hosts",`Failed to add ${n} to hosts file: ${A}`,o)}}}if(s&&!y.usedPorts.has(f)){if(!await Nr(f,d,o))m("setup","Starting HTTP redirect server",o),hb(o,f,h),y.usedPorts.add(f);else if(m("setup","Port 80 is in use, skipping HTTP redirect",o),o)b.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let p=s?h:f,w=await Nr(p,d,o),v;if(w){if(m("setup",`Port ${p} is already in use`,o),o)b.warn(`Port ${p} is already in use. This may be another instance of rpx or another service.`);if(p===443){if(v=await y.getNextAvailablePort(3443,!0),m("setup",`Using port ${v} instead of ${p}`,o),o)b.info(`Using port ${v} instead. Access your site at https://${n}:${v}`)}else if(v=await y.getNextAvailablePort(p+1000,!0),m("setup",`Using port ${v} instead of ${p}`,o),o)b.info(`Using port ${v} instead. Access your site at http://${n}:${v}`)}else v=p,y.usedPorts.add(v),m("setup",`Using standard ${p===443?"HTTPS":"HTTP"} port ${p} for ${n}`,o);await Ak(t,n,v,i,s,a,o,u,l,os(e.auth),r,e.loadBalancer)}catch(p){m("setup",`Setup failed: ${p}`,o),b.error(`Failed to setup reverse proxy: ${p.message}`),Qc({domains:[n],hosts:typeof c==="boolean"?c:c?.hosts,certs:typeof c==="boolean"?c:c?.certs,verbose:o,vitePluginUsage:a})}}function hb(e,t=80,r=443,n,i,s){m("redirect",`Starting HTTP redirect server on port ${t}`,e);let o=Xc.createServer((c,a)=>{let l=c.url?c.url.split("?",1)[0]:"";if(l.startsWith("/.well-known/acme-challenge/")){if(i){let d=i.challengeStore.handlePath(l);if(d!==void 0){m("redirect",`Serving on-demand ACME challenge ${l}`,e),a.writeHead(200,{"content-type":"text/plain"}),a.end(d);return}}if(n){let d=vc(n,l);if(d!=null){m("redirect",`Serving ACME challenge ${l}`,e),a.writeHead(200,{"content-type":"text/plain"}),a.end(d);return}}if(i){a.writeHead(404,{"content-type":"text/plain"}),a.end("challenge not found");return}}let u=c.headers.host||"",f=u.includes(":")?u.slice(0,u.indexOf(":")):u;if(i&&f&&!i.hasCert(f)&&(!s||s(f)))i.ensureCert(f).catch(()=>{});let h=r===443?f:`${f}:${r}`;m("redirect",`Redirecting request from ${u}${c.url} to https://${h}`,e),a.writeHead(301,{Location:`https://${h}${c.url}`}),a.end()}).listen(t);Os.add(o),m("redirect","HTTP redirect server started",e)}function db(e){let t={...Gt,...e};if(m("proxy",`Starting proxy with options: ${ur(t)}`,t?.verbose),t.viaDaemon){if(!t.from||!t.to){b.error("viaDaemon mode requires both `from` and `to`");return}yd({proxies:[{id:t.id,from:t.from,to:t.to,path:t.path,cleanUrls:t.cleanUrls,changeOrigin:t.changeOrigin,pathRewrites:t.pathRewrites}],verbose:t.verbose}).catch((a)=>{b.error(`Failed to register with rpx daemon: ${a.message}`),q.exit(1)});return}let r=t.to||"",n=r.split(".").pop()?.toLowerCase()||"",i=q.platform==="darwin"&&r&&!r.includes("localhost")&&!r.includes("127.0.0.1"),s=["dev","app","page","new","day","foo"],o=["test","localhost","local","example","invalid"];if(i&&s.includes(n)&&t?.verbose)b.warn(`The .${n} TLD may not work reliably for local development`),b.info(` Google owns .${n} with HSTS preloading, which can bypass local DNS`),b.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(i)Promise.resolve().then(() => (As(),Lc)).then(({setupDevelopmentDns:a})=>{a({domains:[r],verbose:t.verbose}).then((l)=>{if(l)Promise.resolve().then(()=>{if(t.verbose)if(o.includes(n))b.success(`DNS server started for .${n} domains`);else b.success(`DNS server started for .${n} domains (hosts file entry also added)`)});else m("dns",`Could not start DNS server - ${r} may not resolve in browser`,t.verbose)})}).catch((a)=>{m("dns",`Failed to start DNS server: ${a}`,t.verbose)});let c={from:t.from,to:t.to,cleanUrls:t.cleanUrls,https:ts(t),cleanup:t.cleanup,vitePluginUsage:t.vitePluginUsage,changeOrigin:t.changeOrigin,verbose:t.verbose,regenerateUntrustedCerts:t.regenerateUntrustedCerts};m("proxy",`Server options: ${ur(c)}`,t.verbose),fb(c).catch((a)=>{m("proxy",`Failed to start proxy: ${a}`,t.verbose),b.error(`Failed to start proxy: ${a.message}`),Qc({domains:[t.to],hosts:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.hosts,certs:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.certs,verbose:t.verbose})})}function kk(e){return e?.verbose||!1}function $d(e){if(e?.hostsManagement===!1)return!1;let t=e?.cleanup;if(t===!1)return!1;if(t&&typeof t==="object"&&t.hosts===!1)return!1;return!0}async function el(e){let t={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(e)t={...t,...e};let r=kk(t),n=t.https===!1;if(t.localCa)ws(t.localCa,t.onDemandTls);let i=$d(t);if(m("config",`Starting with config: ${ur(t,2)}`,r),m("config",`Is multi-proxy? ${"proxies"in t}`,r),m("config",`Hosts management enabled? ${i}`,r),t.viaDaemon){let k="proxies"in t&&Array.isArray(t.proxies)?t.proxies.map((L)=>({id:L.id,from:L.from,to:L.to,path:L.path,cleanUrls:L.cleanUrls??t.cleanUrls,changeOrigin:L.changeOrigin??t.changeOrigin,pathRewrites:L.pathRewrites})):[{id:t.id,from:t.from,to:t.to??"rpx.localhost",path:t.path,cleanUrls:t.cleanUrls,changeOrigin:t.changeOrigin,pathRewrites:t.pathRewrites}];await yd({proxies:k,verbose:r});return}if("proxies"in t&&Array.isArray(t.proxies)){m("servers",`Found ${t.proxies.length} proxies in config`,r);for(let x of t.proxies)if(x.start){let k=`${x.from}-${x.to}`;try{m("watch",`Starting command for ${k} with command: ${x.start.command}`,r),b.info(`Starting command for ${k}...`),await qc.startProcess(k,x.start,r);let L=qr(x.from),ee=new URL(L.startsWith("http")?L:`http://${L}`),Re=ee.hostname||"localhost",Ge=Number(ee.port)||80;try{await Ns(Re,Ge,r),m("watch",`Dev server is ready at ${Re}:${Ge}`,r)}catch(jt){m("watch",`Connection check failed, but continuing with proxy setup: ${jt}`,r),b.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(L){throw m("watch",`Failed to start command for ${k}: ${L}`,r),Error(`Failed to start command for ${k}: ${L}`)}}else m("watch",`No start command for proxy ${x.from} -> ${x.to}`,r)}else if("start"in t&&t.start){m("watch","Found start command in single proxy config",r);let x=`${t.from}-${t.to}`;try{if(t.start)m("watch",`Starting command: ${t.start.command}`,r),await qc.startProcess(x,t.start,r);let k=qr(t.from),L=new URL(k.startsWith("http")?k:`http://${k}`),ee=L.hostname||"localhost",Re=Number(L.port)||80;try{await Ns(ee,Re,r),m("watch",`Dev server is ready at ${ee}:${Re}`,r)}catch(Ge){m("watch",`Connection check failed, but continuing with proxy setup: ${Ge}`,r),b.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(k){throw m("watch",`Failed to run start command: ${k}`,r),Error(`Failed to run start command: ${k}`)}}else m("watch","No start command found in config",r);let s="proxies"in t&&Array.isArray(t.proxies)?t.proxies[0]?.to:("to"in t)?t.to:"rpx.localhost";if(q.platform!=="win32"&&(t.https||i)){if(!Er())try{m("sudo","Pre-acquiring sudo credentials for privileged operations",r),Tk("sudo -v",{stdio:"inherit"})}catch{m("sudo","Could not pre-acquire sudo credentials",r)}}let o=[],c=null;if(t.productionCerts&&!n){if(o=await ms(t.productionCerts,r),o.length>0)m("ssl",`Using ${o.length} production SNI cert(s): ${o.map((x)=>x.serverName).join(", ")}`,r)}if(t.localCa&&!n){let x=await vs(t.localCa,{verbose:r,onDemandTls:t.onDemandTls}),k=new Set(x.entries.map((L)=>L.serverName));o=[...x.entries,...o.filter((L)=>!k.has(L.serverName))],c=x.defaultTls,m("ssl",`Local CA: ${x.leafMinted?`minted leaf (${x.renewalReason})`:"reusing leaf"} for ${[...k].join(", ")}; valid until ${x.notAfter.toISOString()}`,r)}if(t.https){let x=o.length>0?null:await Or(t);if(!x&&o.length===0){if(m("ssl",`No valid or trusted certificates found for ${s}, generating new ones`,t.verbose),await es(t),x=await Or(t),!x)throw Error(`Failed to load SSL certificates after generation for ${s}`)}else m("ssl",`Using existing and trusted certificates for ${s}`,t.verbose);t._cachedSSLConfig=x}let a="proxies"in t&&Array.isArray(t.proxies)?t.proxies.map((x)=>({...x,https:t.https,cleanup:t.cleanup,cleanUrls:x.cleanUrls??("cleanUrls"in t?t.cleanUrls:!1),vitePluginUsage:t.vitePluginUsage,changeOrigin:x.changeOrigin??t.changeOrigin,verbose:r,_cachedSSLConfig:t._cachedSSLConfig})):[{from:"from"in t?t.from:"localhost:5173",to:"to"in t?t.to:"rpx.localhost",cleanUrls:"cleanUrls"in t?t.cleanUrls:!1,https:t.https,cleanup:t.cleanup,vitePluginUsage:t.vitePluginUsage,start:"start"in t?t.start:void 0,changeOrigin:t.changeOrigin,auth:"auth"in t?t.auth:void 0,verbose:r,_cachedSSLConfig:t._cachedSSLConfig}],l=a.map((x)=>x.to||"rpx.localhost"),u=n?null:o.length>0?o:t._cachedSSLConfig??null,f=l.filter((x)=>x&&!x.includes("localhost")&&!x.includes("127.0.0.1")),h=["dev","app","page","new","day","foo"],d=["test","localhost","local","example","invalid"],y=[...new Set(f.map((x)=>x.split(".").pop()?.toLowerCase()))],g=y.filter((x)=>!!x&&h.includes(x));if(g.length>0&&r)b.warn(`The following TLDs may not work reliably for local development: ${g.map((x)=>`.${x}`).join(", ")}`),b.info(" These TLDs have HSTS preloading which can bypass local DNS"),b.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(i&&q.platform==="darwin"&&f.length>0){let{setupDevelopmentDns:x}=await Promise.resolve().then(() => (As(),Lc));if(await x({domains:f,verbose:r})){if(r)if(y.every((ee)=>!!ee&&d.includes(ee)))b.success(`DNS server started for ${y.map((ee)=>`.${ee}`).join(", ")} domains`);else b.success(`DNS server started for ${y.map((ee)=>`.${ee}`).join(", ")} domains (hosts file entries also added)`)}else m("dns","Could not start DNS server - custom domains may not resolve",r)}let p=async()=>{m("cleanup","Starting cleanup handler",t.verbose);try{let{tearDownDevelopmentDns:x}=await Promise.resolve().then(() => (As(),Lc));await x({verbose:t.verbose})}catch(x){m("cleanup",`Error stopping DNS server: ${x}`,t.verbose)}try{await qc.stopAll(t.verbose)}catch(x){m("cleanup",`Error stopping processes: ${x}`,t.verbose)}await Qc({domains:l,hosts:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.hosts,certs:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.certs,verbose:t.verbose||!1})};q.on("SIGINT",p),q.on("SIGTERM",p);let w=t.singlePortMode===!0,v=t.httpsPort??443,P=t.httpPort??80,A=t.originGuard?sb(t.originGuard):null,R=!!u&&(a.length>1||w||o.length>0),D=!u&&a.length>0&&(w||a.length>1),F=t.maxTlsContexts;if(R&&u){m("proxies",`Creating shared HTTPS server for ${a.length} domains on port ${v}`,r);let x=await ab(a,i,r),k=null,L=t.onDemandTls,ee=L?.enabled?new oi({config:L,certsDir:L.certsDir??t.productionCerts?.certsDir??lb.join(Zc.homedir(),".stacks","rpx","on-demand-certs"),initial:o,verbose:r,onCertAdded:(rt)=>{if(gs()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",r),setTimeout(()=>q.kill(q.pid,"SIGTERM"),10).unref();else jt(rt)}}):null,Re=null,Ge=!1;async function jt(rt){if(Re=rt,Ge)return;Ge=!0;try{while(Re){let O=Re;if(Re=null,m("proxies",`rebuilding :${v} with ${O.length} SNI cert(s)`,r),k)Os.delete(k),k.stop(!1);let pe=!1;for(let ye=0;!pe&&ye<60;ye++){let Ir=Yc({routeEntries:x,listenPort:v,sslConfig:O,defaultTls:c,maxTlsContexts:F,originGuard:A,verbose:r});if(Ir){k=Ir,pe=!0;break}await new Promise((tn)=>setTimeout(tn,Math.min(25*2**Math.min(ye,4),500)))}if(!pe)b.error(`rpx: CRITICAL — could not rebind :${v} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{Ge=!1}}if(!await Nr(P,"0.0.0.0",r)){let rt=new Set(x.map((pe)=>pe.host)),O=(pe)=>rt.has(pe)||[...rt].some((ye)=>Ur(pe,ye));hb(r,P,v,t.acmeChallengeWebroot,ee,O)}if(await Nr(v,"0.0.0.0",r)){if(m("proxies",`Port ${v} is already in use, cannot start shared proxy`,r),r)b.warn(`Port ${v} is in use. Shared HTTPS proxy cannot start.`);return}let St=ee&&ee.sniEntries().length>0?ee.sniEntries():u;if(k=Yc({routeEntries:x,listenPort:v,sslConfig:St,defaultTls:c,maxTlsContexts:F,originGuard:A,verbose:r}),!k){b.error(`Shared HTTPS proxy failed to bind :${v}; not exiting`);return}}else if(D){m("proxies",`Creating shared HTTP server for ${a.length} domains on port ${P}`,r);let x=await ab(a,i,r);if(await Nr(P,"0.0.0.0",r)){if(m("proxies",`Port ${P} is already in use, cannot start shared proxy`,r),r)b.warn(`Port ${P} is in use. Shared HTTP proxy cannot start.`);return}if(!Yc({routeEntries:x,listenPort:P,sslConfig:null,originGuard:A,verbose:r})){b.error(`Shared HTTP proxy failed to bind :${P}; not exiting`);return}}else for(let x of a)try{let k=x.to||"rpx.localhost";m("proxy",`Starting proxy for ${k} with SSL config: ${!!u}`,x.verbose),await fb({from:x.from||"localhost:5173",to:k,cleanUrls:x.cleanUrls||!1,https:x.https||!1,cleanup:x.cleanup||!1,vitePluginUsage:x.vitePluginUsage||!1,verbose:x.verbose||!1,_cachedSSLConfig:t._cachedSSLConfig,changeOrigin:x.changeOrigin||!1,loadBalancer:x.loadBalancer,auth:x.auth,path:x.path,pathRewrites:x.pathRewrites,httpPort:t.httpPort,httpsPort:t.httpsPort})}catch(k){m("proxies",`Failed to start proxy for ${x.to}: ${k}`,x.verbose),b.error(`Failed to start proxy for ${x.to}:`,k)}}async function ab(e,t,r){let n=[],i=new Set;for(let s of e){let o=s.to||"rpx.localhost",c=s.cleanUrls||!1,a=s.path,l=fr(a),u=os(s.auth);if(s.redirect){let f=rv(s.redirect);n.push({host:o,path:a,route:{redirect:f,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → redirect ${f.status} ${f.to}${u?" (auth)":""}`,r)}else if(s.static)n.push({host:o,path:a,route:{static:yc(s.static,c),cleanUrls:c,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → static ${typeof s.static==="string"?s.static:s.static.dir}${u?" (auth)":""}`,r);else{let f=qr(s.from),h=new URL(f.startsWith("http")?f:`http://${f}`),d=rs(s.from??h.host,s.loadBalancer);is(d),Jc.add(d),n.push({host:o,path:a,route:{sourceHost:h.host,upstreamPool:d,cleanUrls:c,changeOrigin:s.changeOrigin||!1,pathRewrites:s.pathRewrites,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → ${h.host}${u?" (auth)":""}`,r)}if(i.has(o))continue;if(i.add(o),t&&!yn(o)&&!o.includes("localhost")&&!o.includes("127.0.0.1"))try{if(!(await Ss([o],r))[0])await xs([o],r)}catch{m("hosts",`Could not add hosts entry for ${o}`,r)}}return n}var ks=null;function mb(){if(q.env.RPX_BIND_HOSTNAME)return q.env.RPX_BIND_HOSTNAME;if(ks)return ks;try{ks=Object.values(Zc.networkInterfaces()).flat().some((r)=>r&&r.family==="IPv6")?"::":"0.0.0.0"}catch{ks="0.0.0.0"}return ks}function Yc(e){let{routeEntries:t,listenPort:r,sslConfig:n,defaultTls:i,maxTlsContexts:s,originGuard:o,verbose:c}=e,a=us(t),l=cs((h,d)=>fs(a,h,d),c),u=o?(h,d)=>o(h)??l(h,d):l,f=ls(c);try{let h=Bun.serve({port:r,hostname:mb(),reusePort:ti(),...n?{tls:Array.isArray(n)?ds({sni:n,defaultTls:i,maxTlsContexts:s,verbose:c}):si({key:n.key,cert:n.cert,ca:n.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(d,y){return u(d,y)},websocket:f,error(d){return m("server",`Shared proxy server error: ${d}`,c),new Response(`Server Error: ${d.message}`,{status:500})}});return Os.add(h),m("proxies",`Shared ${n?"HTTPS":"HTTP"} proxy listening on port ${r} for ${a.size} domains`,c),h}catch(h){return m("proxies",`Failed to start shared proxy: ${h}`,c),console.error("Failed to start shared proxy:",h),null}}function Ok(e){if(e?.vitePluginUsage||!e?.verbose)return;if(console.log(""),console.log(` ${Mt.green(Mt.bold("rpx"))} ${Mt.green(`v${Rs}`)}`),console.log(` ${Mt.green("➜")} ${Mt.dim(e?.from??"")} ${Mt.dim("➜")} ${Mt.cyan(e?.ssl?`https://${e?.to}`:`http://${e?.to}`)}`),e?.listenPort!==(e?.ssl?443:80))console.log(` ${Mt.green("➜")} Listening on port ${e?.listenPort}`);if(e?.cleanUrls)console.log(` ${Mt.green("➜")} Clean URLs enabled`)}fe();var Cd="/etc/rpx/certs",Ds="/etc/rpx/sites.d";function Fk(e,t){console.error(`[rpx gateway] SKIPPING malformed fragment ${e}; its host(s) will 404 until fixed: ${t.message}`)}async function Lk(e,t=Fk){let r=[];try{r=(await Nk(e)).filter((i)=>i.endsWith(".json")).sort()}catch{return[]}let n=[];for(let i of r)try{let s=JSON.parse(await Dk(gb.join(e,i),"utf8"));if(!s||typeof s!=="object"||Array.isArray(s))throw TypeError("fragment is not a JSON object");n.push({file:i,fragment:s})}catch(s){t(i,s instanceof Error?s:Error(String(s)))}return n}function Bk(e,t={}){let r=t.onWarning??((y)=>console.warn(`[rpx gateway] ${y}`)),n=[],i=new Set,s=new Map,o=new Set,c=new Set,a,l=t.certsDir??Cd,u,f,h=!1;for(let{file:y,fragment:g}of e){for(let p of Array.isArray(g.proxies)?g.proxies:[]){let w=p.id||`${p.to}${p.path??""}`;if(i.has(w)){r(`duplicate route ${w} in ${y} ignored; first declared by ${s.get(w)}`);continue}i.add(w),s.set(w,y),n.push(p)}for(let p of g.onDemandTls?.allowedSuffixes??[])o.add(p);if(a??=g.onDemandTls?.email,g.onDemandTls&&g.onDemandTls.staging!==!0)h=!0;if(g.productionCerts?.certsDir)l=g.productionCerts.certsDir;if(u??=g.acmeChallengeWebroot,g.originGuard&&g.originGuard.header&&g.originGuard.value)if(f??={header:g.originGuard.header,value:g.originGuard.value},g.originGuard.header===f.header&&g.originGuard.value===f.value)for(let p of g.originGuard.hosts??[])c.add(p);else r(`origin-guard secret in ${y} differs from the one already in force; its hosts stay unguarded rather than rejecting all traffic`)}let d={proxies:n,productionCerts:{certsDir:l,certsDirServerNames:[...new Set(n.map((y)=>y.to).filter(Boolean))]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(o.size>0)d.onDemandTls={enabled:!0,allowedSuffixes:[...o],email:a,certsDir:l,staging:!h};if(u)d.acmeChallengeWebroot=u;if(f)d.originGuard={header:f.header,value:f.value,hosts:[...c]};return d}async function Ik(e={}){let t=e.sitesDir??Ds,r=e.verbose??pb.env.RPX_VERBOSE!=="false",n=await Lk(t,e.onFragmentError);m("gateway",`merged ${n.length} fragment(s) from ${t}: ${n.map((o)=>o.file).join(", ")||"<none>"}`,r);let s={...Bk(n,{certsDir:e.certsDir}),verbose:r,singlePortMode:!0};if(e.https===!1)s.https=!1;if(e.httpPort!==void 0)s.httpPort=e.httpPort;if(e.httpsPort!==void 0)s.httpsPort=e.httpsPort;if(e.localCa)s.localCa=e.localCa;if(e.maxTlsContexts!==void 0)s.maxTlsContexts=e.maxTlsContexts;return s}async function yb(e={}){let t=await Ik(e);if(("proxies"in t&&Array.isArray(t.proxies)?t.proxies:[]).length===0&&!e.localCa)console.warn(`[rpx gateway] no routes found under ${e.sitesDir??Ds}; every request will answer 404 until a fragment is deployed`);await el(t)}fe();Fe.chdir(_k(Mk(jk(import.meta.url)),".."));var He=new fl("rpx");He.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("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").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").example("rpx start --single-port-mode --https-port 8443").action(async(e)=>{if(!e?.from||!e.to)return el(Gt);let t={from:e.from,to:e.to,https:{keyPath:e.keyPath,certPath:e.certPath,caCertPath:e.caCertPath},cleanup:{certs:e.certsCleanup||!1,hosts:e.hostsCleanup||!1},verbose:e.verbose||!1,changeOrigin:e.changeOrigin||!1,singlePortMode:e.singlePortMode||!1,httpPort:e.httpPort!==void 0?Number(e.httpPort):void 0,httpsPort:e.httpsPort!==void 0?Number(e.httpsPort):void 0,viaDaemon:e.viaDaemon||!1,id:e.id};if(e.startCommand){let r={command:e.startCommand};if(e.startCwd)r.cwd=e.startCwd;if(e.startEnv)try{r.env=JSON.parse(e.startEnv)}catch(n){console.error("Failed to parse start-env JSON:",n),Fe.exit(1)}t.start=r}return db(t)});He.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{let r=oc(Gt)?Gt.proxies.find((n)=>n.to===e||`${n.from}-${n.to}`===e):Gt.to===e?Gt:null;if(!r?.start)console.error(`No watch configuration found for proxy: ${e}`),Fe.exit(1);try{await Vc.startProcess(e,r.start,t.verbose),console.log(`Started dev server for ${e}`)}catch(n){console.error(`Failed to start dev server for ${e}:`,n),Fe.exit(1)}});He.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{try{await Vc.stopProcess(e,t.verbose),console.log(`Stopped dev server for ${e}`)}catch(r){console.error(`Failed to stop dev server for ${e}:`,r),Fe.exit(1)}});He.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(e)=>{try{await Vc.stopAll(e.verbose),console.log("Stopped all dev servers")}catch(t){console.error("Failed to stop all dev servers:",t),Fe.exit(1)}});function wb(e){if(e===void 0)return;let t=typeof e==="string"?Number.parseInt(e,10):e;if(!Number.isInteger(t)||t<0||t>65535)throw Error(`invalid port: ${JSON.stringify(e)}`);return t}function vb(e){return(e??"").split(",").map((t)=>t.trim()).filter(Boolean)}He.command("gateway","Serve every app fragment under a sites.d directory on :80/:443 (production gateway)").option("--sites-dir <path>",`Directory of per-app <slug>.json fragments (default ${Ds})`).option("--certs-dir <path>",`Fallback directory of real PEM certs when no fragment names one (default ${Cd})`).option("--no-https","Serve plain HTTP on the http port only; bind nothing on the https port").option("--http-port <port>","Shared HTTP port: redirect + ACME http-01, or the only listener with --no-https (default 80)").option("--https-port <port>","Shared HTTPS port (default 443)").option("--local-ca-dir <path>","LAN production mode: directory for a local Root CA and its leaf (enables localCa)").option("--local-ca-hosts <hosts>","Comma-separated LAN hostnames the local leaf must cover (e.g. pi-stacks.local)").option("--local-ca-ips <ips>","Comma-separated IP addresses the local leaf must cover (e.g. 192.168.1.20)").option("--install-trust","Install the local Root CA into the system trust store on start (needs root)").option("--max-tls-contexts <n>","Memory guard: most SNI certificates kept live (default 256)").option("--verbose","Enable verbose logging (default on; RPX_VERBOSE=false turns it off)").example("rpx gateway --sites-dir /etc/rpx/sites.d").example("rpx gateway --sites-dir /etc/rpx/sites.d --no-https --http-port 8080").example("rpx gateway --local-ca-dir /etc/rpx/local-ca --local-ca-hosts pi-stacks.local --local-ca-ips 192.168.1.20 --install-trust").action(async(e)=>{try{let t=vb(e.localCaHosts),r=vb(e.localCaIps);if((t.length>0||r.length>0||e.installTrust)&&!e.localCaDir)throw Error("--local-ca-hosts / --local-ca-ips / --install-trust need --local-ca-dir");if(e.localCaDir&&t.length===0)throw Error("--local-ca-dir needs at least one --local-ca-hosts entry");await yb({sitesDir:e.sitesDir??Ds,certsDir:e.certsDir,https:e.https!==!1,httpPort:wb(e.httpPort),httpsPort:wb(e.httpsPort),maxTlsContexts:e.maxTlsContexts===void 0?void 0:Number.parseInt(String(e.maxTlsContexts),10),localCa:e.localCaDir?{dir:e.localCaDir,hosts:t,ips:r,installTrust:e.installTrust===!0}:void 0,verbose:e.verbose===void 0?void 0:e.verbose})}catch(t){console.error(`Failed to start rpx gateway: ${t.message}`),Fe.exit(1)}});async function bb(e){let r={...(await ug().catch(()=>null))?.onDemand??{},enabled:!0};if(e){let n=e.split(",").map((i)=>i.trim()).filter(Boolean);if(n.length>0)r.roots=n}return r}He.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("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(e)=>{try{let t=e.onDemand?await bb(e.roots):void 0;await(await eb({rpxDir:e.rpxDir,registryDir:e.registryDir,httpsPort:typeof e.httpsPort==="string"?Number.parseInt(e.httpsPort,10):e.httpsPort,httpPort:typeof e.httpPort==="string"?Number.parseInt(e.httpPort,10):e.httpPort,hostname:e.hostname,productionCerts:e.certsDir?{certsDir:e.certsDir}:void 0,workers:e.workers===void 0?void 0:typeof e.workers==="string"?Number.parseInt(e.workers,10):e.workers,onDemandSites:t,verbose:e.verbose??!0})).done,Fe.exit(0)}catch(t){console.error(`Failed to start rpx daemon: ${t.message}`),Fe.exit(1)}});He.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(e)=>{let t=typeof e.timeout==="string"?Number.parseInt(e.timeout,10):e.timeout,r=await tb({rpxDir:e.rpxDir,timeoutMs:t,forceAfterTimeout:e.force!==!1,verbose:e.verbose});if(!r.stopped&&r.pid===null){console.log("rpx daemon is not running");return}if(!r.stopped){console.log(`rpx daemon pid=${r.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${r.pid} stopped${r.forced?" (SIGKILL)":""}`)});He.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(e)=>{let t=e.rpxDir??De(),r=await Lr(t),n=await jc(t),i=e.registryDir,s=await xt(i).catch(()=>[]);if(e.json){console.log(JSON.stringify({running:n,pid:r,pidFile:Br(t),rpxDir:t,registryDir:i??dt(),entries:s},null,2));return}if(!n){if(console.log("rpx daemon: not running"),r!==null)console.log(`(stale pid file at ${Br(t)} → pid ${r})`)}else console.log(`rpx daemon: running (pid=${r})`),console.log(`pid file: ${Br(t)}`);if(console.log(`registry: ${i??dt()}`),s.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${s.length}):`);for(let o of s){let c=o.pid!==void 0?`, pid=${o.pid}`:"";console.log(` https://${o.to} → ${o.from} (id=${o.id}${c})`)}});He.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(e)=>{if(!e.id||!e.from||!e.to)console.error("rpx register requires --id, --from, and --to"),Fe.exit(1);if(!Dr(e.id))console.error(`invalid id: ${JSON.stringify(e.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),Fe.exit(1);try{await ai({id:e.id,from:e.from,to:e.to,cwd:e.cwd,createdAt:new Date().toISOString(),cleanUrls:e.cleanUrls,changeOrigin:e.changeOrigin},e.registryDir,e.verbose)}catch(t){console.error(`failed to write registry entry: ${t.message}`),Fe.exit(1)}if(e.skipSpawn){console.log(`registered ${e.to} → ${e.from} (daemon spawn skipped)`);return}try{let t=await Uc({rpxDir:e.rpxDir,verbose:e.verbose}),r=t.spawned?"spawned":"attached to";console.log(`registered https://${e.to} → ${e.from} (${r} daemon pid=${t.pid})`)}catch(t){console.error(`registered entry but daemon spawn failed: ${t.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),Fe.exit(1)}});He.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(e,t)=>{if(!Dr(e))console.error(`invalid id: ${JSON.stringify(e)}`),Fe.exit(1);let r=await Zh(e,t.registryDir,t.verbose);if(!r){console.log(`no registry entry for id=${e}`);return}await Jr(e,t.registryDir,t.verbose),console.log(`unregistered ${r.to} (id=${e})`)});He.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(e)=>{let t=e.rpxDir??De();if(await jc(t)){console.log("rpx daemon is running — DNS overrides are managed by the daemon");return}await rb({rpxDir:t,verbose:e.verbose}),console.log("DNS reconcile complete")});He.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(e)=>{let t=await bb(e.roots),r=pg(t),n=await xt(e.registryDir).catch(()=>[]),i=new Set(n.map((c)=>c.to)),s=r.map((c)=>({host:c.host,dir:c.dir,command:c.command,source:c.source,live:i.has(c.host)}));if(e.json){console.log(JSON.stringify(s,null,2));return}let o=t.roots??["~/Code"];if(s.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${o.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${s.length}) — scanned ${o.join(", ")}:`);for(let c of s)console.log(` ${c.live?"●":"○"} https://${c.host} ${c.live?"(live)":"(idle)"}`),console.log(` ${c.command} ${c.dir}`)});He.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(e,t)=>{let{readFile:r}=await import("node:fs/promises"),{join:n}=await import("node:path"),i=t.rpxDir??De(),s=n(i,"sites",`${xo(e.split(":")[0])}.log`),o;try{o=await r(s,"utf8")}catch{console.log(`no log for ${e} (it may not have been booted yet) — looked in ${s}`);return}let c=t.lines===void 0?void 0:typeof t.lines==="string"?Number.parseInt(t.lines,10):t.lines,a=o.split(`
387
+ `);Fe.stdout.write((c&&c>0?a.slice(-c):a).join(`
388
+ `))});He.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(Rs)});He.version(Rs);He.help();He.run();