@stacksjs/rpx 0.11.19 → 0.11.21
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/acme-challenge.d.ts +13 -0
- package/dist/auth.d.ts +21 -0
- package/dist/bin/cli.js +252 -200
- package/dist/cert-inspect.d.ts +5 -3
- package/dist/{chunk-83dqq28c.js → chunk-1108y1dk.js} +1 -1
- package/dist/{chunk-0f32jmrb.js → chunk-c9brkawa.js} +1 -1
- package/dist/{chunk-w888yhnp.js → chunk-cqkz06bg.js} +1 -1
- package/dist/chunk-qs36t2rf.js +224 -0
- package/dist/daemon.d.ts +4 -1
- package/dist/https.d.ts +1 -0
- package/dist/index.d.ts +33 -1
- package/dist/index.js +7 -7
- package/dist/proxy-handler.d.ts +18 -1
- package/dist/proxy-pool.d.ts +5 -0
- package/dist/redirect.d.ts +40 -0
- package/dist/registry.d.ts +2 -1
- package/dist/site-resolver.d.ts +106 -0
- package/dist/site-splash.d.ts +19 -0
- package/dist/site-supervisor.d.ts +56 -0
- package/dist/start.d.ts +31 -8
- package/dist/types.d.ts +64 -0
- package/package.json +6 -7
- package/dist/chunk-rs8gqpax.js +0 -174
- package/src/cert-inspect.ts +0 -69
- package/src/colors.ts +0 -13
- package/src/config.ts +0 -45
- package/src/daemon-runner.ts +0 -180
- package/src/daemon.ts +0 -1209
- package/src/dns-state.ts +0 -116
- package/src/dns.ts +0 -568
- package/src/host-match.ts +0 -52
- package/src/host-routes.ts +0 -147
- package/src/hosts.ts +0 -283
- package/src/https.ts +0 -905
- package/src/index.ts +0 -161
- package/src/logger.ts +0 -19
- package/src/macos-trust.ts +0 -175
- package/src/on-demand.ts +0 -264
- package/src/origin-guard.ts +0 -127
- package/src/port-manager.ts +0 -183
- package/src/process-manager.ts +0 -164
- package/src/proxy-handler.ts +0 -387
- package/src/proxy-pool.ts +0 -1003
- package/src/registry.ts +0 -366
- package/src/sni.ts +0 -93
- package/src/start.ts +0 -1421
- package/src/static-files.ts +0 -201
- package/src/types.ts +0 -267
- package/src/utils.ts +0 -243
package/dist/bin/cli.js
CHANGED
|
@@ -1,268 +1,320 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
3
|
#!/usr/bin/env bun
|
|
4
|
-
import{createRequire as SF}from"node:module";var LF=Object.defineProperty;var OF=($)=>$;function QF($,w){this[$]=OF.bind(null,w)}var BW=($,w)=>{for(var A in w)LF($,A,{get:w[A],enumerable:!0,configurable:!0,set:QF.bind(w,A)})};var F0=($,w)=>()=>($&&(w=$($=0)),w);var m=SF(import.meta.url);import{existsSync as hW,statSync as VW}from"fs";import{existsSync as xE,mkdirSync as _q,readdirSync as kq,readFileSync as PE,writeFileSync as Dq}from"fs";import{homedir as iw}from"os";import{dirname as Pq,resolve as J$}from"path";import HY from"process";import{existsSync as LW,statSync as OW}from"fs";import{existsSync as r8,mkdirSync as bE,readdirSync as uE,writeFileSync as iE}from"fs";import{homedir as cw}from"os";import{dirname as QW,resolve as i0}from"path";import Cw from"process";import{join as cE,relative as vE,resolve as SW}from"path";import XY from"process";import{existsSync as EB,mkdirSync as lq,readdirSync as pq,writeFileSync as tq}from"fs";import{homedir as S8}from"os";import{dirname as sq,resolve as u0}from"path";import l1 from"process";import{join as mE,relative as dE,resolve as _W}from"path";import JY from"process";import{existsSync as GB,mkdirSync as AM,readdirSync as YM,writeFileSync as XM}from"fs";import{dirname as UM,resolve as UY}from"path";import a8 from"process";import{Buffer as Jw}from"buffer";import{createCipheriv as gE,createDecipheriv as nE,randomBytes as _8}from"crypto";import{closeSync as k8,createReadStream as kW,createWriteStream as lE,existsSync as D8,fsyncSync as DW,openSync as ZW,writeFileSync as pE}from"fs";import{access as tE,constants as xW,mkdir as rE,readdir as uA,rename as PW,stat as vw,unlink as iA,writeFile as Z8}from"fs/promises";import{join as mw}from"path";import O0 from"process";import{pipeline as aE}from"stream/promises";import{createGzip as bW}from"zlib";import dw from"process";import k$ from"process";import{Buffer as Q$}from"buffer";import{createCipheriv as sE,createDecipheriv as oE,randomBytes as x8}from"crypto";import{closeSync as P8,createReadStream as uW,createWriteStream as eE,existsSync as cA,fsyncSync as iW,openSync as cW,writeFileSync as $5}from"fs";import{access as w5,constants as vW,mkdir as A5,readdir as vA,rename as mW,stat as gw,unlink as mA,writeFile as b8}from"fs/promises";import{isAbsolute as Y5,join as nw,resolve as X5}from"path";import k from"process";import{pipeline as J5}from"stream/promises";import{createGzip as dW}from"zlib";import lw from"process";import D$ from"process";import dA from"process";import{existsSync as gA}from"fs";import{resolve as u8}from"path";import{existsSync as U5}from"fs";import{existsSync as f5,readdirSync as W5}from"fs";import{extname as i8,resolve as gW}from"path";import B5 from"process";import{join as j5,relative as z5,resolve as nW}from"path";import fY from"process";import{Buffer as S$}from"buffer";import{createCipheriv as F5,createDecipheriv as E5,randomBytes as c8}from"crypto";import{closeSync as v8,createReadStream as lW,createWriteStream as G5,existsSync as nA,fsyncSync as pW,openSync as tW,writeFileSync as K5}from"fs";import{access as T5,constants as rW,mkdir as H5,readdir as lA,rename as aW,stat as pw,unlink as pA,writeFile as m8}from"fs/promises";import{isAbsolute as N5,join as tw,resolve as R5}from"path";import D from"process";import{pipeline as q5}from"stream/promises";import{createGzip as sW}from"zlib";import rw from"process";import Z$ from"process";import rA from"process";import{existsSync as aA}from"fs";import{resolve as t8}from"path";import{existsSync as cG}from"fs";class zB{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let X=this.generateKey($,A),J=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!hW($))return!0;return VW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let X=hW(A)?VW(A):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,X)=>Y+X.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class FB{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:X,...A}),J}catch(J){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...A}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((X)=>X.duration),Y=A.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function y5($,w){this[$]=I5.bind(null,w)}class WJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let X=this.generateKey($,A),J=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!LW($))return!0;return OW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let X=LW(A)?OW(A):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,X)=>Y+X.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class BJ{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:X,...A}),J}catch(J){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...A}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((X)=>X.duration),Y=A.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function V5($,w={}){let Y=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return Y?`${$}:${Y}`:$}function L5($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function O5($){return $.getStats().size*2}function jJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&o(w[0])&&"id"in w[0]&&w[0].id===3&&o(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(o(w)&&o($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(o($)&&"arr"in $&&Array.isArray($.arr)&&o(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&o(w[0])&&o($[0])){let Y=[...w];for(let X of $)if(o(X)&&"name"in X){if(!Y.find((U)=>o(U)&&("name"in U)&&U.name===X.name))Y.push(X)}else if(o(X)&&"path"in X){if(!Y.find((U)=>o(U)&&("path"in U)&&U.path===X.path))Y.push(X)}else if(!Y.some((J)=>WY(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!o(w)||!o($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if(o(X)&&o(A[Y]))A[Y]=jJ(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&o(X[0])&&o(A[Y][0])){let J=[...X];for(let U of A[Y])if(o(U)&&"name"in U){if(!J.find((f)=>o(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(o(U)&&"path"in U){if(!J.find((f)=>o(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((W)=>WY(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function WY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!WY($[A],w[A]))return!1;return!0}if(o($)&&o(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!WY($[X],w[X]))return!1}return!0}return!1}function o($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function Q5($,w){if(!GB($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return jJ(w,Y)}catch{return null}}catch{return null}}async function S5({name:$="",cwd:w,defaultConfig:A}){let Y=w||a8.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let W of X){let f=UY(Y,`${U}${W}`),B=await Q5(f,A);if(B!==null)return B}try{let U=UY(Y,"package.json");if(GB(U)){let f=(await import(U))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return jJ(A,f)}catch{}}}catch{}return A}function _5($,w={}){let A=JY.cwd();while(A.includes("storage"))A=_W(A,"..");let Y=_W(A,$||"");if(w?.relative)return dE(JY.cwd(),Y);return Y}async function k5(){try{let $=await S5({name:"clarity",defaultConfig:eA,cwd:JY.cwd(),endpoint:"",headers:{}});return{...eA,...$}}catch{return eA}}function X0(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function D5(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof k$<"u"){let $=k$.type;if($==="renderer"||$==="worker")return!1;return!!(k$.versions&&(k$.versions.node||k$.versions.bun))}return!1}class TB{async format($){let w=await D5(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:dw.pid,hostname:w(),environment:dw.env.NODE_ENV||"development",platform:dw.platform,version:dw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:dw.env.NODE_ENV||dw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class BY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...o8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new TB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??O0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...$Y,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...$Y};return{...$Y,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:o8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await tE(this.config.logDirectory,xW.F_OK|xW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await rE(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Jw.from($);try{if(!D8(this.currentLogFile))await Z8(this.currentLogFile,"",{mode:420});if(X=ZW(this.currentLogFile,"a",420),pE(X,f,{flag:"a"}),DW(X),X!==void 0)k8(X),X=void 0;if((await vw(this.currentLogFile)).size===0){if(await Z8(this.currentLogFile,f,{flag:"w",mode:420}),(await vw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let E=W*2**J;await new Promise((F)=>setTimeout(F,E)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{k8(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 mw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return mw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return mw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(X0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return _8(16).toString("hex")}generateKey(){return _8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=_8(16),Y=gE("aes-256-gcm",w,A),X=Jw.concat([Y.update($,"utf8"),Y.final()]),J=Y.getAuthTag();return{encrypted:Jw.concat([A,X,J]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=bW(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(Jw.from(Jw.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(X0())return;let $=await vw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await uA(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await vw(A).catch(()=>null))try{if(await PW(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await iA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await Z8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await vw(A).catch(()=>null))await PW(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await uA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await iA(mw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=kW($),Y=lE(w),X=bW();await aE(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),D8(this.currentLogFile))try{let $=ZW(this.currentLogFile,"r+");DW($),k8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!X0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await uA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await iA(mw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?t.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=O0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${t.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!X0()){let B=VB[$],j=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:t.gray(U),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:t.green(U),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z),W){let E=W.split(`
|
|
5
|
-
`);for(let
|
|
6
|
-
`;if(W
|
|
7
|
-
`;
|
|
8
|
-
`,
|
|
9
|
-
`),U=Math.max(...J.map((
|
|
10
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||
|
|
12
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||X0()||!O0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(X0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await uA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let J=mw(this.config.logDirectory,Y);if($.before)try{if((await vw(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}A.push(J)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await iA(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function oA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let Y=[...w];for(let X of $)if(d(X)&&"name"in X){if(!Y.find((U)=>d(U)&&("name"in U)&&U.name===X.name))Y.push(X)}else if(d(X)&&"path"in X){if(!Y.find((U)=>d(U)&&("path"in U)&&U.path===X.path))Y.push(X)}else if(!Y.some((J)=>jY(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!d(w)||!d($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if(d(X)&&d(A[Y]))A[Y]=oA(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&d(X[0])&&d(A[Y][0])){let J=[...X];for(let U of A[Y])if(d(U)&&"name"in U){if(!J.find((f)=>d(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(d(U)&&"path"in U){if(!J.find((f)=>d(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((W)=>jY(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function zJ($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:oA($,w);if(Array.isArray($))return A==="replace"?w:oA($,w);if(!d(w)||!d($))return w;let Y={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[X],U=Y[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(A==="replace")Y[X]=J;else Y[X]=oA(U,J);else if(d(J)&&d(U))Y[X]=zJ(U,J,A);else Y[X]=J}return Y}function jY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!jY($[A],w[A]))return!1;return!0}if(d($)&&d(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!jY($[X],w[X]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function tA($,w,A="replace"){if(!EB($))return null;try{let Y=await import($),X=Y.default||Y;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return zJ(w,X,A)}catch{return null}}catch{return null}}function Z5($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${z.map(E).join("_")}`,T=`${Y}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(A)S0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=J(j,z);else{let K=l1.env[F]||l1.env[T];if(K!==void 0){if(A)S0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((N)=>N.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return J(X)}async function x5({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let f=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?Z5($,X,J):X,B=A||l1.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)S0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),E=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,u0(B,"config"),u0(B,".config"),Y?u0(B,Y):void 0].filter(Boolean)));for(let H of K){if(J)S0.info(`Searching for configuration in: ${H}`);let R=[u0(B,"config"),u0(B,".config")].concat(Y?[u0(B,Y)]:[]).includes(H)?[...z,...E,...F,...T]:[...E,...z,...T,...F];for(let M of R)for(let y of j){let I=u0(H,`${M}${y}`),C=await tA(I,f,W);if(C!==null){if(J)S0.success(`Configuration loaded from: ${I}`);return C}}}if($){let H=u0(S8(),".config",$),N=["config",`${$}.config`];if(w)N.push(`${w}.config`);if(J)S0.info(`Checking user config directory: ${H}`);for(let R of N)for(let M of j){let y=u0(H,`${R}${M}`),I=await tA(y,f,W);if(I!==null){if(J)S0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let H=u0(S8(),".config"),N=[`.${$}.config`];if(w)N.push(`.${w}.config`);if(J)S0.info(`Checking user config directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=u0(H,`${R}${M}`),I=await tA(y,f,W);if(I!==null){if(J)S0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let H=S8(),N=[`.${$}.config`,`.${$}`];if(w)N.push(`.${w}.config`),N.push(`.${w}`);if(J)S0.info(`Checking user home directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=u0(H,`${R}${M}`),I=await tA(y,f,W);if(I!==null){if(J)S0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let H=u0(B,"package.json");if(EB(H)){let N=await import(H),R=N[$];if(!R&&w){if(R=N[w],R&&J)S0.success(`Using alias "${w}" 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}`);return zJ(f,R,W)}catch(M){if(J)S0.warn("Failed to merge package.json config:",M)}}}catch(H){if(J)S0.warn("Failed to load package.json:",H)}if(J)S0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function P5($,w={}){let A=XY.cwd();while(A.includes("storage"))A=SW(A,"..");let Y=SW(A,$||"");if(w?.relative)return vE(XY.cwd(),Y);return Y}async function b5(){try{let $=await x5({name:"clarity",alias:"logging",defaultConfig:wY,cwd:XY.cwd()});return{...wY,...$||{}}}catch{return wY}}function G0(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function u5(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D$<"u"){let $=D$.type;if($==="renderer"||$==="worker")return!1;return!!(D$.versions&&(D$.versions.node||D$.versions.bun))}return!1}class HB{async format($){let w=await u5(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:lw.pid,hostname:w(),environment:lw.env.NODE_ENV||"development",platform:lw.platform,version:lw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:lw.env.NODE_ENV||lw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...e8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new HB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...AY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...AY};return{...AY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:e8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!G0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await w5(this.config.logDirectory,vW.F_OK|vW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await A5(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Q$.from($);try{if(!cA(this.currentLogFile))await b8(this.currentLogFile,"",{mode:420});if(X=cW(this.currentLogFile,"a",420),$5(X,f,{flag:"a"}),iW(X),X!==void 0)P8(X),X=void 0;if((await gw(this.currentLogFile)).size===0){if(await b8(this.currentLogFile,f,{flag:"w",mode:420}),(await gw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let E=W*2**J;await new Promise((F)=>setTimeout(F,E)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{P8(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return nw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return nw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return nw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(G0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return x8(16).toString("hex")}generateKey(){return x8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=x8(16),Y=sE("aes-256-gcm",w,A),X=Q$.isBuffer($)?$:Q$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=Q$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=dW(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(Q$.from(Q$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(G0())return;if(!this.shouldWriteToFile())return;let $=await gw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await vA(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await gw(A).catch(()=>null))try{if(await mW(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await mA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await b8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await gw(A).catch(()=>null))await mW(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await vA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await mA(nw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=uW($),Y=eE(w),X=dW();await J5(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),cA(this.currentLogFile))try{let $=cW(this.currentLogFile,"r+");iW($),P8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!G0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await vA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await mA(nw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?P.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||G0())return!1;let $=typeof k.env.NO_COLOR<"u",w=k.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=k.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${P.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=P.underline(P.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(A,Y)=>P.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>P.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>P.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>P.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>P.strikethrough(Y)),w}supportsHyperlinks(){if(G0())return!1;let $=k.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=k.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(Y5(w)||w.startsWith("./")||w.startsWith("../"))w=X5(w);else return null;return cA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":LB[$],E=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:P.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:P.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
13
|
-
`);for(let
|
|
14
|
-
`;if(
|
|
15
|
-
`;if(
|
|
16
|
-
`);if(this[
|
|
17
|
-
`,
|
|
18
|
-
`),
|
|
19
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
21
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
4
|
+
import{createRequire as m6}from"node:module";var c6=Object.defineProperty;var v6=($)=>$;function i6($,w){this[$]=v6.bind(null,w)}var oB=($,w)=>{for(var Y in w)c6($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:i6.bind(w,Y)})};var o=($,w)=>()=>($&&(w=$($=0)),w);var b=m6(import.meta.url);import{existsSync as Nj,statSync as Ej}from"fs";import{existsSync as pF,mkdirSync as c4,readdirSync as v4,readFileSync as rF,writeFileSync as i4}from"fs";import{homedir as nw}from"os";import{dirname as d4,resolve as Y$}from"path";import kA from"process";import{existsSync as fj,statSync as qj}from"fs";import{existsSync as yJ,mkdirSync as tF,readdirSync as aF,writeFileSync as sF}from"fs";import{homedir as pw}from"os";import{dirname as Tj,resolve as v0}from"path";import _w from"process";import{join as oF,relative as eF,resolve as Hj}from"path";import RA from"process";import{existsSync as Y9,mkdirSync as $I,readdirSync as wI,writeFileSync as YI}from"fs";import{homedir as XJ}from"os";import{dirname as JI,resolve as c0}from"path";import JY from"process";import{join as $K,relative as wK,resolve as Rj}from"path";import MA from"process";import{existsSync as A9,mkdirSync as zI,readdirSync as GI,writeFileSync as FI}from"fs";import{dirname as NI,resolve as IA}from"path";import CJ from"process";import{Buffer as Bw}from"buffer";import{createCipheriv as YK,createDecipheriv as AK,randomBytes as JJ}from"crypto";import{closeSync as UJ,createReadStream as Mj,createWriteStream as XK,existsSync as WJ,fsyncSync as Ij,openSync as Vj,writeFileSync as JK}from"fs";import{access as UK,constants as yj,mkdir as WK,readdir as $A,rename as Cj,stat as rw,unlink as wA,writeFile as BJ}from"fs/promises";import{join as tw}from"path";import Q0 from"process";import{pipeline as BK}from"stream/promises";import{createGzip as Qj}from"zlib";import aw from"process";import D$ from"process";import{Buffer as Z$}from"buffer";import{createCipheriv as jK,createDecipheriv as zK,randomBytes as jJ}from"crypto";import{closeSync as zJ,createReadStream as Lj,createWriteStream as GK,existsSync as YA,fsyncSync as Oj,openSync as _j,writeFileSync as FK}from"fs";import{access as KK,constants as Sj,mkdir as NK,readdir as AA,rename as hj,stat as sw,unlink as XA,writeFile as GJ}from"fs/promises";import{isAbsolute as EK,join as ow,resolve as fK}from"path";import k from"process";import{pipeline as qK}from"stream/promises";import{createGzip as Zj}from"zlib";import ew from"process";import x$ from"process";import JA from"process";import{existsSync as UA}from"fs";import{resolve as FJ}from"path";import{existsSync as TK}from"fs";import{existsSync as HK,readdirSync as RK}from"fs";import{extname as KJ,resolve as kj}from"path";import MK from"process";import{join as IK,relative as VK,resolve as Dj}from"path";import VA from"process";import{Buffer as k$}from"buffer";import{createCipheriv as yK,createDecipheriv as CK,randomBytes as NJ}from"crypto";import{closeSync as EJ,createReadStream as xj,createWriteStream as QK,existsSync as WA,fsyncSync as Pj,openSync as bj,writeFileSync as LK}from"fs";import{access as OK,constants as uj,mkdir as _K,readdir as BA,rename as cj,stat as $1,unlink as jA,writeFile as fJ}from"fs/promises";import{isAbsolute as SK,join as w1,resolve as hK}from"path";import D from"process";import{pipeline as ZK}from"stream/promises";import{createGzip as vj}from"zlib";import Y1 from"process";import P$ from"process";import GA from"process";import{existsSync as FA}from"fs";import{resolve as IJ}from"path";import{existsSync as o7}from"fs";class $9{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!Nj($))return!0;return Ej($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=Nj(Y)?Ej(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class w9{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function xK($,w){this[$]=DK.bind(null,w)}class bJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!fj($))return!0;return qj($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=fj(Y)?qj(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class uJ{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function uK($,w={}){let A=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return A?`${$}:${A}`:$}function cK($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function vK($){return $.getStats().size*2}function cJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&$0(w[0])&&"id"in w[0]&&w[0].id===3&&$0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if($0(w)&&$0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if($0($)&&"arr"in $&&Array.isArray($.arr)&&$0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&$0(w[0])&&$0($[0])){let A=[...w];for(let X of $)if($0(X)&&"name"in X){if(!A.find((U)=>$0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if($0(X)&&"path"in X){if(!A.find((U)=>$0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>yA(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!$0(w)||!$0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if($0(X)&&$0(Y[A]))Y[A]=cJ(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&$0(X[0])&&$0(Y[A][0])){let J=[...X];for(let U of Y[A])if($0(U)&&"name"in U){if(!J.find((W)=>$0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if($0(U)&&"path"in U){if(!J.find((W)=>$0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((B)=>yA(B,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 yA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!yA($[Y],w[Y]))return!1;return!0}if($0($)&&$0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!yA($[X],w[X]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function iK($,w){if(!A9($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return cJ(w,A)}catch{return null}}catch{return null}}async function mK({name:$="",cwd:w,defaultConfig:Y}){let A=w||CJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=IA(A,`${U}${B}`),j=await iK(W,Y);if(j!==null)return j}try{let U=IA(A,"package.json");if(A9(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return cJ(Y,W)}catch{}}}catch{}return Y}function gK($,w={}){let Y=MA.cwd();while(Y.includes("storage"))Y=Rj(Y,"..");let A=Rj(Y,$||"");if(w?.relative)return wK(MA.cwd(),A);return A}async function dK(){try{let $=await mK({name:"clarity",defaultConfig:EA,cwd:MA.cwd(),endpoint:"",headers:{}});return{...EA,...$}}catch{return EA}}function U0(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lK(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D$<"u"){let $=D$.type;if($==="renderer"||$==="worker")return!1;return!!(D$.versions&&(D$.versions.node||D$.versions.bun))}return!1}class J9{async format($){let w=await lK(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:aw.pid,hostname:w(),environment:aw.env.NODE_ENV||"development",platform:aw.platform,version:aw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:aw.env.NODE_ENV||aw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class CA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...LJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new J9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??Q0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...fA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...fA};return{...fA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:LJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await UK(this.config.logDirectory,yj.F_OK|yj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await WK(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Bw.from($);try{if(!WJ(this.currentLogFile))await BJ(this.currentLogFile,"",{mode:420});if(X=Vj(this.currentLogFile,"a",420),JK(X,W,{flag:"a"}),Ij(X),X!==void 0)UJ(X),X=void 0;if((await rw(this.currentLogFile)).size===0){if(await BJ(this.currentLogFile,W,{flag:"w",mode:420}),(await rw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let F=B*2**J;await new Promise((K)=>setTimeout(K,F)),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{UJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 tw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return tw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return tw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.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 w=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(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return JJ(16).toString("hex")}generateKey(){return JJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=JJ(16),A=YK("aes-256-gcm",w,Y),X=Bw.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:Bw.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Qj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(Bw.from(Bw.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(U0())return;let $=await rw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let 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,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await rw(Y).catch(()=>null))try{if(await Cj(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await wA(B)}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 BJ(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 rw(Y).catch(()=>null))await Cj(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await $A(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await wA(tw(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=Mj($),A=XK(w),X=Qj();await BK(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!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(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),WJ(this.currentLogFile))try{let $=Vj(this.currentLogFile,"r+");Ij($),UJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await $A(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await wA(tw(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?t.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push(w);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let W=Q0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${t.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,F=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(F)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.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,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!U0()){let j=E9[$],z=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:t.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:t.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let F=B.split(`
|
|
5
|
+
`);for(let K of F)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:t.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let W=`${J} ${this.environment}.${$.toUpperCase()}: ${U}
|
|
6
|
+
`;if(B)W+=`${B}
|
|
7
|
+
`;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time($){let w=performance.now();if(this.fancy&&!U0()){let Y=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:t.blue("◐"),tag:Y,message:`${t.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
|
|
8
|
+
`,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let z=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:t.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!U0())console.error(j.trim());await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new CA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(U0())throw Error("createReadStream is not supported in browser environments");if(!WJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Mj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Bw.isBuffer($)?$:Bw.from($,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),B=AK("aes-256-gcm",Y,X);return B.setAuthTag(J),Bw.concat([B.update(U),B.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!U0()){let J=$.split(`
|
|
9
|
+
`),U=Math.max(...J.map((z)=>z.length))+2,B=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,j=J.map((z)=>{let G=" ".repeat(U-z.length-2);return`│ ${z}${G} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:t.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:t.cyan(B)})),j.forEach((z)=>console.error(this.formatConsoleMessage({timestamp:Y,message:t.cyan(z),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:t.cyan(W),showTimestamp:!1}))}else if(!U0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let X=`${A} ${this.environment}.INFO: [BOX] ${$}
|
|
10
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(U0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${t.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();Q0.stdin.removeListener("data",Y);try{if(typeof Q0.stdin.setRawMode==="function")Q0.stdin.setRawMode(!1)}catch{}Q0.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof Q0.stdin.setRawMode==="function")Q0.stdin.setRawMode(!0)}catch{}Q0.stdin.resume(),Q0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,B=0;if(Y=$.replace(U,(W,j)=>{if(j==="%")return"%";if(B>=w.length)return W;let z=w[B++];switch(j){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}}),B<w.length)Y+=` ${w.slice(B).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?t.gray(this.formatTag(this.name)):"",B=t.blue("◐");console.error(`${B} ${U} ${t.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
11
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||U0()||$<=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:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,B)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),B!==void 0)this.activeProgressBar.message=B;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,B="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;Q0.stdout.write(`${"\r".padEnd(Q0.stdout.columns||80)}\r`),this.log(B,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||U0()||!Q0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=t.green("━".repeat(A)),U=t.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=w||Y===100?t.green("✓"):t.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${t.gray(this.formatTag(this.name))}`:"",F=`\r${z}${G} ${B} ${W}${j}`,K=Q0.stdout.columns||80,f=" ".repeat(Math.max(0,K-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${f}`,Q0.stdout.write($.lastRenderedLine),w)Q0.stdout.write(`
|
|
12
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||U0()||!Q0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await $A(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=tw(this.config.logDirectory,A);if($.before)try{if((await rw(J)).mtime>=$.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 wA(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(w){console.error("Error during log clearing process:",w)}}}function NA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let A=[...w];for(let X of $)if(d(X)&&"name"in X){if(!A.find((U)=>d(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(d(X)&&"path"in X){if(!A.find((U)=>d(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>QA(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!d(w)||!d($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(d(X)&&d(Y[A]))Y[A]=NA(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&d(X[0])&&d(Y[A][0])){let J=[...X];for(let U of Y[A])if(d(U)&&"name"in U){if(!J.find((W)=>d(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(d(U)&&"path"in U){if(!J.find((W)=>d(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((B)=>QA(B,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 vJ($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:NA($,w);if(Array.isArray($))return Y==="replace"?w:NA($,w);if(!d(w)||!d($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[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]=NA(U,J);else if(d(J)&&d(U))A[X]=vJ(U,J,Y);else A[X]=J}return A}function QA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!QA($[Y],w[Y]))return!1;return!0}if(d($)&&d(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!QA($[X],w[X]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function zA($,w,Y="replace"){if(!Y9($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return vJ(w,X,Y)}catch{return null}}catch{return null}}function nK($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],F=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),K=`${A}_${G.map(F).join("_")}`,f=`${A}_${G.map((E)=>E.toUpperCase()).join("_")}`;if(Y)O0.info(`Checking environment variable ${K} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let E=JY.env[K]||JY.env[f];if(E!==void 0){if(Y)O0.info(`Using environment variable ${E?K:f} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(E);else if(typeof z==="boolean")W[j]=E.toLowerCase()==="true";else if(Array.isArray(z))try{let q=JSON.parse(E);if(Array.isArray(q))W[j]=q;else W[j]=E.split(",").map((T)=>T.trim())}catch{W[j]=E.split(",").map((q)=>q.trim())}else W[j]=E}}}return W}return J(X)}async function pK({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?nK($,X,J):X,j=Y||JY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)O0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),F=[`${$}.config`,`.${$}.config`].filter(Boolean),K=w?[w,`.${w}`]:[],f=w?[`${w}.config`,`.${w}.config`]:[],E=Array.from(new Set([j,c0(j,"config"),c0(j,".config"),A?c0(j,A):void 0].filter(Boolean)));for(let q of E){if(J)O0.info(`Searching for configuration in: ${q}`);let M=[c0(j,"config"),c0(j,".config")].concat(A?[c0(j,A)]:[]).includes(q)?[...G,...F,...K,...f]:[...F,...G,...f,...K];for(let y of M)for(let Q of z){let H=c0(q,`${y}${Q}`),I=await zA(H,W,B);if(I!==null){if(J)O0.success(`Configuration loaded from: ${H}`);return I}}}if($){let q=c0(XJ(),".config",$),T=["config",`${$}.config`];if(w)T.push(`${w}.config`);if(J)O0.info(`Checking user config directory: ${q}`);for(let M of T)for(let y of z){let Q=c0(q,`${M}${y}`),H=await zA(Q,W,B);if(H!==null){if(J)O0.success(`Configuration loaded from user config directory: ${Q}`);return H}}}if($){let q=c0(XJ(),".config"),T=[`.${$}.config`];if(w)T.push(`.${w}.config`);if(J)O0.info(`Checking user config directory for dotfile configs: ${q}`);for(let M of T)for(let y of z){let Q=c0(q,`${M}${y}`),H=await zA(Q,W,B);if(H!==null){if(J)O0.success(`Configuration loaded from user config directory dotfile: ${Q}`);return H}}}if($){let q=XJ(),T=[`.${$}.config`,`.${$}`];if(w)T.push(`.${w}.config`),T.push(`.${w}`);if(J)O0.info(`Checking user home directory for dotfile configs: ${q}`);for(let M of T)for(let y of z){let Q=c0(q,`${M}${y}`),H=await zA(Q,W,B);if(H!==null){if(J)O0.success(`Configuration loaded from user home directory: ${Q}`);return H}}}try{let q=c0(j,"package.json");if(Y9(q)){let T=await import(q),M=T[$];if(!M&&w){if(M=T[w],M&&J)O0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)O0.success(`Configuration loaded from package.json: ${M===T[$]?$:w}`);return vJ(W,M,B)}catch(y){if(J)O0.warn("Failed to merge package.json config:",y)}}}catch(q){if(J)O0.warn("Failed to load package.json:",q)}if(J)O0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function rK($,w={}){let Y=RA.cwd();while(Y.includes("storage"))Y=Hj(Y,"..");let A=Hj(Y,$||"");if(w?.relative)return eF(RA.cwd(),A);return A}async function tK(){try{let $=await pK({name:"clarity",alias:"logging",defaultConfig:qA,cwd:RA.cwd()});return{...qA,...$||{}}}catch{return qA}}function K0(){if(x$.env.NODE_ENV==="test"||x$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function aK(){if(x$.env.NODE_ENV==="test"||x$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof x$<"u"){let $=x$.type;if($==="renderer"||$==="worker")return!1;return!!(x$.versions&&(x$.versions.node||x$.versions.bun))}return!1}class U9{async format($){let w=await aK(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:ew.pid,hostname:w(),environment:ew.env.NODE_ENV||"development",platform:ew.platform,version:ew.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ew.env.NODE_ENV||ew.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class LA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...OJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new U9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...TA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...TA};return{...TA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:OJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!K0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await KK(this.config.logDirectory,Sj.F_OK|Sj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await NK(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Z$.from($);try{if(!YA(this.currentLogFile))await GJ(this.currentLogFile,"",{mode:420});if(X=_j(this.currentLogFile,"a",420),FK(X,W,{flag:"a"}),Oj(X),X!==void 0)zJ(X),X=void 0;if((await sw(this.currentLogFile)).size===0){if(await GJ(this.currentLogFile,W,{flag:"w",mode:420}),(await sw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let F=B*2**J;await new Promise((K)=>setTimeout(K,F)),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{zJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 ow(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ow(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return ow(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(K0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.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 w=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(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return jJ(16).toString("hex")}generateKey(){return jJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=jJ(16),A=jK("aes-256-gcm",w,Y),X=Z$.isBuffer($)?$:Z$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=Z$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Zj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(Z$.from(Z$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(K0())return;if(!this.shouldWriteToFile())return;let $=await sw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await AA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await sw(Y).catch(()=>null))try{if(await hj(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await XA(B)}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 GJ(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 sw(Y).catch(()=>null))await hj(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await AA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await XA(ow(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=Lj($),A=GK(w),X=Zj();await qK(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!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(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),YA(this.currentLogFile))try{let $=_j(this.currentLogFile,"r+");Oj($),zJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!K0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await AA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await XA(ow(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?u.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||K0())return!1;let $=typeof k.env.NO_COLOR<"u",w=k.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push(w);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let W=k.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${u.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,F=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(F)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),w}supportsHyperlinks(){if(K0())return!1;let $=k.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=k.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(EK(w)||w.startsWith("./")||w.startsWith("../"))w=fK(w);else return null;return YA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":f9[$],F=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",K;switch($){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:u.gray(W),level:$}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:u.green(W),level:$}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.error(K),B){let f=B.split(`
|
|
13
|
+
`);for(let E of f)if(E.trim()&&!E.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:u.gray(` ${E}`),level:$,showTimestamp:!1}))}break}}else if(!K0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
|
|
14
|
+
`;if(B)z+=`${B}
|
|
15
|
+
`;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress($,w=""){let Y={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!K0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!K0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!K0()&&k.stdout.isTTY)k.stdout.write(`
|
|
16
|
+
`);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!K0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=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($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
|
|
17
|
+
`,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":u.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!K0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new LA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(K0())throw Error("createReadStream is not supported in browser environments");if(!YA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Lj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Z$.isBuffer($)?$:Z$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=zK("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=Z$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
|
|
18
|
+
`),W=Math.max(...B.map((F)=>F.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((F)=>{return this.formatConsoleMessage({timestamp:Y,message:u.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(j),showTimestamp:!1})),G.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(z),showTimestamp:!1}))}else if(!K0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
19
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(K0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${u.cyan("?")} ${$} (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(""),w(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($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=$.replace(W,(z,G)=>{if(G==="%")return"%";if(j>=w.length)return z;let F=w[j++];switch(G){case"s":return String(F);case"d":case"i":return Number(F).toString();case"j":case"o":return JSON.stringify(F,null,2);default:return z}}),j<w.length)Y+=` ${w.slice(j).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?u.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${j}${W} ${u.cyan(A)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
20
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!k.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=u.green("━".repeat(A)),U=u.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?u.green("✓"):u.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",F=`\r${z}${G} ${B} ${W}${j}`,K=k.stdout.columns||80,f=" ".repeat(Math.max(0,K-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${f}`,k.stdout.write($.lastRenderedLine),w)k.stdout.write(`
|
|
21
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||K0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(K0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await AA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=ow(this.config.logDirectory,A);if($.before)try{if((await sw(J)).mtime>=$.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 XA(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(w){console.error("Error during log clearing process:",w)}}}async function W9($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function B9($){return $ instanceof a0}function sK($){return $ instanceof OA}function oK($){if(B9($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}class DA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return BY.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=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=JA.env[W]||(j?JA.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=JA.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof _A)throw G;throw jw.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw jw.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(JA.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
|
|
22
22
|
|
|
23
|
-
`;for(let
|
|
24
|
-
`,
|
|
25
|
-
`,
|
|
26
|
-
`,
|
|
23
|
+
`;for(let A of $)Y+=`${A.key}
|
|
24
|
+
`,Y+=` Type: ${A.type}
|
|
25
|
+
`,Y+=` Description: ${A.description}
|
|
26
|
+
`,Y+=` Example: ${A.example}
|
|
27
27
|
|
|
28
|
-
`;return
|
|
28
|
+
`;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
|
|
29
29
|
|
|
30
|
-
`;
|
|
31
|
-
`,
|
|
32
|
-
`;for(let
|
|
33
|
-
`;return A}}function v5($,w){let A=CB("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function qB($,w,A={}){return MB($,w,A,new WeakMap)}function MB($,w,A,Y){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=A;if(w===null||w===void 0)return J?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return IB($,w,X,Y);if(!U$(w)||!U$($))return w;return n5($,w,A,Y)}function IB($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return m5($,w);case"smart":return d5($,w,Y);default:return w}return w}function m5($,w){let A=[...w];for(let Y of $)if(!A.some((X)=>s8(X,Y)))A.push(Y);return A}function d5($,w,A){if(w.length===0)return $;if($.length===0)return w;if(U$(w[0])&&U$($[0]))return g5($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}function g5($,w,A){let Y=[...w];for(let X of $){if(!U$(X)){Y.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(Y.find((B)=>U$(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)Y.push(X)}return Y}function n5($,w,A,Y){let X=w;if(U$(X)&&Y.has(X))return Y.get(X);let J={...$};if(U$(X))Y.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],f=J[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(U$(W)&&U$(f))J[U]=MB(f,W,A,Y);else if(Array.isArray(W)||Array.isArray(f))J[U]=IB(f,W,A.arrayMergeMode||"smart",Y);else J[U]=W}return J}function FJ($,w,A="replace"){return qB($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function s8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!s8($[A],w[A]))return!1;return!0}if(U$($)&&U$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!s8($[X],w[X]))return!1}return!0}return!1}function U$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class RY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=A;if(X){let B=aw.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!gA($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,E="default"in j,F=Object.keys(j).length>0;if(!E&&!F)throw new p1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new p1($,Error("Configuration must export a valid object"),"unknown");let H={config:FJ(w,z,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)aw.setWithFileCheck("file",H,$,J);return H}catch(B){throw B instanceof Error?Uw.configLoad($,B):Uw.configLoad($,Error(String(B)))}};if(U)return r1.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let X=await this.loadFromPath(Y,w,A);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,X)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),X=[];for(let J of Y)for(let U of this.extensions)X.push(u8(w,`${J}${U}`));return X}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return NB(async()=>{return gA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!gA($))return Y;if(w||A){let X=this.generateNamePatterns(w||"",A);for(let J of X)for(let U of this.extensions){let W=u8($,`${J}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let W=u8($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!gA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let X=await this.loadFromPath(Y,{},w);if(X)A.set(Y,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${Y}:`,X)}})),A}}class EJ{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:f=!1}=A,B=async()=>{let j=[],z=[],E={stopOnFirstError:Y,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,E);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],E);else return this.validateWithJSONSchema($,w,E)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await r1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!U5(w))throw new t1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),X=Y.default||Y;if(Array.isArray(X))return this.validateWithRules($,X,A);else return this.validateWithJSONSchema($,X,A)}catch(Y){throw new t1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],X=[];return this.validateObjectAgainstSchema($,w,"",Y,X,A),{isValid:Y.length===0,errors:Y,warnings:X}}validateObjectAgainstSchema($,w,A,Y,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,X,J),J.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],f,B,Y,X,J),J.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(U))if(!W.has(f))X.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),W=this.validateWithRule(U,J,J.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:X}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)Y.push({path:A,message:w.message||X,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let X of A)if(Y&&typeof Y==="object"&&X in Y)Y=Y[X];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,X,J,U]=Y;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:QB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class GJ{fileLoader=new RY;envProcessor=new NY;validator=new EJ;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:X,validate:J,...U}=$;try{if(A?.enabled){let f=this.checkCache(U.name||"",U);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(f){let B=U.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),E=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(E||j))throw f;if(z&&(!B||!E))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(f);if(Y.slowThreshold&&f.duration>Y.slowThreshold)H$.warn(`Slow configuration loading detected: ${f.duration}ms for ${U.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw H$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=J||Cw.cwd(),E=[],F=await this.loadLocalConfiguration(Y,X,z,U,W,B,j,f,A);if(F)return E.push(...this.getLocalSearchPaths(Y,X,z,U)),this.finalizeResult(F,E,f,Y,j);let T=await this.loadHomeConfiguration(Y,X,W,B,j,f);if(T)return E.push(...this.getHomeSearchPaths(Y,X)),this.finalizeResult(T,E,f,Y,j);let K=await this.loadPackageJsonConfiguration(Y,X,z,W,B,j,f);if(K)return E.push(i0(z,"package.json")),this.finalizeResult(K,E,f,Y,j);if(E.push(...this.getAllSearchPaths(Y,X,z,U)),w)throw Uw.configNotFound(Y,E,X);return{...await this.applyEnvironmentVariables(Y,W,f,j),warnings:[`No configuration file found for "${Y}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,X,J,U,W,f){let B=W?n1($,X,U):X,j=this.getLocalDirectories(A,Y);for(let z of j){if(U)H$.info(`Searching for configuration in: ${z}`);let E=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(E,B,{arrayStrategy:J,verbose:U,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(U)H$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,X,J){if(!$)return null;let U=J?n1($,A,X):A,W=[i0(cw(),".config",$),i0(cw(),".config"),cw()];for(let f of W){if(X)H$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:X});if(j){if(X)H$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,Y,X,J,U){let W=U?n1($,Y,J):Y;try{let f=i0(A,"package.json");if(!r8(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)H$.success(`Configuration loaded from package.json: ${z}`);return{config:FJ(W,j,X),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(J)H$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:n1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let X=[];if(A){let J=A($);if(J)X.push(...J)}if(w){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 Uw.configValidation(Y||"unknown",X,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return aw.get(A)||null}cacheResult($,w,A,Y){let X=this.generateCacheKey($,Y);aw.set(X,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,i0($,"config"),i0($,".config"),w?i0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let X=[];return X.push(...this.getLocalSearchPaths($,w,A,Y)),X.push(...this.getHomeSearchPaths($,w)),X.push(i0(A,"package.json")),X}getLocalSearchPaths($,w,A,Y){let X=this.getLocalDirectories(A,Y),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let A=[i0(cw(),".config",$),i0(cw(),".config"),cw()],Y=[];for(let X of A)Y.push(...this.fileLoader.generateConfigPaths($,X,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function oW($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function l5($){return x$.loadConfig({...$,__strictErrorHandling:!0})}async function yB($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await x$.loadConfig($);else Y=await x$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let X=Y instanceof Error?Y.name:"UnknownError",J=Y instanceof Error?Y.message:String(Y);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&$.verbose)H$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await x$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function p5($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await x$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&oW(A)))return(await x$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await x$.loadConfig({...$,cwd:$.cwd||Cw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&oW(w)))return(await x$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function t5($,w,A="replace"){let Y=new RY;try{let X=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function n1($,w,A=!1){let Y=new NY,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of E)if(F=Cw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=J(j,z)}return f}return J(w)}function r5($){let w=i0(Cw.cwd(),$.configDir),A=i0(Cw.cwd(),$.generatedDir),Y=i0(A,"config-types.ts");if(!r8(QW(Y)))bE(QW(Y),{recursive:!0,mode:511});let X=r8(w)?uE(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${CG}
|
|
30
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
31
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
32
|
+
`;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
33
|
+
`;return Y}}function eK($,w){let Y=K9("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function j9($,w,Y={}){return z9($,w,Y,new WeakMap)}function z9($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return G9($,w,X,A);if(!A$(w)||!A$($))return w;return A7($,w,Y,A)}function G9($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return $7($,w);case"smart":return w7($,w,A);default:return w}return w}function $7($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>QJ(X,A)))Y.push(A);return Y}function w7($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(A$(w[0])&&A$($[0]))return Y7($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function Y7($,w,Y){let A=[...w];for(let X of $){if(!A$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>A$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function A7($,w,Y,A){let X=w;if(A$(X)&&A.has(X))return A.get(X);let J={...$};if(A$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(A$(B)&&A$(W))J[U]=z9(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=G9(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function iJ($,w,Y="replace"){return j9($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function QJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!QJ($[Y],w[Y]))return!1;return!0}if(A$($)&&A$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!QJ($[X],w[X]))return!1}return!0}return!1}function A$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class xA{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:B=!1}=Y;if(X){let j=A1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!UA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,F="default"in z,K=Object.keys(z).length>0;if(!F&&!K)throw new UY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new UY($,Error("Configuration must export a valid object"),"unknown");let q={config:iJ(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)A1.setWithFileCheck("file",q,$,J);return q}catch(j){throw j instanceof Error?jw.configLoad($,j):jw.configLoad($,Error(String(j)))}};if(U)return BY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(FJ(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return W9(async()=>{return UA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!UA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=FJ($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=FJ($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!UA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class mJ{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],F={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,F);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],F);else return this.validateWithJSONSchema($,w,F)}catch(K){return z.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await BY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!TK(w))throw new WY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new WY(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:T9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class gJ{fileLoader=new xA;envProcessor=new DA;validator=new mJ;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),F=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(F||z))throw W;if(G&&(!j||!F))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)F$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw F$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||_w.cwd(),F=[],K=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(K)return F.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(K,F,W,A,z);let f=await this.loadHomeConfiguration(A,X,B,j,z,W);if(f)return F.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(f,F,W,A,z);let E=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(E)return F.push(v0(G,"package.json")),this.finalizeResult(E,F,W,A,z);if(F.push(...this.getAllSearchPaths(A,X,G,U)),w)throw jw.configNotFound(A,F,X);return{...await this.applyEnvironmentVariables(A,B,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,B,W){let j=B?XY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)F$.info(`Searching for configuration in: ${G}`);let F=this.fileLoader.generateConfigPaths($,G,w),K=await this.fileLoader.tryLoadFromPaths(F,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(K){if(U)F$.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?XY($,Y,X):Y,B=[v0(pw(),".config",$),v0(pw(),".config"),pw()];for(let W of B){if(X)F$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)F$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?XY($,A,J):A;try{let W=v0(Y,"package.json");if(!yJ(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)F$.success(`Configuration loaded from package.json: ${G}`);return{config:iJ(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)F$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:XY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 jw.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return A1.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);A1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,v0($,"config"),v0($,".config"),w?v0($,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(v0(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[v0(pw(),".config",$),v0(pw(),".config"),pw()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function ij($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||A}async function X7($){return b$.loadConfig({...$,__strictErrorHandling:!0})}async function F9($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await b$.loadConfig($);else A=await b$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)F$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await b$.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}async function J7($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await b$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&ij(Y)))return(await b$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await b$.loadConfig({...$,cwd:$.cwd||_w.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&ij(w)))return(await b$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function U7($,w,Y="replace"){let A=new xA;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function XY($,w,Y=!1){let A=new DA,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],F=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((E)=>E.toUpperCase()).join("")}`,`${X}_${G.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,f;for(let E of F)if(K=_w.env[E],K!==void 0){f=E;break}if(K!==void 0&&f)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(K.toLowerCase());else if(typeof z==="number"){let E=Number(K);if(!Number.isNaN(E))W[j]=E}else if(Array.isArray(z))try{W[j]=JSON.parse(K)}catch{W[j]=K.split(",").map((E)=>E.trim())}else W[j]=K;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function W7($){let w=v0(_w.cwd(),$.configDir),Y=v0(_w.cwd(),$.generatedDir),A=v0(Y,"config-types.ts");if(!yJ(Tj(A)))tF(Tj(A),{recursive:!0,mode:511});let X=yJ(w)?aF(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${P7}
|
|
34
34
|
export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
|
|
35
|
-
`;
|
|
36
|
-
${X.map((
|
|
35
|
+
`;sF(A,J,{mode:438})}function B7($){let w=null,Y=null,A=()=>{if(!Y)Y=F9($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)F$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in $?$.defaultConfig:{};return w=X,A(),new Proxy({},{get(J,U){if(w)return w[U];let B=X[U];return A(),B},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,B){if(!w)w={...X};return w[U]=B,!0}})}function j7($){let w=kj(MK.cwd(),$?.configDir||"./config");function Y(){if(!HK(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=RK(w).filter((W)=>X.has(KJ(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:j}of U){let z=KJ(j).toLowerCase(),G=B.get(W);if(!G){B.set(W,j);continue}let F=KJ(G).toLowerCase();if(J.indexOf(z)<J.indexOf(F))B.set(W,j)}return Array.from(B.entries()).map(([W,j])=>({base:W,file:j})).sort((W,j)=>W.base.localeCompare(j.base))}function A(){let X=Y(),J=X.map((j)=>j.base),U=J.length?J.map((j)=>`'${j}'`).join(" | "):"string",B=X.length?`{
|
|
36
|
+
${X.map((j)=>{let z=kj(w,j.file).replace(/\\/g,"/");return` '${j.base}': typeof import('${z}').default`}).join(`,
|
|
37
37
|
`)}
|
|
38
38
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
39
|
-
export type ConfigByName = ${
|
|
39
|
+
export type ConfigByName = ${B}
|
|
40
40
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
41
41
|
export type ConfigOf = Config
|
|
42
|
-
`}return{name:"bunfig-plugin",setup(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:Y(),loader:"ts"}})}}}function VG($,w={}){let A=fY.cwd();while(A.includes("storage"))A=nW(A,"..");let Y=nW(A,$||"");if(w?.relative)return z5(fY.cwd(),Y);return Y}function T0(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function OG(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z$<"u"){let $=Z$.type;if($==="renderer"||$==="worker")return!1;return!!(Z$.versions&&(Z$.versions.node||Z$.versions.bun))}return!1}class DB{async format($){let w=await OG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:rw.pid,hostname:w(),environment:rw.env.NODE_ENV||"development",platform:rw.platform,version:rw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:rw.env.NODE_ENV||rw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...GY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new DB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...p8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...p8};return{...p8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:GY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await T5(this.config.logDirectory,rW.F_OK|rW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await H5(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:S$.from($);try{if(!nA(this.currentLogFile))await m8(this.currentLogFile,"",{mode:420});if(X=tW(this.currentLogFile,"a",420),K5(X,f,{flag:"a"}),pW(X),X!==void 0)v8(X),X=void 0;if((await pw(this.currentLogFile)).size===0){if(await m8(this.currentLogFile,f,{flag:"w",mode:420}),(await pw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let E=W*2**J;await new Promise((F)=>setTimeout(F,E)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{v8(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 tw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return tw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return tw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return c8(16).toString("hex")}generateKey(){return c8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=c8(16),Y=F5("aes-256-gcm",w,A),X=S$.isBuffer($)?$:S$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=S$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=sW(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(S$.from(S$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let $=await pw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await lA(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await pw(A).catch(()=>null))try{if(await aW(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await pA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await m8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await pw(A).catch(()=>null))await aW(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await lA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await pA(tw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=lW($),Y=G5(w),X=sW();await q5(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),nA(this.currentLogFile))try{let $=tW(this.currentLogFile,"r+");pW($),v8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await lA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await pA(tw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=D.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${i.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=i.underline(i.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(A,Y)=>i.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>i.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>i.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>i.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>i.strikethrough(Y)),w}supportsHyperlinks(){if(T0())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=D.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(N5(w)||w.startsWith("./")||w.startsWith("../"))w=R5(w);else return null;return nA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":DG[$],E=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:i.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:i.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
43
|
-
`);for(let
|
|
44
|
-
`;if(
|
|
45
|
-
`;if(
|
|
46
|
-
`);if(this[
|
|
47
|
-
`,
|
|
48
|
-
`),
|
|
49
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
51
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
42
|
+
`}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 u7($,w={}){let Y=VA.cwd();while(Y.includes("storage"))Y=Dj(Y,"..");let A=Dj(Y,$||"");if(w?.relative)return VK(VA.cwd(),A);return A}function E0(){if(P$.env.NODE_ENV==="test"||P$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function v7(){if(P$.env.NODE_ENV==="test"||P$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof P$<"u"){let $=P$.type;if($==="renderer"||$==="worker")return!1;return!!(P$.versions&&(P$.versions.node||P$.versions.bun))}return!1}class I9{async format($){let w=await v7(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Y1.pid,hostname:w(),environment:Y1.env.NODE_ENV||"development",platform:Y1.platform,version:Y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Y1.env.NODE_ENV||Y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class PA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...SA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new I9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...MJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...MJ};return{...MJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:SA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await OK(this.config.logDirectory,uj.F_OK|uj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await _K(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:k$.from($);try{if(!WA(this.currentLogFile))await fJ(this.currentLogFile,"",{mode:420});if(X=bj(this.currentLogFile,"a",420),LK(X,W,{flag:"a"}),Pj(X),X!==void 0)EJ(X),X=void 0;if((await $1(this.currentLogFile)).size===0){if(await fJ(this.currentLogFile,W,{flag:"w",mode:420}),(await $1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let F=B*2**J;await new Promise((K)=>setTimeout(K,F)),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{EJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 $=new Date().toISOString().split("T")[0];return w1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.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 w=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(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return NJ(16).toString("hex")}generateKey(){return NJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=NJ(16),A=yK("aes-256-gcm",w,Y),X=k$.isBuffer($)?$:k$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=k$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=vj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(k$.from(k$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let $=await $1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await BA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await $1(Y).catch(()=>null))try{if(await cj(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await jA(B)}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 fJ(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 $1(Y).catch(()=>null))await cj(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await BA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await jA(w1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=xj($),A=QK(w),X=vj();await ZK(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!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(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),WA(this.currentLogFile))try{let $=bj(this.currentLogFile,"r+");Pj($),EJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await BA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await jA(w1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push(w);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let W=D.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${i.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,F=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(F)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=i.underline(i.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>i.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>i.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>i.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>i.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>i.strikethrough(A)),w}supportsHyperlinks(){if(E0())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=D.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(SK(w)||w.startsWith("./")||w.startsWith("../"))w=hK(w);else return null;return WA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":l7[$],F=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",K;switch($){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:i.gray(W),level:$}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:i.green(W),level:$}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.error(K),B){let f=B.split(`
|
|
43
|
+
`);for(let E of f)if(E.trim()&&!E.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:i.gray(` ${E}`),level:$,showTimestamp:!1}))}break}}else if(!E0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
|
|
44
|
+
`;if(B)z+=`${B}
|
|
45
|
+
`;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress($,w=""){let Y={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!E0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!E0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!E0()&&D.stdout.isTTY)D.stdout.write(`
|
|
46
|
+
`);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!E0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":i.blue("◐"),tag:Y,message:`${i.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
|
|
47
|
+
`,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":i.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!E0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new PA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(E0())throw Error("createReadStream is not supported in browser environments");if(!WA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return xj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=k$.isBuffer($)?$:k$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=CK("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=k$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
|
|
48
|
+
`),W=Math.max(...B.map((F)=>F.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((F)=>{return this.formatConsoleMessage({timestamp:Y,message:i.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(j),showTimestamp:!1})),G.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(z),showTimestamp:!1}))}else if(!E0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
49
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(E0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${i.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();D.stdin.removeListener("data",Y);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=$.replace(W,(z,G)=>{if(G==="%")return"%";if(j>=w.length)return z;let F=w[j++];switch(G){case"s":return String(F);case"d":case"i":return Number(F).toString();case"j":case"o":return JSON.stringify(F,null,2);default:return z}}),j<w.length)Y+=` ${w.slice(j).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?i.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${i.blue("◐")} `;console.error(`${j}${W} ${i.cyan(A)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
50
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=i.green("━".repeat(A)),U=i.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?i.green("✓"):i.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${i.gray(this.formatTag(this.name))}`:"",F=`\r${z}${G} ${B} ${W}${j}`,K=D.stdout.columns||80,f=" ".repeat(Math.max(0,K-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${f}`,D.stdout.write($.lastRenderedLine),w)D.stdout.write(`
|
|
51
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||E0()||!D.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(E0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await BA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=w1(this.config.logDirectory,A);if($.before)try{if((await $1(J)).mtime>=$.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(w){console.error("Error during log clearing process:",w)}}}async function n7($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class lJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return PJ.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=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=GA.env[W]||(j?GA.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=GA.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof dJ)throw G;throw X1.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw X1.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(GA.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
|
|
52
52
|
|
|
53
|
-
`;for(let
|
|
54
|
-
`,
|
|
55
|
-
`,
|
|
56
|
-
`,
|
|
53
|
+
`;for(let A of $)Y+=`${A.key}
|
|
54
|
+
`,Y+=` Type: ${A.type}
|
|
55
|
+
`,Y+=` Description: ${A.description}
|
|
56
|
+
`,Y+=` Example: ${A.example}
|
|
57
57
|
|
|
58
|
-
`;return
|
|
58
|
+
`;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
|
|
59
59
|
|
|
60
|
-
`;
|
|
61
|
-
`,
|
|
62
|
-
`;for(let
|
|
63
|
-
`;return A}}function xG($,w,A={}){return vB($,w,A,new WeakMap)}function vB($,w,A,Y){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=A;if(w===null||w===void 0)return J?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return mB($,w,X,Y);if(!f$(w)||!f$($))return w;return iG($,w,A,Y)}function mB($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return PG($,w);case"smart":return bG($,w,Y);default:return w}return w}function PG($,w){let A=[...w];for(let Y of $)if(!A.some((X)=>UJ(X,Y)))A.push(Y);return A}function bG($,w,A){if(w.length===0)return $;if($.length===0)return w;if(f$(w[0])&&f$($[0]))return uG($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}function uG($,w,A){let Y=[...w];for(let X of $){if(!f$(X)){Y.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(Y.find((B)=>f$(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)Y.push(X)}return Y}function iG($,w,A,Y){let X=w;if(f$(X)&&Y.has(X))return Y.get(X);let J={...$};if(f$(X))Y.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],f=J[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(f$(W)&&f$(f))J[U]=vB(f,W,A,Y);else if(Array.isArray(W)||Array.isArray(f))J[U]=mB(f,W,A.arrayMergeMode||"smart",Y);else J[U]=W}return J}function dB($,w,A="replace"){return xG($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function UJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!UJ($[A],w[A]))return!1;return!0}if(f$($)&&f$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!UJ($[X],w[X]))return!1}return!0}return!1}function f$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class gB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=A;if(X){let B=YY.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!aA($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,E="default"in j,F=Object.keys(j).length>0;if(!E&&!F)throw new KY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new KY($,Error("Configuration must export a valid object"),"unknown");let H={config:dB(w,z,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)YY.setWithFileCheck("file",H,$,J);return H}catch(B){throw B instanceof Error?sw.configLoad($,B):sw.configLoad($,Error(String(B)))}};if(U)return fJ.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let X=await this.loadFromPath(Y,w,A);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,X)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),X=[];for(let J of Y)for(let U of this.extensions)X.push(t8(w,`${J}${U}`));return X}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of Y){if(!J)continue;if(A.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)A.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return A.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return ZG(async()=>{return aA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!aA($))return Y;if(w||A){let X=this.generateNamePatterns(w||"",A);for(let J of X)for(let U of this.extensions){let W=t8($,`${J}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let W=t8($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!aA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let X=await this.loadFromPath(Y,{},w);if(X)A.set(Y,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${Y}:`,X)}})),A}}class nB{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:f=!1}=A,B=async()=>{let j=[],z=[],E={stopOnFirstError:Y,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,E);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],E);else return this.validateWithJSONSchema($,w,E)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await fJ.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!cG(w))throw new TY(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),X=Y.default||Y;if(Array.isArray(X))return this.validateWithRules($,X,A);else return this.validateWithJSONSchema($,X,A)}catch(Y){throw new TY(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],X=[];return this.validateObjectAgainstSchema($,w,"",Y,X,A),{isValid:Y.length===0,errors:Y,warnings:X}}validateObjectAgainstSchema($,w,A,Y,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,X,J),J.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],f,B,Y,X,J),J.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(U))if(!W.has(f))X.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),W=this.validateWithRule(U,J,J.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:X}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)Y.push({path:A,message:w.message||X,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let X of A)if(Y&&typeof Y==="object"&&X in Y)Y=Y[X];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,X,J,U]=Y;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:vG},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function mG($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class lB{fileLoader=new gB;envProcessor=new TJ;validator=new nB;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:X,validate:J,...U}=$;try{if(A?.enabled){let f=this.checkCache(U.name||"",U);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(f){let B=U.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),E=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(E||j))throw f;if(z&&(!B||!E))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(f);if(Y.slowThreshold&&f.duration>Y.slowThreshold)_$.warn(`Slow configuration loading detected: ${f.duration}ms for ${U.name}`);W.metrics=f}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let f=Date.now()-w;throw _$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=J||HY.cwd(),E=[],F=await this.loadLocalConfiguration(Y,X,z,U,W,B,j,f,A);if(F)return E.push(...this.getLocalSearchPaths(Y,X,z,U)),this.finalizeResult(F,E,f,Y,j);let T=await this.loadHomeConfiguration(Y,X,W,B,j,f);if(T)return E.push(...this.getHomeSearchPaths(Y,X)),this.finalizeResult(T,E,f,Y,j);let K=await this.loadPackageJsonConfiguration(Y,X,z,W,B,j,f);if(K)return E.push(J$(z,"package.json")),this.finalizeResult(K,E,f,Y,j);if(E.push(...this.getAllSearchPaths(Y,X,z,U)),w)throw sw.configNotFound(Y,E,X);return{...await this.applyEnvironmentVariables(Y,W,f,j),warnings:[`No configuration file found for "${Y}"${mG(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,X,J,U,W,f){let B=W?sA($,X,U):X,j=this.getLocalDirectories(A,Y);for(let z of j){if(U)_$.info(`Searching for configuration in: ${z}`);let E=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(E,B,{arrayStrategy:J,verbose:U,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(U)_$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,X,J){if(!$)return null;let U=J?sA($,A,X):A,W=[J$(iw(),".config",$),J$(iw(),".config"),iw()];for(let f of W){if(X)_$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:X});if(j){if(X)_$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,Y,X,J,U){let W=U?sA($,Y,J):Y;try{let f=J$(A,"package.json");if(!xE(f))return null;let B={};try{B=JSON.parse(PE(f,"utf8"))}catch(E){if(J)_$.warn("Failed to parse package.json:",[E instanceof Error?E:Error(String(E))]);return null}let j=B[$],z=$;if(!j&&w){let E=Array.isArray(w)?w:[w];for(let F of E){if(!F)continue;if(B[F]){j=B[F],z=F;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)_$.success(`Configuration loaded from package.json: ${z}`);return{config:dB(W,j,X),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(J)_$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:sA($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let X=[];if(A){let J=A($);if(J)X.push(...J)}if(w){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 sw.configValidation(Y||"unknown",X,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return YY.get(A)||null}cacheResult($,w,A,Y){let X=this.generateCacheKey($,Y);YY.set(X,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,J$($,"config"),J$($,".config"),w?J$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let X=[];return X.push(...this.getLocalSearchPaths($,w,A,Y)),X.push(...this.getHomeSearchPaths($,w)),X.push(J$(A,"package.json")),X}getLocalSearchPaths($,w,A,Y){let X=this.getLocalDirectories(A,Y),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let A=[J$(iw(),".config",$),J$(iw(),".config"),iw()],Y=[];for(let X of A)Y.push(...this.fileLoader.generateConfigPaths($,X,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function sA($,w,A=!1){let Y=new TJ,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of E)if(F=HY.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=J(j,z)}return f}return J(w)}var YY,fJ,M5,I5=($)=>$,C5=($,w)=>{for(var A in w)M5($,A,{get:w[A],enumerable:!0,configurable:!0,set:y5.bind(w,A)})},h5=($,w)=>()=>($&&(w=$($=0)),w),KB,CB,aw,r1,hB,o5,e5,eW,eA,o8,Q0,t,$G,$B,wG,wB,AG,YG,d8,XG,AB,YB,g8,JG,UG,fG,WG,$Y,VB,BG,S0,jG,zG,XB,wY,e8,K0,P,FG,JB,EG,UB,GG,KG,n8,TG,fB,WB,HG,l8,NG,RG,qG,MG,IG,AY,LB,yG,CG="0.15.6",e0,FY,p1,$J,wJ,EY,AJ,YJ,t1,XJ,JJ,Uw,OB,QB,H$,x$,SB,_B,hG,LG,kB,GY,pM,C0,i,tM,QG,rM,SG,aM,sM,BB,oM,_G,kG,eM,jB,$I,wI,AI,YI,XI,p8,DG,JI,N$,ZB,KY,xB,PB,KJ,bB,uB,TY,iB,cB,sw,vG,_$,jI,zI,FI;var HJ=F0(()=>{YY=new zB,fJ=new FB,M5=Object.defineProperty;KB={};C5(KB,{withErrorRecovery:()=>NB,tryLoadConfig:()=>t5,loadConfigWithResult:()=>l5,loadConfig:()=>yB,isRetryableError:()=>c5,isConfigNotFoundError:()=>i5,isBunfigError:()=>RB,globalPerformanceMonitor:()=>r1,globalCache:()=>aw,getEnvOrDefault:()=>v5,generateConfigTypes:()=>r5,defaultGeneratedDir:()=>_B,defaultConfigDir:()=>SB,deepMergeWithArrayStrategy:()=>FJ,deepMerge:()=>qB,createLibraryConfig:()=>a5,config:()=>p5,bunfigPlugin:()=>s5,applyEnvVarsToConfig:()=>n1,TypeGenerationError:()=>YJ,SchemaValidationError:()=>t1,PluginError:()=>JJ,PerformanceMonitor:()=>BJ,FileSystemError:()=>AJ,ErrorFactory:()=>Uw,EnvVarError:()=>EY,EnvProcessor:()=>NY,ConfigValidator:()=>EJ,ConfigValidationError:()=>$J,ConfigNotFoundError:()=>FY,ConfigMergeError:()=>wJ,ConfigLoader:()=>GJ,ConfigLoadError:()=>p1,ConfigFileLoader:()=>RY,ConfigCache:()=>WJ,CacheUtils:()=>hB,BunfigError:()=>e0,BrowserConfigError:()=>XJ,ArrayMergeStrategies:()=>OB});hG=h5(async()=>{CB=import.meta.require,aw=new WJ,r1=new BJ,hB={createKey:V5,isEquivalent:L5,estimateMemoryUsage:O5},o5=UY(a8.cwd(),"config"),e5=UY(a8.cwd(),"src/generated"),eW=JY.env.CLARITY_LOG_DIR||mE(_5(),"logs"),eA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:eW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},o8=await k5(),Q0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},t=Q0,$G=Q0.red,$B=Q0.green,wG=Q0.yellow,wB=Q0.blue,AG=Q0.magenta,YG=Q0.cyan,d8=Q0.white,XG=Q0.gray,AB=Q0.bgRed,YB=Q0.bgYellow,g8=Q0.bold,JG=Q0.dim,UG=Q0.italic,fG=Q0.underline,WG=Q0.reset,$Y={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},VB={debug:"\uD83D\uDD0D",info:wB("ℹ"),success:$B("✓"),warning:YB(d8(g8(" WARN "))),error:AB(d8(g8(" ERROR ")))},BG=new BY("stacks"),S0=new BY("bunfig",{showTags:!0}),jG=u0(l1.cwd(),"config"),zG=u0(l1.cwd(),"src/generated"),XB=XY.env.CLARITY_LOG_DIR||cE(P5(),"logs"),wY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:XB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},e8=await b5(),K0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P=K0,FG=K0.red,JB=K0.green,EG=K0.yellow,UB=K0.blue,GG=K0.magenta,KG=K0.cyan,n8=K0.white,TG=K0.gray,fB=K0.bgRed,WB=K0.bgYellow,HG=K0.bgGray,l8=K0.bold,NG=K0.dim,RG=K0.italic,qG=K0.underline,MG=K0.strikethrough,IG=K0.reset,AY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},LB={debug:"\uD83D\uDD0D",info:UB("ℹ"),success:JB("✓"),warning:WB(n8(l8(" WARN "))),error:fB(n8(l8(" ERROR ")))},yG=new zY("stacks"),e0=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},FY=class extends e0{code="CONFIG_NOT_FOUND";constructor(w,A,Y){let X=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},p1=class extends e0{code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},$J=class extends e0{code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},wJ=class extends e0{code="CONFIG_MERGE_ERROR";constructor(w,A,Y,X){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},EY=class extends e0{code="ENV_VAR_ERROR";constructor(w,A,Y,X){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:X})}},AJ=class extends e0{code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},YJ=class extends e0{code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},t1=class extends e0{code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},XJ=class extends e0{code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,X){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:X})}},JJ=class extends e0{code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Uw={configNotFound($,w,A){return new FY($,w,A)},configLoad($,w,A){return new p1($,w,A)},configValidation($,w,A){return new $J($,w,A)},configMerge($,w,A,Y){return new wJ($,w,A,Y)},envVar($,w,A,Y){return new EY($,w,A,Y)},fileSystem($,w,A){return new AJ($,w,A)},typeGeneration($,w,A){return new YJ($,w,A)},schemaValidation($,w,A){return new t1($,w,A)},browserConfig($,w,A,Y){return new XJ($,w,A,Y)},plugin($,w,A){return new JJ($,w,A)}},OB={replace:"replace",concat:"concat",smart:"smart"},QB=/^https?:\/\//,H$=new zY("bunfig",{showTags:!0}),x$=new GJ,SB=i0(Cw.cwd(),"config"),_B=i0(Cw.cwd(),"src/generated")});LG=fY.env.CLARITY_LOG_DIR||j5(VG(),"logs"),kB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:LG,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},GY={...kB},pM=(async()=>{try{let{loadConfig:$}=await hG().then(()=>KB),w=await $({name:"clarity",alias:"logging",defaultConfig:kB,cwd:fY.cwd()});if(w)Object.assign(GY,w)}catch{}return GY})();C0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},i=C0,tM=C0.red,QG=C0.green,rM=C0.yellow,SG=C0.blue,aM=C0.magenta,sM=C0.cyan,BB=C0.white,oM=C0.gray,_G=C0.bgRed,kG=C0.bgYellow,eM=C0.bgGray,jB=C0.bold,$I=C0.dim,wI=C0.italic,AI=C0.underline,YI=C0.strikethrough,XI=C0.reset,p8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},DG={debug:"\uD83D\uDD0D",info:SG("ℹ"),success:QG("✓"),warning:kG(BB(jB(" WARN "))),error:_G(BB(jB(" ERROR ")))};JI=new qY("stacks");N$=class N$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};ZB=class ZB extends N${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],X="";if(Y.length===1)X=` or alias "${Y[0]}"`;else if(Y.length>1)X=` or aliases ${Y.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};KY=class KY extends N${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}};xB=class xB extends N${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};PB=class PB extends N${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};KJ=class KJ extends N${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};bB=class bB extends N${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}};uB=class uB extends N${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}};TY=class TY extends N${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};iB=class iB extends N${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};cB=class cB extends N${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}};sw={configNotFound($,w,A){return new ZB($,w,A)},configLoad($,w,A){return new KY($,w,A)},configValidation($,w,A){return new xB($,w,A)},configMerge($,w,A,Y){return new PB($,w,A,Y)},envVar($,w,A,Y){return new KJ($,w,A,Y)},fileSystem($,w,A){return new bB($,w,A)},typeGeneration($,w,A){return new uB($,w,A)},schemaValidation($,w,A){return new TY($,w,A)},browserConfig($,w,A,Y){return new iB($,w,A,Y)},plugin($,w,A){return new cB($,w,A)}};vG=/^https?:\/\//;_$=new qY("bunfig",{showTags:!0});jI=new lB;zI=J$(HY.cwd(),"config"),FI=J$(HY.cwd(),"src/generated")});var q;var fw=F0(()=>{q={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as nG}from"node:module";import{Resolver as qJ}from"node:dns/promises";import{createHash as pG,sign as tG}from"node:crypto";import{createHash as rG}from"node:crypto";import{sign as aG}from"node:crypto";import{generateKeyPairSync as ej,X509Certificate as J6}from"node:crypto";import MJ from"node:os";import IJ from"node:path";import{existsSync as tB,statSync as rB}from"fs";import{existsSync as f6,mkdirSync as SI,readdirSync as _I,readFileSync as W6,writeFileSync as kI}from"fs";import{homedir as ew}from"os";import{dirname as xI,resolve as B$}from"path";import UX from"process";import{existsSync as aB,statSync as sB}from"fs";import{existsSync as lJ,mkdirSync as B6,readdirSync as j6,writeFileSync as z6}from"fs";import{homedir as $1}from"os";import{dirname as oB,resolve as v0}from"path";import Vw from"process";import{join as F6,relative as E6,resolve as eB}from"path";import dY from"process";import{existsSync as $9,mkdirSync as nI,readdirSync as lI,writeFileSync as pI}from"fs";import{homedir as yJ}from"os";import{dirname as aI,resolve as c0}from"path";import $A from"process";import{join as G6,relative as K6,resolve as $j}from"path";import gY from"process";import{existsSync as w9,mkdirSync as w4,readdirSync as A4,writeFileSync as Y4}from"fs";import{dirname as J4,resolve as nY}from"path";import pJ from"process";import{Buffer as Ww}from"buffer";import{createCipheriv as T6,createDecipheriv as H6,randomBytes as CJ}from"crypto";import{closeSync as hJ,createReadStream as wj,createWriteStream as N6,existsSync as VJ,fsyncSync as Aj,openSync as Yj,writeFileSync as R6}from"fs";import{access as q6,constants as Xj,mkdir as M6,readdir as MY,rename as Jj,stat as w1,unlink as IY,writeFile as LJ}from"fs/promises";import{join as A1}from"path";import _0 from"process";import{pipeline as I6}from"stream/promises";import{createGzip as Uj}from"zlib";import Y1 from"process";import i$ from"process";import{Buffer as P$}from"buffer";import{createCipheriv as y6,createDecipheriv as C6,randomBytes as OJ}from"crypto";import{closeSync as QJ,createReadStream as fj,createWriteStream as h6,existsSync as yY,fsyncSync as Wj,openSync as Bj,writeFileSync as V6}from"fs";import{access as L6,constants as jj,mkdir as O6,readdir as CY,rename as zj,stat as X1,unlink as hY,writeFile as SJ}from"fs/promises";import{isAbsolute as Q6,join as J1,resolve as S6}from"path";import g from"process";import{pipeline as _6}from"stream/promises";import{createGzip as Fj}from"zlib";import U1 from"process";import c$ from"process";import VY from"process";import{existsSync as LY}from"fs";import{resolve as _J}from"path";import{existsSync as k6}from"fs";import{existsSync as D6,readdirSync as Z6}from"fs";import{extname as kJ,resolve as Ej}from"path";import x6 from"process";import{join as P6,relative as b6,resolve as Gj}from"path";import lY from"process";import{Buffer as b$}from"buffer";import{createCipheriv as u6,createDecipheriv as i6,randomBytes as DJ}from"crypto";import{closeSync as ZJ,createReadStream as Kj,createWriteStream as c6,existsSync as OY,fsyncSync as Tj,openSync as Hj,writeFileSync as v6}from"fs";import{access as m6,constants as Nj,mkdir as d6,readdir as QY,rename as Rj,stat as f1,unlink as SY,writeFile as xJ}from"fs/promises";import{isAbsolute as g6,join as W1,resolve as n6}from"path";import n from"process";import{pipeline as l6}from"stream/promises";import{createGzip as qj}from"zlib";import B1 from"process";import v$ from"process";import _Y from"process";import{existsSync as kY}from"fs";import{resolve as PJ}from"path";import{existsSync as p6}from"fs";import{exec as KT}from"node:child_process";import Zj from"node:fs";import TT from"node:os";import R$ from"node:path";import b9 from"node:process";import{promisify as HT}from"node:util";import E1 from"node:crypto";import m$ from"node:fs";import UU from"node:path";import{execSync as ij}from"node:child_process";import XX from"node:os";async function cj($,w,A={}){let Y=A.timeoutMs??120000,X=A.intervalMs??3000,J=$.split(".").slice(-2).join("."),U;try{let B=new qJ,j=await B.resolveNs(J),z=(await Promise.all(j.map((E)=>B.resolve4(E).catch(()=>[])))).flat();if(z.length>0)U=new qJ,U.setServers(z)}catch{}let W=Date.now()+Y,f=U??new qJ;for(;;){try{if((await f.resolveTxt($)).some((B)=>B.join("")===w))return!0}catch{}if(Date.now()>=W)return!1;await new Promise((B)=>setTimeout(B,X))}}class e1{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(e1.PATH_PREFIX);if(w===-1)return;let A=$.slice(w+e1.PATH_PREFIX.length);return this.get(A)}}function xY($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function mJ($){return Buffer.from($,"base64url")}function vj($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function mj($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return pG("sha256").update(w).digest("base64url")}function dj($){let{protectedHeader:w,payload:A,privateKey:Y}=$,X=xY(JSON.stringify(w)),J=A===""?"":xY(JSON.stringify(A)),U=`${X}.${J}`,W=tG("sha256",Buffer.from(U),{key:Y,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:xY(W)}}class mY{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=vj($.accountPublicKey),this.thumbprint=mj(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:A,useJwk:Y}=$,X={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(Y)X.jwk=this.jwk;else X.kid=this.requireKid();let J=dj({protectedHeader:X,payload:A,privateKey:this.accountKey}),U=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)}),W=U.headers.get("replay-nonce");if(W)this.nonce=W;let f=U.headers.get("content-type")??"",B;if(f.includes("application/pem-certificate-chain")||f.startsWith("text/"))B=await U.text();else{let j=await U.text();B=j?JSON.parse(j):{}}if(U.status>=400){let j=B??{};throw new vY(`ACME request to ${w} failed (HTTP ${U.status}): ${j.type??""} ${j.detail??""}`.trim(),j,U.status)}return{status:U.status,headers:U.headers,body:B,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),A={termsOfServiceAgreed:!0};if($.email)A.contact=[`mailto:${$.email}`];let Y=await this.signedPost({url:w.newAccount,payload:A,useJwk:!0});if(!Y.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=Y.location,this.accountKid}async newOrder($){let w=await this.directory(),A={identifiers:$.map((X)=>({type:"dns",value:X}))},Y=await this.signedPost({url:w.newOrder,payload:A});if(!Y.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:Y.body,orderUrl:Y.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return rG("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,X=Date.now()+A;while(Date.now()<X){let J=await this.getAuthorization($);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((W)=>W.status==="invalid");throw new vY(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await pB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,X=Date.now()+A;while(Date.now()<X){let J=await this.getOrder($);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 ${$} became invalid`);await pB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let A=$.challenges.find((Y)=>Y.type===w);if(!A)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return A}}function lj($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],A=w[0];if(!A)return{certPem:`${$.trim()}
|
|
64
|
-
`,chainPem:""};let
|
|
60
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
61
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
62
|
+
`;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
63
|
+
`;return Y}}function p7($,w,Y={}){return S9($,w,Y,new WeakMap)}function S9($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return h9($,w,X,A);if(!X$(w)||!X$($))return w;return s7($,w,Y,A)}function h9($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return r7($,w);case"smart":return t7($,w,A);default:return w}return w}function r7($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>xJ(X,A)))Y.push(A);return Y}function t7($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(X$(w[0])&&X$($[0]))return a7($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function a7($,w,Y){let A=[...w];for(let X of $){if(!X$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>X$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function s7($,w,Y,A){let X=w;if(X$(X)&&A.has(X))return A.get(X);let J={...$};if(X$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(X$(B)&&X$(W))J[U]=S9(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=h9(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function Z9($,w,Y="replace"){return p7($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function xJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!xJ($[Y],w[Y]))return!1;return!0}if(X$($)&&X$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!xJ($[X],w[X]))return!1}return!0}return!1}function X$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class k9{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:B=!1}=Y;if(X){let j=HA.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!FA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,F="default"in z,K=Object.keys(z).length>0;if(!F&&!K)throw new hA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new hA($,Error("Configuration must export a valid object"),"unknown");let q={config:Z9(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)HA.setWithFileCheck("file",q,$,J);return q}catch(j){throw j instanceof Error?X1.configLoad($,j):X1.configLoad($,Error(String(j)))}};if(U)return PJ.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(IJ(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return n7(async()=>{return FA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!FA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=IJ($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=IJ($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!FA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class D9{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],F={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,F);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],F);else return this.validateWithJSONSchema($,w,F)}catch(K){return z.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await PJ.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!o7(w))throw new ZA(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new ZA(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:e7},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function $N($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((Y)=>`"${Y}"`).join(", ")}`}class x9{fileLoader=new k9;envProcessor=new lJ;validator=new D9;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),F=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(F||z))throw W;if(G&&(!j||!F))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)V$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){if(B instanceof Error&&B.name==="ConfigNotFoundError")throw B;let W=Date.now()-w;throw V$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||kA.cwd(),F=[],K=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(K)return F.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(K,F,W,A,z);let f=await this.loadHomeConfiguration(A,X,B,j,z,W);if(f)return F.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(f,F,W,A,z);let E=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(E)return F.push(Y$(G,"package.json")),this.finalizeResult(E,F,W,A,z);if(F.push(...this.getAllSearchPaths(A,X,G,U)),w)throw X1.configNotFound(A,F,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${$N(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?KA($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)V$.info(`Searching for configuration in: ${G}`);let F=this.fileLoader.generateConfigPaths($,G,w),K=await this.fileLoader.tryLoadFromPaths(F,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(K){if(U)V$.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?KA($,Y,X):Y,B=[Y$(nw(),".config",$),Y$(nw(),".config"),nw()];for(let W of B){if(X)V$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)V$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?KA($,A,J):A;try{let W=Y$(Y,"package.json");if(!pF(W))return null;let j={};try{j=JSON.parse(rF(W,"utf8"))}catch(F){if(J)V$.warn("Failed to parse package.json:",[F instanceof Error?F:Error(String(F))]);return null}let z=j[$],G=$;if(!z&&w){let F=Array.isArray(w)?w:[w];for(let K of F){if(!K)continue;if(j[K]){z=j[K],G=K;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)V$.success(`Configuration loaded from package.json: ${G}`);return{config:Z9(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)V$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,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:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 X1.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($,A);HA.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,Y$($,"config"),Y$($,".config"),w?Y$($,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(Y$(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[Y$(nw(),".config",$),Y$(nw(),".config"),nw()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}async function nJ($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await VJ.loadConfig($);else A=await VJ.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)V$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await VJ.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}function KA($,w,Y=!1){let A=new lJ,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],F=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((E)=>E.toUpperCase()).join("")}`,`${X}_${G.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,f;for(let E of F)if(K=kA.env[E],K!==void 0){f=E;break}if(K!==void 0&&f)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(K.toLowerCase());else if(typeof z==="number"){let E=Number(K);if(!Number.isNaN(E))W[j]=E}else if(Array.isArray(z))try{W[j]=JSON.parse(K)}catch{W[j]=K.split(",").map((E)=>E.trim())}else W[j]=K;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}var HA,PJ,kK,DK=($)=>$,PK=($,w)=>{for(var Y in w)kK($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:xK.bind(w,Y)})},bK=($,w)=>()=>($&&(w=$($=0)),w),X9,K9,A1,BY,N9,z7,G7,mj,EA,LJ,L0,t,F7,gj,K7,dj,N7,E7,qJ,f7,lj,nj,TJ,q7,T7,H7,R7,fA,E9,M7,O0,I7,V7,pj,qA,OJ,N0,u,y7,rj,C7,tj,Q7,L7,HJ,O7,aj,sj,_7,RJ,S7,h7,Z7,k7,D7,TA,f9,x7,P7="0.15.6",a0,OA,UY,_J,SJ,_A,hJ,ZJ,WY,kJ,DJ,jw,q9,T9,F$,b$,H9,R9,b7,c7,M9,SA,wV,I0,i,YV,i7,AV,m7,XV,JV,oj,UV,g7,d7,WV,ej,BV,jV,zV,GV,FV,MJ,l7,KV,K$,V9,hA,y9,C9,dJ,Q9,L9,ZA,O9,_9,X1,e7,V$,VJ,TV,HV;var pJ=o(()=>{HA=new $9,PJ=new w9,kK=Object.defineProperty;X9={};PK(X9,{withErrorRecovery:()=>W9,tryLoadConfig:()=>U7,loadConfigWithResult:()=>X7,loadConfig:()=>F9,isRetryableError:()=>oK,isConfigNotFoundError:()=>sK,isBunfigError:()=>B9,globalPerformanceMonitor:()=>BY,globalCache:()=>A1,getEnvOrDefault:()=>eK,generateConfigTypes:()=>W7,defaultGeneratedDir:()=>R9,defaultConfigDir:()=>H9,deepMergeWithArrayStrategy:()=>iJ,deepMerge:()=>j9,createLibraryConfig:()=>B7,config:()=>J7,bunfigPlugin:()=>j7,applyEnvVarsToConfig:()=>XY,TypeGenerationError:()=>ZJ,SchemaValidationError:()=>WY,PluginError:()=>DJ,PerformanceMonitor:()=>uJ,FileSystemError:()=>hJ,ErrorFactory:()=>jw,EnvVarError:()=>_A,EnvProcessor:()=>DA,ConfigValidator:()=>mJ,ConfigValidationError:()=>_J,ConfigNotFoundError:()=>OA,ConfigMergeError:()=>SJ,ConfigLoader:()=>gJ,ConfigLoadError:()=>UY,ConfigFileLoader:()=>xA,ConfigCache:()=>bJ,CacheUtils:()=>N9,BunfigError:()=>a0,BrowserConfigError:()=>kJ,ArrayMergeStrategies:()=>q9});b7=bK(async()=>{K9=import.meta.require,A1=new bJ,BY=new uJ,N9={createKey:uK,isEquivalent:cK,estimateMemoryUsage:vK},z7=IA(CJ.cwd(),"config"),G7=IA(CJ.cwd(),"src/generated"),mj=MA.env.CLARITY_LOG_DIR||$K(gK(),"logs"),EA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:mj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},LJ=await dK(),L0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},t=L0,F7=L0.red,gj=L0.green,K7=L0.yellow,dj=L0.blue,N7=L0.magenta,E7=L0.cyan,qJ=L0.white,f7=L0.gray,lj=L0.bgRed,nj=L0.bgYellow,TJ=L0.bold,q7=L0.dim,T7=L0.italic,H7=L0.underline,R7=L0.reset,fA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},E9={debug:"\uD83D\uDD0D",info:dj("ℹ"),success:gj("✓"),warning:nj(qJ(TJ(" WARN "))),error:lj(qJ(TJ(" ERROR ")))},M7=new CA("stacks"),O0=new CA("bunfig",{showTags:!0}),I7=c0(JY.cwd(),"config"),V7=c0(JY.cwd(),"src/generated"),pj=RA.env.CLARITY_LOG_DIR||oF(rK(),"logs"),qA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:pj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},OJ=await tK(),N0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},u=N0,y7=N0.red,rj=N0.green,C7=N0.yellow,tj=N0.blue,Q7=N0.magenta,L7=N0.cyan,HJ=N0.white,O7=N0.gray,aj=N0.bgRed,sj=N0.bgYellow,_7=N0.bgGray,RJ=N0.bold,S7=N0.dim,h7=N0.italic,Z7=N0.underline,k7=N0.strikethrough,D7=N0.reset,TA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},f9={debug:"\uD83D\uDD0D",info:tj("ℹ"),success:rj("✓"),warning:sj(HJ(RJ(" WARN "))),error:aj(HJ(RJ(" ERROR ")))},x7=new LA("stacks"),a0=class extends Error{timestamp;context;constructor(w,Y={}){super(w);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 w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},OA=class extends a0{code="CONFIG_NOT_FOUND";constructor(w,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},UY=class extends a0{code="CONFIG_LOAD_ERROR";constructor(w,Y,A){super(`Failed to load configuration from "${w}": ${Y.message}`,{configPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},_J=class extends a0{code="CONFIG_VALIDATION_ERROR";constructor(w,Y,A){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},SJ=class extends a0{code="CONFIG_MERGE_ERROR";constructor(w,Y,A,X){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},_A=class extends a0{code="ENV_VAR_ERROR";constructor(w,Y,A,X){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:X})}},hJ=class extends a0{code="FILE_SYSTEM_ERROR";constructor(w,Y,A){super(`File system ${w} failed for "${Y}": ${A.message}`,{operation:w,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},ZJ=class extends a0{code="TYPE_GENERATION_ERROR";constructor(w,Y,A){super(`Failed to generate types from "${w}" to "${Y}": ${A.message}`,{configDir:w,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},WY=class extends a0{code="SCHEMA_VALIDATION_ERROR";constructor(w,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},kJ=class extends a0{code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,X){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:X})}},DJ=class extends a0{code="PLUGIN_ERROR";constructor(w,Y,A){super(`Plugin "${w}" failed during ${Y}: ${A.message}`,{pluginName:w,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},jw={configNotFound($,w,Y){return new OA($,w,Y)},configLoad($,w,Y){return new UY($,w,Y)},configValidation($,w,Y){return new _J($,w,Y)},configMerge($,w,Y,A){return new SJ($,w,Y,A)},envVar($,w,Y,A){return new _A($,w,Y,A)},fileSystem($,w,Y){return new hJ($,w,Y)},typeGeneration($,w,Y){return new ZJ($,w,Y)},schemaValidation($,w,Y){return new WY($,w,Y)},browserConfig($,w,Y,A){return new kJ($,w,Y,A)},plugin($,w,Y){return new DJ($,w,Y)}},q9={replace:"replace",concat:"concat",smart:"smart"},T9=/^https?:\/\//,F$=new LA("bunfig",{showTags:!0}),b$=new gJ,H9=v0(_w.cwd(),"config"),R9=v0(_w.cwd(),"src/generated")});c7=VA.env.CLARITY_LOG_DIR||IK(u7(),"logs"),M9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:c7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},SA={...M9},wV=(async()=>{try{let{loadConfig:$}=await b7().then(()=>X9),w=await $({name:"clarity",alias:"logging",defaultConfig:M9,cwd:VA.cwd()});if(w)Object.assign(SA,w)}catch{}return SA})();I0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},i=I0,YV=I0.red,i7=I0.green,AV=I0.yellow,m7=I0.blue,XV=I0.magenta,JV=I0.cyan,oj=I0.white,UV=I0.gray,g7=I0.bgRed,d7=I0.bgYellow,WV=I0.bgGray,ej=I0.bold,BV=I0.dim,jV=I0.italic,zV=I0.underline,GV=I0.strikethrough,FV=I0.reset,MJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},l7={debug:"\uD83D\uDD0D",info:m7("ℹ"),success:i7("✓"),warning:d7(oj(ej(" WARN "))),error:g7(oj(ej(" ERROR ")))};KV=new PA("stacks");K$=class K$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};V9=class V9 extends K${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 "${$}"${X} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};hA=class hA extends K${code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}};y9=class y9 extends K${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};C9=class C9 extends K${code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};dJ=class dJ extends K${code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}};Q9=class Q9 extends K${code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};L9=class L9 extends K${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};ZA=class ZA extends K${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};O9=class O9 extends K${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};_9=class _9 extends K${code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};X1={configNotFound($,w,Y){return new V9($,w,Y)},configLoad($,w,Y){return new hA($,w,Y)},configValidation($,w,Y){return new y9($,w,Y)},configMerge($,w,Y,A){return new C9($,w,Y,A)},envVar($,w,Y,A){return new dJ($,w,Y,A)},fileSystem($,w,Y){return new Q9($,w,Y)},typeGeneration($,w,Y){return new L9($,w,Y)},schemaValidation($,w,Y){return new ZA($,w,Y)},browserConfig($,w,Y,A){return new O9($,w,Y,A)},plugin($,w,Y){return new _9($,w,Y)}};e7=/^https?:\/\//;V$=new PA("bunfig",{showTags:!0});VJ=new x9;TV=Y$(kA.cwd(),"config"),HV=Y$(kA.cwd(),"src/generated")});function U1($){return $.startsWith("*.")}function zY($,w){if(!U1(w))return!1;let Y=w.slice(1);return $.length>Y.length&&$.endsWith(Y)}function bA($,w){let Y=$.get(w);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of $){if(!U1(J))continue;if(zY(w,J)){let B=J.length-1;if(B>X)X=B,A=U}}return A}var R;var u$=o(()=>{R={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as EN}from"node:module";import{Resolver as eJ}from"node:dns/promises";import{createHash as qN,sign as TN}from"node:crypto";import{createHash as HN}from"node:crypto";import{sign as RN}from"node:crypto";import{generateKeyPairSync as pz,X509Certificate as _N}from"node:crypto";import $U from"node:os";import wU from"node:path";import{existsSync as d9,statSync as l9}from"fs";import{existsSync as hN,mkdirSync as mV,readdirSync as gV,readFileSync as ZN,writeFileSync as dV}from"fs";import{homedir as B1}from"os";import{dirname as pV,resolve as U$}from"path";import yX from"process";import{existsSync as n9,statSync as p9}from"fs";import{existsSync as CU,mkdirSync as kN,readdirSync as DN,writeFileSync as xN}from"fs";import{homedir as j1}from"os";import{dirname as r9,resolve as m0}from"path";import hw from"process";import{join as PN,relative as bN,resolve as t9}from"path";import WX from"process";import{existsSync as rz,mkdirSync as Ay,readdirSync as Xy,writeFileSync as Jy}from"fs";import{homedir as YU}from"os";import{dirname as By,resolve as i0}from"path";import EY from"process";import{join as uN,relative as cN,resolve as a9}from"path";import BX from"process";import{existsSync as tz,mkdirSync as Ky,readdirSync as Ny,writeFileSync as Ey}from"fs";import{dirname as qy,resolve as jX}from"path";import QU from"process";import{Buffer as zw}from"buffer";import{createCipheriv as vN,createDecipheriv as iN,randomBytes as AU}from"crypto";import{closeSync as XU,createReadStream as s9,createWriteStream as mN,existsSync as JU,fsyncSync as o9,openSync as e9,writeFileSync as gN}from"fs";import{access as dN,constants as $z,mkdir as lN,readdir as cA,rename as wz,stat as z1,unlink as vA,writeFile as UU}from"fs/promises";import{join as G1}from"path";import _0 from"process";import{pipeline as nN}from"stream/promises";import{createGzip as Yz}from"zlib";import F1 from"process";import m$ from"process";import{Buffer as c$}from"buffer";import{createCipheriv as pN,createDecipheriv as rN,randomBytes as WU}from"crypto";import{closeSync as BU,createReadStream as Az,createWriteStream as tN,existsSync as iA,fsyncSync as Xz,openSync as Jz,writeFileSync as aN}from"fs";import{access as sN,constants as Uz,mkdir as oN,readdir as mA,rename as Wz,stat as K1,unlink as gA,writeFile as jU}from"fs/promises";import{isAbsolute as eN,join as N1,resolve as $E}from"path";import l from"process";import{pipeline as wE}from"stream/promises";import{createGzip as Bz}from"zlib";import E1 from"process";import g$ from"process";import dA from"process";import{existsSync as lA}from"fs";import{resolve as zU}from"path";import{existsSync as YE}from"fs";import{existsSync as AE,readdirSync as XE}from"fs";import{extname as GU,resolve as jz}from"path";import JE from"process";import{join as UE,relative as WE,resolve as zz}from"path";import zX from"process";import{Buffer as v$}from"buffer";import{createCipheriv as BE,createDecipheriv as jE,randomBytes as FU}from"crypto";import{closeSync as KU,createReadStream as Gz,createWriteStream as zE,existsSync as nA,fsyncSync as Fz,openSync as Kz,writeFileSync as GE}from"fs";import{access as FE,constants as Nz,mkdir as KE,readdir as pA,rename as Ez,stat as f1,unlink as rA,writeFile as NU}from"fs/promises";import{isAbsolute as NE,join as q1,resolve as EE}from"path";import n from"process";import{pipeline as fE}from"stream/promises";import{createGzip as fz}from"zlib";import T1 from"process";import d$ from"process";import tA from"process";import{existsSync as aA}from"fs";import{resolve as EU}from"path";import{existsSync as qE}from"fs";import{exec as cf}from"node:child_process";import bU from"node:fs";import vf from"node:os";import N$ from"node:path";import h2 from"node:process";import{promisify as mf}from"node:util";import I1 from"node:crypto";import l$ from"node:fs";import vU from"node:path";import Gq from"node:crypto";import{execSync as Nq}from"node:child_process";import IX from"node:os";async function Dz($,w,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=$.split(".").slice(-2).join("."),U;try{let j=new eJ,z=await j.resolveNs(J),G=(await Promise.all(z.map((F)=>j.resolve4(F).catch(()=>[])))).flat();if(G.length>0)U=new eJ,U.setServers(G)}catch{}let B=Date.now()+A,W=U??new eJ;for(;;){try{if((await W.resolveTxt($)).some((j)=>j.join("")===w))return!0}catch{}if(Date.now()>=B)return!1;await new Promise((j)=>setTimeout(j,X))}}class NY{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(NY.PATH_PREFIX);if(w===-1)return;let Y=$.slice(w+NY.PATH_PREFIX.length);return this.get(Y)}}function eA($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function MU($){return Buffer.from($,"base64url")}function xz($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function Pz($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return qN("sha256").update(w).digest("base64url")}function bz($){let{protectedHeader:w,payload:Y,privateKey:A}=$,X=eA(JSON.stringify(w)),J=Y===""?"":eA(JSON.stringify(Y)),U=`${X}.${J}`,B=TN("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:eA(B)}}class UX{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=xz($.accountPublicKey),this.thumbprint=Pz(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:Y,useJwk:A}=$,X={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(A)X.jwk=this.jwk;else X.kid=this.requireKid();let J=bz({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)}),B=U.headers.get("replay-nonce");if(B)this.nonce=B;let W=U.headers.get("content-type")??"",j;if(W.includes("application/pem-certificate-chain")||W.startsWith("text/"))j=await U.text();else{let z=await U.text();j=z?JSON.parse(z):{}}if(U.status>=400){let z=j??{};throw new JX(`ACME request to ${w} failed (HTTP ${U.status}): ${z.type??""} ${z.detail??""}`.trim(),z,U.status)}return{status:U.status,headers:U.headers,body:j,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),Y={termsOfServiceAgreed:!0};if($.email)Y.contact=[`mailto:${$.email}`];let A=await this.signedPost({url:w.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($){let w=await this.directory(),Y={identifiers:$.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:w.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($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return HN("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization($);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((B)=>B.status==="invalid");throw new JX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await g9(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getOrder($);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 ${$} became invalid`);await g9(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let Y=$.challenges.find((A)=>A.type===w);if(!Y)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return Y}}function vz($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=w[0];if(!Y)return{certPem:`${$.trim()}
|
|
64
|
+
`,chainPem:""};let A=`${Y.trim()}
|
|
65
65
|
`,X=w.slice(1).map((J)=>J.trim()).join(`
|
|
66
|
-
`);return{certPem:
|
|
67
|
-
`:""}}function pj($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function pB($){return new Promise((w)=>setTimeout(w,$))}function sG($){if($<128)return Buffer.from([$]);let w=[],A=$;while(A>0)w.unshift(A&255),A>>=8;return Buffer.from([128|w.length,...w])}function zw($,w){return Buffer.concat([Buffer.from([$]),sG(w.length),w])}function tj($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let A=[],Y=$;while(Y>0)A.unshift(Y&255),Y>>=8;if(A[0]&128)A.unshift(0);w=Buffer.from(A)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return zw(2,w)}function hw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let A=[40*w[0]+w[1]];for(let Y=2;Y<w.length;Y++){let X=w[Y],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);A.push(...J)}return zw(6,Buffer.from(A))}function W$(...$){return zw(48,Buffer.concat($))}function dJ(...$){return zw(49,Buffer.concat($))}function gJ($){return zw(3,Buffer.concat([Buffer.from([0]),$]))}function rj($){return zw(4,$)}function aj($){return zw(12,Buffer.from($,"utf8"))}function nJ($,w,A){let Y=128|(A?32:0)|$;return zw(Y,w)}function X6($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let A=mJ(w.x),Y=mJ(w.y);if(A.length!==32||Y.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${A.length} y=${Y.length}`);return Buffer.concat([Buffer.from([4]),A,Y])}function sj($){let{domains:w,publicKey:A,privateKey:Y}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let X=W$(dJ(W$(hw(w6),aj(w[0])))),J=W$(W$(hw(oG),hw(eG)),gJ(X6(A))),U=w.map((K)=>nJ(2,Buffer.from(K,"ascii"),!1)),W=W$(...U),f=W$(hw(Y6),rj(W)),B=W$(f),j=W$(hw(A6),dJ(B)),z=nJ(0,j,!0),E=W$(tj(0),X,J,z),F=aG("sha256",E,Y),T=W$(hw($6));return W$(E,T,gJ(F))}function oj($){return sj($).toString("base64url")}function U6($){if($){let{createPrivateKey:X,createPublicKey:J}=lG("node:crypto"),U=X($),W=J(U);return{privateKey:U,publicKey:W,pem:$}}let{privateKey:w,publicKey:A}=ej("ec",{namedCurve:"P-256"}),Y=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:A,pem:Y}}async function fU($){let{domains:w,method:A}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(A==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((z)=>z.startsWith("*."))&&A!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let Y=$.directoryUrl??($.staging===!1?nj:gj),X=U6($.accountKeyPem),J=new mY({directoryUrl:Y,accountKey:X.privateKey,accountPublicKey:X.publicKey});await J.newAccount({email:$.email});let{order:U,orderUrl:W}=await J.newOrder(w),f=$.http01Store??JX,B=[],j=[];try{for(let I of U.authorizations){let C=await J.getAuthorization(I);if(C.status==="valid")continue;let j0=mY.selectChallenge(C,A);if(A==="dns-01"){let Q=pj(C.identifier.value),_=J.dns01TxtValue(j0.token);await $.dnsProvider.setTxt(Q,_),B.push({name:Q,value:_}),await cj(Q,_,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else f.add(j0.token,J.keyAuthorization(j0.token)),j.push(j0.token);await J.notifyChallengeReady(j0.url),await J.pollAuthorization(I,{timeoutMs:$.timeoutMs})}let{privateKey:z,publicKey:E}=ej("ec",{namedCurve:"P-256"}),F=oj({domains:w,publicKey:E,privateKey:z});await J.finalizeOrder(U.finalize,F);let T=await J.pollOrder(W,{timeoutMs:$.timeoutMs}),K=await J.downloadCertificate(T),{certPem:H,chainPem:N}=lj(K),R=N?`${H}${N}`:H,M=z.export({format:"pem",type:"pkcs8"}).toString(),y=new Date(new J6(H).validTo);return{certPem:H,keyPem:M,chainPem:N,fullChainPem:R,accountKeyPem:X.pem,notAfter:y}}finally{for(let{name:z,value:E}of B)await $.dnsProvider?.removeTxt(z,E).catch(()=>{});for(let z of j)f.remove(z)}}class A9{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let X=this.generateKey($,A),J=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!tB($))return!0;return rB($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let X=tB(A)?rB(A):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,X)=>Y+X.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class Y9{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:X,...A}),J}catch(J){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...A}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((X)=>X.duration),Y=A.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function a6($,w){this[$]=r6.bind(null,w)}class BU{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let X=this.generateKey($,A),J=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!aB($))return!0;return sB($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let X=aB(A)?sB(A):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,X)=>Y+X.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class jU{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:X,...A}),J}catch(J){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...A}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((X)=>X.duration),Y=A.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function e6($,w={}){let A=Object.keys(w).sort().map((Y)=>`${Y}:${w[Y]}`).join("|");return A?`${$}:${A}`:$}function $K($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function wK($){return $.getStats().size*2}function zU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&e(w[0])&&"id"in w[0]&&w[0].id===3&&e(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(e(w)&&e($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(e($)&&"arr"in $&&Array.isArray($.arr)&&e(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&e(w[0])&&e($[0])){let Y=[...w];for(let X of $)if(e(X)&&"name"in X){if(!Y.find((J)=>e(J)&&("name"in J)&&J.name===X.name))Y.push(X)}else if(e(X)&&"path"in X){if(!Y.find((J)=>e(J)&&("path"in J)&&J.path===X.path))Y.push(X)}else if(!Y.some((J)=>tY(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!e(w)||!e($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if(e(X)&&e(A[Y]))A[Y]=zU(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&e(X[0])&&e(A[Y][0])){let J=[...X];for(let U of A[Y])if(e(U)&&"name"in U){if(!J.find((W)=>e(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(e(U)&&"path"in U){if(!J.find((W)=>e(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((W)=>tY(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function tY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!tY($[A],w[A]))return!1;return!0}if(e($)&&e(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!tY($[X],w[X]))return!1}return!0}return!1}function e($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function AK($,w){if(!w9($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return zU(w,Y)}catch{return null}}catch{return null}}async function YK({name:$="",cwd:w,defaultConfig:A}){let Y=w||pJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let W of X){let f=nY(Y,`${U}${W}`),B=await AK(f,A);if(B!==null)return B}try{let U=nY(Y,"package.json");if(w9(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return zU(A,W)}catch{}}}catch{}return A}function XK($,w={}){let A=gY.cwd();while(A.includes("storage"))A=$j(A,"..");let Y=$j(A,$||"");if(w?.relative)return K6(gY.cwd(),Y);return Y}async function JK(){try{let $=await YK({name:"clarity",defaultConfig:bY,cwd:gY.cwd(),endpoint:"",headers:{}});return{...bY,...$}}catch{return bY}}function J0(){if(i$.env.NODE_ENV==="test"||i$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function UK(){if(i$.env.NODE_ENV==="test"||i$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof i$<"u"){let $=i$.type;if($==="renderer"||$==="worker")return!1;return!!(i$.versions&&(i$.versions.node||i$.versions.bun))}return!1}class J9{async format($){let w=await UK(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Y1.pid,hostname:w(),environment:Y1.env.NODE_ENV||"development",platform:Y1.platform,version:Y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Y1.env.NODE_ENV||Y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...rJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new J9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...uY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...uY};return{...uY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:rJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let w=(async()=>{let Y,X=0,J=3,U=1000;while(X<J)try{try{try{await q6(this.config.logDirectory,Xj.F_OK|Xj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await M6(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Ww.from($);try{if(!VJ(this.currentLogFile))await LJ(this.currentLogFile,"",{mode:420});if(Y=Yj(this.currentLogFile,"a",420),R6(Y,W,{flag:"a"}),Aj(Y),Y!==void 0)hJ(Y),Y=void 0;if((await w1(this.currentLogFile)).size===0){if(await LJ(this.currentLogFile,W,{flag:"w",mode:420}),(await w1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(X<J-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,j);let z=U*2**X;await new Promise((E)=>setTimeout(E,z)),X++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{hJ(Y)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(W){if(X===J-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}X++;let f=U*2**(X-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return A1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return A1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return A1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(J0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.maxKeys:1,J=Math.max(1,X);if(Y.length>J)for(let[U]of Y.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}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 $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=CJ(16),Y=T6("aes-256-gcm",w,A),X=Ww.concat([Y.update($,"utf8"),Y.final()]),J=Y.getAuthTag();return{encrypted:Ww.concat([A,X,J]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=Uj(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(Ww.from(Ww.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(J0())return;let $=await w1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await MY(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await w1(A).catch(()=>null))try{if(await Jj(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await IY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await LJ(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await w1(A).catch(()=>null))await Jj(A,J)}if(this.currentLogFile=Y,w.maxFiles){let X=(await MY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await IY(A1(this.config.logDirectory,J))}}}async compressLogFile($,w){let A=wj($),Y=N6(w),X=Uj();await I6(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),VJ(this.currentLogFile))try{let $=Yj(this.currentLogFile,"r+");Aj($),hJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!J0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await MY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await IY(A1(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?r.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=_0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${r.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!J0()){let B=K9[$],j=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:r.gray(U),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:r.green(U),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z),W){let E=W.split(`
|
|
68
|
-
`);for(let
|
|
69
|
-
`;if(W
|
|
70
|
-
`;
|
|
71
|
-
`,
|
|
72
|
-
`),U=Math.max(...J.map((
|
|
73
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(
|
|
74
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
75
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||J0()||!_0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(J0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await MY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=A1(this.config.logDirectory,Y);if($.before)try{if((await w1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await IY(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function PY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&l(w[0])&&"id"in w[0]&&w[0].id===3&&l(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(l(w)&&l($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(l($)&&"arr"in $&&Array.isArray($.arr)&&l(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&l(w[0])&&l($[0])){let Y=[...w];for(let X of $)if(l(X)&&"name"in X){if(!Y.find((J)=>l(J)&&("name"in J)&&J.name===X.name))Y.push(X)}else if(l(X)&&"path"in X){if(!Y.find((J)=>l(J)&&("path"in J)&&J.path===X.path))Y.push(X)}else if(!Y.some((J)=>aY(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!l(w)||!l($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if(l(X)&&l(A[Y]))A[Y]=PY(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&l(X[0])&&l(A[Y][0])){let J=[...X];for(let U of A[Y])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((W)=>aY(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function FU($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:PY($,w);if(Array.isArray($))return A==="replace"?w:PY($,w);if(!l(w)||!l($))return w;let Y={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[X],U=Y[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(A==="replace")Y[X]=J;else Y[X]=PY(U,J);else if(l(J)&&l(U))Y[X]=FU(U,J,A);else Y[X]=J}return Y}function aY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!aY($[A],w[A]))return!1;return!0}if(l($)&&l(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!aY($[X],w[X]))return!1}return!0}return!1}function l($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function DY($,w,A="replace"){if(!$9($))return null;try{let Y=await import($),X=Y.default||Y;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return FU(w,X,A)}catch{return null}}catch{return null}}function fK($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${z.map(E).join("_")}`,T=`${Y}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(A)D0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=J(j,z);else{let K=$A.env[F]||$A.env[T];if(K!==void 0){if(A)D0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((N)=>N.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return J(X)}async function WK({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let f=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?fK($,X,J):X,B=A||$A.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),E=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,c0(B,"config"),c0(B,".config"),Y?c0(B,Y):void 0].filter(Boolean)));for(let H of K){if(J)D0.info(`Searching for configuration in: ${H}`);let N=[c0(B,"config"),c0(B,".config")].concat(Y?[c0(B,Y)]:[]).includes(H)?[...z,...E,...F,...T]:[...E,...z,...T,...F];for(let R of N)for(let M of j){let y=c0(H,`${R}${M}`),I=await DY(y,f,W);if(I!==null){if(J)D0.success(`Configuration loaded from: ${y}`);return I}}}if($){let H=c0(yJ(),".config",$),N=["config",`${$}.config`];if(w)N.push(`${w}.config`);if(J)D0.info(`Checking user config directory: ${H}`);for(let R of N)for(let M of j){let y=c0(H,`${R}${M}`),I=await DY(y,f,W);if(I!==null){if(J)D0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let H=c0(yJ(),".config"),N=[`.${$}.config`];if(w)N.push(`.${w}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=c0(H,`${R}${M}`),I=await DY(y,f,W);if(I!==null){if(J)D0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let H=yJ(),N=[`.${$}.config`,`.${$}`];if(w)N.push(`.${w}.config`),N.push(`.${w}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=c0(H,`${R}${M}`),I=await DY(y,f,W);if(I!==null){if(J)D0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let H=c0(B,"package.json");if($9(H)){let N=await import(H),R=N[$];if(!R&&w){if(R=N[w],R&&J)D0.success(`Using alias "${w}" 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}`);return FU(f,R,W)}catch(M){if(J)D0.warn("Failed to merge package.json config:",M)}}}catch(H){if(J)D0.warn("Failed to load package.json:",H)}if(J)D0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function BK($,w={}){let A=dY.cwd();while(A.includes("storage"))A=eB(A,"..");let Y=eB(A,$||"");if(w?.relative)return E6(dY.cwd(),Y);return Y}async function jK(){try{let $=await WK({name:"clarity",alias:"logging",defaultConfig:iY,cwd:dY.cwd()});return{...iY,...$||{}}}catch{return iY}}function H0(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zK(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c$<"u"){let $=c$.type;if($==="renderer"||$==="worker")return!1;return!!(c$.versions&&(c$.versions.node||c$.versions.bun))}return!1}class U9{async format($){let w=await zK(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:U1.pid,hostname:w(),environment:U1.env.NODE_ENV||"development",platform:U1.platform,version:U1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:U1.env.NODE_ENV||U1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class sY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...aJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new U9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...cY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...cY};return{...cY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:aJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let Y,X=0,J=3,U=1000;while(X<J)try{try{try{await L6(this.config.logDirectory,jj.F_OK|jj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await O6(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P$.from($);try{if(!yY(this.currentLogFile))await SJ(this.currentLogFile,"",{mode:420});if(Y=Bj(this.currentLogFile,"a",420),V6(Y,W,{flag:"a"}),Wj(Y),Y!==void 0)QJ(Y),Y=void 0;if((await X1(this.currentLogFile)).size===0){if(await SJ(this.currentLogFile,W,{flag:"w",mode:420}),(await X1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(X<J-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,j);let z=U*2**X;await new Promise((E)=>setTimeout(E,z)),X++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{QJ(Y)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(W){if(X===J-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}X++;let f=U*2**(X-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return J1(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 J1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return J1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.maxKeys:1,J=Math.max(1,X);if(Y.length>J)for(let[U]of Y.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return OJ(16).toString("hex")}generateKey(){return OJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=OJ(16),Y=y6("aes-256-gcm",w,A),X=P$.isBuffer($)?$:P$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=P$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=Fj(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(P$.from(P$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let $=await X1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await CY(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await X1(A).catch(()=>null))try{if(await zj(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await hY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await SJ(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await X1(A).catch(()=>null))await zj(A,J)}if(this.currentLogFile=Y,w.maxFiles){let X=(await CY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await hY(J1(this.config.logDirectory,J))}}}async compressLogFile($,w){let A=fj($),Y=h6(w),X=Fj();await _6(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),yY(this.currentLogFile))try{let $=Bj(this.currentLogFile,"r+");Wj($),QJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await CY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await hY(J1(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let $=typeof g.env.NO_COLOR<"u",w=g.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=g.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${b.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=b.underline(b.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(A,Y)=>b.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>b.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>b.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>b.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>b.strikethrough(Y)),w}supportsHyperlinks(){if(H0())return!1;let $=g.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=g.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(Q6(w)||w.startsWith("./")||w.startsWith("../"))w=S6(w);else return null;return yY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":T9[$],E=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:b.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:b.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
76
|
-
`);for(let
|
|
77
|
-
`;if(
|
|
78
|
-
`;if(
|
|
79
|
-
`);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
80
|
-
`,
|
|
81
|
-
`),
|
|
82
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
83
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
84
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
66
|
+
`);return{certPem:A,chainPem:X?`${X}
|
|
67
|
+
`:""}}function iz($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function g9($){return new Promise((w)=>setTimeout(w,$))}function MN($){if($<128)return Buffer.from([$]);let w=[],Y=$;while(Y>0)w.unshift(Y&255),Y>>=8;return Buffer.from([128|w.length,...w])}function Kw($,w){return Buffer.concat([Buffer.from([$]),MN(w.length),w])}function mz($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let Y=[],A=$;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);w=Buffer.from(Y)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return Kw(2,w)}function Sw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let Y=[40*w[0]+w[1]];for(let A=2;A<w.length;A++){let X=w[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 Kw(6,Buffer.from(Y))}function J$(...$){return Kw(48,Buffer.concat($))}function IU(...$){return Kw(49,Buffer.concat($))}function VU($){return Kw(3,Buffer.concat([Buffer.from([0]),$]))}function gz($){return Kw(4,$)}function dz($){return Kw(12,Buffer.from($,"utf8"))}function yU($,w,Y){let A=128|(Y?32:0)|$;return Kw(A,w)}function ON($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let Y=MU(w.x),A=MU(w.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 lz($){let{domains:w,publicKey:Y,privateKey:A}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let X=J$(IU(J$(Sw(CN),dz(w[0])))),J=J$(J$(Sw(IN),Sw(VN)),VU(ON(Y))),U=w.map((E)=>yU(2,Buffer.from(E,"ascii"),!1)),B=J$(...U),W=J$(Sw(LN),gz(B)),j=J$(W),z=J$(Sw(QN),IU(j)),G=yU(0,z,!0),F=J$(mz(0),X,J,G),K=RN("sha256",F,A),f=J$(Sw(yN));return J$(F,f,VU(K))}function nz($){return lz($).toString("base64url")}function SN($){if($){let{createPrivateKey:X,createPublicKey:J}=fN("node:crypto"),U=X($),B=J(U);return{privateKey:U,publicKey:B,pem:$}}let{privateKey:w,publicKey:Y}=pz("ec",{namedCurve:"P-256"}),A=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:Y,pem:A}}async function iU($){let{domains:w,method:Y}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((G)=>G.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=$.directoryUrl??($.staging===!1?cz:uz),X=SN($.accountKeyPem),J=new UX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey});await J.newAccount({email:$.email});let{order:U,orderUrl:B}=await J.newOrder(w),W=$.http01Store??VX,j=[],z=[];try{for(let H of U.authorizations){let I=await J.getAuthorization(H);if(I.status==="valid")continue;let _=UX.selectChallenge(I,Y);if(Y==="dns-01"){let h=iz(I.identifier.value),u0=J.dns01TxtValue(_.token);await $.dnsProvider.setTxt(h,u0),j.push({name:h,value:u0}),await Dz(h,u0,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else W.add(_.token,J.keyAuthorization(_.token)),z.push(_.token);await J.notifyChallengeReady(_.url),await J.pollAuthorization(H,{timeoutMs:$.timeoutMs})}let{privateKey:G,publicKey:F}=pz("ec",{namedCurve:"P-256"}),K=nz({domains:w,publicKey:F,privateKey:G});await J.finalizeOrder(U.finalize,K);let f=await J.pollOrder(B,{timeoutMs:$.timeoutMs}),E=await J.downloadCertificate(f),{certPem:q,chainPem:T}=vz(E),M=T?`${q}${T}`:q,y=G.export({format:"pem",type:"pkcs8"}).toString(),Q=new Date(new _N(q).validTo);return{certPem:q,keyPem:y,chainPem:T,fullChainPem:M,accountKeyPem:X.pem,notAfter:Q}}finally{for(let{name:G,value:F}of j)await $.dnsProvider?.removeTxt(G,F).catch(()=>{});for(let G of z)W.remove(G)}}class az{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!d9($))return!0;return l9($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=d9(Y)?l9(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class sz{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function RE($,w){this[$]=HE.bind(null,w)}class gU{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!n9($))return!0;return p9($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=n9(Y)?p9(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class dU{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function VE($,w={}){let Y=Object.keys(w).sort().map((A)=>`${A}:${w[A]}`).join("|");return Y?`${$}:${Y}`:$}function yE($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function CE($){return $.getStats().size*2}function lU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&w0(w[0])&&"id"in w[0]&&w[0].id===3&&w0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(w0(w)&&w0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(w0($)&&"arr"in $&&Array.isArray($.arr)&&w0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&w0(w[0])&&w0($[0])){let A=[...w];for(let X of $)if(w0(X)&&"name"in X){if(!A.find((J)=>w0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(w0(X)&&"path"in X){if(!A.find((J)=>w0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>FX(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!w0(w)||!w0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(w0(X)&&w0(Y[A]))Y[A]=lU(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&w0(X[0])&&w0(Y[A][0])){let J=[...X];for(let U of Y[A])if(w0(U)&&"name"in U){if(!J.find((B)=>w0(B)&&("name"in B)&&B.name===U.name))J.push(U)}else if(w0(U)&&"path"in U){if(!J.find((B)=>w0(B)&&("path"in B)&&B.path===U.path))J.push(U)}else if(!J.some((B)=>FX(B,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 FX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!FX($[Y],w[Y]))return!1;return!0}if(w0($)&&w0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!FX($[X],w[X]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function QE($,w){if(!tz($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return lU(w,A)}catch{return null}}catch{return null}}async function LE({name:$="",cwd:w,defaultConfig:Y}){let A=w||QU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=jX(A,`${U}${B}`),j=await QE(W,Y);if(j!==null)return j}try{let U=jX(A,"package.json");if(tz(U)){let B=(await import(U))[$];if(B&&typeof B==="object"&&!Array.isArray(B))try{return lU(Y,B)}catch{}}}catch{}return Y}function OE($,w={}){let Y=BX.cwd();while(Y.includes("storage"))Y=a9(Y,"..");let A=a9(Y,$||"");if(w?.relative)return cN(BX.cwd(),A);return A}async function _E(){try{let $=await LE({name:"clarity",defaultConfig:wX,cwd:BX.cwd(),endpoint:"",headers:{}});return{...wX,...$}}catch{return wX}}function W0(){if(m$.env.NODE_ENV==="test"||m$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function SE(){if(m$.env.NODE_ENV==="test"||m$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof m$<"u"){let $=m$.type;if($==="renderer"||$==="worker")return!1;return!!(m$.versions&&(m$.versions.node||m$.versions.bun))}return!1}class ez{async format($){let w=await SE(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:F1.pid,hostname:w(),environment:F1.env.NODE_ENV||"development",platform:F1.platform,version:F1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:F1.env.NODE_ENV||F1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class KX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...OU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new ez,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...YX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...YX};return{...YX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:OU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await dN(this.config.logDirectory,$z.F_OK|$z.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await lN(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 B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:zw.from($);try{if(!JU(this.currentLogFile))await UU(this.currentLogFile,"",{mode:420});if(A=e9(this.currentLogFile,"a",420),gN(A,B,{flag:"a"}),o9(A),A!==void 0)XU(A),A=void 0;if((await z1(this.currentLogFile)).size===0){if(await UU(this.currentLogFile,B,{flag:"w",mode:420}),(await z1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{XU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}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 G1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return G1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return G1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,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 $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.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 AU(16).toString("hex")}generateKey(){return AU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=AU(16),A=vN("aes-256-gcm",w,Y),X=zw.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:zw.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Yz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(zw.from(zw.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(W0())return;let $=await z1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await cA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await z1(Y).catch(()=>null))try{if(await wz(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await vA(B)}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 UU(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 z1(Y).catch(()=>null))await wz(Y,J)}if(this.currentLogFile=A,w.maxFiles){let X=(await cA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await vA(G1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=s9($),A=mN(w),X=Yz();await nN(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!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(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),JU(this.currentLogFile))try{let $=e9(this.currentLogFile,"r+");o9($),XU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await cA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await vA(G1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?a.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push(w);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let W=_0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${a.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,F=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(F)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.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,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!W0()){let j=j2[$],z=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:a.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:a.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let F=B.split(`
|
|
68
|
+
`);for(let K of F)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:a.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!W0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let W=`${J} ${this.environment}.${$.toUpperCase()}: ${U}
|
|
69
|
+
`;if(B)W+=`${B}
|
|
70
|
+
`;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time($){let w=performance.now();if(this.fancy&&!W0()){let Y=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:a.blue("◐"),tag:Y,message:`${a.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
|
|
71
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.fancy&&!W0()){let j=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:a.green("✓"),tag:j,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 $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new KX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(W0())throw Error("createReadStream is not supported in browser environments");if(!JU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return s9(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=zw.isBuffer($)?$:zw.from($,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),B=iN("aes-256-gcm",Y,X);return B.setAuthTag(J),zw.concat([B.update(U),B.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!W0()){let J=$.split(`
|
|
72
|
+
`),U=Math.max(...J.map((z)=>z.length))+2,B=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,j=J.map((z)=>{let G=" ".repeat(U-z.length-2);return`│ ${z}${G} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:a.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(B)})),j.forEach((z)=>console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(z),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(W),showTimestamp:!1}))}else if(!W0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let X=`${A} ${this.environment}.INFO: [BOX] ${$}
|
|
73
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(W0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${a.cyan("?")} ${$} (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(""),w(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($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let X=/%([sdijfo%])/g,J=0;if(Y=$.replace(X,(U,B)=>{if(B==="%")return"%";if(J>=w.length)return U;let W=w[J++];switch(B){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<w.length)Y+=` ${w.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?a.gray(this.formatTag(this.name)):"",J=a.blue("◐");console.error(`${J} ${X} ${a.cyan(Y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
74
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress($,w=""){if(!this.enabled||!this.fancy||W0()||$<=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:$,current:0,message:w,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($,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($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=a.green("━".repeat(A)),U=a.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=w||Y===100?a.green("✓"):a.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${a.gray(this.formatTag(this.name))}`:"",F=`\r${z}${G} ${B} ${W}${j}`,K=_0.stdout.columns||80,f=" ".repeat(Math.max(0,K-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${f}`,_0.stdout.write($.lastRenderedLine),w)_0.stdout.write(`
|
|
75
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||W0()||!_0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await cA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=G1(this.config.logDirectory,A);if($.before)try{if((await z1(X)).mtime>=$.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 vA(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(w){console.error("Error during log clearing process:",w)}}}function $X($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let A=[...w];for(let X of $)if(p(X)&&"name"in X){if(!A.find((J)=>p(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(p(X)&&"path"in X){if(!A.find((J)=>p(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>NX(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!p(w)||!p($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(p(X)&&p(Y[A]))Y[A]=$X(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&p(X[0])&&p(Y[A][0])){let J=[...X];for(let U of Y[A])if(p(U)&&"name"in U){if(!J.find((B)=>p(B)&&("name"in B)&&B.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((B)=>p(B)&&("path"in B)&&B.path===U.path))J.push(U)}else if(!J.some((B)=>NX(B,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 nU($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:$X($,w);if(Array.isArray($))return Y==="replace"?w:$X($,w);if(!p(w)||!p($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[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]=$X(U,J);else if(p(J)&&p(U))A[X]=nU(U,J,Y);else A[X]=J}return A}function NX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!NX($[Y],w[Y]))return!1;return!0}if(p($)&&p(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!NX($[X],w[X]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function sA($,w,Y="replace"){if(!rz($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return nU(w,X,Y)}catch{return null}}catch{return null}}function hE($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],F=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),K=`${A}_${G.map(F).join("_")}`,f=`${A}_${G.map((E)=>E.toUpperCase()).join("_")}`;if(Y)h0.info(`Checking environment variable ${K} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let E=EY.env[K]||EY.env[f];if(E!==void 0){if(Y)h0.info(`Using environment variable ${E?K:f} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(E);else if(typeof z==="boolean")W[j]=E.toLowerCase()==="true";else if(Array.isArray(z))try{let q=JSON.parse(E);if(Array.isArray(q))W[j]=q;else W[j]=E.split(",").map((T)=>T.trim())}catch{W[j]=E.split(",").map((q)=>q.trim())}else W[j]=E}}}return W}return J(X)}async function ZE({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?hE($,X,J):X,j=Y||EY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)h0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),F=[`${$}.config`,`.${$}.config`].filter(Boolean),K=w?[w,`.${w}`]:[],f=w?[`${w}.config`,`.${w}.config`]:[],E=Array.from(new Set([j,i0(j,"config"),i0(j,".config"),A?i0(j,A):void 0].filter(Boolean)));for(let q of E){if(J)h0.info(`Searching for configuration in: ${q}`);let T=[i0(j,"config"),i0(j,".config")].concat(A?[i0(j,A)]:[]).includes(q)?[...G,...F,...K,...f]:[...F,...G,...f,...K];for(let M of T)for(let y of z){let Q=i0(q,`${M}${y}`),H=await sA(Q,W,B);if(H!==null){if(J)h0.success(`Configuration loaded from: ${Q}`);return H}}}if($){let q=i0(YU(),".config",$),T=["config",`${$}.config`];if(w)T.push(`${w}.config`);if(J)h0.info(`Checking user config directory: ${q}`);for(let M of T)for(let y of z){let Q=i0(q,`${M}${y}`),H=await sA(Q,W,B);if(H!==null){if(J)h0.success(`Configuration loaded from user config directory: ${Q}`);return H}}}if($){let q=i0(YU(),".config"),T=[`.${$}.config`];if(w)T.push(`.${w}.config`);if(J)h0.info(`Checking user config directory for dotfile configs: ${q}`);for(let M of T)for(let y of z){let Q=i0(q,`${M}${y}`),H=await sA(Q,W,B);if(H!==null){if(J)h0.success(`Configuration loaded from user config directory dotfile: ${Q}`);return H}}}if($){let q=YU(),T=[`.${$}.config`,`.${$}`];if(w)T.push(`.${w}.config`),T.push(`.${w}`);if(J)h0.info(`Checking user home directory for dotfile configs: ${q}`);for(let M of T)for(let y of z){let Q=i0(q,`${M}${y}`),H=await sA(Q,W,B);if(H!==null){if(J)h0.success(`Configuration loaded from user home directory: ${Q}`);return H}}}try{let q=i0(j,"package.json");if(rz(q)){let T=await import(q),M=T[$];if(!M&&w){if(M=T[w],M&&J)h0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)h0.success(`Configuration loaded from package.json: ${M===T[$]?$:w}`);return nU(W,M,B)}catch(y){if(J)h0.warn("Failed to merge package.json config:",y)}}}catch(q){if(J)h0.warn("Failed to load package.json:",q)}if(J)h0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function kE($,w={}){let Y=WX.cwd();while(Y.includes("storage"))Y=t9(Y,"..");let A=t9(Y,$||"");if(w?.relative)return bN(WX.cwd(),A);return A}async function DE(){try{let $=await ZE({name:"clarity",alias:"logging",defaultConfig:AX,cwd:WX.cwd()});return{...AX,...$||{}}}catch{return AX}}function f0(){if(g$.env.NODE_ENV==="test"||g$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xE(){if(g$.env.NODE_ENV==="test"||g$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof g$<"u"){let $=g$.type;if($==="renderer"||$==="worker")return!1;return!!(g$.versions&&(g$.versions.node||g$.versions.bun))}return!1}class $2{async format($){let w=await xE(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:E1.pid,hostname:w(),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 EX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={..._U},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new $2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??l.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...XX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...XX};return{...XX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:_U.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!f0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await sN(this.config.logDirectory,Uz.F_OK|Uz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await oN(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 B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:c$.from($);try{if(!iA(this.currentLogFile))await jU(this.currentLogFile,"",{mode:420});if(A=Jz(this.currentLogFile,"a",420),aN(A,B,{flag:"a"}),Xz(A),A!==void 0)BU(A),A=void 0;if((await K1(this.currentLogFile)).size===0){if(await jU(this.currentLogFile,B,{flag:"w",mode:420}),(await K1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{BU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}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 $=new Date().toISOString().split("T")[0];return N1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(f0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,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 $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.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 WU(16).toString("hex")}generateKey(){return WU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=WU(16),A=pN("aes-256-gcm",w,Y),X=c$.isBuffer($)?$:c$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=c$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Bz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(c$.from(c$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(f0())return;if(!this.shouldWriteToFile())return;let $=await K1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await mA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await K1(Y).catch(()=>null))try{if(await Wz(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await gA(B)}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 jU(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 Wz(Y,J)}if(this.currentLogFile=A,w.maxFiles){let X=(await mA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await gA(N1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=Az($),A=tN(w),X=Bz();await wE(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!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(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),iA(this.currentLogFile))try{let $=Jz(this.currentLogFile,"r+");Xz($),BU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!f0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await mA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await gA(N1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||f0())return!1;let $=typeof l.env.NO_COLOR<"u",w=l.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof l.stderr<"u"&&l.stderr.isTTY||typeof l.stdout<"u"&&l.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push(w);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let W=l.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${c.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,F=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(F)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),w}supportsHyperlinks(){if(f0())return!1;let $=l.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=l.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(eN(w)||w.startsWith("./")||w.startsWith("../"))w=$E(w);else return null;return iA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":z2[$],F=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",K;switch($){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:c.gray(W),level:$}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:c.green(W),level:$}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.error(K),B){let f=B.split(`
|
|
76
|
+
`);for(let E of f)if(E.trim()&&!E.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:c.gray(` ${E}`),level:$,showTimestamp:!1}))}break}}else if(!f0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
|
|
77
|
+
`;if(B)z+=`${B}
|
|
78
|
+
`;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,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!f0()&&l.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()&&!f0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!f0()&&l.stdout.isTTY)l.stdout.write(`
|
|
79
|
+
`);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!f0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=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($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
|
|
80
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":c.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!f0())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new EX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(f0())throw Error("createReadStream is not supported in browser environments");if(!iA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Az(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=c$.isBuffer($)?$:c$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=rN("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=c$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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 f0()}isServerMode(){return!f0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
|
|
81
|
+
`),W=Math.max(...B.map((F)=>F.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((F)=>{return this.formatConsoleMessage({timestamp:Y,message:c.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(j),showTimestamp:!1})),G.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(z),showTimestamp:!1}))}else if(!f0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
82
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(f0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${c.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();l.stdin.removeListener("data",Y);try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!1)}catch{}l.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!0)}catch{}l.stdin.resume(),l.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,B=0;if(Y=$.replace(U,(W,j)=>{if(j==="%")return"%";if(B>=w.length)return W;let z=w[B++];switch(j){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}}),B<w.length)Y+=` ${w.slice(B).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?c.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${c.blue("◐")} `;console.error(`${B}${U} ${c.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
83
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!l.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=c.green("━".repeat(A)),U=c.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?c.green("✓"):c.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",F=`\r${z}${G} ${B} ${W}${j}`,K=l.stdout.columns||80,f=" ".repeat(Math.max(0,K-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${f}`,l.stdout.write($.lastRenderedLine),w)l.stdout.write(`
|
|
84
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||f0()||!l.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(f0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await mA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=N1(this.config.logDirectory,A);if($.before)try{if((await K1(X)).mtime>=$.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 gA(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(w){console.error("Error during log clearing process:",w)}}}async function w2($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function Y2($){return $ instanceof s0}function PE($){return $ instanceof fX}function bE($){if(Y2($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((w)=>$.message.toLowerCase().includes(w.toLowerCase()))}class CX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return HY.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=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=dA.env[W]||(j?dA.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=dA.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof qX)throw G;throw Fw.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw Fw.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(dA.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
|
|
85
85
|
|
|
86
|
-
`;for(let
|
|
87
|
-
`,
|
|
88
|
-
`,
|
|
89
|
-
`,
|
|
86
|
+
`;for(let A of $)Y+=`${A.key}
|
|
87
|
+
`,Y+=` Type: ${A.type}
|
|
88
|
+
`,Y+=` Description: ${A.description}
|
|
89
|
+
`,Y+=` Example: ${A.example}
|
|
90
90
|
|
|
91
|
-
`;return
|
|
91
|
+
`;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
|
|
92
92
|
|
|
93
|
-
`;
|
|
94
|
-
`,
|
|
95
|
-
`;for(let
|
|
96
|
-
`;return A}}function GK($,w){let A=E9("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function B9($,w,A={}){return j9($,w,A,new WeakMap)}function j9($,w,A,Y){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=A;if(w===null||w===void 0)return J?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return z9($,w,X,Y);if(!j$(w)||!j$($))return w;return NK($,w,A,Y)}function z9($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return KK($,w);case"smart":return TK($,w,Y);default:return w}return w}function KK($,w){let A=[...w];for(let Y of $)if(!A.some((X)=>tJ(X,Y)))A.push(Y);return A}function TK($,w,A){if(w.length===0)return $;if($.length===0)return w;if(j$(w[0])&&j$($[0]))return HK($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}function HK($,w,A){let Y=[...w];for(let X of $){if(!j$(X)){Y.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(Y.find((f)=>j$(f)&&(W in f)&&f[W]===X[W])){U=!0;break}}if(!U)Y.push(X)}return Y}function NK($,w,A,Y){let X=w;if(j$(X)&&Y.has(X))return Y.get(X);let J={...$};if(j$(X))Y.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],f=J[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(j$(W)&&j$(f))J[U]=j9(f,W,A,Y);else if(Array.isArray(W)||Array.isArray(f))J[U]=z9(f,W,A.arrayMergeMode||"smart",Y);else J[U]=W}return J}function EU($,w,A="replace"){return B9($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function tJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!tJ($[A],w[A]))return!1;return!0}if(j$($)&&j$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!tJ($[X],w[X]))return!1}return!0}return!1}function j$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class WX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=A;if(X){let B=z1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!LY($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,E="default"in j,F=Object.keys(j).length>0;if(!E&&!F)throw new wA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new wA($,Error("Configuration must export a valid object"),"unknown");let T={config:EU(w,z,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)z1.setWithFileCheck("file",T,$,J);return T}catch(B){throw B instanceof Error?jw.configLoad($,B):jw.configLoad($,Error(String(B)))}};if(U)return XA.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let X=await this.loadFromPath(Y,w,A);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,X)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),X=[];for(let J of Y)for(let U of this.extensions)X.push(_J(w,`${J}${U}`));return X}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return f9(async()=>{return LY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!LY($))return Y;if(w||A){let X=this.generateNamePatterns(w||"",A);for(let J of X)for(let U of this.extensions){let W=_J($,`${J}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let W=_J($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!LY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let X=await this.loadFromPath(Y,{},w);if(X)A.set(Y,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${Y}:`,X)}})),A}}class GU{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:f=!1}=A,B=async()=>{let j=[],z=[],E={stopOnFirstError:Y,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,E);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],E);else return this.validateWithJSONSchema($,w,E)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await XA.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!k6(w))throw new AA(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),X=Y.default||Y;if(Array.isArray(X))return this.validateWithRules($,X,A);else return this.validateWithJSONSchema($,X,A)}catch(Y){throw new AA(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],X=[];return this.validateObjectAgainstSchema($,w,"",Y,X,A),{isValid:Y.length===0,errors:Y,warnings:X}}validateObjectAgainstSchema($,w,A,Y,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,X,J),J.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],f,B,Y,X,J),J.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(U))if(!W.has(f))X.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),W=this.validateWithRule(U,J,J.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:X}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)Y.push({path:A,message:w.message||X,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let X of A)if(Y&&typeof Y==="object"&&X in Y)Y=Y[X];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,X,J,U]=Y;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:N9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class KU{fileLoader=new WX;envProcessor=new fX;validator=new GU;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:X,validate:J,...U}=$;try{if(A?.enabled){let f=this.checkCache(U.name||"",U);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(f){let B=U.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),E=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(E||j))throw f;if(z&&(!B||!E))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(f);if(Y.slowThreshold&&f.duration>Y.slowThreshold)q$.warn(`Slow configuration loading detected: ${f.duration}ms for ${U.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw q$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=J||Vw.cwd(),E=[],F=await this.loadLocalConfiguration(Y,X,z,U,W,B,j,f,A);if(F)return E.push(...this.getLocalSearchPaths(Y,X,z,U)),this.finalizeResult(F,E,f,Y,j);let T=await this.loadHomeConfiguration(Y,X,W,B,j,f);if(T)return E.push(...this.getHomeSearchPaths(Y,X)),this.finalizeResult(T,E,f,Y,j);let K=await this.loadPackageJsonConfiguration(Y,X,z,W,B,j,f);if(K)return E.push(v0(z,"package.json")),this.finalizeResult(K,E,f,Y,j);if(E.push(...this.getAllSearchPaths(Y,X,z,U)),w)throw jw.configNotFound(Y,E,X);return{...await this.applyEnvironmentVariables(Y,W,f,j),warnings:[`No configuration file found for "${Y}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,X,J,U,W,f){let B=W?s1($,X,U):X,j=this.getLocalDirectories(A,Y);for(let z of j){if(U)q$.info(`Searching for configuration in: ${z}`);let E=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(E,B,{arrayStrategy:J,verbose:U,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(U)q$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,X,J){if(!$)return null;let U=J?s1($,A,X):A,W=[v0($1(),".config",$),v0($1(),".config"),$1()];for(let f of W){if(X)q$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:X});if(j){if(X)q$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,Y,X,J,U){let W=U?s1($,Y,J):Y;try{let f=v0(A,"package.json");if(!lJ(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)q$.success(`Configuration loaded from package.json: ${z}`);return{config:EU(W,j,X),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(J)q$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:s1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let X=[];if(A){let J=A($);if(J)X.push(...J)}if(w){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 jw.configValidation(Y||"unknown",X,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return z1.get(A)||null}cacheResult($,w,A,Y){let X=this.generateCacheKey($,Y);z1.set(X,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,v0($,"config"),v0($,".config"),w?v0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let X=[];return X.push(...this.getLocalSearchPaths($,w,A,Y)),X.push(...this.getHomeSearchPaths($,w)),X.push(v0(A,"package.json")),X}getLocalSearchPaths($,w,A,Y){let X=this.getLocalDirectories(A,Y),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let A=[v0($1(),".config",$),v0($1(),".config"),$1()],Y=[];for(let X of A)Y.push(...this.fileLoader.generateConfigPaths($,X,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function Mj($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||A}async function RK($){return d$.loadConfig({...$,__strictErrorHandling:!0})}async function F9($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await d$.loadConfig($);else Y=await d$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let X=Y instanceof Error?Y.name:"UnknownError",J=Y instanceof Error?Y.message:String(Y);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&$.verbose)q$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let U=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await d$.applyEnvironmentVariables(U.name||"",w,!0,U.verbose||!1))?.config??w;return w}}async function qK($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await d$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&Mj(A)))return(await d$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await d$.loadConfig({...$,cwd:$.cwd||Vw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&Mj(w)))return(await d$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function MK($,w,A="replace"){let Y=new WX;try{let X=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function s1($,w,A=!1){let Y=new fX,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of E)if(F=Vw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=J(j,z)}return f}return J(w)}function IK($){let w=v0(Vw.cwd(),$.configDir),A=v0(Vw.cwd(),$.generatedDir),Y=v0(A,"config-types.ts");if(!lJ(oB(Y)))B6(oB(Y),{recursive:!0,mode:511});let X=lJ(w)?j6(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${sK}
|
|
93
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
94
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
95
|
+
`;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
96
|
+
`;return Y}}function uE($,w){let Y=W2("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function A2($,w,Y={}){return X2($,w,Y,new WeakMap)}function X2($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return J2($,w,X,A);if(!W$(w)||!W$($))return w;return mE($,w,Y,A)}function J2($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return cE($,w);case"smart":return vE($,w,A);default:return w}return w}function cE($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>LU(X,A)))Y.push(A);return Y}function vE($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(W$(w[0])&&W$($[0]))return iE($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function iE($,w,Y){let A=[...w];for(let X of $){if(!W$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((W)=>W$(W)&&(B in W)&&W[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function mE($,w,Y,A){let X=w;if(W$(X)&&A.has(X))return A.get(X);let J={...$};if(W$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(W$(B)&&W$(W))J[U]=X2(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=J2(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function pU($,w,Y="replace"){return A2($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function LU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!LU($[Y],w[Y]))return!1;return!0}if(W$($)&&W$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!LU($[X],w[X]))return!1}return!0}return!1}function W$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class QX{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:B=!1}=Y;if(X){let j=R1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!lA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,F="default"in z,K=Object.keys(z).length>0;if(!F&&!K)throw new fY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new fY($,Error("Configuration must export a valid object"),"unknown");let f={config:pU(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)R1.setWithFileCheck("file",f,$,J);return f}catch(j){throw j instanceof Error?Fw.configLoad($,j):Fw.configLoad($,Error(String(j)))}};if(U)return HY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(zU(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return w2(async()=>{return lA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!lA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=zU($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=zU($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!lA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class rU{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],F={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,F);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],F);else return this.validateWithJSONSchema($,w,F)}catch(K){return z.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await HY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!YE(w))throw new qY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new qY(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:F2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class tU{fileLoader=new QX;envProcessor=new CX;validator=new rU;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),F=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(F||z))throw W;if(G&&(!j||!F))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)E$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw E$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||hw.cwd(),F=[],K=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(K)return F.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(K,F,W,A,z);let f=await this.loadHomeConfiguration(A,X,B,j,z,W);if(f)return F.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(f,F,W,A,z);let E=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(E)return F.push(m0(G,"package.json")),this.finalizeResult(E,F,W,A,z);if(F.push(...this.getAllSearchPaths(A,X,G,U)),w)throw Fw.configNotFound(A,F,X);return{...await this.applyEnvironmentVariables(A,B,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,B,W){let j=B?FY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)E$.info(`Searching for configuration in: ${G}`);let F=this.fileLoader.generateConfigPaths($,G,w),K=await this.fileLoader.tryLoadFromPaths(F,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(K){if(U)E$.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?FY($,Y,X):Y,B=[m0(j1(),".config",$),m0(j1(),".config"),j1()];for(let W of B){if(X)E$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)E$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?FY($,A,J):A;try{let W=m0(Y,"package.json");if(!CU(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)E$.success(`Configuration loaded from package.json: ${G}`);return{config:pU(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)E$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:FY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 Fw.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($,A);R1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,m0($,"config"),m0($,".config"),w?m0($,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(m0(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[m0(j1(),".config",$),m0(j1(),".config"),j1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function qz($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||Y}async function gE($){return n$.loadConfig({...$,__strictErrorHandling:!0})}async function U2($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await n$.loadConfig($);else A=await n$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)E$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await n$.applyEnvironmentVariables(U.name||"",w,!0,U.verbose||!1))?.config??w;return w}}async function dE($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await n$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&qz(Y)))return(await n$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await n$.loadConfig({...$,cwd:$.cwd||hw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&qz(w)))return(await n$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function lE($,w,Y="replace"){let A=new QX;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function FY($,w,Y=!1){let A=new CX,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],F=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((E)=>E.toUpperCase()).join("")}`,`${X}_${G.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,f;for(let E of F)if(K=hw.env[E],K!==void 0){f=E;break}if(K!==void 0&&f)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(K.toLowerCase());else if(typeof z==="number"){let E=Number(K);if(!Number.isNaN(E))W[j]=E}else if(Array.isArray(z))try{W[j]=JSON.parse(K)}catch{W[j]=K.split(",").map((E)=>E.trim())}else W[j]=K;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function nE($){let w=m0(hw.cwd(),$.configDir),Y=m0(hw.cwd(),$.generatedDir),A=m0(Y,"config-types.ts");if(!CU(r9(A)))kN(r9(A),{recursive:!0,mode:511});let X=CU(w)?DN(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${Mf}
|
|
97
97
|
export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
|
|
98
|
-
`;
|
|
99
|
-
${X.map((
|
|
98
|
+
`;xN(A,J,{mode:438})}function pE($){let w=null,Y=null,A=()=>{if(!Y)Y=U2($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)E$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in $?$.defaultConfig:{};return w=X,A(),new Proxy({},{get(J,U){if(w)return w[U];let B=X[U];return A(),B},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,B){if(!w)w={...X};return w[U]=B,!0}})}function rE($){let w=jz(JE.cwd(),$?.configDir||"./config");function Y(){if(!AE(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=XE(w).filter((W)=>X.has(GU(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:j}of U){let z=GU(j).toLowerCase(),G=B.get(W);if(!G){B.set(W,j);continue}let F=GU(G).toLowerCase();if(J.indexOf(z)<J.indexOf(F))B.set(W,j)}return Array.from(B.entries()).map(([W,j])=>({base:W,file:j})).sort((W,j)=>W.base.localeCompare(j.base))}function A(){let X=Y(),J=X.map((W)=>W.base),U=J.length?J.map((W)=>`'${W}'`).join(" | "):"string",B=X.length?`{
|
|
99
|
+
${X.map((W)=>{let j=jz(w,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${j}').default`}).join(`,
|
|
100
100
|
`)}
|
|
101
101
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
102
|
-
export type ConfigByName = ${
|
|
102
|
+
export type ConfigByName = ${B}
|
|
103
103
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
104
104
|
export type ConfigOf = Config
|
|
105
|
-
`}return{name:"bunfig-plugin",setup(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:Y(),loader:"ts"}})}}}function eK($,w={}){let A=lY.cwd();while(A.includes("storage"))A=Gj(A,"..");let Y=Gj(A,$||"");if(w?.relative)return b6(lY.cwd(),Y);return Y}function R0(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wT(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof v$<"u"){let $=v$.type;if($==="renderer"||$==="worker")return!1;return!!(v$.versions&&(v$.versions.node||v$.versions.bun))}return!1}class I9{async format($){let w=await wT(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:B1.pid,hostname:w(),environment:B1.env.NODE_ENV||"development",platform:B1.platform,version:B1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:B1.env.NODE_ENV||B1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class BX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...$X},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new I9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...vJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...vJ};return{...vJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:$X.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!R0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let Y,X=0,J=3,U=1000;while(X<J)try{try{try{await m6(this.config.logDirectory,Nj.F_OK|Nj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await d6(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:b$.from($);try{if(!OY(this.currentLogFile))await xJ(this.currentLogFile,"",{mode:420});if(Y=Hj(this.currentLogFile,"a",420),v6(Y,W,{flag:"a"}),Tj(Y),Y!==void 0)ZJ(Y),Y=void 0;if((await f1(this.currentLogFile)).size===0){if(await xJ(this.currentLogFile,W,{flag:"w",mode:420}),(await f1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(X<J-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,j);let z=U*2**X;await new Promise((E)=>setTimeout(E,z)),X++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{ZJ(Y)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(W){if(X===J-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}X++;let f=U*2**(X-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return W1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return W1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return W1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(R0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.maxKeys:1,J=Math.max(1,X);if(Y.length>J)for(let[U]of Y.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return DJ(16).toString("hex")}generateKey(){return DJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=DJ(16),Y=u6("aes-256-gcm",w,A),X=b$.isBuffer($)?$:b$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=b$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=qj(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(b$.from(b$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(R0())return;if(!this.shouldWriteToFile())return;let $=await f1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await QY(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await f1(A).catch(()=>null))try{if(await Rj(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await SY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await xJ(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await f1(A).catch(()=>null))await Rj(A,J)}if(this.currentLogFile=Y,w.maxFiles){let X=(await QY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await SY(W1(this.config.logDirectory,J))}}}async compressLogFile($,w){let A=Kj($),Y=c6(w),X=qj();await l6(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),OY(this.currentLogFile))try{let $=Hj(this.currentLogFile,"r+");Tj($),ZJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!R0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await QY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await SY(W1(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||R0())return!1;let $=typeof n.env.NO_COLOR<"u",w=n.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=n.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${c.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=c.underline(c.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(A,Y)=>c.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>c.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>c.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>c.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>c.strikethrough(Y)),w}supportsHyperlinks(){if(R0())return!1;let $=n.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=n.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(g6(w)||w.startsWith("./")||w.startsWith("../"))w=n6(w);else return null;return OY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":UT[$],E=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:c.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:c.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
106
|
-
`);for(let
|
|
107
|
-
`;if(
|
|
108
|
-
`;if(
|
|
109
|
-
`);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
110
|
-
`,
|
|
111
|
-
`),
|
|
112
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
113
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!n.stdout.isTTY)return;let
|
|
114
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
105
|
+
`}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 Vf($,w={}){let Y=zX.cwd();while(Y.includes("storage"))Y=zz(Y,"..");let A=zz(Y,$||"");if(w?.relative)return WE(zX.cwd(),A);return A}function T0(){if(d$.env.NODE_ENV==="test"||d$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Cf(){if(d$.env.NODE_ENV==="test"||d$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof d$<"u"){let $=d$.type;if($==="renderer"||$==="worker")return!1;return!!(d$.versions&&(d$.versions.node||d$.versions.bun))}return!1}class f2{async format($){let w=await Cf(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:T1.pid,hostname:w(),environment:T1.env.NODE_ENV||"development",platform:T1.platform,version:T1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:T1.env.NODE_ENV||T1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class LX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...TX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new f2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...RU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...RU};return{...RU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await FE(this.config.logDirectory,Nz.F_OK|Nz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await KE(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 B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:v$.from($);try{if(!nA(this.currentLogFile))await NU(this.currentLogFile,"",{mode:420});if(A=Kz(this.currentLogFile,"a",420),GE(A,B,{flag:"a"}),Fz(A),A!==void 0)KU(A),A=void 0;if((await f1(this.currentLogFile)).size===0){if(await NU(this.currentLogFile,B,{flag:"w",mode:420}),(await f1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{KU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}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 q1(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 q1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return q1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,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 $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.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 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 $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=FU(16),A=BE("aes-256-gcm",w,Y),X=v$.isBuffer($)?$:v$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=v$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=fz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(v$.from(v$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let $=await f1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await pA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await f1(Y).catch(()=>null))try{if(await Ez(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await rA(B)}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 NU(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 Ez(Y,J)}if(this.currentLogFile=A,w.maxFiles){let X=(await pA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await rA(q1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=Gz($),A=zE(w),X=fz();await fE(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!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(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),nA(this.currentLogFile))try{let $=Kz(this.currentLogFile,"r+");Fz($),KU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await pA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await rA(q1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?m.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let $=typeof n.env.NO_COLOR<"u",w=n.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push(w);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let W=n.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${m.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,F=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(F)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),w}supportsHyperlinks(){if(T0())return!1;let $=n.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=n.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(NE(w)||w.startsWith("./")||w.startsWith("../"))w=EE(w);else return null;return nA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":Sf[$],F=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",K;switch($){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:m.gray(W),level:$}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:m.green(W),level:$}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.error(K),B){let f=B.split(`
|
|
106
|
+
`);for(let E of f)if(E.trim()&&!E.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:m.gray(` ${E}`),level:$,showTimestamp:!1}))}break}}else if(!T0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
|
|
107
|
+
`;if(B)z+=`${B}
|
|
108
|
+
`;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,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&n.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()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!T0()&&n.stdout.isTTY)n.stdout.write(`
|
|
109
|
+
`);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!T0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=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($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
|
|
110
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":m.green("✓"),tag:j,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 $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new LX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(T0())throw Error("createReadStream is not supported in browser environments");if(!nA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Gz(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=v$.isBuffer($)?$:v$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=jE("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=v$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
|
|
111
|
+
`),W=Math.max(...B.map((F)=>F.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((F)=>{return this.formatConsoleMessage({timestamp:Y,message:m.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(j),showTimestamp:!1})),G.forEach((F)=>console.error(F)),console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(z),showTimestamp:!1}))}else if(!T0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
112
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(T0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${m.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();n.stdin.removeListener("data",Y);try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!1)}catch{}n.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!0)}catch{}n.stdin.resume(),n.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,B=0;if(Y=$.replace(U,(W,j)=>{if(j==="%")return"%";if(B>=w.length)return W;let z=w[B++];switch(j){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}}),B<w.length)Y+=` ${w.slice(B).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)):"",B=this.options.showIcons===!1?"":`${m.blue("◐")} `;console.error(`${B}${U} ${m.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
113
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!n.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=m.green("━".repeat(A)),U=m.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?m.green("✓"):m.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",F=`\r${z}${G} ${B} ${W}${j}`,K=n.stdout.columns||80,f=" ".repeat(Math.max(0,K-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${f}`,n.stdout.write($.lastRenderedLine),w)n.stdout.write(`
|
|
114
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||T0()||!n.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(T0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await pA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=q1(this.config.logDirectory,A);if($.before)try{if((await f1(X)).mtime>=$.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 rA(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(w){console.error("Error during log clearing process:",w)}}}async function hf($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class sU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return mU.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=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=tA.env[W]||(j?tA.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=tA.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof aU)throw G;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($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw M1.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(tA.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
|
|
115
115
|
|
|
116
|
-
`;for(let
|
|
117
|
-
`,
|
|
118
|
-
`,
|
|
119
|
-
`,
|
|
116
|
+
`;for(let A of $)Y+=`${A.key}
|
|
117
|
+
`,Y+=` Type: ${A.type}
|
|
118
|
+
`,Y+=` Description: ${A.description}
|
|
119
|
+
`,Y+=` Example: ${A.example}
|
|
120
120
|
|
|
121
|
-
`;return
|
|
121
|
+
`;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
|
|
122
122
|
|
|
123
|
-
`;
|
|
124
|
-
`,
|
|
125
|
-
`;for(let
|
|
126
|
-
`;return A}}function WT($,w,A={}){return S9($,w,A,new WeakMap)}function S9($,w,A,Y){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=A;if(w===null||w===void 0)return J?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return _9($,w,X,Y);if(!z$(w)||!z$($))return w;return FT($,w,A,Y)}function _9($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return BT($,w);case"smart":return jT($,w,Y);default:return w}return w}function BT($,w){let A=[...w];for(let Y of $)if(!A.some((X)=>YU(X,Y)))A.push(Y);return A}function jT($,w,A){if(w.length===0)return $;if($.length===0)return w;if(z$(w[0])&&z$($[0]))return zT($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}function zT($,w,A){let Y=[...w];for(let X of $){if(!z$(X)){Y.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(Y.find((f)=>z$(f)&&(W in f)&&f[W]===X[W])){U=!0;break}}if(!U)Y.push(X)}return Y}function FT($,w,A,Y){let X=w;if(z$(X)&&Y.has(X))return Y.get(X);let J={...$};if(z$(X))Y.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],f=J[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(z$(W)&&z$(f))J[U]=S9(f,W,A,Y);else if(Array.isArray(W)||Array.isArray(f))J[U]=_9(f,W,A.arrayMergeMode||"smart",Y);else J[U]=W}return J}function k9($,w,A="replace"){return WT($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function YU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!YU($[A],w[A]))return!1;return!0}if(z$($)&&z$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!YU($[X],w[X]))return!1}return!0}return!1}function z$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class D9{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=A;if(X){let B=pY.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!kY($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,E="default"in j,F=Object.keys(j).length>0;if(!E&&!F)throw new wX($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new wX($,Error("Configuration must export a valid object"),"unknown");let T={config:k9(w,z,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)pY.setWithFileCheck("file",T,$,J);return T}catch(B){throw B instanceof Error?F1.configLoad($,B):F1.configLoad($,Error(String(B)))}};if(U)return WU.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let X=await this.loadFromPath(Y,w,A);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,X)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),X=[];for(let J of Y)for(let U of this.extensions)X.push(PJ(w,`${J}${U}`));return X}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of Y){if(!J)continue;if(A.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)A.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return A.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return fT(async()=>{return kY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!kY($))return Y;if(w||A){let X=this.generateNamePatterns(w||"",A);for(let J of X)for(let U of this.extensions){let W=PJ($,`${J}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let W=PJ($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!kY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let X=await this.loadFromPath(Y,{},w);if(X)A.set(Y,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${Y}:`,X)}})),A}}class Z9{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:f=!1}=A,B=async()=>{let j=[],z=[],E={stopOnFirstError:Y,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,E);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],E);else return this.validateWithJSONSchema($,w,E)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await WU.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!p6(w))throw new AX(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),X=Y.default||Y;if(Array.isArray(X))return this.validateWithRules($,X,A);else return this.validateWithJSONSchema($,X,A)}catch(Y){throw new AX(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],X=[];return this.validateObjectAgainstSchema($,w,"",Y,X,A),{isValid:Y.length===0,errors:Y,warnings:X}}validateObjectAgainstSchema($,w,A,Y,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,X,J),J.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],f,B,Y,X,J),J.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(U))if(!W.has(f))X.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),W=this.validateWithRule(U,J,J.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:X}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)Y.push({path:A,message:w.message||X,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let X of A)if(Y&&typeof Y==="object"&&X in Y)Y=Y[X];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,X,J,U]=Y;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ET},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function GT($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class x9{fileLoader=new D9;envProcessor=new HU;validator=new Z9;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:X,validate:J,...U}=$;try{if(A?.enabled){let f=this.checkCache(U.name||"",U);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(f){let B=U.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),E=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(E||j))throw f;if(z&&(!B||!E))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(f);if(Y.slowThreshold&&f.duration>Y.slowThreshold)u$.warn(`Slow configuration loading detected: ${f.duration}ms for ${U.name}`);W.metrics=f}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let f=Date.now()-w;throw u$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=J||UX.cwd(),E=[],F=await this.loadLocalConfiguration(Y,X,z,U,W,B,j,f,A);if(F)return E.push(...this.getLocalSearchPaths(Y,X,z,U)),this.finalizeResult(F,E,f,Y,j);let T=await this.loadHomeConfiguration(Y,X,W,B,j,f);if(T)return E.push(...this.getHomeSearchPaths(Y,X)),this.finalizeResult(T,E,f,Y,j);let K=await this.loadPackageJsonConfiguration(Y,X,z,W,B,j,f);if(K)return E.push(B$(z,"package.json")),this.finalizeResult(K,E,f,Y,j);if(E.push(...this.getAllSearchPaths(Y,X,z,U)),w)throw F1.configNotFound(Y,E,X);return{...await this.applyEnvironmentVariables(Y,W,f,j),warnings:[`No configuration file found for "${Y}"${GT(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,X,J,U,W,f){let B=W?ZY($,X,U):X,j=this.getLocalDirectories(A,Y);for(let z of j){if(U)u$.info(`Searching for configuration in: ${z}`);let E=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(E,B,{arrayStrategy:J,verbose:U,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(U)u$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,X,J){if(!$)return null;let U=J?ZY($,A,X):A,W=[B$(ew(),".config",$),B$(ew(),".config"),ew()];for(let f of W){if(X)u$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:X});if(j){if(X)u$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,Y,X,J,U){let W=U?ZY($,Y,J):Y;try{let f=B$(A,"package.json");if(!f6(f))return null;let B={};try{B=JSON.parse(W6(f,"utf8"))}catch(E){if(J)u$.warn("Failed to parse package.json:",[E instanceof Error?E:Error(String(E))]);return null}let j=B[$],z=$;if(!j&&w){let E=Array.isArray(w)?w:[w];for(let F of E){if(!F)continue;if(B[F]){j=B[F],z=F;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)u$.success(`Configuration loaded from package.json: ${z}`);return{config:k9(W,j,X),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(J)u$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:ZY($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let X=[];if(A){let J=A($);if(J)X.push(...J)}if(w){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 F1.configValidation(Y||"unknown",X,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return pY.get(A)||null}cacheResult($,w,A,Y){let X=this.generateCacheKey($,Y);pY.set(X,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,B$($,"config"),B$($,".config"),w?B$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let X=[];return X.push(...this.getLocalSearchPaths($,w,A,Y)),X.push(...this.getHomeSearchPaths($,w)),X.push(B$(A,"package.json")),X}getLocalSearchPaths($,w,A,Y){let X=this.getLocalDirectories(A,Y),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let A=[B$(ew(),".config",$),B$(ew(),".config"),ew()],Y=[];for(let X of A)Y.push(...this.fileLoader.generateConfigPaths($,X,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function ZY($,w,A=!1){let Y=new HU,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of E)if(F=UX.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=J(j,z)}return f}return J(w)}function XU($,w){let A=[];function Y(X){let J;try{J=Zj.readdirSync(X)}catch{return}for(let U of J){let W=R$.join(X,U);try{if(Zj.statSync(W).isDirectory())Y(W);else if(U===w)A.push(X)}catch{continue}}}return Y($),A}function V($,w,A){if(A||B0.verbose)console.debug(`[tlsx:${$}] ${w}`)}function u9(){return b9.env.SUDO_PASSWORD}function MT($){let w=$.toLowerCase();return RT.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function YX($){if(Array.isArray($))return $.map((A)=>YX(A));if(typeof $==="string")return qT.test($)?xj:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(MT(A)){w[A]=xj;continue}w[A]=YX(Y)}return w}function jX($){return JSON.stringify(YX($))}function IT($){let w=u9();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let A=w.replace(/'/g,"'\\''"),Y=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${A}' | ${Y}`}async function Bw($,w={}){let A=IT($);try{let{stdout:Y,stderr:X}=await NT(A,{cwd:w.cwd||b9.cwd(),timeout:w.timeout||30000});return{stdout:Y.trim(),stderr:X.trim()}}catch(Y){let X=Error(`Failed to execute command: ${$}
|
|
127
|
-
Error: ${
|
|
128
|
-
${
|
|
123
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
124
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
125
|
+
`;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
126
|
+
`;return Y}}function Zf($,w,Y={}){return y2($,w,Y,new WeakMap)}function y2($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return C2($,w,X,A);if(!B$(w)||!B$($))return w;return Pf($,w,Y,A)}function C2($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return kf($,w);case"smart":return Df($,w,A);default:return w}return w}function kf($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>PU(X,A)))Y.push(A);return Y}function Df($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(B$(w[0])&&B$($[0]))return xf($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function xf($,w,Y){let A=[...w];for(let X of $){if(!B$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((W)=>B$(W)&&(B in W)&&W[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function Pf($,w,Y,A){let X=w;if(B$(X)&&A.has(X))return A.get(X);let J={...$};if(B$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(B$(B)&&B$(W))J[U]=y2(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=C2(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function Q2($,w,Y="replace"){return Zf($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function PU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!PU($[Y],w[Y]))return!1;return!0}if(B$($)&&B$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!PU($[X],w[X]))return!1}return!0}return!1}function B$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class L2{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:B=!1}=Y;if(X){let j=GX.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!aA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,F="default"in z,K=Object.keys(z).length>0;if(!F&&!K)throw new HX($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new HX($,Error("Configuration must export a valid object"),"unknown");let f={config:Q2(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)GX.setWithFileCheck("file",f,$,J);return f}catch(j){throw j instanceof Error?M1.configLoad($,j):M1.configLoad($,Error(String(j)))}};if(U)return mU.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(EU(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return hf(async()=>{return aA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!aA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=EU($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=EU($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!aA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class O2{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],F={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,F);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],F);else return this.validateWithJSONSchema($,w,F)}catch(K){return z.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await mU.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!qE(w))throw new RX(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new RX(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:bf},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function uf($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((Y)=>`"${Y}"`).join(", ")}`}class _2{fileLoader=new L2;envProcessor=new sU;validator=new O2;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),F=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(F||z))throw W;if(G&&(!j||!F))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)i$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){if(B instanceof Error&&B.name==="ConfigNotFoundError")throw B;let W=Date.now()-w;throw i$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||yX.cwd(),F=[],K=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(K)return F.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(K,F,W,A,z);let f=await this.loadHomeConfiguration(A,X,B,j,z,W);if(f)return F.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(f,F,W,A,z);let E=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(E)return F.push(U$(G,"package.json")),this.finalizeResult(E,F,W,A,z);if(F.push(...this.getAllSearchPaths(A,X,G,U)),w)throw M1.configNotFound(A,F,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${uf(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?oA($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)i$.info(`Searching for configuration in: ${G}`);let F=this.fileLoader.generateConfigPaths($,G,w),K=await this.fileLoader.tryLoadFromPaths(F,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(K){if(U)i$.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?oA($,Y,X):Y,B=[U$(B1(),".config",$),U$(B1(),".config"),B1()];for(let W of B){if(X)i$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)i$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?oA($,A,J):A;try{let W=U$(Y,"package.json");if(!hN(W))return null;let j={};try{j=JSON.parse(ZN(W,"utf8"))}catch(F){if(J)i$.warn("Failed to parse package.json:",[F instanceof Error?F:Error(String(F))]);return null}let z=j[$],G=$;if(!z&&w){let F=Array.isArray(w)?w:[w];for(let K of F){if(!K)continue;if(j[K]){z=j[K],G=K;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)i$.success(`Configuration loaded from package.json: ${G}`);return{config:Q2(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)i$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:oA($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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($,A);GX.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,U$($,"config"),U$($,".config"),w?U$($,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(U$(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[U$(B1(),".config",$),U$(B1(),".config"),B1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function oA($,w,Y=!1){let A=new sU,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],F=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((E)=>E.toUpperCase()).join("")}`,`${X}_${G.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,f;for(let E of F)if(K=yX.env[E],K!==void 0){f=E;break}if(K!==void 0&&f)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(K.toLowerCase());else if(typeof z==="number"){let E=Number(K);if(!Number.isNaN(E))W[j]=E}else if(Array.isArray(z))try{W[j]=JSON.parse(K)}catch{W[j]=K.split(",").map((E)=>E.trim())}else W[j]=K;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function Z2($){return bU.readFileSync($,"utf8")}function uU($,w){let Y=[];function A(X){let J;try{J=bU.readdirSync(X)}catch{return}for(let U of J){let B=N$.join(X,U);try{if(bU.statSync(B).isDirectory())A(B);else if(U===w)Y.push(X)}catch{continue}}}return A($),Y}function L($,w,Y){if(Y||z0.verbose)console.debug(`[tlsx:${$}] ${w}`)}function k2(){return h2.env.SUDO_PASSWORD}function nf($){let w=$.toLowerCase();return df.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function MX($){if(Array.isArray($))return $.map((Y)=>MX(Y));if(typeof $==="string")return lf.test($)?Sz:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(nf(Y)){w[Y]=Sz;continue}w[Y]=MX(A)}return w}function OX($){return JSON.stringify(MX($))}function pf($){let w=k2();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let Y=w.replace(/'/g,"'\\''"),A=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function Gw($,w={}){let Y=pf($);try{let{stdout:A,stderr:X}=await gf(Y,{cwd:w.cwd||h2.cwd(),timeout:w.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${$}
|
|
127
|
+
Error: ${A.message}`);throw X.stack=A.stack,X}}function D2($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function oU($){let w=N$.join(vf.homedir(),".stacks","ssl"),Y=$.basePath&&$.basePath.trim()!==""?$.basePath:z0.basePath&&z0.basePath.trim()!==""?z0.basePath:w,A=$.certPath?N$.isAbsolute($.certPath)?$.certPath:N$.join(Y,$.certPath):N$.join(Y,z0.certPath),X=$.keyPath?N$.isAbsolute($.keyPath)?$.keyPath:N$.join(Y,$.keyPath):N$.join(Y,z0.keyPath),J=$.caCertPath?N$.isAbsolute($.caCertPath)?$.caCertPath:N$.join(Y,$.caCertPath):N$.join(Y,z0.caCertPath);return{certPath:A,keyPath:X,caCertPath:J,basePath:Y}}function x2($){let w=[],Y=new Set;if($.domain)Y.add($.domain);if($.domains?.length)$.domains.forEach((A)=>Y.add(A));for(let A of Y)w.push({type:2,value:A});if($.altNameIPs?.length)for(let A of $.altNameIPs)w.push({type:7,ip:A});if($.altNameURIs?.length)for(let A of $.altNameURIs)w.push({type:6,value:A});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return L(O.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function eU($){let w=$.notBeforeDays??f$.DEFAULT_NOT_BEFORE_DAYS,Y=$.validityDays??($.validityYears?$.validityYears*365:f$.DEFAULT_VALIDITY_DAYS);L(O.CERT,"Calculating certificate validity dates",$.verbose);let A=new Date(Date.now()-86400*w*1000),X=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),L(O.CERT,`Validity period: ${A.toISOString()} to ${X.toISOString()}`,$.verbose),{notBefore:A,notAfter:X}}function KY($){if($<128)return Buffer.from([$]);let w=[],Y=$;while(Y>0)w.unshift(Y&255),Y>>=8;return Buffer.from([128|w.length,...w])}function e0($,w){let Y=KY(w.length);return Buffer.concat([Buffer.from([$]),Y,w])}function TY($){let w=$.split(".").map(Number),Y=[];Y.push(40*w[0]+w[1]);for(let A=2;A<w.length;A++){let X=w[A],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;Y.push(...J)}return e0(q$.OID,Buffer.from(Y))}function cU($){let w;if(typeof $==="bigint"){let Y=$.toString(16).padStart(2,"0");w=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let Y=$.toString(16).padStart(2,"0");w=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else w=$;if(w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return e0(q$.INTEGER,w)}function P2($,w=0){return e0(q$.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function b2($){return e0(q$.OCTET_STRING,$)}function o0(...$){return e0(q$.SEQUENCE,Buffer.concat($))}function rf(...$){return e0(q$.SET,Buffer.concat($))}function tf($){return e0(q$.PRINTABLE_STRING,Buffer.from($,"ascii"))}function af($){return e0(q$.UTF8_STRING,Buffer.from($,"utf8"))}function sf(){return Buffer.from([q$.NULL,0])}function hz($,w,Y=!0){let A=160|$|(Y?0:0),X=KY(w.length);return Buffer.concat([Buffer.from([A]),X,w])}function Zz($){let w=$.getUTCFullYear();if(w>=2050){let Y=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return e0(q$.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=(w%100).toString().padStart(2,"0"),A=($.getUTCMonth()+1).toString().padStart(2,"0"),X=$.getUTCDate().toString().padStart(2,"0"),J=$.getUTCHours().toString().padStart(2,"0"),U=$.getUTCMinutes().toString().padStart(2,"0"),B=$.getUTCSeconds().toString().padStart(2,"0"),W=`${Y}${A}${X}${J}${U}${B}Z`;return e0(q$.UTC_TIME,Buffer.from(W,"ascii"))}}function of($,w){return o0(Zz($),Zz(w))}function kz($){let w=[];for(let Y of $){let A;switch(Y.shortName){case"CN":A=g0.COMMON_NAME;break;case"C":A=g0.COUNTRY;break;case"L":A=g0.LOCALITY;break;case"ST":A=g0.STATE;break;case"O":A=g0.ORGANIZATION;break;case"OU":A=g0.ORGANIZATIONAL_UNIT;break;default:continue}let X=Y.shortName==="C"?tf(Y.value):af(Y.value),J=o0(TY(A),X);w.push(rf(J))}return o0(...w)}function u2($){return o0(TY($),sf())}function ef($){return $.export({type:"spki",format:"der"})}function $q($){if($.includes(":")){let w=$;if($.includes("::")){let X=$.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],B=8-J.length-U.length,W=Array.from({length:B},()=>"0");w=[...J,...W,...U].join(":")}let Y=w.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(w)}}function wq($){let w=[];for(let Y of $)if(Y.type===2&&Y.value){let A=KY(Y.value.length);w.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=$q(Y.ip),X=KY(A.length);w.push(Buffer.concat([Buffer.from([135]),X,A]))}else if(Y.type===6&&Y.value){let A=KY(Y.value.length);w.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return o0(...w)}function Yq($,w){if($){if(w!==void 0)return o0(e0(1,Buffer.from([255])),cU(w));return o0(e0(1,Buffer.from([255])))}return o0()}function Aq($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let Y=0,A=w;while(A>0&&(A&1)===0)Y++,A>>=1;if(w===0)Y=7;return P2(Buffer.from([w]),Y)}function Xq($){let w=[];if($.serverAuth)w.push(TY(g0.SERVER_AUTH));if($.clientAuth)w.push(TY(g0.CLIENT_AUTH));return o0(...w)}function GY($,w,Y){let A=[TY($)];if(w)A.push(e0(1,Buffer.from([255])));return A.push(b2(Y)),o0(...A)}function Jq($){let w=[];if(w.push(hz(0,cU(2))),w.push(cU($.serialNumber)),w.push(u2(g0.SHA256_WITH_RSA)),w.push(kz($.issuer)),w.push(of($.notBefore,$.notAfter)),w.push(kz($.subject)),w.push(ef($.publicKey)),$.extensions){let Y=[];if($.extensions.basicConstraints)Y.push(GY(g0.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,Yq($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)Y.push(GY(g0.KEY_USAGE,$.extensions.keyUsage.critical??!0,Aq($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)Y.push(GY(g0.EXTENDED_KEY_USAGE,!1,Xq($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)Y.push(GY(g0.SUBJECT_ALT_NAME,!1,wq($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)Y.push(GY(g0.SUBJECT_KEY_IDENTIFIER,!1,b2($.extensions.subjectKeyIdentifier)));if(Y.length>0)w.push(hz(3,o0(...Y)))}return o0(...w)}function Uq($,w){let Y=I1.createSign("SHA256");Y.update($);let A=Y.sign(w);return o0($,u2(g0.SHA256_WITH_RSA),P2(A))}function Wq($,w){let Y=$.toString("base64"),A=[];for(let X=0;X<Y.length;X+=64)A.push(Y.slice(X,X+64));return`-----BEGIN ${w}-----
|
|
128
|
+
${A.join(`
|
|
129
129
|
`)}
|
|
130
130
|
-----END ${w}-----
|
|
131
|
-
`}function
|
|
132
|
-
`);for(let J of X){let[U,...W]=J.split("="),f=W.join("=");if(U&&f)Y.push({shortName:U.trim(),value:f.trim()})}return{publicKey:A,subject:Y}}async function MU($={}){V("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||M$.DEFAULT_KEY_SIZE;V("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:Y}=g9(w),X=[{shortName:"C",value:$.countryName||B0.countryName},{shortName:"ST",value:$.stateName||B0.stateName},{shortName:"L",value:$.localityName||B0.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=RU({validityYears:$.validityYears||M$.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=n9({serialNumber:qU(),notBefore:J,notAfter:U,subject:X,publicKey:Y,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:l9(A),notBefore:J,notAfter:U}}async function IU($){if(V("ca","Generating new certificate",$.verbose),V("ca",`Options: ${jX($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=iT($.rootCA.certificate),A=uT($.rootCA.privateKey);V("ca",`Generating ${M$.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let Y=M$.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=g9(Y),U=$.commonName||i9($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||B0.countryName},{shortName:"ST",value:$.stateName||B0.stateName},{shortName:"L",value:$.localityName||B0.localityName},{shortName:"O",value:$.organizationName||B0.organizationName},{shortName:"CN",value:U}],{notBefore:f,notAfter:B}=RU({validityDays:$.validityDays||M$.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),j=c9($),z=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},E=$.extKeyUsage||{serverAuth:!0},{certificate:F}=n9({serialNumber:qU(),notBefore:f,notAfter:B,subject:W,issuer:w,publicKey:J,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:z,extendedKeyUsage:E,subjectAltName:j});return{certificate:F,privateKey:l9(X),notBefore:f,notAfter:B}}function p9($,w){V(O.STORAGE,`Storing certificate and private key with options: ${jX(w)}`,w?.verbose);let{certPath:A,keyPath:Y}=NU({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});V(O.STORAGE,`Certificate path: ${A}`,w?.verbose),V(O.STORAGE,`Private key path: ${Y}`,w?.verbose);let X=UU.dirname(A);if(!m$.existsSync(X))V(O.STORAGE,`Creating certificate directory: ${X}`,w?.verbose),m$.mkdirSync(X,{recursive:!0});V(O.STORAGE,"Writing certificate file",w?.verbose),m$.writeFileSync(A,$.certificate);let J=UU.dirname(Y);if(!m$.existsSync(J))V(O.STORAGE,`Creating private key directory: ${J}`,w?.verbose),m$.mkdirSync(J,{recursive:!0});return V(O.STORAGE,"Writing private key file",w?.verbose),m$.writeFileSync(Y,$.privateKey),V(O.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function t9($,w){V(O.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=NU({basePath:w?.basePath,caCertPath:w?.caCertPath});V(O.STORAGE,`CA certificate path: ${A}`,w?.verbose);let Y=UU.dirname(A);if(!m$.existsSync(Y))V(O.STORAGE,`Creating CA certificate directory: ${Y}`,w?.verbose),m$.mkdirSync(Y,{recursive:!0});return V(O.STORAGE,"Writing CA certificate file",w?.verbose),m$.writeFileSync(A,$),V(O.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function cT($,w){if(XX.platform()!=="darwin")return!1;try{let A=ij(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return V(O.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(ij("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return V(O.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return V(O.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return V(O.TRUST,`Error checking certificate trust: ${A}`,w),!1}}async function yU($,w,A){V(O.TRUST,`Adding certificate to system trust store with options: ${jX(A)}`,A?.verbose),V(O.TRUST,"Storing certificate and private key",A?.verbose);let Y=p9($,A);V(O.TRUST,"Storing CA certificate",A?.verbose);let X=t9(w,A),J=XX.platform();V(O.TRUST,`Detected platform: ${J}`,A?.verbose);let U=gT[J];if(!U){let W=`Unsupported platform: ${J}`;throw V(O.TRUST,`Error: ${W}`,A?.verbose),Error(W)}return await U.addCertificate(X,A),V(O.TRUST,"Certificate successfully added to system trust store",A?.verbose),Y}var lG,JX,gj="https://acme-staging-v02.api.letsencrypt.org/directory",nj="https://acme-v02.api.letsencrypt.org/directory",vY,oG="1.2.840.10045.2.1",eG="1.2.840.10045.3.1.7",$6="1.2.840.10045.4.3.2",w6="2.5.4.3",A6="1.2.840.113549.1.9.14",Y6="2.5.29.17",pY,WU,t6,r6=($)=>$,s6=($,w)=>{for(var A in w)t6($,A,{get:w[A],enumerable:!0,configurable:!0,set:a6.bind(w,A)})},o6=($,w)=>()=>($&&(w=$($=0)),w),X9,E9,z1,XA,G9,hK,VK,Ij,bY,rJ,k0,r,LK,yj,OK,Cj,QK,SK,bJ,_K,hj,Vj,uJ,kK,DK,ZK,xK,uY,K9,PK,D0,bK,uK,Lj,iY,aJ,N0,b,iK,Oj,cK,Qj,vK,mK,iJ,dK,Sj,_j,gK,cJ,nK,lK,pK,tK,rK,cY,T9,aK,sK="0.15.6",$$,oY,wA,sJ,oJ,eY,eJ,$U,AA,wU,AU,jw,H9,N9,q$,d$,R9,q9,oK,$T,M9,$X,a4,h0,c,s4,AT,o4,YT,e4,$y,kj,wy,XT,JT,Ay,Dj,Yy,Xy,Jy,Uy,fy,vJ,UT,Wy,y$,y9,wX,C9,h9,TU,V9,L9,AX,O9,Q9,F1,ET,u$,By,jy,zy,P9,B0,M$,O,j1,NT,xj="[redacted]",RT,qT,I$,m0,vT,mT,dT,gT;var r9=F0(()=>{lG=nG(import.meta.url);JX=new e1;vY=class vY extends Error{problem;httpStatus;constructor($,w,A){super($);this.name="AcmeError",this.problem=w,this.httpStatus=A}};pY=new A9,WU=new Y9,t6=Object.defineProperty;X9={};s6(X9,{withErrorRecovery:()=>f9,tryLoadConfig:()=>MK,loadConfigWithResult:()=>RK,loadConfig:()=>F9,isRetryableError:()=>EK,isConfigNotFoundError:()=>FK,isBunfigError:()=>W9,globalPerformanceMonitor:()=>XA,globalCache:()=>z1,getEnvOrDefault:()=>GK,generateConfigTypes:()=>IK,defaultGeneratedDir:()=>q9,defaultConfigDir:()=>R9,deepMergeWithArrayStrategy:()=>EU,deepMerge:()=>B9,createLibraryConfig:()=>yK,config:()=>qK,bunfigPlugin:()=>CK,applyEnvVarsToConfig:()=>s1,TypeGenerationError:()=>$U,SchemaValidationError:()=>AA,PluginError:()=>AU,PerformanceMonitor:()=>jU,FileSystemError:()=>eJ,ErrorFactory:()=>jw,EnvVarError:()=>eY,EnvProcessor:()=>fX,ConfigValidator:()=>GU,ConfigValidationError:()=>sJ,ConfigNotFoundError:()=>oY,ConfigMergeError:()=>oJ,ConfigLoader:()=>KU,ConfigLoadError:()=>wA,ConfigFileLoader:()=>WX,ConfigCache:()=>BU,CacheUtils:()=>G9,BunfigError:()=>$$,BrowserConfigError:()=>wU,ArrayMergeStrategies:()=>H9});oK=o6(async()=>{E9=import.meta.require,z1=new BU,XA=new jU,G9={createKey:e6,isEquivalent:$K,estimateMemoryUsage:wK},hK=nY(pJ.cwd(),"config"),VK=nY(pJ.cwd(),"src/generated"),Ij=gY.env.CLARITY_LOG_DIR||G6(XK(),"logs"),bY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ij,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},rJ=await JK(),k0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},r=k0,LK=k0.red,yj=k0.green,OK=k0.yellow,Cj=k0.blue,QK=k0.magenta,SK=k0.cyan,bJ=k0.white,_K=k0.gray,hj=k0.bgRed,Vj=k0.bgYellow,uJ=k0.bold,kK=k0.dim,DK=k0.italic,ZK=k0.underline,xK=k0.reset,uY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},K9={debug:"\uD83D\uDD0D",info:Cj("ℹ"),success:yj("✓"),warning:Vj(bJ(uJ(" WARN "))),error:hj(bJ(uJ(" ERROR ")))},PK=new rY("stacks"),D0=new rY("bunfig",{showTags:!0}),bK=c0($A.cwd(),"config"),uK=c0($A.cwd(),"src/generated"),Lj=dY.env.CLARITY_LOG_DIR||F6(BK(),"logs"),iY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Lj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},aJ=await jK(),N0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},b=N0,iK=N0.red,Oj=N0.green,cK=N0.yellow,Qj=N0.blue,vK=N0.magenta,mK=N0.cyan,iJ=N0.white,dK=N0.gray,Sj=N0.bgRed,_j=N0.bgYellow,gK=N0.bgGray,cJ=N0.bold,nK=N0.dim,lK=N0.italic,pK=N0.underline,tK=N0.strikethrough,rK=N0.reset,cY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},T9={debug:"\uD83D\uDD0D",info:Qj("ℹ"),success:Oj("✓"),warning:_j(iJ(cJ(" WARN "))),error:Sj(iJ(cJ(" ERROR ")))},aK=new sY("stacks"),$$=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},oY=class extends $${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A?` or alias "${A}"`:"";super(`Configuration "${$}"${Y} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}},wA=class extends $${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}},sJ=class extends $${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},oJ=class extends $${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},eY=class extends $${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}},eJ=class extends $${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}},$U=class extends $${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}},AA=class extends $${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},wU=class extends $${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}},AU=class extends $${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}},jw={configNotFound($,w,A){return new oY($,w,A)},configLoad($,w,A){return new wA($,w,A)},configValidation($,w,A){return new sJ($,w,A)},configMerge($,w,A,Y){return new oJ($,w,A,Y)},envVar($,w,A,Y){return new eY($,w,A,Y)},fileSystem($,w,A){return new eJ($,w,A)},typeGeneration($,w,A){return new $U($,w,A)},schemaValidation($,w,A){return new AA($,w,A)},browserConfig($,w,A,Y){return new wU($,w,A,Y)},plugin($,w,A){return new AU($,w,A)}},H9={replace:"replace",concat:"concat",smart:"smart"},N9=/^https?:\/\//,q$=new sY("bunfig",{showTags:!0}),d$=new KU,R9=v0(Vw.cwd(),"config"),q9=v0(Vw.cwd(),"src/generated")});$T=lY.env.CLARITY_LOG_DIR||P6(eK(),"logs"),M9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$T,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},$X={...M9},a4=(async()=>{try{let{loadConfig:$}=await oK().then(()=>X9),w=await $({name:"clarity",alias:"logging",defaultConfig:M9,cwd:lY.cwd()});if(w)Object.assign($X,w)}catch{}return $X})();h0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},c=h0,s4=h0.red,AT=h0.green,o4=h0.yellow,YT=h0.blue,e4=h0.magenta,$y=h0.cyan,kj=h0.white,wy=h0.gray,XT=h0.bgRed,JT=h0.bgYellow,Ay=h0.bgGray,Dj=h0.bold,Yy=h0.dim,Xy=h0.italic,Jy=h0.underline,Uy=h0.strikethrough,fy=h0.reset,vJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},UT={debug:"\uD83D\uDD0D",info:YT("ℹ"),success:AT("✓"),warning:JT(kj(Dj(" WARN "))),error:XT(kj(Dj(" ERROR ")))};Wy=new BX("stacks");y$=class y$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};y9=class y9 extends y${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],X="";if(Y.length===1)X=` or alias "${Y[0]}"`;else if(Y.length>1)X=` or aliases ${Y.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};wX=class wX extends y${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}};C9=class C9 extends y${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};h9=class h9 extends y${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};TU=class TU extends y${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};V9=class V9 extends y${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}};L9=class L9 extends y${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}};AX=class AX extends y${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};O9=class O9 extends y${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};Q9=class Q9 extends y${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}};F1={configNotFound($,w,A){return new y9($,w,A)},configLoad($,w,A){return new wX($,w,A)},configValidation($,w,A){return new C9($,w,A)},configMerge($,w,A,Y){return new h9($,w,A,Y)},envVar($,w,A,Y){return new TU($,w,A,Y)},fileSystem($,w,A){return new V9($,w,A)},typeGeneration($,w,A){return new L9($,w,A)},schemaValidation($,w,A){return new AX($,w,A)},browserConfig($,w,A,Y){return new O9($,w,A,Y)},plugin($,w,A){return new Q9($,w,A)}};ET=/^https?:\/\//;u$=new BX("bunfig",{showTags:!0});By=new x9;jy=B$(UX.cwd(),"config"),zy=B$(UX.cwd(),"src/generated"),P9={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:IJ.join(MJ.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:IJ.join(MJ.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:IJ.join(MJ.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},B0=P9,M$={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"},O={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},j1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};NT=HT(KT);RT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),qT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;I$={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},m0={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"};vT={platform:"darwin",async addCertificate($,w){if(await cT($,w?.verbose)){V(O.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),j1.success("Certificate is already trusted in system keychain");return}V(O.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Bw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let Y=A||B0.commonName;V(O.TRUST,`Removing certificate ${Y} from macOS keychain`,w?.verbose);try{await Bw(`sudo security delete-certificate -c "${Y}" /Library/Keychains/System.keychain`),V(O.TRUST,`Removed certificate ${Y} from macOS keychain`,w?.verbose)}catch(X){throw V(O.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},mT={platform:"win32",async addCertificate($,w){V(O.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Bw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let Y=A||B0.commonName;V(O.TRUST,`Removing certificate ${Y} from Windows certificate store`,w?.verbose);try{await Bw(`certutil -delstore -enterprise Root "${Y}"`),V(O.TRUST,`Removed certificate ${Y} from Windows certificate store`,w?.verbose)}catch(X){throw V(O.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},dT={platform:"linux",async addCertificate($,w){V(O.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=XX.homedir(),Y=M$.LINUX_CERT_DB_FILENAME,X=M$.LINUX_TRUST_ARGS;V(O.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let J=XU(A,Y);if(J.length===0){j1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){V(O.TRUST,`Processing certificate database in ${U}`,w?.verbose);try{V(O.TRUST,`Attempting to delete existing cert for ${B0.commonName}`,w?.verbose),await Bw(`certutil -d sql:${U} -D -n ${B0.commonName}`)}catch(W){V(O.TRUST,`Warning: Error deleting existing cert: ${W}`,w?.verbose),console.warn(`Error deleting existing cert: ${W}`)}V(O.TRUST,`Adding new certificate to ${U}`,w?.verbose),await Bw(`certutil -d sql:${U} -A -t ${X} -n ${B0.commonName} -i ${$}`),j1.info(`Cert added to ${U}`)}},async removeCertificate($,w,A){let Y=A||B0.commonName;V(O.TRUST,`Removing certificate ${Y} from Linux certificate store`,w?.verbose);let X=XX.homedir(),J=M$.LINUX_CERT_DB_FILENAME;V(O.TRUST,`Searching for certificate databases in ${X}`,w?.verbose);let U=XU(X,J);if(U.length===0){j1.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of U){V(O.TRUST,`Processing certificate database in ${W}`,w?.verbose);try{await Bw(`certutil -d sql:${W} -D -n "${Y}"`),j1.info(`Cert removed from ${W}`)}catch(f){V(O.TRUST,`Error removing cert from ${W}: ${f}`,w?.verbose),console.warn(`Error removing cert from ${W}: ${f}`)}}}},gT={darwin:vT,win32:mT,linux:dT}});var CU=F0(()=>{r9()});import{homedir as hU}from"node:os";import{join as VU,resolve as WC}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",nT,LU;var OU=F0(()=>{HJ();nT={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:VU(hU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:VU(hU(),".stacks","ssl","stacks.localhost.crt"),keyPath:VU(hU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},LU=nT});import{execSync as a9}from"node:child_process";function s9($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function zX($){try{let w=a9(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return s9(w)}catch{return null}}function FX($,w){try{let A=a9(`openssl x509 -in "${$}" -noout -text`,{encoding:"utf8"});return w.every((Y)=>A.includes(`DNS:${Y}`))}catch{return!1}}var QU=()=>{};import{existsSync as o9,statSync as e9}from"fs";import{existsSync as tU,mkdirSync as sT,readdirSync as oT,writeFileSync as eT}from"fs";import{homedir as G1}from"os";import{dirname as $2,resolve as g0}from"path";import Lw from"process";import{join as $7,relative as w7,resolve as w2}from"path";import QX from"process";import{existsSync as b2,mkdirSync as MC,readdirSync as IC,writeFileSync as yC}from"fs";import{homedir as SU}from"os";import{dirname as VC,resolve as d0}from"path";import UA from"process";import{join as A7,relative as Y7,resolve as A2}from"path";import SX from"process";import{existsSync as u2,mkdirSync as _C,readdirSync as kC,writeFileSync as DC}from"fs";import{dirname as xC,resolve as _X}from"path";import rU from"process";import{Buffer as Fw}from"buffer";import{createCipheriv as X7,createDecipheriv as J7,randomBytes as _U}from"crypto";import{closeSync as kU,createReadStream as Y2,createWriteStream as U7,existsSync as DU,fsyncSync as X2,openSync as J2,writeFileSync as f7}from"fs";import{access as W7,constants as U2,mkdir as B7,readdir as EX,rename as f2,stat as K1,unlink as GX,writeFile as ZU}from"fs/promises";import{join as T1}from"path";import Z0 from"process";import{pipeline as j7}from"stream/promises";import{createGzip as W2}from"zlib";import H1 from"process";import l$ from"process";import{Buffer as g$}from"buffer";import{createCipheriv as z7,createDecipheriv as F7,randomBytes as xU}from"crypto";import{closeSync as PU,createReadStream as B2,createWriteStream as E7,existsSync as KX,fsyncSync as j2,openSync as z2,writeFileSync as G7}from"fs";import{access as K7,constants as F2,mkdir as T7,readdir as TX,rename as E2,stat as N1,unlink as HX,writeFile as bU}from"fs/promises";import{isAbsolute as H7,join as R1,resolve as N7}from"path";import Z from"process";import{pipeline as R7}from"stream/promises";import{createGzip as G2}from"zlib";import q1 from"process";import p$ from"process";import NX from"process";import{existsSync as RX}from"fs";import{resolve as uU}from"path";import{existsSync as q7}from"fs";import{existsSync as M7,readdirSync as I7}from"fs";import{extname as iU,resolve as K2}from"path";import y7 from"process";import{join as CH,relative as hH,resolve as L2}from"path";import uX from"process";import{Buffer as n$}from"buffer";import{createCipheriv as OH,createDecipheriv as QH,randomBytes as gU}from"crypto";import{closeSync as nU,createReadStream as O2,createWriteStream as SH,existsSync as MX,fsyncSync as Q2,openSync as S2,writeFileSync as _H}from"fs";import{access as kH,constants as _2,mkdir as DH,readdir as IX,rename as k2,stat as M1,unlink as yX,writeFile as lU}from"fs/promises";import{isAbsolute as ZH,join as I1,resolve as xH}from"path";import x from"process";import{pipeline as PH}from"stream/promises";import{createGzip as D2}from"zlib";import y1 from"process";import t$ from"process";function tT($,w){this[$]=pT.bind(null,w)}class Jf{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let X=this.generateKey($,A),J=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!o9($))return!0;return e9($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let X=o9(A)?e9(A):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,X)=>Y+X.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class Uf{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:X,...A}),J}catch(J){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...A}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((X)=>X.duration),Y=A.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function C7($,w={}){let Y=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return Y?`${$}:${Y}`:$}function h7($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function V7($){return $.getStats().size*2}function ff($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&$0(w[0])&&"id"in w[0]&&w[0].id===3&&$0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if($0(w)&&$0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if($0($)&&"arr"in $&&Array.isArray($.arr)&&$0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&$0(w[0])&&$0($[0])){let Y=[...w];for(let X of $)if($0(X)&&"name"in X){if(!Y.find((U)=>$0(U)&&("name"in U)&&U.name===X.name))Y.push(X)}else if($0(X)&&"path"in X){if(!Y.find((U)=>$0(U)&&("path"in U)&&U.path===X.path))Y.push(X)}else if(!Y.some((J)=>kX(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!$0(w)||!$0($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if($0(X)&&$0(A[Y]))A[Y]=ff(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&$0(X[0])&&$0(A[Y][0])){let J=[...X];for(let U of A[Y])if($0(U)&&"name"in U){if(!J.find((f)=>$0(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if($0(U)&&"path"in U){if(!J.find((f)=>$0(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((W)=>kX(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function kX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!kX($[A],w[A]))return!1;return!0}if($0($)&&$0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!kX($[X],w[X]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function L7($,w){if(!u2($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return ff(w,Y)}catch{return null}}catch{return null}}async function O7({name:$="",cwd:w,defaultConfig:A}){let Y=w||rU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let W of X){let f=_X(Y,`${U}${W}`),B=await L7(f,A);if(B!==null)return B}try{let U=_X(Y,"package.json");if(u2(U)){let f=(await import(U))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return ff(A,f)}catch{}}}catch{}return A}function Q7($,w={}){let A=SX.cwd();while(A.includes("storage"))A=A2(A,"..");let Y=A2(A,$||"");if(w?.relative)return Y7(SX.cwd(),Y);return Y}async function S7(){try{let $=await O7({name:"clarity",defaultConfig:hX,cwd:SX.cwd(),endpoint:"",headers:{}});return{...hX,...$}}catch{return hX}}function U0(){if(l$.env.NODE_ENV==="test"||l$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _7(){if(l$.env.NODE_ENV==="test"||l$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof l$<"u"){let $=l$.type;if($==="renderer"||$==="worker")return!1;return!!(l$.versions&&(l$.versions.node||l$.versions.bun))}return!1}class i2{async format($){let w=await _7(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:H1.pid,hostname:w(),environment:H1.env.NODE_ENV||"development",platform:H1.platform,version:H1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:H1.env.NODE_ENV||H1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class DX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...sU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new i2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??Z0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...VX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...VX};return{...VX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:sU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await W7(this.config.logDirectory,U2.F_OK|U2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await B7(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Fw.from($);try{if(!DU(this.currentLogFile))await ZU(this.currentLogFile,"",{mode:420});if(X=J2(this.currentLogFile,"a",420),f7(X,f,{flag:"a"}),X2(X),X!==void 0)kU(X),X=void 0;if((await K1(this.currentLogFile)).size===0){if(await ZU(this.currentLogFile,f,{flag:"w",mode:420}),(await K1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let E=W*2**J;await new Promise((F)=>setTimeout(F,E)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{kU(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return T1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return T1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return T1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return _U(16).toString("hex")}generateKey(){return _U(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=_U(16),Y=X7("aes-256-gcm",w,A),X=Fw.concat([Y.update($,"utf8"),Y.final()]),J=Y.getAuthTag();return{encrypted:Fw.concat([A,X,J]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=W2(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(Fw.from(Fw.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(U0())return;let $=await K1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await EX(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await K1(A).catch(()=>null))try{if(await f2(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await GX(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await ZU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await K1(A).catch(()=>null))await f2(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await EX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await GX(T1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=Y2($),Y=U7(w),X=W2();await j7(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),DU(this.currentLogFile))try{let $=J2(this.currentLogFile,"r+");X2($),kU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await EX(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await GX(T1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?a.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=Z0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${a.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!U0()){let B=r2[$],j=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:a.gray(U),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:a.green(U),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z),W){let E=W.split(`
|
|
133
|
-
`);for(let
|
|
134
|
-
`;if(W)f+=`${W}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||U0()||!Z0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await EX(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let J=T1(this.config.logDirectory,Y);if($.before)try{if((await K1(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}A.push(J)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await GX(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function CX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let Y=[...w];for(let X of $)if(p(X)&&"name"in X){if(!Y.find((U)=>p(U)&&("name"in U)&&U.name===X.name))Y.push(X)}else if(p(X)&&"path"in X){if(!Y.find((U)=>p(U)&&("path"in U)&&U.path===X.path))Y.push(X)}else if(!Y.some((J)=>ZX(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!p(w)||!p($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if(p(X)&&p(A[Y]))A[Y]=CX(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&p(X[0])&&p(A[Y][0])){let J=[...X];for(let U of A[Y])if(p(U)&&"name"in U){if(!J.find((f)=>p(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((f)=>p(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((W)=>ZX(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function Wf($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:CX($,w);if(Array.isArray($))return A==="replace"?w:CX($,w);if(!p(w)||!p($))return w;let Y={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[X],U=Y[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(A==="replace")Y[X]=J;else Y[X]=CX(U,J);else if(p(J)&&p(U))Y[X]=Wf(U,J,A);else Y[X]=J}return Y}function ZX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!ZX($[A],w[A]))return!1;return!0}if(p($)&&p(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!ZX($[X],w[X]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function qX($,w,A="replace"){if(!b2($))return null;try{let Y=await import($),X=Y.default||Y;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return Wf(w,X,A)}catch{return null}}catch{return null}}function k7($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${z.map(E).join("_")}`,T=`${Y}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(A)P0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=J(j,z);else{let K=UA.env[F]||UA.env[T];if(K!==void 0){if(A)P0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((N)=>N.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return J(X)}async function D7({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let f=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?k7($,X,J):X,B=A||UA.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)P0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),E=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,d0(B,"config"),d0(B,".config"),Y?d0(B,Y):void 0].filter(Boolean)));for(let H of K){if(J)P0.info(`Searching for configuration in: ${H}`);let R=[d0(B,"config"),d0(B,".config")].concat(Y?[d0(B,Y)]:[]).includes(H)?[...z,...E,...F,...T]:[...E,...z,...T,...F];for(let M of R)for(let y of j){let I=d0(H,`${M}${y}`),C=await qX(I,f,W);if(C!==null){if(J)P0.success(`Configuration loaded from: ${I}`);return C}}}if($){let H=d0(SU(),".config",$),N=["config",`${$}.config`];if(w)N.push(`${w}.config`);if(J)P0.info(`Checking user config directory: ${H}`);for(let R of N)for(let M of j){let y=d0(H,`${R}${M}`),I=await qX(y,f,W);if(I!==null){if(J)P0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let H=d0(SU(),".config"),N=[`.${$}.config`];if(w)N.push(`.${w}.config`);if(J)P0.info(`Checking user config directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=d0(H,`${R}${M}`),I=await qX(y,f,W);if(I!==null){if(J)P0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let H=SU(),N=[`.${$}.config`,`.${$}`];if(w)N.push(`.${w}.config`),N.push(`.${w}`);if(J)P0.info(`Checking user home directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=d0(H,`${R}${M}`),I=await qX(y,f,W);if(I!==null){if(J)P0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let H=d0(B,"package.json");if(b2(H)){let N=await import(H),R=N[$];if(!R&&w){if(R=N[w],R&&J)P0.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)P0.success(`Configuration loaded from package.json: ${R===N[$]?$:w}`);return Wf(f,R,W)}catch(M){if(J)P0.warn("Failed to merge package.json config:",M)}}}catch(H){if(J)P0.warn("Failed to load package.json:",H)}if(J)P0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function Z7($,w={}){let A=QX.cwd();while(A.includes("storage"))A=w2(A,"..");let Y=w2(A,$||"");if(w?.relative)return w7(QX.cwd(),Y);return Y}async function x7(){try{let $=await D7({name:"clarity",alias:"logging",defaultConfig:LX,cwd:QX.cwd()});return{...LX,...$||{}}}catch{return LX}}function q0(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function P7(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p$<"u"){let $=p$.type;if($==="renderer"||$==="worker")return!1;return!!(p$.versions&&(p$.versions.node||p$.versions.bun))}return!1}class c2{async format($){let w=await P7(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:q1.pid,hostname:w(),environment:q1.env.NODE_ENV||"development",platform:q1.platform,version:q1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:q1.env.NODE_ENV||q1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...oU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new c2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...OX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...OX};return{...OX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:oU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await K7(this.config.logDirectory,F2.F_OK|F2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await T7(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:g$.from($);try{if(!KX(this.currentLogFile))await bU(this.currentLogFile,"",{mode:420});if(X=z2(this.currentLogFile,"a",420),G7(X,f,{flag:"a"}),j2(X),X!==void 0)PU(X),X=void 0;if((await N1(this.currentLogFile)).size===0){if(await bU(this.currentLogFile,f,{flag:"w",mode:420}),(await N1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let E=W*2**J;await new Promise((F)=>setTimeout(F,E)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{PU(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return R1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return R1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return R1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return xU(16).toString("hex")}generateKey(){return xU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=xU(16),Y=z7("aes-256-gcm",w,A),X=g$.isBuffer($)?$:g$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=g$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=G2(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(g$.from(g$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let $=await N1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await TX(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await N1(A).catch(()=>null))try{if(await E2(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await HX(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await bU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await N1(A).catch(()=>null))await E2(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await TX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await HX(R1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=B2($),Y=E7(w),X=G2();await R7(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),KX(this.currentLogFile))try{let $=z2(this.currentLogFile,"r+");j2($),PU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await TX(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await HX(R1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?u.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let $=typeof Z.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=Z.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${u.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=u.underline(u.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(A,Y)=>u.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>u.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>u.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>u.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>u.strikethrough(Y)),w}supportsHyperlinks(){if(q0())return!1;let $=Z.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=Z.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(H7(w)||w.startsWith("./")||w.startsWith("../"))w=N7(w);else return null;return KX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":a2[$],E=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:u.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:u.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
141
|
-
|
|
142
|
-
`;if(W)j+=`${W}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
`)
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
131
|
+
`}function $W(){let $=I1.randomBytes(20);return $[0]=$[0]&127||1,$}function c2($=2048){let{privateKey:w,publicKey:Y}=I1.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:Y}}function Bq($){let w=$.export({type:"spki",format:"der"});return I1.createHash("sha1").update(w).digest()}function v2($){let w={serialNumber:$.serialNumber||$W(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:Bq($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let Y=Jq(w),A=Uq(Y,$.signingKey);return{certificate:Wq(A,"CERTIFICATE"),certificateDer:A}}function i2($){return $.export({type:"pkcs8",format:"pem"})}function jq($){return I1.createPrivateKey($)}function zq($){let w=new I1.X509Certificate($),Y=w.publicKey,A=[],X=w.subject.split(`
|
|
132
|
+
`);for(let J of X){let[U,...B]=J.split("="),W=B.join("=");if(U&&W)A.push({shortName:U.trim(),value:W.trim()})}return{publicKey:Y,subject:A}}async function wW($={}){L("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||f$.DEFAULT_KEY_SIZE;L("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:Y,publicKey:A}=c2(w),X=[{shortName:"C",value:$.countryName||z0.countryName},{shortName:"ST",value:$.stateName||z0.stateName},{shortName:"L",value:$.localityName||z0.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=eU({validityYears:$.validityYears||f$.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:B}=v2({serialNumber:$W(),notBefore:J,notAfter:U,subject:X,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:B,privateKey:i2(Y),notBefore:J,notAfter:U}}async function YW($){if(L("ca","Generating new certificate",$.verbose),L("ca",`Options: ${OX($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=zq($.rootCA.certificate),Y=jq($.rootCA.privateKey);L("ca",`Generating ${f$.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let A=f$.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=c2(A),U=$.commonName||D2($),B=$.certificateAttributes||[{shortName:"C",value:$.countryName||z0.countryName},{shortName:"ST",value:$.stateName||z0.stateName},{shortName:"L",value:$.localityName||z0.localityName},{shortName:"O",value:$.organizationName||z0.organizationName},{shortName:"CN",value:U}],{notBefore:W,notAfter:j}=eU({validityDays:$.validityDays||f$.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),z=x2($),G=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},F=$.extKeyUsage||{serverAuth:!0},{certificate:K}=v2({serialNumber:$W(),notBefore:W,notAfter:j,subject:B,issuer:w,publicKey:J,signingKey:Y,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:G,extendedKeyUsage:F,subjectAltName:z});return{certificate:K,privateKey:i2(X),notBefore:W,notAfter:j}}function m2($,w){L(O.STORAGE,`Storing certificate and private key with options: ${OX(w)}`,w?.verbose);let{certPath:Y,keyPath:A}=oU({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});L(O.STORAGE,`Certificate path: ${Y}`,w?.verbose),L(O.STORAGE,`Private key path: ${A}`,w?.verbose);let X=vU.dirname(Y);if(!l$.existsSync(X))L(O.STORAGE,`Creating certificate directory: ${X}`,w?.verbose),l$.mkdirSync(X,{recursive:!0});L(O.STORAGE,"Writing certificate file",w?.verbose),l$.writeFileSync(Y,$.certificate);let J=vU.dirname(A);if(!l$.existsSync(J))L(O.STORAGE,`Creating private key directory: ${J}`,w?.verbose),l$.mkdirSync(J,{recursive:!0});return L(O.STORAGE,"Writing private key file",w?.verbose),l$.writeFileSync(A,$.privateKey),L(O.STORAGE,"Certificate and private key stored successfully",w?.verbose),Y}function g2($,w){L(O.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:Y}=oU({basePath:w?.basePath,caCertPath:w?.caCertPath});L(O.STORAGE,`CA certificate path: ${Y}`,w?.verbose);let A=vU.dirname(Y);if(!l$.existsSync(A))L(O.STORAGE,`Creating CA certificate directory: ${A}`,w?.verbose),l$.mkdirSync(A,{recursive:!0});return L(O.STORAGE,"Writing CA certificate file",w?.verbose),l$.writeFileSync(Y,$),L(O.STORAGE,"CA certificate stored successfully",w?.verbose),Y}function _X($){let w;if($.startsWith("-----BEGIN CERTIFICATE-----"))w=$;else w=Z2($);return new Gq.X509Certificate(w)}function SX($){return _X($).fingerprint256.replace(/:/g,"").toUpperCase()}function AW($){return d2(_X($).subject)}function Fq($){let w=[],Y=$.split(`
|
|
133
|
+
`);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)w.push({shortName:X.trim(),value:U.trim()})}return w}function d2($){return Fq($).find((w)=>w.shortName==="CN")?.value||""}function Kq($){let w=[],Y=d2($.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))w.push(Y);let A=$.subjectAltName;if(A){let X=A.split(", ");for(let J of X)if(J.startsWith("DNS:"))w.push(J.slice(4))}return[...new Set(w)]}function XW($,w){let Y=_X($),A=Kq(Y);for(let X of A){if(X===w)return!0;if(X.startsWith("*.")){let J=X.slice(2);if(w.endsWith(J)&&w.indexOf(".")===w.lastIndexOf("."))return!0}}return!1}async function Eq($,w){if(IX.platform()!=="darwin")return!1;try{let Y=SX($);if(!Y)return L(O.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(Nq("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
134
|
+
`).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return L(O.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return L(O.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(Y){return L(O.TRUST,`Error checking certificate trust: ${Y}`,w),!1}}async function JW($,w,Y){L(O.TRUST,`Adding certificate to system trust store with options: ${OX(Y)}`,Y?.verbose),L(O.TRUST,"Storing certificate and private key",Y?.verbose);let A=m2($,Y);L(O.TRUST,"Storing CA certificate",Y?.verbose);let X=g2(w,Y),J=IX.platform();L(O.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=Hq[J];if(!U){let B=`Unsupported platform: ${J}`;throw L(O.TRUST,`Error: ${B}`,Y?.verbose),Error(B)}return await U.addCertificate(X,Y),L(O.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var fN,VX,uz="https://acme-staging-v02.api.letsencrypt.org/directory",cz="https://acme-v02.api.letsencrypt.org/directory",JX,IN="1.2.840.10045.2.1",VN="1.2.840.10045.3.1.7",yN="1.2.840.10045.4.3.2",CN="2.5.4.3",QN="1.2.840.113549.1.9.14",LN="2.5.29.17",GX,mU,TE,HE=($)=>$,ME=($,w)=>{for(var Y in w)TE($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:RE.bind(w,Y)})},IE=($,w)=>()=>($&&(w=$($=0)),w),oz,W2,R1,HY,B2,tE,aE,Tz,wX,OU,S0,a,sE,Hz,oE,Rz,eE,$f,fU,wf,Mz,Iz,qU,Yf,Af,Xf,Jf,YX,j2,Uf,h0,Wf,Bf,Vz,AX,_U,q0,c,jf,yz,zf,Cz,Gf,Ff,TU,Kf,Qz,Lz,Nf,HU,Ef,ff,qf,Tf,Hf,XX,z2,Rf,Mf="0.15.6",s0,fX,fY,SU,hU,qX,ZU,kU,qY,DU,xU,Fw,G2,F2,E$,n$,K2,N2,If,yf,E2,TX,BC,V0,m,jC,Qf,zC,Lf,GC,FC,Oz,KC,Of,_f,NC,_z,EC,fC,qC,TC,HC,RU,Sf,RC,T$,q2,HX,T2,H2,aU,R2,M2,RX,I2,V2,M1,bf,i$,MC,IC,VC,S2,z0,f$,O,H1,gf,Sz="[redacted]",df,lf,q$,g0,fq,qq,Tq,Hq;var l2=o(()=>{fN=EN(import.meta.url);VX=new NY;JX=class JX extends Error{problem;httpStatus;constructor($,w,Y){super($);this.name="AcmeError",this.problem=w,this.httpStatus=Y}};GX=new az,mU=new sz,TE=Object.defineProperty;oz={};ME(oz,{withErrorRecovery:()=>w2,tryLoadConfig:()=>lE,loadConfigWithResult:()=>gE,loadConfig:()=>U2,isRetryableError:()=>bE,isConfigNotFoundError:()=>PE,isBunfigError:()=>Y2,globalPerformanceMonitor:()=>HY,globalCache:()=>R1,getEnvOrDefault:()=>uE,generateConfigTypes:()=>nE,defaultGeneratedDir:()=>N2,defaultConfigDir:()=>K2,deepMergeWithArrayStrategy:()=>pU,deepMerge:()=>A2,createLibraryConfig:()=>pE,config:()=>dE,bunfigPlugin:()=>rE,applyEnvVarsToConfig:()=>FY,TypeGenerationError:()=>kU,SchemaValidationError:()=>qY,PluginError:()=>xU,PerformanceMonitor:()=>dU,FileSystemError:()=>ZU,ErrorFactory:()=>Fw,EnvVarError:()=>qX,EnvProcessor:()=>CX,ConfigValidator:()=>rU,ConfigValidationError:()=>SU,ConfigNotFoundError:()=>fX,ConfigMergeError:()=>hU,ConfigLoader:()=>tU,ConfigLoadError:()=>fY,ConfigFileLoader:()=>QX,ConfigCache:()=>gU,CacheUtils:()=>B2,BunfigError:()=>s0,BrowserConfigError:()=>DU,ArrayMergeStrategies:()=>G2});If=IE(async()=>{W2=import.meta.require,R1=new gU,HY=new dU,B2={createKey:VE,isEquivalent:yE,estimateMemoryUsage:CE},tE=jX(QU.cwd(),"config"),aE=jX(QU.cwd(),"src/generated"),Tz=BX.env.CLARITY_LOG_DIR||uN(OE(),"logs"),wX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Tz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},OU=await _E(),S0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},a=S0,sE=S0.red,Hz=S0.green,oE=S0.yellow,Rz=S0.blue,eE=S0.magenta,$f=S0.cyan,fU=S0.white,wf=S0.gray,Mz=S0.bgRed,Iz=S0.bgYellow,qU=S0.bold,Yf=S0.dim,Af=S0.italic,Xf=S0.underline,Jf=S0.reset,YX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},j2={debug:"\uD83D\uDD0D",info:Rz("ℹ"),success:Hz("✓"),warning:Iz(fU(qU(" WARN "))),error:Mz(fU(qU(" ERROR ")))},Uf=new KX("stacks"),h0=new KX("bunfig",{showTags:!0}),Wf=i0(EY.cwd(),"config"),Bf=i0(EY.cwd(),"src/generated"),Vz=WX.env.CLARITY_LOG_DIR||PN(kE(),"logs"),AX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Vz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},_U=await DE(),q0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},c=q0,jf=q0.red,yz=q0.green,zf=q0.yellow,Cz=q0.blue,Gf=q0.magenta,Ff=q0.cyan,TU=q0.white,Kf=q0.gray,Qz=q0.bgRed,Lz=q0.bgYellow,Nf=q0.bgGray,HU=q0.bold,Ef=q0.dim,ff=q0.italic,qf=q0.underline,Tf=q0.strikethrough,Hf=q0.reset,XX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},z2={debug:"\uD83D\uDD0D",info:Cz("ℹ"),success:yz("✓"),warning:Lz(TU(HU(" WARN "))),error:Qz(TU(HU(" ERROR ")))},Rf=new EX("stacks"),s0=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},fX=class extends s0{code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${$}"${A} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}},fY=class extends s0{code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}},SU=class extends s0{code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},hU=class extends s0{code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},qX=class extends s0{code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}},ZU=class extends s0{code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},kU=class extends s0{code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},qY=class extends s0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},DU=class extends s0{code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}},xU=class extends s0{code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Fw={configNotFound($,w,Y){return new fX($,w,Y)},configLoad($,w,Y){return new fY($,w,Y)},configValidation($,w,Y){return new SU($,w,Y)},configMerge($,w,Y,A){return new hU($,w,Y,A)},envVar($,w,Y,A){return new qX($,w,Y,A)},fileSystem($,w,Y){return new ZU($,w,Y)},typeGeneration($,w,Y){return new kU($,w,Y)},schemaValidation($,w,Y){return new qY($,w,Y)},browserConfig($,w,Y,A){return new DU($,w,Y,A)},plugin($,w,Y){return new xU($,w,Y)}},G2={replace:"replace",concat:"concat",smart:"smart"},F2=/^https?:\/\//,E$=new EX("bunfig",{showTags:!0}),n$=new tU,K2=m0(hw.cwd(),"config"),N2=m0(hw.cwd(),"src/generated")});yf=zX.env.CLARITY_LOG_DIR||UE(Vf(),"logs"),E2={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},TX={...E2},BC=(async()=>{try{let{loadConfig:$}=await If().then(()=>oz),w=await $({name:"clarity",alias:"logging",defaultConfig:E2,cwd:zX.cwd()});if(w)Object.assign(TX,w)}catch{}return TX})();V0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},m=V0,jC=V0.red,Qf=V0.green,zC=V0.yellow,Lf=V0.blue,GC=V0.magenta,FC=V0.cyan,Oz=V0.white,KC=V0.gray,Of=V0.bgRed,_f=V0.bgYellow,NC=V0.bgGray,_z=V0.bold,EC=V0.dim,fC=V0.italic,qC=V0.underline,TC=V0.strikethrough,HC=V0.reset,RU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Sf={debug:"\uD83D\uDD0D",info:Lf("ℹ"),success:Qf("✓"),warning:_f(Oz(_z(" WARN "))),error:Of(Oz(_z(" ERROR ")))};RC=new LX("stacks");T$=class T$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};q2=class q2 extends T${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 "${$}"${X} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};HX=class HX extends T${code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}};T2=class T2 extends T${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};H2=class H2 extends T${code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};aU=class aU extends T${code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}};R2=class R2 extends T${code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};M2=class M2 extends T${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};RX=class RX extends T${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};I2=class I2 extends T${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};V2=class V2 extends T${code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};M1={configNotFound($,w,Y){return new q2($,w,Y)},configLoad($,w,Y){return new HX($,w,Y)},configValidation($,w,Y){return new T2($,w,Y)},configMerge($,w,Y,A){return new H2($,w,Y,A)},envVar($,w,Y,A){return new aU($,w,Y,A)},fileSystem($,w,Y){return new R2($,w,Y)},typeGeneration($,w,Y){return new M2($,w,Y)},schemaValidation($,w,Y){return new RX($,w,Y)},browserConfig($,w,Y,A){return new I2($,w,Y,A)},plugin($,w,Y){return new V2($,w,Y)}};bf=/^https?:\/\//;i$=new LX("bunfig",{showTags:!0});MC=new _2;IC=U$(yX.cwd(),"config"),VC=U$(yX.cwd(),"src/generated"),S2={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:wU.join($U.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:wU.join($U.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:wU.join($U.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},z0=S2,f$={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"},O={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},H1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};gf=mf(cf);df=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),lf=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;q$={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},g0={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"};fq={platform:"darwin",async addCertificate($,w){if(await Eq($,w?.verbose)){L(O.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),H1.success("Certificate is already trusted in system keychain");return}L(O.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Gw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,Y){let A=Y||z0.commonName;L(O.TRUST,`Removing certificate ${A} from macOS keychain`,w?.verbose);try{await Gw(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),L(O.TRUST,`Removed certificate ${A} from macOS keychain`,w?.verbose)}catch(X){throw L(O.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},qq={platform:"win32",async addCertificate($,w){L(O.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Gw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,Y){let A=Y||z0.commonName;L(O.TRUST,`Removing certificate ${A} from Windows certificate store`,w?.verbose);try{await Gw(`certutil -delstore -enterprise Root "${A}"`),L(O.TRUST,`Removed certificate ${A} from Windows certificate store`,w?.verbose)}catch(X){throw L(O.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},Tq={platform:"linux",async addCertificate($,w){L(O.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let Y=IX.homedir(),A=f$.LINUX_CERT_DB_FILENAME,X=f$.LINUX_TRUST_ARGS;L(O.TRUST,`Searching for certificate databases in ${Y}`,w?.verbose);let J=uU(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){L(O.TRUST,`Processing certificate database in ${U}`,w?.verbose);try{L(O.TRUST,`Attempting to delete existing cert for ${z0.commonName}`,w?.verbose),await Gw(`certutil -d sql:${U} -D -n ${z0.commonName}`)}catch(B){L(O.TRUST,`Warning: Error deleting existing cert: ${B}`,w?.verbose),console.warn(`Error deleting existing cert: ${B}`)}L(O.TRUST,`Adding new certificate to ${U}`,w?.verbose),await Gw(`certutil -d sql:${U} -A -t ${X} -n ${z0.commonName} -i ${$}`),H1.info(`Cert added to ${U}`)}},async removeCertificate($,w,Y){let A=Y||z0.commonName;L(O.TRUST,`Removing certificate ${A} from Linux certificate store`,w?.verbose);let X=IX.homedir(),J=f$.LINUX_CERT_DB_FILENAME;L(O.TRUST,`Searching for certificate databases in ${X}`,w?.verbose);let U=uU(X,J);if(U.length===0){H1.warn("No certificate databases found. Cannot remove certificate.");return}for(let B of U){L(O.TRUST,`Processing certificate database in ${B}`,w?.verbose);try{await Gw(`certutil -d sql:${B} -D -n "${A}"`),H1.info(`Cert removed from ${B}`)}catch(W){L(O.TRUST,`Error removing cert from ${B}: ${W}`,w?.verbose),console.warn(`Error removing cert from ${B}: ${W}`)}}}},Hq={darwin:fq,win32:qq,linux:Tq}});var hX=o(()=>{l2()});import{homedir as UW}from"node:os";import{join as WW,resolve as T3}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Mq,BW;var jW=o(()=>{pJ();Mq={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:WW(UW(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:WW(UW(),".stacks","ssl","stacks.localhost.crt"),keyPath:WW(UW(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},BW=Mq});function Zw($){try{return SX($)}catch{return null}}function zW($){try{return AW($)||null}catch{return null}}function ZX($,w){try{return w.every((Y)=>XW($,Y))}catch{return!1}}var kX=o(()=>{hX()});import{existsSync as n2,statSync as p2}from"fs";import{existsSync as _W,mkdirSync as Lq,readdirSync as Oq,writeFileSync as _q}from"fs";import{homedir as V1}from"os";import{dirname as r2,resolve as l0}from"path";import kw from"process";import{join as Sq,relative as hq,resolve as t2}from"path";import aX from"process";import{existsSync as hG,mkdirSync as h3,readdirSync as Z3,writeFileSync as k3}from"fs";import{homedir as GW}from"os";import{dirname as P3,resolve as d0}from"path";import MY from"process";import{join as Zq,relative as kq,resolve as a2}from"path";import sX from"process";import{existsSync as ZG,mkdirSync as i3,readdirSync as m3,writeFileSync as g3}from"fs";import{dirname as l3,resolve as oX}from"path";import SW from"process";import{Buffer as Nw}from"buffer";import{createCipheriv as Dq,createDecipheriv as xq,randomBytes as FW}from"crypto";import{closeSync as KW,createReadStream as s2,createWriteStream as Pq,existsSync as NW,fsyncSync as o2,openSync as e2,writeFileSync as bq}from"fs";import{access as uq,constants as $G,mkdir as cq,readdir as DX,rename as wG,stat as y1,unlink as xX,writeFile as EW}from"fs/promises";import{join as C1}from"path";import Z0 from"process";import{pipeline as vq}from"stream/promises";import{createGzip as YG}from"zlib";import Q1 from"process";import t$ from"process";import{Buffer as p$}from"buffer";import{createCipheriv as iq,createDecipheriv as mq,randomBytes as fW}from"crypto";import{closeSync as qW,createReadStream as AG,createWriteStream as gq,existsSync as PX,fsyncSync as XG,openSync as JG,writeFileSync as dq}from"fs";import{access as lq,constants as UG,mkdir as nq,readdir as bX,rename as WG,stat as L1,unlink as uX,writeFile as TW}from"fs/promises";import{isAbsolute as pq,join as O1,resolve as rq}from"path";import x from"process";import{pipeline as tq}from"stream/promises";import{createGzip as BG}from"zlib";import _1 from"process";import a$ from"process";import cX from"process";import{existsSync as vX}from"fs";import{resolve as HW}from"path";import{existsSync as aq}from"fs";import{existsSync as sq,readdirSync as oq}from"fs";import{extname as RW,resolve as jG}from"path";import eq from"process";import{join as $H,relative as wH,resolve as MG}from"path";import J8 from"process";import{Buffer as r$}from"buffer";import{createCipheriv as XH,createDecipheriv as JH,randomBytes as CW}from"crypto";import{closeSync as QW,createReadStream as IG,createWriteStream as UH,existsSync as mX,fsyncSync as VG,openSync as yG,writeFileSync as WH}from"fs";import{access as BH,constants as CG,mkdir as jH,readdir as gX,rename as QG,stat as S1,unlink as dX,writeFile as LW}from"fs/promises";import{isAbsolute as zH,join as h1,resolve as GH}from"path";import P from"process";import{pipeline as FH}from"stream/promises";import{createGzip as LG}from"zlib";import Z1 from"process";import s$ from"process";function yq($,w){this[$]=Vq.bind(null,w)}class vW{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!n2($))return!0;return p2($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=n2(Y)?p2(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class iW{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function $T($,w={}){let A=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return A?`${$}:${A}`:$}function wT($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function YT($){return $.getStats().size*2}function mW($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&Y0(w[0])&&"id"in w[0]&&w[0].id===3&&Y0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(Y0(w)&&Y0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(Y0($)&&"arr"in $&&Array.isArray($.arr)&&Y0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&Y0(w[0])&&Y0($[0])){let A=[...w];for(let X of $)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)=>eX(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!Y0(w)||!Y0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(Y0(X)&&Y0(Y[A]))Y[A]=mW(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((B)=>eX(B,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 eX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!eX($[Y],w[Y]))return!1;return!0}if(Y0($)&&Y0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!eX($[X],w[X]))return!1}return!0}return!1}function Y0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function AT($,w){if(!ZG($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return mW(w,A)}catch{return null}}catch{return null}}async function XT({name:$="",cwd:w,defaultConfig:Y}){let A=w||SW.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=oX(A,`${U}${B}`),j=await AT(W,Y);if(j!==null)return j}try{let U=oX(A,"package.json");if(ZG(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return mW(Y,W)}catch{}}}catch{}return Y}function JT($,w={}){let Y=sX.cwd();while(Y.includes("storage"))Y=a2(Y,"..");let A=a2(Y,$||"");if(w?.relative)return kq(sX.cwd(),A);return A}async function UT(){try{let $=await XT({name:"clarity",defaultConfig:nX,cwd:sX.cwd(),endpoint:"",headers:{}});return{...nX,...$}}catch{return nX}}function B0(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function WT(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t$<"u"){let $=t$.type;if($==="renderer"||$==="worker")return!1;return!!(t$.versions&&(t$.versions.node||t$.versions.bun))}return!1}class kG{async format($){let w=await WT(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Q1.pid,hostname:w(),environment:Q1.env.NODE_ENV||"development",platform:Q1.platform,version:Q1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Q1.env.NODE_ENV||Q1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $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=$,this.config={...ZW},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new kG,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??Z0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...pX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...pX};return{...pX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:ZW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await uq(this.config.logDirectory,$G.F_OK|$G.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await cq(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Nw.from($);try{if(!NW(this.currentLogFile))await EW(this.currentLogFile,"",{mode:420});if(X=e2(this.currentLogFile,"a",420),bq(X,W,{flag:"a"}),o2(X),X!==void 0)KW(X),X=void 0;if((await y1(this.currentLogFile)).size===0){if(await EW(this.currentLogFile,W,{flag:"w",mode:420}),(await y1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let F=B*2**J;await new Promise((K)=>setTimeout(K,F)),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(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 C1(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 C1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return C1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(B0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.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 w=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(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return FW(16).toString("hex")}generateKey(){return FW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=FW(16),A=Dq("aes-256-gcm",w,Y),X=Nw.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:Nw.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=YG(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(Nw.from(Nw.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(B0())return;let $=await y1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let 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,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await y1(Y).catch(()=>null))try{if(await wG(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await xX(B)}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 EW(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 wG(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await DX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await xX(C1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=s2($),A=Pq(w),X=YG();await vq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!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(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),NW(this.currentLogFile))try{let $=e2(this.currentLogFile,"r+");o2($),KW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!B0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await DX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await xX(C1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?s.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push(w);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let W=Z0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${s.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,F=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(F)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.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,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!B0()){let j=gG[$],z=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:s.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:s.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let F=B.split(`
|
|
135
|
+
`);for(let K of F)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:s.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!B0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let W=`${J} ${this.environment}.${$.toUpperCase()}: ${U}
|
|
136
|
+
`;if(B)W+=`${B}
|
|
137
|
+
`;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time($){let w=performance.now();if(this.fancy&&!B0()){let Y=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:s.blue("◐"),tag:Y,message:`${s.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
|
|
138
|
+
`,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!B0()){let z=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:s.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!B0())console.error(j.trim());await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new $8(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(B0())throw Error("createReadStream is not supported in browser environments");if(!NW(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return s2(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Nw.isBuffer($)?$:Nw.from($,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),B=xq("aes-256-gcm",Y,X);return B.setAuthTag(J),Nw.concat([B.update(U),B.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 B0()}isServerMode(){return!B0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!B0()){let J=$.split(`
|
|
139
|
+
`),U=Math.max(...J.map((z)=>z.length))+2,B=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,j=J.map((z)=>{let G=" ".repeat(U-z.length-2);return`│ ${z}${G} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:s.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(B)})),j.forEach((z)=>console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(z),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(W),showTimestamp:!1}))}else if(!B0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let X=`${A} ${this.environment}.INFO: [BOX] ${$}
|
|
140
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(B0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${s.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();Z0.stdin.removeListener("data",Y);try{if(typeof Z0.stdin.setRawMode==="function")Z0.stdin.setRawMode(!1)}catch{}Z0.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof Z0.stdin.setRawMode==="function")Z0.stdin.setRawMode(!0)}catch{}Z0.stdin.resume(),Z0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,B=0;if(Y=$.replace(U,(W,j)=>{if(j==="%")return"%";if(B>=w.length)return W;let z=w[B++];switch(j){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}}),B<w.length)Y+=` ${w.slice(B).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!B0()){let U=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",B=s.blue("◐");console.error(`${B} ${U} ${s.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
141
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||B0()||$<=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:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,B)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),B!==void 0)this.activeProgressBar.message=B;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B0())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,B="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B0())return;Z0.stdout.write(`${"\r".padEnd(Z0.stdout.columns||80)}\r`),this.log(B,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||B0()||!Z0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=s.green("━".repeat(A)),U=s.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=w||Y===100?s.green("✓"):s.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${s.gray(this.formatTag(this.name))}`:"",F=`\r${z}${G} ${B} ${W}${j}`,K=Z0.stdout.columns||80,f=" ".repeat(Math.max(0,K-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${f}`,Z0.stdout.write($.lastRenderedLine),w)Z0.stdout.write(`
|
|
142
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||B0()||!Z0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(B0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await DX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=C1(this.config.logDirectory,A);if($.before)try{if((await y1(J)).mtime>=$.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 xX(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(w){console.error("Error during log clearing process:",w)}}}function lX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&r(w[0])&&"id"in w[0]&&w[0].id===3&&r(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(r(w)&&r($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(r($)&&"arr"in $&&Array.isArray($.arr)&&r(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&r(w[0])&&r($[0])){let A=[...w];for(let X of $)if(r(X)&&"name"in X){if(!A.find((U)=>r(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(r(X)&&"path"in X){if(!A.find((U)=>r(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(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!r(w)||!r($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(r(X)&&r(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&&r(X[0])&&r(Y[A][0])){let J=[...X];for(let U of Y[A])if(r(U)&&"name"in U){if(!J.find((W)=>r(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((W)=>r(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((B)=>w8(B,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 gW($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:lX($,w);if(Array.isArray($))return Y==="replace"?w:lX($,w);if(!r(w)||!r($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[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(r(J)&&r(U))A[X]=gW(U,J,Y);else A[X]=J}return A}function w8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!w8($[Y],w[Y]))return!1;return!0}if(r($)&&r(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!w8($[X],w[X]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function iX($,w,Y="replace"){if(!hG($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return gW(w,X,Y)}catch{return null}}catch{return null}}function BT($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],F=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),K=`${A}_${G.map(F).join("_")}`,f=`${A}_${G.map((E)=>E.toUpperCase()).join("_")}`;if(Y)D0.info(`Checking environment variable ${K} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let E=MY.env[K]||MY.env[f];if(E!==void 0){if(Y)D0.info(`Using environment variable ${E?K:f} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(E);else if(typeof z==="boolean")W[j]=E.toLowerCase()==="true";else if(Array.isArray(z))try{let q=JSON.parse(E);if(Array.isArray(q))W[j]=q;else W[j]=E.split(",").map((T)=>T.trim())}catch{W[j]=E.split(",").map((q)=>q.trim())}else W[j]=E}}}return W}return J(X)}async function jT({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?BT($,X,J):X,j=Y||MY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),F=[`${$}.config`,`.${$}.config`].filter(Boolean),K=w?[w,`.${w}`]:[],f=w?[`${w}.config`,`.${w}.config`]:[],E=Array.from(new Set([j,d0(j,"config"),d0(j,".config"),A?d0(j,A):void 0].filter(Boolean)));for(let q of E){if(J)D0.info(`Searching for configuration in: ${q}`);let M=[d0(j,"config"),d0(j,".config")].concat(A?[d0(j,A)]:[]).includes(q)?[...G,...F,...K,...f]:[...F,...G,...f,...K];for(let y of M)for(let Q of z){let H=d0(q,`${y}${Q}`),I=await iX(H,W,B);if(I!==null){if(J)D0.success(`Configuration loaded from: ${H}`);return I}}}if($){let q=d0(GW(),".config",$),T=["config",`${$}.config`];if(w)T.push(`${w}.config`);if(J)D0.info(`Checking user config directory: ${q}`);for(let M of T)for(let y of z){let Q=d0(q,`${M}${y}`),H=await iX(Q,W,B);if(H!==null){if(J)D0.success(`Configuration loaded from user config directory: ${Q}`);return H}}}if($){let q=d0(GW(),".config"),T=[`.${$}.config`];if(w)T.push(`.${w}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${q}`);for(let M of T)for(let y of z){let Q=d0(q,`${M}${y}`),H=await iX(Q,W,B);if(H!==null){if(J)D0.success(`Configuration loaded from user config directory dotfile: ${Q}`);return H}}}if($){let q=GW(),T=[`.${$}.config`,`.${$}`];if(w)T.push(`.${w}.config`),T.push(`.${w}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${q}`);for(let M of T)for(let y of z){let Q=d0(q,`${M}${y}`),H=await iX(Q,W,B);if(H!==null){if(J)D0.success(`Configuration loaded from user home directory: ${Q}`);return H}}}try{let q=d0(j,"package.json");if(hG(q)){let T=await import(q),M=T[$];if(!M&&w){if(M=T[w],M&&J)D0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)D0.success(`Configuration loaded from package.json: ${M===T[$]?$:w}`);return gW(W,M,B)}catch(y){if(J)D0.warn("Failed to merge package.json config:",y)}}}catch(q){if(J)D0.warn("Failed to load package.json:",q)}if(J)D0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function zT($,w={}){let Y=aX.cwd();while(Y.includes("storage"))Y=t2(Y,"..");let A=t2(Y,$||"");if(w?.relative)return hq(aX.cwd(),A);return A}async function GT(){try{let $=await jT({name:"clarity",alias:"logging",defaultConfig:rX,cwd:aX.cwd()});return{...rX,...$||{}}}catch{return rX}}function H0(){if(a$.env.NODE_ENV==="test"||a$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function FT(){if(a$.env.NODE_ENV==="test"||a$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof a$<"u"){let $=a$.type;if($==="renderer"||$==="worker")return!1;return!!(a$.versions&&(a$.versions.node||a$.versions.bun))}return!1}class DG{async format($){let w=await FT(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:_1.pid,hostname:w(),environment:_1.env.NODE_ENV||"development",platform:_1.platform,version:_1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_1.env.NODE_ENV||_1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Y8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...kW},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new DG,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...tX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...tX};return{...tX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:kW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await lq(this.config.logDirectory,UG.F_OK|UG.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await nq(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:p$.from($);try{if(!PX(this.currentLogFile))await TW(this.currentLogFile,"",{mode:420});if(X=JG(this.currentLogFile,"a",420),dq(X,W,{flag:"a"}),XG(X),X!==void 0)qW(X),X=void 0;if((await L1(this.currentLogFile)).size===0){if(await TW(this.currentLogFile,W,{flag:"w",mode:420}),(await L1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let F=B*2**J;await new Promise((K)=>setTimeout(K,F)),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{qW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 O1(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 O1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return O1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.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 w=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(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return fW(16).toString("hex")}generateKey(){return fW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=fW(16),A=iq("aes-256-gcm",w,Y),X=p$.isBuffer($)?$:p$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=p$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=BG(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(p$.from(p$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let $=await L1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.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,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await L1(Y).catch(()=>null))try{if(await WG(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await uX(B)}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 TW(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 L1(Y).catch(()=>null))await WG(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await bX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await uX(O1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=AG($),A=gq(w),X=BG();await tq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!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(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),PX(this.currentLogFile))try{let $=JG(this.currentLogFile,"r+");XG($),qW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await bX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await uX(O1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?v.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let $=typeof x.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push(w);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let W=x.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${v.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,F=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(F)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=v.underline(v.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>v.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),w}supportsHyperlinks(){if(H0())return!1;let $=x.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=x.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(pq(w)||w.startsWith("./")||w.startsWith("../"))w=rq(w);else return null;return PX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":dG[$],F=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",K;switch($){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:v.gray(W),level:$}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:v.green(W),level:$}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.error(K),B){let f=B.split(`
|
|
143
|
+
`);for(let E of f)if(E.trim()&&!E.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:v.gray(` ${E}`),level:$,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
|
|
144
|
+
`;if(B)z+=`${B}
|
|
145
|
+
`;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress($,w=""){let Y={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!H0()&&x.stdout.isTTY)x.stdout.write(`
|
|
146
|
+
`);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=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($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
|
|
147
|
+
`,j=j.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:B,icon:this.options.showIcons===!1?"":v.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!H0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new Y8(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(H0())throw Error("createReadStream is not supported in browser environments");if(!PX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return AG(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=p$.isBuffer($)?$:p$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=mq("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=p$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
|
|
148
|
+
`),W=Math.max(...B.map((F)=>F.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((F)=>{return this.formatConsoleMessage({timestamp:Y,message:v.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(j),showTimestamp:!1})),G.forEach((F)=>console.error(F)),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}
|
|
149
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(H0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${v.cyan("?")} ${$} (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(""),w(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($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=$.replace(W,(z,G)=>{if(G==="%")return"%";if(j>=w.length)return z;let F=w[j++];switch(G){case"s":return String(F);case"d":case"i":return Number(F).toString();case"j":case"o":return JSON.stringify(F,null,2);default:return z}}),j<w.length)Y+=` ${w.slice(j).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)):"",j=this.options.showIcons===!1?"":`${v.blue("◐")} `;console.error(`${j}${W} ${v.cyan(A)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
150
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!x.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=v.green("━".repeat(A)),U=v.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?v.green("✓"):v.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",F=`\r${z}${G} ${B} ${W}${j}`,K=x.stdout.columns||80,f=" ".repeat(Math.max(0,K-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${f}`,x.stdout.write($.lastRenderedLine),w)x.stdout.write(`
|
|
151
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||H0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await bX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=O1(this.config.logDirectory,A);if($.before)try{if((await L1(J)).mtime>=$.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(w){console.error("Error during log clearing process:",w)}}}async function xG($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function PG($){return $ instanceof $$}function KT($){return $ instanceof A8}function NT($){if(PG($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}class W8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return yY.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=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=cX.env[W]||(j?cX.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=cX.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof X8)throw G;throw Ew.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw Ew.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(cX.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
|
|
150
152
|
|
|
151
|
-
`;for(let
|
|
152
|
-
`,
|
|
153
|
-
`,
|
|
154
|
-
`,
|
|
153
|
+
`;for(let A of $)Y+=`${A.key}
|
|
154
|
+
`,Y+=` Type: ${A.type}
|
|
155
|
+
`,Y+=` Description: ${A.description}
|
|
156
|
+
`,Y+=` Example: ${A.example}
|
|
155
157
|
|
|
156
|
-
`;return
|
|
158
|
+
`;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
|
|
157
159
|
|
|
158
|
-
`;
|
|
159
|
-
`,
|
|
160
|
-
`;for(let
|
|
161
|
-
`;return A}}function i7($,w){let A=p2("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function d2($,w,A={}){return g2($,w,A,new WeakMap)}function g2($,w,A,Y){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=A;if(w===null||w===void 0)return J?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return n2($,w,X,Y);if(!F$(w)||!F$($))return w;return d7($,w,A,Y)}function n2($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return c7($,w);case"smart":return v7($,w,Y);default:return w}return w}function c7($,w){let A=[...w];for(let Y of $)if(!A.some((X)=>aU(X,Y)))A.push(Y);return A}function v7($,w,A){if(w.length===0)return $;if($.length===0)return w;if(F$(w[0])&&F$($[0]))return m7($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}function m7($,w,A){let Y=[...w];for(let X of $){if(!F$(X)){Y.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(Y.find((B)=>F$(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)Y.push(X)}return Y}function d7($,w,A,Y){let X=w;if(F$(X)&&Y.has(X))return Y.get(X);let J={...$};if(F$(X))Y.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],f=J[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(F$(W)&&F$(f))J[U]=g2(f,W,A,Y);else if(Array.isArray(W)||Array.isArray(f))J[U]=n2(f,W,A.arrayMergeMode||"smart",Y);else J[U]=W}return J}function Bf($,w,A="replace"){return d2($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function aU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!aU($[A],w[A]))return!1;return!0}if(F$($)&&F$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!aU($[X],w[X]))return!1}return!0}return!1}function F$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class vX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=A;if(X){let B=C1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!RX($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,E="default"in j,F=Object.keys(j).length>0;if(!E&&!F)throw new fA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new fA($,Error("Configuration must export a valid object"),"unknown");let H={config:Bf(w,z,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)C1.setWithFileCheck("file",H,$,J);return H}catch(B){throw B instanceof Error?Ew.configLoad($,B):Ew.configLoad($,Error(String(B)))}};if(U)return BA.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let X=await this.loadFromPath(Y,w,A);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,X)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),X=[];for(let J of Y)for(let U of this.extensions)X.push(uU(w,`${J}${U}`));return X}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return v2(async()=>{return RX($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!RX($))return Y;if(w||A){let X=this.generateNamePatterns(w||"",A);for(let J of X)for(let U of this.extensions){let W=uU($,`${J}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let W=uU($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!RX($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let X=await this.loadFromPath(Y,{},w);if(X)A.set(Y,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${Y}:`,X)}})),A}}class jf{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:f=!1}=A,B=async()=>{let j=[],z=[],E={stopOnFirstError:Y,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,E);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],E);else return this.validateWithJSONSchema($,w,E)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await BA.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!q7(w))throw new WA(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),X=Y.default||Y;if(Array.isArray(X))return this.validateWithRules($,X,A);else return this.validateWithJSONSchema($,X,A)}catch(Y){throw new WA(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],X=[];return this.validateObjectAgainstSchema($,w,"",Y,X,A),{isValid:Y.length===0,errors:Y,warnings:X}}validateObjectAgainstSchema($,w,A,Y,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,X,J),J.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],f,B,Y,X,J),J.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(U))if(!W.has(f))X.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),W=this.validateWithRule(U,J,J.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:X}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)Y.push({path:A,message:w.message||X,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let X of A)if(Y&&typeof Y==="object"&&X in Y)Y=Y[X];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,X,J,U]=Y;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:o2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class zf{fileLoader=new vX;envProcessor=new cX;validator=new jf;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:X,validate:J,...U}=$;try{if(A?.enabled){let f=this.checkCache(U.name||"",U);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(f){let B=U.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),E=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(E||j))throw f;if(z&&(!B||!E))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(f);if(Y.slowThreshold&&f.duration>Y.slowThreshold)C$.warn(`Slow configuration loading detected: ${f.duration}ms for ${U.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw C$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=J||Lw.cwd(),E=[],F=await this.loadLocalConfiguration(Y,X,z,U,W,B,j,f,A);if(F)return E.push(...this.getLocalSearchPaths(Y,X,z,U)),this.finalizeResult(F,E,f,Y,j);let T=await this.loadHomeConfiguration(Y,X,W,B,j,f);if(T)return E.push(...this.getHomeSearchPaths(Y,X)),this.finalizeResult(T,E,f,Y,j);let K=await this.loadPackageJsonConfiguration(Y,X,z,W,B,j,f);if(K)return E.push(g0(z,"package.json")),this.finalizeResult(K,E,f,Y,j);if(E.push(...this.getAllSearchPaths(Y,X,z,U)),w)throw Ew.configNotFound(Y,E,X);return{...await this.applyEnvironmentVariables(Y,W,f,j),warnings:[`No configuration file found for "${Y}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,X,J,U,W,f){let B=W?JA($,X,U):X,j=this.getLocalDirectories(A,Y);for(let z of j){if(U)C$.info(`Searching for configuration in: ${z}`);let E=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(E,B,{arrayStrategy:J,verbose:U,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(U)C$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,X,J){if(!$)return null;let U=J?JA($,A,X):A,W=[g0(G1(),".config",$),g0(G1(),".config"),G1()];for(let f of W){if(X)C$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:X});if(j){if(X)C$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,Y,X,J,U){let W=U?JA($,Y,J):Y;try{let f=g0(A,"package.json");if(!tU(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)C$.success(`Configuration loaded from package.json: ${z}`);return{config:Bf(W,j,X),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(J)C$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:JA($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let X=[];if(A){let J=A($);if(J)X.push(...J)}if(w){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 Ew.configValidation(Y||"unknown",X,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return C1.get(A)||null}cacheResult($,w,A,Y){let X=this.generateCacheKey($,Y);C1.set(X,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,g0($,"config"),g0($,".config"),w?g0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let X=[];return X.push(...this.getLocalSearchPaths($,w,A,Y)),X.push(...this.getHomeSearchPaths($,w)),X.push(g0(A,"package.json")),X}getLocalSearchPaths($,w,A,Y){let X=this.getLocalDirectories(A,Y),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let A=[g0(G1(),".config",$),g0(G1(),".config"),G1()],Y=[];for(let X of A)Y.push(...this.fileLoader.generateConfigPaths($,X,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function T2($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function g7($){return r$.loadConfig({...$,__strictErrorHandling:!0})}async function l2($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await r$.loadConfig($);else Y=await r$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let X=Y instanceof Error?Y.name:"UnknownError",J=Y instanceof Error?Y.message:String(Y);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&$.verbose)C$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await r$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function n7($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await r$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&T2(A)))return(await r$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await r$.loadConfig({...$,cwd:$.cwd||Lw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&T2(w)))return(await r$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function l7($,w,A="replace"){let Y=new vX;try{let X=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function JA($,w,A=!1){let Y=new cX,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of E)if(F=Lw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=J(j,z)}return f}return J(w)}function p7($){let w=g0(Lw.cwd(),$.configDir),A=g0(Lw.cwd(),$.generatedDir),Y=g0(A,"config-types.ts");if(!tU($2(Y)))sT($2(Y),{recursive:!0,mode:511});let X=tU(w)?oT(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${IH}
|
|
160
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
161
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
162
|
+
`;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
163
|
+
`;return Y}}function ET($,w){let Y=iG("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function bG($,w,Y={}){return uG($,w,Y,new WeakMap)}function uG($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return cG($,w,X,A);if(!j$(w)||!j$($))return w;return HT($,w,Y,A)}function cG($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return fT($,w);case"smart":return qT($,w,A);default:return w}return w}function fT($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>hW(X,A)))Y.push(A);return Y}function qT($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(j$(w[0])&&j$($[0]))return TT($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function TT($,w,Y){let A=[...w];for(let X of $){if(!j$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>j$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function HT($,w,Y,A){let X=w;if(j$(X)&&A.has(X))return A.get(X);let J={...$};if(j$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(j$(B)&&j$(W))J[U]=uG(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=cG(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function dW($,w,Y="replace"){return bG($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function hW($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!hW($[Y],w[Y]))return!1;return!0}if(j$($)&&j$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!hW($[X],w[X]))return!1}return!0}return!1}function j$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class B8{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:B=!1}=Y;if(X){let j=k1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!vX($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,F="default"in z,K=Object.keys(z).length>0;if(!F&&!K)throw new IY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new IY($,Error("Configuration must export a valid object"),"unknown");let q={config:dW(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)k1.setWithFileCheck("file",q,$,J);return q}catch(j){throw j instanceof Error?Ew.configLoad($,j):Ew.configLoad($,Error(String(j)))}};if(U)return yY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(HW(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return xG(async()=>{return vX($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!vX($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=HW($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=HW($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!vX($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class lW{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],F={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,F);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],F);else return this.validateWithJSONSchema($,w,F)}catch(K){return z.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await yY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!aq(w))throw new VY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new VY(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:nG},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class nW{fileLoader=new B8;envProcessor=new W8;validator=new lW;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),F=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(F||z))throw W;if(G&&(!j||!F))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)H$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw H$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||kw.cwd(),F=[],K=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(K)return F.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(K,F,W,A,z);let f=await this.loadHomeConfiguration(A,X,B,j,z,W);if(f)return F.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(f,F,W,A,z);let E=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(E)return F.push(l0(G,"package.json")),this.finalizeResult(E,F,W,A,z);if(F.push(...this.getAllSearchPaths(A,X,G,U)),w)throw Ew.configNotFound(A,F,X);return{...await this.applyEnvironmentVariables(A,B,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,B,W){let j=B?RY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)H$.info(`Searching for configuration in: ${G}`);let F=this.fileLoader.generateConfigPaths($,G,w),K=await this.fileLoader.tryLoadFromPaths(F,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(K){if(U)H$.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?RY($,Y,X):Y,B=[l0(V1(),".config",$),l0(V1(),".config"),V1()];for(let W of B){if(X)H$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)H$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?RY($,A,J):A;try{let W=l0(Y,"package.json");if(!_W(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)H$.success(`Configuration loaded from package.json: ${G}`);return{config:dW(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)H$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:RY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 Ew.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($,A);k1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,l0($,"config"),l0($,".config"),w?l0($,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(l0(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[l0(V1(),".config",$),l0(V1(),".config"),V1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function zG($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||A}async function RT($){return o$.loadConfig({...$,__strictErrorHandling:!0})}async function vG($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await o$.loadConfig($);else A=await o$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)H$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await o$.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}async function MT($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await o$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&zG(Y)))return(await o$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await o$.loadConfig({...$,cwd:$.cwd||kw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&zG(w)))return(await o$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function IT($,w,Y="replace"){let A=new B8;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function RY($,w,Y=!1){let A=new W8,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],F=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((E)=>E.toUpperCase()).join("")}`,`${X}_${G.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,f;for(let E of F)if(K=kw.env[E],K!==void 0){f=E;break}if(K!==void 0&&f)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(K.toLowerCase());else if(typeof z==="number"){let E=Number(K);if(!Number.isNaN(E))W[j]=E}else if(Array.isArray(z))try{W[j]=JSON.parse(K)}catch{W[j]=K.split(",").map((E)=>E.trim())}else W[j]=K;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function VT($){let w=l0(kw.cwd(),$.configDir),Y=l0(kw.cwd(),$.generatedDir),A=l0(Y,"config-types.ts");if(!_W(r2(A)))Lq(r2(A),{recursive:!0,mode:511});let X=_W(w)?Oq(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${oT}
|
|
162
164
|
export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
|
|
163
|
-
`;
|
|
164
|
-
${X.map((
|
|
165
|
+
`;_q(A,J,{mode:438})}function yT($){let w=null,Y=null,A=()=>{if(!Y)Y=vG($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)H$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in $?$.defaultConfig:{};return w=X,A(),new Proxy({},{get(J,U){if(w)return w[U];let B=X[U];return A(),B},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,B){if(!w)w={...X};return w[U]=B,!0}})}function CT($){let w=jG(eq.cwd(),$?.configDir||"./config");function Y(){if(!sq(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=oq(w).filter((W)=>X.has(RW(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:j}of U){let z=RW(j).toLowerCase(),G=B.get(W);if(!G){B.set(W,j);continue}let F=RW(G).toLowerCase();if(J.indexOf(z)<J.indexOf(F))B.set(W,j)}return Array.from(B.entries()).map(([W,j])=>({base:W,file:j})).sort((W,j)=>W.base.localeCompare(j.base))}function A(){let X=Y(),J=X.map((j)=>j.base),U=J.length?J.map((j)=>`'${j}'`).join(" | "):"string",B=X.length?`{
|
|
166
|
+
${X.map((j)=>{let z=jG(w,j.file).replace(/\\/g,"/");return` '${j.base}': typeof import('${z}').default`}).join(`,
|
|
165
167
|
`)}
|
|
166
168
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
167
|
-
export type ConfigByName = ${
|
|
169
|
+
export type ConfigByName = ${B}
|
|
168
170
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
169
171
|
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:Y(),loader:"ts"}})}}}function VH($,w={}){let A=uX.cwd();while(A.includes("storage"))A=L2(A,"..");let Y=L2(A,$||"");if(w?.relative)return hH(uX.cwd(),Y);return Y}function I0(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bH(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t$<"u"){let $=t$.type;if($==="renderer"||$==="worker")return!1;return!!(t$.versions&&(t$.versions.node||t$.versions.bun))}return!1}class Az{async format($){let w=await bH(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:y1.pid,hostname:w(),environment:y1.env.NODE_ENV||"development",platform:y1.platform,version:y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:y1.env.NODE_ENV||y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ow{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...iX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Az,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...pU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...pU};return{...pU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:iX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!I0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await kH(this.config.logDirectory,_2.F_OK|_2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await DH(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:n$.from($);try{if(!MX(this.currentLogFile))await lU(this.currentLogFile,"",{mode:420});if(X=S2(this.currentLogFile,"a",420),_H(X,f,{flag:"a"}),Q2(X),X!==void 0)nU(X),X=void 0;if((await M1(this.currentLogFile)).size===0){if(await lU(this.currentLogFile,f,{flag:"w",mode:420}),(await M1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let E=W*2**J;await new Promise((F)=>setTimeout(F,E)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{nU(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 I1(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 I1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return I1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(I0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}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 $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=gU(16),Y=OH("aes-256-gcm",w,A),X=n$.isBuffer($)?$:n$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=n$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=D2(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(n$.from(n$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(I0())return;if(!this.shouldWriteToFile())return;let $=await M1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await IX(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await M1(A).catch(()=>null))try{if(await k2(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await yX(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await lU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await M1(A).catch(()=>null))await k2(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await IX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await yX(I1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=O2($),Y=SH(w),X=D2();await PH(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),MX(this.currentLogFile))try{let $=S2(this.currentLogFile,"r+");Q2($),nU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!I0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await IX(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await yX(I1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?v.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||I0())return!1;let $=typeof x.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=x.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${v.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=v.underline(v.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(A,Y)=>v.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>v.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>v.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>v.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>v.strikethrough(Y)),w}supportsHyperlinks(){if(I0())return!1;let $=x.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=x.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(ZH(w)||w.startsWith("./")||w.startsWith("../"))w=xH(w);else return null;return MX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":mH[$],E=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:v.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:v.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
171
|
-
`);for(let
|
|
172
|
-
`;if(
|
|
173
|
-
`;if(
|
|
174
|
-
`);if(this[
|
|
175
|
-
`,
|
|
176
|
-
`),
|
|
177
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(
|
|
178
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
179
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||I0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(I0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await IX(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let J=I1(this.config.logDirectory,Y);if($.before)try{if((await M1(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}A.push(J)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await yX(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var lT,pT=($)=>$,rT=($,w)=>{for(var A in w)lT($,A,{get:w[A],enumerable:!0,configurable:!0,set:tT.bind(w,A)})},aT=($,w)=>()=>($&&(w=$($=0)),w),P2,p2,C1,BA,t2,a7,s7,H2,hX,sU,x0,a,o7,N2,e7,R2,$H,wH,cU,AH,q2,M2,vU,YH,XH,JH,UH,VX,r2,fH,P0,WH,BH,I2,LX,oU,M0,u,jH,y2,zH,C2,FH,EH,mU,GH,h2,V2,KH,dU,TH,HH,NH,RH,qH,OX,a2,MH,IH="0.15.6",Y$,PX,fA,eU,$f,bX,wf,Af,WA,Yf,Xf,Ew,s2,o2,C$,r$,e2,$z,yH,LH,wz,iX,Fh,V0,v,yh,uH,Ch,iH,hh,Vh,Z2,Lh,cH,vH,Oh,x2,Qh,Sh,_h,kh,Dh,pU,mH,Zh;var Ff=F0(()=>{lT=Object.defineProperty;P2={};rT(P2,{withErrorRecovery:()=>v2,tryLoadConfig:()=>l7,loadConfigWithResult:()=>g7,loadConfig:()=>l2,isRetryableError:()=>u7,isConfigNotFoundError:()=>b7,isBunfigError:()=>m2,globalPerformanceMonitor:()=>BA,globalCache:()=>C1,getEnvOrDefault:()=>i7,generateConfigTypes:()=>p7,defaultGeneratedDir:()=>$z,defaultConfigDir:()=>e2,deepMergeWithArrayStrategy:()=>Bf,deepMerge:()=>d2,createLibraryConfig:()=>t7,config:()=>n7,bunfigPlugin:()=>r7,applyEnvVarsToConfig:()=>JA,TypeGenerationError:()=>Af,SchemaValidationError:()=>WA,PluginError:()=>Xf,PerformanceMonitor:()=>Uf,FileSystemError:()=>wf,ErrorFactory:()=>Ew,EnvVarError:()=>bX,EnvProcessor:()=>cX,ConfigValidator:()=>jf,ConfigValidationError:()=>eU,ConfigNotFoundError:()=>PX,ConfigMergeError:()=>$f,ConfigLoader:()=>zf,ConfigLoadError:()=>fA,ConfigFileLoader:()=>vX,ConfigCache:()=>Jf,CacheUtils:()=>t2,BunfigError:()=>Y$,BrowserConfigError:()=>Yf,ArrayMergeStrategies:()=>s2});yH=aT(async()=>{p2=import.meta.require,C1=new Jf,BA=new Uf,t2={createKey:C7,isEquivalent:h7,estimateMemoryUsage:V7},a7=_X(rU.cwd(),"config"),s7=_X(rU.cwd(),"src/generated"),H2=SX.env.CLARITY_LOG_DIR||A7(Q7(),"logs"),hX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:H2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},sU=await S7(),x0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},a=x0,o7=x0.red,N2=x0.green,e7=x0.yellow,R2=x0.blue,$H=x0.magenta,wH=x0.cyan,cU=x0.white,AH=x0.gray,q2=x0.bgRed,M2=x0.bgYellow,vU=x0.bold,YH=x0.dim,XH=x0.italic,JH=x0.underline,UH=x0.reset,VX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},r2={debug:"\uD83D\uDD0D",info:R2("ℹ"),success:N2("✓"),warning:M2(cU(vU(" WARN "))),error:q2(cU(vU(" ERROR ")))},fH=new DX("stacks"),P0=new DX("bunfig",{showTags:!0}),WH=d0(UA.cwd(),"config"),BH=d0(UA.cwd(),"src/generated"),I2=QX.env.CLARITY_LOG_DIR||$7(Z7(),"logs"),LX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:I2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},oU=await x7(),M0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},u=M0,jH=M0.red,y2=M0.green,zH=M0.yellow,C2=M0.blue,FH=M0.magenta,EH=M0.cyan,mU=M0.white,GH=M0.gray,h2=M0.bgRed,V2=M0.bgYellow,KH=M0.bgGray,dU=M0.bold,TH=M0.dim,HH=M0.italic,NH=M0.underline,RH=M0.strikethrough,qH=M0.reset,OX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},a2={debug:"\uD83D\uDD0D",info:C2("ℹ"),success:y2("✓"),warning:V2(mU(dU(" WARN "))),error:h2(mU(dU(" ERROR ")))},MH=new xX("stacks"),Y$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},PX=class extends Y${code="CONFIG_NOT_FOUND";constructor(w,A,Y){let X=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},fA=class extends Y${code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},eU=class extends Y${code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},$f=class extends Y${code="CONFIG_MERGE_ERROR";constructor(w,A,Y,X){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},bX=class extends Y${code="ENV_VAR_ERROR";constructor(w,A,Y,X){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:X})}},wf=class extends Y${code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Af=class extends Y${code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},WA=class extends Y${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},Yf=class extends Y${code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,X){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:X})}},Xf=class extends Y${code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Ew={configNotFound($,w,A){return new PX($,w,A)},configLoad($,w,A){return new fA($,w,A)},configValidation($,w,A){return new eU($,w,A)},configMerge($,w,A,Y){return new $f($,w,A,Y)},envVar($,w,A,Y){return new bX($,w,A,Y)},fileSystem($,w,A){return new wf($,w,A)},typeGeneration($,w,A){return new Af($,w,A)},schemaValidation($,w,A){return new WA($,w,A)},browserConfig($,w,A,Y){return new Yf($,w,A,Y)},plugin($,w,A){return new Xf($,w,A)}},s2={replace:"replace",concat:"concat",smart:"smart"},o2=/^https?:\/\//,C$=new xX("bunfig",{showTags:!0}),r$=new zf,e2=g0(Lw.cwd(),"config"),$z=g0(Lw.cwd(),"src/generated")});LH=uX.env.CLARITY_LOG_DIR||CH(VH(),"logs"),wz={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:LH,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},iX={...wz},Fh=(async()=>{try{let{loadConfig:$}=await yH().then(()=>P2),w=await $({name:"clarity",alias:"logging",defaultConfig:wz,cwd:uX.cwd()});if(w)Object.assign(iX,w)}catch{}return iX})();V0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},v=V0,yh=V0.red,uH=V0.green,Ch=V0.yellow,iH=V0.blue,hh=V0.magenta,Vh=V0.cyan,Z2=V0.white,Lh=V0.gray,cH=V0.bgRed,vH=V0.bgYellow,Oh=V0.bgGray,x2=V0.bold,Qh=V0.dim,Sh=V0.italic,_h=V0.underline,kh=V0.strikethrough,Dh=V0.reset,pU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},mH={debug:"\uD83D\uDD0D",info:iH("ℹ"),success:uH("✓"),warning:vH(Z2(x2(" WARN "))),error:cH(Z2(x2(" ERROR ")))};Zh=new Ow("stacks")});var h1={};BW(h1,{shouldReusePort:()=>Sw,safeStringify:()=>E$,safeDeleteFile:()=>Tf,resolvePathRewrite:()=>Kf,redactSensitive:()=>mX,isValidRootCA:()=>Gf,isSingleProxyOptions:()=>zA,isSingleProxyConfig:()=>tH,isProcessElevated:()=>dX,isMultiProxyOptions:()=>_w,isMultiProxyConfig:()=>Jz,getSudoPassword:()=>Qw,getPrimaryDomain:()=>gX,extractHostname:()=>pH,execSudoSync:()=>jA,debugLog:()=>G});import{execSync as Ef}from"node:child_process";import*as Xz from"node:fs/promises";function Qw(){return process.env.SUDO_PASSWORD}function dX(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function jA($){if(dX())return Ef($,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let w=Qw(),A=$.replace(/'/g,"'\\''");if(w)return Ef(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return Ef(`sudo -n sh -c '${A}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function G($,w,A){if(A)dH.debug(`[rpx:${$}] ${w}`)}function Sw(){let $=process.env.RPX_REUSE_PORT;return $==="1"||$==="true"}function lH($){let w=$.toLowerCase();return gH.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function mX($){if(Array.isArray($))return $.map((A)=>mX(A));if(typeof $==="string")return nH.test($)?Yz:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(lH(A)){w[A]=Yz;continue}w[A]=mX(Y)}return w}function E$($,w){return JSON.stringify(mX($),null,w)}function pH($){if(_w($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if(zA($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function Gf($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function gX($){if(!$)return"stacks.localhost";if(_w($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(zA($))return $.to||"stacks.localhost";return"stacks.localhost"}function Jz($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function _w($){return"proxies"in $&&Array.isArray($.proxies)}function zA($){return"to"in $&&typeof $.to==="string"}function tH($){return!!($&&("to"in $)&&!("proxies"in $))}function Kf($,w){if(!w||w.length===0)return null;for(let A of w)if($===A.from||$.startsWith(`${A.from}/`)){let Y=A.to.startsWith("http")?new URL(A.to).host:A.to,X=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:Y,targetPath:X}}return null}async function Tf($,w){try{await Xz.unlink($),G("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")G("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var dH,Yz="[redacted]",gH,nH;var f0=F0(()=>{Ff();dH=new Ow("rpx",{showTags:!1});gH=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),nH=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as nX}from"node:child_process";import{homedir as rH}from"node:os";import{join as aH}from"node:path";function lX(){return aH(rH(),"Library/Keychains/login.keychain-db")}function Nf(){return[L1,lX()]}function Uz($,w=Hf){let A=nX(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),Y=[];for(let X of A.split(`
|
|
180
|
-
`)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)
|
|
181
|
-
`))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===
|
|
172
|
+
`}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 YH($,w={}){let Y=J8.cwd();while(Y.includes("storage"))Y=MG(Y,"..");let A=MG(Y,$||"");if(w?.relative)return wH(J8.cwd(),A);return A}function M0(){if(s$.env.NODE_ENV==="test"||s$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function KH(){if(s$.env.NODE_ENV==="test"||s$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof s$<"u"){let $=s$.type;if($==="renderer"||$==="worker")return!1;return!!(s$.versions&&(s$.versions.node||s$.versions.bun))}return!1}class aG{async format($){let w=await KH(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Z1.pid,hostname:w(),environment:Z1.env.NODE_ENV||"development",platform:Z1.platform,version:Z1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Z1.env.NODE_ENV||Z1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Dw{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...U8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new aG,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...OW,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...OW};return{...OW,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:U8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await BH(this.config.logDirectory,CG.F_OK|CG.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await jH(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:r$.from($);try{if(!mX(this.currentLogFile))await LW(this.currentLogFile,"",{mode:420});if(X=yG(this.currentLogFile,"a",420),WH(X,W,{flag:"a"}),VG(X),X!==void 0)QW(X),X=void 0;if((await S1(this.currentLogFile)).size===0){if(await LW(this.currentLogFile,W,{flag:"w",mode:420}),(await S1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let F=B*2**J;await new Promise((K)=>setTimeout(K,F)),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{QW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 h1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return h1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return h1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.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 w=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(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return CW(16).toString("hex")}generateKey(){return CW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=CW(16),A=XH("aes-256-gcm",w,Y),X=r$.isBuffer($)?$:r$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=r$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=LG(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(r$.from(r$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let $=await S1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await gX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await S1(Y).catch(()=>null))try{if(await QG(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await dX(B)}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 LW(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 S1(Y).catch(()=>null))await QG(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await gX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await dX(h1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=IG($),A=UH(w),X=LG();await FH(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!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(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),mX(this.currentLogFile))try{let $=yG(this.currentLogFile,"r+");VG($),QW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await gX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await dX(h1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let $=typeof P.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push(w);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let W=P.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${g.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,F=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(F)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),w}supportsHyperlinks(){if(M0())return!1;let $=P.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=P.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(zH(w)||w.startsWith("./")||w.startsWith("../"))w=GH(w);else return null;return mX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":TH[$],F=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",K;switch($){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:g.gray(W),level:$}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:g.green(W),level:$}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:G,tag:F,message:W,level:$}),console.error(K),B){let f=B.split(`
|
|
173
|
+
`);for(let E of f)if(E.trim()&&!E.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:g.gray(` ${E}`),level:$,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
|
|
174
|
+
`;if(B)z+=`${B}
|
|
175
|
+
`;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress($,w=""){let Y={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!M0()&&P.stdout.isTTY)P.stdout.write(`
|
|
176
|
+
`);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=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($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
|
|
177
|
+
`,j=j.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:B,icon:this.options.showIcons===!1?"":g.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new Dw(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!mX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return IG(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=r$.isBuffer($)?$:r$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=JH("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=r$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
|
|
178
|
+
`),W=Math.max(...B.map((F)=>F.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((F)=>{return this.formatConsoleMessage({timestamp:Y,message:g.cyan(F),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(j),showTimestamp:!1})),G.forEach((F)=>console.error(F)),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}
|
|
179
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(M0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${g.cyan("?")} ${$} (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(""),w(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($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=$.replace(W,(z,G)=>{if(G==="%")return"%";if(j>=w.length)return z;let F=w[j++];switch(G){case"s":return String(F);case"d":case"i":return Number(F).toString();case"j":case"o":return JSON.stringify(F,null,2);default:return z}}),j<w.length)Y+=` ${w.slice(j).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)):"",j=this.options.showIcons===!1?"":`${g.blue("◐")} `;console.error(`${j}${W} ${g.cyan(A)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
180
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!P.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=g.green("━".repeat(A)),U=g.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?g.green("✓"):g.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",F=`\r${z}${G} ${B} ${W}${j}`,K=P.stdout.columns||80,f=" ".repeat(Math.max(0,K-F.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${F}${f}`,P.stdout.write($.lastRenderedLine),w)P.stdout.write(`
|
|
181
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await gX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=h1(this.config.logDirectory,A);if($.before)try{if((await S1(J)).mtime>=$.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 dX(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(w){console.error("Error during log clearing process:",w)}}}var Iq,Vq=($)=>$,Cq=($,w)=>{for(var Y in w)Iq($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:yq.bind(w,Y)})},Qq=($,w)=>()=>($&&(w=$($=0)),w),SG,iG,k1,yY,mG,QT,LT,GG,nX,ZW,k0,s,OT,FG,_T,KG,ST,hT,MW,ZT,NG,EG,IW,kT,DT,xT,PT,pX,gG,bT,D0,uT,cT,fG,rX,kW,R0,v,vT,qG,iT,TG,mT,gT,VW,dT,HG,RG,lT,yW,nT,pT,rT,tT,aT,tX,dG,sT,oT="0.15.6",$$,A8,IY,DW,xW,X8,PW,bW,VY,uW,cW,Ew,lG,nG,H$,o$,pG,rG,eT,AH,tG,U8,IQ,y0,g,kQ,NH,DQ,EH,xQ,PQ,OG,bQ,fH,qH,uQ,_G,cQ,vQ,iQ,mQ,gQ,OW,TH,dQ;var pW=o(()=>{Iq=Object.defineProperty;SG={};Cq(SG,{withErrorRecovery:()=>xG,tryLoadConfig:()=>IT,loadConfigWithResult:()=>RT,loadConfig:()=>vG,isRetryableError:()=>NT,isConfigNotFoundError:()=>KT,isBunfigError:()=>PG,globalPerformanceMonitor:()=>yY,globalCache:()=>k1,getEnvOrDefault:()=>ET,generateConfigTypes:()=>VT,defaultGeneratedDir:()=>rG,defaultConfigDir:()=>pG,deepMergeWithArrayStrategy:()=>dW,deepMerge:()=>bG,createLibraryConfig:()=>yT,config:()=>MT,bunfigPlugin:()=>CT,applyEnvVarsToConfig:()=>RY,TypeGenerationError:()=>bW,SchemaValidationError:()=>VY,PluginError:()=>cW,PerformanceMonitor:()=>iW,FileSystemError:()=>PW,ErrorFactory:()=>Ew,EnvVarError:()=>X8,EnvProcessor:()=>W8,ConfigValidator:()=>lW,ConfigValidationError:()=>DW,ConfigNotFoundError:()=>A8,ConfigMergeError:()=>xW,ConfigLoader:()=>nW,ConfigLoadError:()=>IY,ConfigFileLoader:()=>B8,ConfigCache:()=>vW,CacheUtils:()=>mG,BunfigError:()=>$$,BrowserConfigError:()=>uW,ArrayMergeStrategies:()=>lG});eT=Qq(async()=>{iG=import.meta.require,k1=new vW,yY=new iW,mG={createKey:$T,isEquivalent:wT,estimateMemoryUsage:YT},QT=oX(SW.cwd(),"config"),LT=oX(SW.cwd(),"src/generated"),GG=sX.env.CLARITY_LOG_DIR||Zq(JT(),"logs"),nX={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},ZW=await UT(),k0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},s=k0,OT=k0.red,FG=k0.green,_T=k0.yellow,KG=k0.blue,ST=k0.magenta,hT=k0.cyan,MW=k0.white,ZT=k0.gray,NG=k0.bgRed,EG=k0.bgYellow,IW=k0.bold,kT=k0.dim,DT=k0.italic,xT=k0.underline,PT=k0.reset,pX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},gG={debug:"\uD83D\uDD0D",info:KG("ℹ"),success:FG("✓"),warning:EG(MW(IW(" WARN "))),error:NG(MW(IW(" ERROR ")))},bT=new $8("stacks"),D0=new $8("bunfig",{showTags:!0}),uT=d0(MY.cwd(),"config"),cT=d0(MY.cwd(),"src/generated"),fG=aX.env.CLARITY_LOG_DIR||Sq(zT(),"logs"),rX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:fG,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},kW=await GT(),R0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},v=R0,vT=R0.red,qG=R0.green,iT=R0.yellow,TG=R0.blue,mT=R0.magenta,gT=R0.cyan,VW=R0.white,dT=R0.gray,HG=R0.bgRed,RG=R0.bgYellow,lT=R0.bgGray,yW=R0.bold,nT=R0.dim,pT=R0.italic,rT=R0.underline,tT=R0.strikethrough,aT=R0.reset,tX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},dG={debug:"\uD83D\uDD0D",info:TG("ℹ"),success:qG("✓"),warning:RG(VW(yW(" WARN "))),error:HG(VW(yW(" ERROR ")))},sT=new Y8("stacks"),$$=class extends Error{timestamp;context;constructor(w,Y={}){super(w);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 w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},A8=class extends $${code="CONFIG_NOT_FOUND";constructor(w,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},IY=class extends $${code="CONFIG_LOAD_ERROR";constructor(w,Y,A){super(`Failed to load configuration from "${w}": ${Y.message}`,{configPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},DW=class extends $${code="CONFIG_VALIDATION_ERROR";constructor(w,Y,A){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},xW=class extends $${code="CONFIG_MERGE_ERROR";constructor(w,Y,A,X){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},X8=class extends $${code="ENV_VAR_ERROR";constructor(w,Y,A,X){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:X})}},PW=class extends $${code="FILE_SYSTEM_ERROR";constructor(w,Y,A){super(`File system ${w} failed for "${Y}": ${A.message}`,{operation:w,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},bW=class extends $${code="TYPE_GENERATION_ERROR";constructor(w,Y,A){super(`Failed to generate types from "${w}" to "${Y}": ${A.message}`,{configDir:w,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},VY=class extends $${code="SCHEMA_VALIDATION_ERROR";constructor(w,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},uW=class extends $${code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,X){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:X})}},cW=class extends $${code="PLUGIN_ERROR";constructor(w,Y,A){super(`Plugin "${w}" failed during ${Y}: ${A.message}`,{pluginName:w,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Ew={configNotFound($,w,Y){return new A8($,w,Y)},configLoad($,w,Y){return new IY($,w,Y)},configValidation($,w,Y){return new DW($,w,Y)},configMerge($,w,Y,A){return new xW($,w,Y,A)},envVar($,w,Y,A){return new X8($,w,Y,A)},fileSystem($,w,Y){return new PW($,w,Y)},typeGeneration($,w,Y){return new bW($,w,Y)},schemaValidation($,w,Y){return new VY($,w,Y)},browserConfig($,w,Y,A){return new uW($,w,Y,A)},plugin($,w,Y){return new cW($,w,Y)}},lG={replace:"replace",concat:"concat",smart:"smart"},nG=/^https?:\/\//,H$=new Y8("bunfig",{showTags:!0}),o$=new nW,pG=l0(kw.cwd(),"config"),rG=l0(kw.cwd(),"src/generated")});AH=J8.env.CLARITY_LOG_DIR||$H(YH(),"logs"),tG={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:AH,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},U8={...tG},IQ=(async()=>{try{let{loadConfig:$}=await eT().then(()=>SG),w=await $({name:"clarity",alias:"logging",defaultConfig:tG,cwd:J8.cwd()});if(w)Object.assign(U8,w)}catch{}return U8})();y0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},g=y0,kQ=y0.red,NH=y0.green,DQ=y0.yellow,EH=y0.blue,xQ=y0.magenta,PQ=y0.cyan,OG=y0.white,bQ=y0.gray,fH=y0.bgRed,qH=y0.bgYellow,uQ=y0.bgGray,_G=y0.bold,cQ=y0.dim,vQ=y0.italic,iQ=y0.underline,mQ=y0.strikethrough,gQ=y0.reset,OW={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},TH={debug:"\uD83D\uDD0D",info:EH("ℹ"),success:NH("✓"),warning:qH(OG(_G(" WARN "))),error:fH(OG(_G(" ERROR ")))};dQ=new Dw("stacks")});var x1={};oB(x1,{shouldReusePort:()=>D1,safeStringify:()=>R$,safeDeleteFile:()=>sW,resolvePathRewrite:()=>aW,redactSensitive:()=>j8,isValidRootCA:()=>tW,isSingleProxyOptions:()=>QY,isSingleProxyConfig:()=>yH,isProcessElevated:()=>z8,isMultiProxyOptions:()=>Pw,isMultiProxyConfig:()=>eG,getSudoPassword:()=>xw,getPrimaryDomain:()=>G8,extractHostname:()=>VH,execSudoSync:()=>CY,debugLog:()=>N});import{execSync as rW}from"node:child_process";import*as oG from"node:fs/promises";function xw(){return process.env.SUDO_PASSWORD}function z8(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function CY($){if(z8())return rW($,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let w=xw(),Y=$.replace(/'/g,"'\\''");if(w)return rW(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return rW(`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 N($,w,Y){if(Y)HH.debug(`[rpx:${$}] ${w}`)}function D1(){let $=process.env.RPX_REUSE_PORT;return $==="1"||$==="true"}function IH($){let w=$.toLowerCase();return RH.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function j8($){if(Array.isArray($))return $.map((Y)=>j8(Y));if(typeof $==="string")return MH.test($)?sG:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(IH(Y)){w[Y]=sG;continue}w[Y]=j8(A)}return w}function R$($,w){return JSON.stringify(j8($),null,w)}function VH($){if(Pw($))return $.proxies.map((w)=>{let Y=w.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(QY($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function tW($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function G8($){if(!$)return"stacks.localhost";if(Pw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(QY($))return $.to||"stacks.localhost";return"stacks.localhost"}function eG($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function Pw($){return"proxies"in $&&Array.isArray($.proxies)}function QY($){return"to"in $&&typeof $.to==="string"}function yH($){return!!($&&("to"in $)&&!("proxies"in $))}function aW($,w){if(!w||w.length===0)return null;for(let Y of w)if($===Y.from||$.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,X=Y.stripPrefix===!0?$.slice(Y.from.length)||"/":$;return{targetHost:A,targetPath:X}}return null}async function sW($,w){try{await oG.unlink($),N("certificates",`Successfully deleted: ${$}`,w)}catch(Y){if(Y.code!=="ENOENT")N("certificates",`Warning: Could not delete ${$}: ${Y}`,w)}}var HH,sG="[redacted]",RH,MH;var X0=o(()=>{pW();HH=new Dw("rpx",{showTags:!1});RH=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),MH=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as F8}from"node:child_process";import{homedir as CH}from"node:os";import{join as QH}from"node:path";function K8(){return QH(CH(),"Library/Keychains/login.keychain-db")}function eW(){return[b1,K8()]}function $5($,w=oW){let Y=F8(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
|
|
182
|
+
`)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)A.push(J[1].toUpperCase())}return A}function $B($){if(process.platform!=="darwin")return;let w=Zw($.caPath);if(!w)return;let Y=$.commonName??oW,A=$.keychains??eW();for(let X of A)for(let J of $5(X,Y)){if(J===w)continue;try{if(X.startsWith("/Library"))CY(`security delete-certificate -Z ${J} "${X}"`);else F8(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});N("ssl",`Removed stale Root CA ${J} from ${X}`,$.verbose)}catch{}}}function wB($,w,Y){if(process.platform!=="darwin")return N8($,Y);try{let X=F8(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return N("ssl",`verify-cert ${w}: ${X?"trusted":"not trusted"}`,Y?.verbose),X}catch{return!1}}function N8($,w){let Y=Zw($);if(!Y)return!1;for(let A of eW())try{let X=F8(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let J of X.split(`
|
|
183
|
+
`))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return N("ssl",`Root CA fingerprint found in ${A}`,w?.verbose),!0}}catch{}return!1}var P1="-d -r trustRoot -p ssl -p basic",b1="/Library/Keychains/System.keychain",oW="rpx.localhost";var YB=o(()=>{kX();X0()});import{execSync as AB}from"node:child_process";import G0 from"node:fs/promises";import*as XB from"node:os";import{homedir as u1}from"node:os";import*as A5 from"node:path";import{join as F0}from"node:path";import*as fw from"node:process";function JB($,w){return[...new Set($.filter(Boolean))].map((Y)=>({serverName:Y,cert:w.cert,key:w.key}))}function UB($,w,Y){let A=F0(u1(),".stacks","ssl"),X=[...new Set([w,...$,"rpx.localhost"])];return{https:{certPath:E8,keyPath:F0(A,"rpx.localhost.key"),caCertPath:F0(A,"rpx.localhost.ca.crt"),commonName:w},verbose:Y,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function X5($){return{caCertPath:F0($,OH),caKeyPath:F0($,_H)}}async function SH($,w){try{let[Y,A]=await Promise.all([G0.readFile($.caCertPath,"utf8"),G0.readFile($.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return N("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:Y,privateKey:A}}catch(Y){return N("ssl",`No existing Root CA at ${$.caCertPath} (${Y.code||Y}), will create one`,w),null}}function w5($){let w=new Set;w.add($);let Y=$.split(".");if(Y.length>=2)w.add(`*.${Y.slice(1).join(".")}`);return Array.from(w)}function J5($){let Y=G8($).replace(/\*/g,"wildcard"),A=F0(u1(),".stacks","ssl"),X=A;if(typeof $?.https==="object")return X=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:A,{caCertPath:$.https.caCertPath||F0(X,`${Y}.ca.crt`),certPath:$.https.certPath||F0(X,`${Y}.crt`),keyPath:$.https.keyPath||F0(X,`${Y}.key`)};return{caCertPath:F0(X,`${Y}.ca.crt`),certPath:F0(X,`${Y}.crt`),keyPath:F0(X,`${Y}.key`)}}function Y5($){let w=new Set;if(Pw($))$.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";w5(A).forEach((X)=>w.add(X))});else if(QY($)){let Y=$.to||"rpx.localhost";w5(Y).forEach((A)=>w.add(A))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function c1($){if(qw&&!$.forceRegenerate){N("ssl","Using cached SSL configuration",$.verbose);return}f8();let w=Pw($)?$.proxies.map((z)=>z.to):[$.to];N("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let Y=LY($,$.verbose),A=Y.basePath||F0(u1(),".stacks","ssl");await G0.mkdir(A,{recursive:!0});let X=X5(A),J=await SH(X,$.verbose),U=!1;if(!J){if($.verbose)R.info("Generating Root CA certificate (one-time)...");J=await wW(Y);try{await Promise.all([G0.writeFile(X.caCertPath,J.certificate),G0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,N("ssl",`Persisted Root CA at ${X.caCertPath}`,$.verbose)}catch(z){throw N("ssl",`Error saving Root CA files: ${z}`,$.verbose),Error(`Failed to save Root CA files: ${z}`)}}else N("ssl",`Reusing existing Root CA from ${X.caCertPath}`,$.verbose);if($.verbose)R.info(`Generating host certificate for: ${w.join(", ")}`);let B=await YW({...Y,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([G0.writeFile(Y.certPath,B.certificate),G0.writeFile(Y.keyPath,B.privateKey),G0.writeFile(Y.caCertPath,J.certificate)]),N("ssl","Certificate files saved successfully",$.verbose)}catch(z){throw N("ssl",`Error saving certificate files: ${z}`,$.verbose),Error(`Failed to save certificate files: ${z}`)}if(U?!1:await W5(X.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(N("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)R.success("Root CA is already trusted in system trust store");if(qw={key:B.privateKey,cert:B.certificate,ca:J.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)R.info("Adding certificate to system trust store (may require sudo permission)...");let j=!1;if(fw.platform==="darwin")try{$B({caPath:X.caCertPath,verbose:$.verbose});let z=K8();try{AB(`security add-trusted-cert ${P1} -k "${z}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(CY(`security add-trusted-cert ${P1} -k ${b1} "${X.caCertPath}"`),$.verbose)R.success("Successfully added Root CA to system trust store");j=!0;let G=F0(A,"trust-rpx-cert.sh"),F=`#!/bin/bash
|
|
182
184
|
echo "Trusting RPX Root CA"
|
|
183
|
-
sudo security add-trusted-cert ${
|
|
185
|
+
sudo security add-trusted-cert ${P1} -k ${b1} "${X.caCertPath}"
|
|
184
186
|
echo "Root CA trusted! Please restart your browser."
|
|
185
187
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
186
|
-
`;await
|
|
188
|
+
`;await G0.writeFile(G,F,{mode:493})}catch(z){if($.verbose)R.warn(`Could not add Root CA to trust store automatically: ${z}`);let G=F0(A,"trust-rpx-cert.sh"),F=`#!/bin/bash
|
|
187
189
|
echo "Trusting RPX Root CA"
|
|
188
|
-
sudo security add-trusted-cert ${
|
|
190
|
+
sudo security add-trusted-cert ${P1} -k ${b1} "${X.caCertPath}"
|
|
189
191
|
echo "Root CA trusted! Please restart your browser."
|
|
190
192
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
191
|
-
`;if(await
|
|
193
|
+
`;if(await G0.writeFile(G,F,{mode:493}),$.verbose)R.info(`Created a trust helper script at: ${G}`),R.info(`If you're still having certificate issues, run: sh ${G}`)}else if(fw.platform==="linux")try{let{exec:z}=await import("node:child_process"),G="/usr/local/share/ca-certificates/rpx",F=`
|
|
192
194
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
193
195
|
cp "${X.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
194
196
|
update-ca-certificates
|
|
195
197
|
echo "RPX Root CA installed. Please restart your browser."
|
|
196
|
-
`,
|
|
198
|
+
`,K=F0(XB.tmpdir(),`rpx-trust-${Date.now()}.sh`);await G0.writeFile(K,F,{mode:493}),await new Promise((f)=>{z(`sudo bash "${K}"`,(E)=>{if(E){if($.verbose)R.warn(`Could not trust certificates: ${E}`);f(!1)}else{if($.verbose)R.success("Successfully added certificates to system trust store");f(!0)}})}),await G0.unlink(K).catch(()=>{}),j=!0}catch(z){if($.verbose)R.warn(`Failed to trust certificates: ${z}`)}else if(fw.platform==="win32")try{let z=`
|
|
197
199
|
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${X.caCertPath.replace(/\//g,"\\")}")
|
|
198
200
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
199
201
|
$store.Open("ReadWrite")
|
|
200
202
|
$store.Add($cert)
|
|
201
203
|
$store.Close()
|
|
202
204
|
Write-Host "Root CA trusted successfully!"
|
|
203
|
-
`,
|
|
204
|
-
`),J=X===-1?
|
|
205
|
-
|
|
206
|
-
|
|
205
|
+
`,G=F0(XB.tmpdir(),"rpx-trust.ps1");if(await G0.writeFile(G,z),AB(`powershell -ExecutionPolicy Bypass -File "${G}"`),$.verbose)R.success("Successfully added certificate to Windows trust store");j=!0}catch(z){if($.verbose)R.warn(`Could not trust certificate: ${z}`)}else try{await JW(B,J.certificate,Y),j=!0}catch(z){if($.verbose)R.warn(`Could not add certificate to trust store: ${z}`)}if(qw={key:B.privateKey,cert:B.certificate,ca:J.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!j&&$.verbose)R.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),R.warn("This will bypass the warning and you should only need to do it once")}function f8(){qw=null}async function e$($){if(!$)return null;if(qw)return qw;let w=LY($);try{let[Y,A,X]=await Promise.all([G0.access(w.keyPath).then(()=>!0).catch(()=>!1),G0.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?G0.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return N("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let J="regenerateUntrustedCerts"in $,U=$.regenerateUntrustedCerts,B=J?U!==!1:!0;N("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${B}`,$.verbose);let W=w.basePath||F0(u1(),".stacks","ssl"),j=X5(W);if(!(B?await W5(j.caCertPath,$):!0))return N("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[G,F,K]=await Promise.all([G0.readFile(w.keyPath,"utf8"),G0.readFile(w.certPath,"utf8"),X&&w.caCertPath?G0.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(K&&!K.includes("-----BEGIN CERTIFICATE-----"))return N("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(Pw($))try{let{X509Certificate:f}=await import("node:crypto"),q=new f(F).subjectAltName||"",M=$.proxies.map((y)=>y.to).filter((y)=>!q.includes(`DNS:${y}`));if(M.length>0)return N("ssl",`Certificate missing SANs for: ${M.join(", ")}, will regenerate`,$.verbose),null}catch(f){N("ssl",`Could not verify cert SANs: ${f}`,$.verbose)}return N("ssl","Successfully loaded existing certificates",$.verbose),qw={key:G,cert:F,ca:K},qw}catch(Y){return N("ssl",`Error checking existing certificates: ${Y}`,$.verbose),null}}function LY($,w){let Y=G8($);N("ssl",`Primary domain: ${Y}`,w);let A=J5($),X=F0(u1(),".stacks","ssl");if(typeof $.https==="object"){let J=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:$.https.caCertPath||A.caCertPath,certPath:$.https.certPath||A.certPath,keyPath:$.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||Y,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(Y5($)).map((B)=>({type:2,value:B}))};if(tW($.https.rootCA))U.rootCA=$.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:w||!1,subjectAltNames:Array.from(Y5($)).map((J)=>({type:2,value:J}))}}async function U5($,w){let Y=J5({to:$,verbose:w}),A=[Y.caCertPath,Y.certPath,Y.keyPath];N("certificates","Attempting to clean up relating certificates",w),await Promise.all(A.map((X)=>sW(X,w)))}async function W5($,w){try{if(N("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),fw.platform==="darwin"){if(w?.serverName)return wB($,w.serverName,{verbose:w?.verbose});return N8($,{verbose:w?.verbose})}else if(fw.platform==="win32")try{let Y=zW($)||"";if(!Y)return N("ssl","Could not extract certificate subject",w?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(AB(A).toString().includes(Y))return N("ssl","Certificate found in trusted root store",w?.verbose),!0;return N("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(Y){return N("ssl",`Error checking certificate trust on Windows: ${Y}`,w?.verbose),!1}else if(fw.platform==="linux")try{let Y=Zw($);if(!Y)return N("ssl","Could not extract certificate fingerprint",w?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await G0.readdir(X)}catch{continue}for(let U of J){let B=Zw(A5.join(X,U));if(B&&B===Y)return N("ssl",`Certificate fingerprint found in ${X}`,w?.verbose),!0}}return N("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(Y){return N("ssl",`Error checking certificate trust on Linux: ${Y}`,w?.verbose),!1}return N("ssl",`Platform ${fw.platform} not supported for certificate trust check`,w?.verbose),!1}catch(Y){return N("ssl",`Error checking if certificate is trusted: ${Y}`,w?.verbose),!1}}var qw=null,E8,OH="rpx-root-ca.crt",_H="rpx-root-ca.key";var q8=o(()=>{hX();u$();jW();YB();X0();YB();kX();kX();E8=F0(u1(),".stacks","ssl","rpx.localhost.crt")});import{createHash as j5,timingSafeEqual as B5}from"node:crypto";import{readFileSync as hH}from"node:fs";function OY($,w){let Y=Buffer.from($,"utf8"),A=Buffer.from(w,"utf8");if(Y.length!==A.length)return B5(Y,Y),!1;return B5(Y,A)}function kH($,w){let Y=(F)=>j5("md5").update(F).digest(),A=Buffer.from($,"utf8"),X=Buffer.from(w,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let F=A.length;F>0;F-=16)U.push(J.subarray(0,Math.min(F,16)));for(let F=A.length;F>0;F>>=1)U.push(F&1?Buffer.from([0]):A.subarray(0,1));let B=Y(Buffer.concat(U));for(let F=0;F<1000;F++){let K=[];if(K.push(F&1?A:B.subarray(0,16)),F%3)K.push(X);if(F%7)K.push(A);K.push(F&1?B.subarray(0,16):A),B=Y(Buffer.concat(K))}let W="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",j=(F,K)=>{let f="",E=F;for(let q=0;q<K;q++)f+=W[E&63],E>>=6;return f},z=B,G="";return G+=j(z[0]<<16|z[6]<<8|z[12],4),G+=j(z[1]<<16|z[7]<<8|z[13],4),G+=j(z[2]<<16|z[8]<<8|z[14],4),G+=j(z[3]<<16|z[9]<<8|z[15],4),G+=j(z[4]<<16|z[10]<<8|z[5],4),G+=j(z[11],2),`$apr1$${w}$${G}`}function DH($,w){if(/^\$2[aby]?\$/.test(w))try{return Bun.password.verifySync($,w)}catch{return!1}if(w.startsWith("$apr1$")){let A=w.split("$")[2]??"";return OY(kH($,A),w)}if(w.startsWith("{SHA}")){let Y=j5("sha1").update($,"utf8").digest("base64");return OY(`{SHA}${Y}`,w)}return OY($,w)}function xH($){let w=new Map;for(let Y of $.split(`
|
|
206
|
+
`)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;w.set(A.slice(0,X),A.slice(X+1))}return w}function v1($){if(!$)return;let w=($.realm??"").trim()||"Restricted",Y=[];if($.username)Y.push({username:$.username,password:$.password??""});for(let J of $.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if($.htpasswdFile)try{A=xH(hH($.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:w,verify:(J,U)=>{let B=!1;for(let W of Y)if(OY(J,W.username)&&OY(U,W.password))B=!0;if(A){let W=A.get(J);if(W&&DH(U,W))B=!0}return B}}}function z5($,w,Y){if(w.startsWith(ZH))return;let A=$.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 j=W.indexOf(":");if(j>=0&&Y.verify(W.slice(0,j),W.slice(j+1)))return}let B=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${B}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var ZH="/.well-known/acme-challenge/";var _Y=()=>{};function uH($){return bH.has($.toUpperCase())}function cH(){let $=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite($)&&$>0?$:30000}function vH($){let w=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(w)&&w>0?w:$*8}function iH(){let $=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite($)&&$>0?$:0}function mH(){let $=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite($)&&$>0?$:0}function gH(){let $=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite($)&&$>0?$:256}class f5{socket=null;buf=new Uint8Array(dH);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($){let w=this.socket,Y=w.write($);while(Y<$.length){if(this.closed)throw T8;await new Promise((A)=>{this.drainWaiter=A}),Y+=w.write($.subarray(Y))}}wakeDrain(){let $=this.drainWaiter;if($)this.drainWaiter=null,$()}push($){if(this.bodyQueue){let w=$.length<=this.bodyRemaining?$.length:this.bodyRemaining;if(w>0)this.bodyQueue.push($.slice(0,w)),this.queuedBytes+=w;if(this.bodyRemaining-=w,w<$.length)this.appendToBuf($.subarray(w));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf($),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()>lH)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=nH)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf($){let w=this.len+$.length;if(w>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,w));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set($,this.len),this.len=w}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let $=this.waiter;if($)this.waiter=null,$()}waitForData($){if(this.len>$||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}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 q5{host;port;maxTotal;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=cH();maxWaiters;checkoutIdleMs=iH();inUse=new Set;constructor($,w,Y){this.host=$;this.port=w;this.maxTotal=Y;this.maxWaiters=vH(Y)}trackCheckout($){if($.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add($),this.ensureSweeper()}dial(){let $=new f5;return PH({hostname:this.host,port:this.port,socket:{data:(w,Y)=>$.push(Y),drain:()=>$.wakeDrain(),close:()=>$.markClosed(),end:()=>$.markClosed(),error:()=>$.markClosed(),connectError:()=>$.markClosed(),timeout:()=>$.markTimedOut()}}).then((w)=>{let Y=w;Y.setNoDelay?.(!0);let A=mH();if(A>0)Y.timeout?.(A);return $.socket=w,$})}acquireIdleSync(){while(this.idle.length){let $=this.idle.pop();if(!$.closed)return $.socket?.ref(),$.pos=0,$.len=0,this.trackCheckout($),$;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw bw;let $=await this.waitForSlot();if($===bw)throw bw;if($)return $.pos=0,$.len=0,this.trackCheckout($),$}this.open++;try{let $=await this.dial();return this.trackCheckout($),$}catch($){throw this.open--,this.wakeWaiter(),$}}waitForSlot(){return new Promise(($)=>{let w=!1,Y=(J)=>{if(w)return;w=!0,clearTimeout(X),$(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(bw)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release($){if(this.inUse.delete($),$.closed){this.open--,this.wakeWaiter();return}$.clearStreaming(),$.compact(),$.fresh=!1;let w=this.waiters.shift();if(w){$.socket?.ref(),this.trackCheckout($),w($);return}$.idleSince=Date.now(),$.socket?.unref(),this.idle.push($),this.ensureSweeper()}destroy($){this.inUse.delete($),$.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let $=this.waiters.shift();if($)$(null)}ensureSweeper(){if(this.sweeper)return;let $=this.checkoutIdleMs>0?Math.min(WB,this.checkoutIdleMs):WB;this.sweeper=setInterval(()=>this.sweep(),$),this.sweeper.unref?.()}sweep(){let $=Date.now(),w=$-WB;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=w)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=$-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)clearInterval(this.sweeper),this.sweeper=null}}function sH($,w){let Y=G5.get($);if(!Y){let A=$.lastIndexOf(":"),X=A===-1?$:$.slice(0,A),J=A===-1?80:Number($.slice(A+1));Y=new q5(X,J,w),G5.set($,Y)}return Y}function F5($,w,Y){for(let A=Y+3;A<w;A++)if($[A]===10&&$[A-1]===13&&$[A-2]===10&&$[A-3]===13)return A-3;return-1}function oH($,w,Y){let A=E5.decode($.subarray(w,Y)),X=A.indexOf(`\r
|
|
207
|
+
`),J=X===-1?A:A.slice(0,X),U=J.indexOf(" "),B=Number.parseInt(J.slice(U+1,U+5),10),W=J.startsWith("HTTP/1.0"),j=[],z=-1,G=!1,F=W,K=!1,f=!1,E=X===-1?A.length:X+2;while(E<A.length){let q=A.indexOf(`\r
|
|
208
|
+
`,E);if(q===-1)q=A.length;let T=A.slice(E,q);if(E=q+2,T==="")continue;let M=T.indexOf(":");if(M===-1)continue;let y=T.slice(0,M),Q=T.slice(M+1).trim(),H=y.charCodeAt(0)|32;if(H===99||H===116||H===107){let I=y.toLowerCase();if(I==="content-length"){let _=/^\d+$/.test(Q)?Number(Q):Number.NaN;if(!Number.isSafeInteger(_)||z>=0&&z!==_)f=!0;else z=_;continue}if(I==="transfer-encoding"){if(Q.toLowerCase().includes("chunked"))G=!0;continue}if(I==="connection"){let _=Q.toLowerCase();if(_.includes("close"))F=!0;if(_.includes("keep-alive"))K=!0;continue}if(I==="keep-alive")continue}j.push([y,Q])}if(W&&K)F=!1;if(G&&z>=0)z=-1;return{status:B,headerEnd:Y,headers:j,contentLength:z,chunked:G,closeConn:F,malformed:f}}function eH($,w){return w||$===204||$===304}async function T5($){let{hostPort:w,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:B}=$,W=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw SY;let j=null;if(B){let K=X.get("content-length"),f=K?Number.parseInt(K,10):Number.NaN;if(Number.isNaN(f)||f>K5)throw SY;if(j=await UR(B),j===null)throw SY}let z=JR(Y,A,X,w,J,U,j),G=z;if(j&&j.length)G=new Uint8Array(z.length+j.length),G.set(z),G.set(j,z.length);let F=sH(w,$.maxPerHost??gH());for(let K=0;;K++){if(K>0)await new Promise((E)=>{setTimeout(E,K)});let f;try{f=F.acquireIdleSync()??await F.acquireOrDial()}catch(E){if(E!==bw&&K<4)continue;throw E}try{let E=f.socket.write(G);if(E<G.length)await f.writeAll(G.subarray(E));return await wR(F,f,W)}catch(E){let q=E===T8&&K<4&&(f.fresh||uH(Y));if(F.destroy(f),q)continue;if(E===T8)throw Error("upstream closed connection");throw E}}}async function $R($){let w=F5($.buf,$.len,$.pos);while(w===-1){if($.closed){if($.timedOut)throw BB;if($.len===$.pos)throw T8;throw Error("upstream closed mid-header")}if($.len-$.pos>N5)throw Error("upstream header block too large");await $.waitForData($.len),w=F5($.buf,$.len,$.pos)}return w}async function wR($,w,Y){let A;for(;;){let J=await $R(w);if(A=oH(w.buf,w.pos,J),w.pos=J+4,A.status>=100&&A.status<200)continue;break}if(A.malformed)throw $.destroy(w),Error("upstream sent malformed response framing");let X=A.headers;if(eH(A.status,Y))return H5($,w,A.closeConn),new Response(null,{status:A.status,headers:X});if(A.chunked)return new Response(XR($,w,A.closeConn),{status:A.status,headers:X});if(A.contentLength>=0){if(w.len-w.pos>=A.contentLength){let U=w.pos+A.contentLength,B=w.len>U,W=null;if(A.contentLength>=pH)W=w.buf.subarray(w.pos,U),w.buf=new Uint8Array(rH);else if(A.contentLength>0)W=w.buf.slice(w.pos,U);if(w.pos=0,w.len=0,A.closeConn||B)$.destroy(w);else $.release(w);return new Response(W,{status:A.status,headers:X})}return new Response(YR($,w,A.contentLength,A.closeConn),{status:A.status,headers:X})}return new Response(AR(w),{status:A.status,headers:X})}function H5($,w,Y){if(Y||w.pos!==w.len)$.destroy(w);else $.release(w)}function YR($,w,Y,A){let X=w.len-w.pos,J=X>0?w.buf.slice(w.pos,w.len):null;w.pos=0,w.len=0,w.bodyQueue=[],w.bodyRemaining=Y-X,w.queuedBytes=0,w.streamingBody=!0;let U=(B)=>{if(w.bodyQueue=null,A||w.len>0)$.destroy(w);else $.release(w);B.close()};return new ReadableStream({start(B){if(J)B.enqueue(J);if(w.bodyRemaining===0&&w.bodyQueue.length===0)U(B)},async pull(B){for(;;){let W=w.bodyQueue;if(W&&W.length>0){let j=W.shift();if(w.queuedBytes-=j.length,w.resumeIfDrained(),B.enqueue(j),w.bodyRemaining===0&&W.length===0)U(B);return}if(w.bodyRemaining===0){if(w.bodyQueue)U(B);return}if(w.closed){w.bodyQueue=null,$.destroy(w),B.error(Error("upstream closed mid-body"));return}await w.waitForBody()}},cancel(){w.bodyQueue=null,$.destroy(w)}})}function AR($){return $.streamingBody=!0,new ReadableStream({async pull(w){for(;;){if($.len>$.pos){w.enqueue($.buf.slice($.pos,$.len)),$.pos=$.len,$.resumeIfDrained();return}if($.closed){$.destroy(),w.close();return}await $.waitForData($.len)}},cancel(){$.destroy()}})}function XR($,w,Y){w.streamingBody=!0;let A=0,X=!1;async function J(){for(;;){for(let U=w.pos;U+1<w.len;U++)if(w.buf[U]===13&&w.buf[U+1]===10){let B=E5.decode(w.buf.subarray(w.pos,U));return w.pos=U+2,B}if(w.closed)throw Error("upstream closed mid-chunk-header");if(w.len-w.pos>N5)throw Error("upstream chunk header too large");await w.waitForData(w.len)}}return new ReadableStream({async pull(U){for(;;){if(A>0){if(w.len===w.pos){if(w.closed){$.destroy(w),U.error(Error("upstream closed mid-chunk"));return}await w.waitForData(w.len);continue}let z=Math.min(A,w.len-w.pos);if(U.enqueue(w.buf.slice(w.pos,w.pos+z)),w.pos+=z,A-=z,w.resumeIfDrained(),A===0)X=!0;return}if(X)await J(),X=!1;let B=await J(),W=B.indexOf(";"),j=Number.parseInt(W===-1?B:B.slice(0,W),16);if(!Number.isInteger(j)||j<0){$.destroy(w),U.error(Error("upstream sent malformed chunk size"));return}if(j===0){for(;;)if(await J()==="")break;H5($,w,Y),U.close();return}A=j}},cancel(){$.destroy(w)}})}function JR($,w,Y,A,X,J,U){let B=`${$} ${w} HTTP/1.1\r
|
|
209
|
+
host: ${A}\r
|
|
207
210
|
x-forwarded-for: 127.0.0.1\r
|
|
208
211
|
x-forwarded-proto: https\r
|
|
209
212
|
x-forwarded-host: ${X}\r
|
|
210
|
-
`;if(J!==void 0)
|
|
211
|
-
`;let
|
|
212
|
-
`}if(
|
|
213
|
-
`,U&&!
|
|
214
|
-
`;return
|
|
215
|
-
`,jN.encode(W)}async function MN($){let w=$.getReader(),A=[],Y=0;for(;;){let{done:U,value:W}=await w.read();if(U)break;if(W){if(Y+=W.length,Y>Tz)return w.cancel().catch(()=>{}),null;A.push(W)}}if(A.length===1)return A[0];let X=new Uint8Array(Y),J=0;for(let U of A)X.set(U,J),J+=U.length;return X}var wN,EA,sX,hf,_1,Tz=1048576,Ez=30000,UN=16384,fN=262144,WN=8192,BN=4096,jN,Hz,zN,Gz;var Iz=F0(()=>{({connect:wN}=Bun),EA=Symbol("rpx.pool.fallback"),sX=Symbol("rpx.pool.stale"),hf=Symbol("rpx.pool.timeout"),_1=Symbol("rpx.pool.busy");jN=new TextEncoder,Hz=new TextDecoder,zN=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);Gz=new Map});import*as G$ from"node:path";function GA($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function yN($){let w=G$.extname($).toLowerCase();return IN[w]??"application/octet-stream"}function CN($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let A=G$.posix.normalize(`/${w}`);if(A.includes(".."))return null;return A.replace(/^\/+/,"")}function hN($,w){let A=CN($);if(A===null)return null;let Y=G$.posix.extname(A);if(w.cleanUrls&&Y===".html"){let X=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:G$.join(w.dir,A),redirectTo:X||"/"}}if(A===""||$.endsWith("/"))return{filePath:G$.join(w.dir,A,"index.html")};if(Y!=="")return{filePath:G$.join(w.dir,A)};if(w.pathRewriteStyle==="flat")return{filePath:G$.join(w.dir,`${A}.html`)};return{filePath:G$.join(w.dir,A,"index.html")}}async function yz($,w){let A=hN($,w);if(!A)return new Response("Forbidden",{status:403});if(A.redirectTo)return new Response(null,{status:301,headers:{Location:A.redirectTo}});let Y=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",X=Bun.file(A.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":yN(A.filePath),"Cache-Control":Y}});if(w.spa){let J=G$.join(w.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 IN;var KA=F0(()=>{IN={".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 LN($){let w=$.headers.get("host")||"",A=w.indexOf(":");return A===-1?w:w.slice(0,A)}function hz($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let A=$.slice(w.length);return A===""?"/":A}return $}function Cz($,w,A){let Y=w.sourceHost??"",J=w.stripBasePathPrefix??!1?hz($,w.basePath):$,U=Kf(J,w.pathRewrites);if(U)Y=U.targetHost,J=U.targetPath,G("request",`Path rewrite: ${$} → ${Y}${J}`,A);return{targetHost:Y,targetPath:J}}function ON($){let w=$.indexOf("://"),A=w===-1?$.indexOf("/"):$.indexOf("/",w+3);if(A===-1)return{pathname:"/",search:""};let Y=$.indexOf("?",A);if(Y===-1)return{pathname:$.slice(A),search:""};return{pathname:$.slice(A,Y),search:$.slice(Y)}}function k1($,w){let A=async(Y,X)=>{let{pathname:J,search:U}=ON(Y.url),W=LN(Y),f=$(W,J);if(!f)return G("request",`No route found for host: ${W}`,w),new Response(`No proxy configured for ${W}`,{status:404});if(f.static){let T=f.stripBasePathPrefix??!0?hz(J,f.basePath):J;return yz(T,f.static)}if(Y.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!X||!f.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:F,targetPath:T}=Cz(J,f,w),K=`ws://${F}${T}${U}`,H={};for(let[M,y]of Y.headers)if(!VN.has(M.toLowerCase())&&M.toLowerCase()!=="host")H[M]=y;H.host=F,H["x-forwarded-for"]="127.0.0.1",H["x-forwarded-proto"]="https",H["x-forwarded-host"]=W;let N={targetUrl:K,forwardHeaders:H};if(X.upgrade(Y,{data:N})){G("ws",`upgraded ${W}${T} → ${K}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}if(!f.sourceHost)return new Response(`No upstream configured for ${W}`,{status:502});if(f.cleanUrls&&J.endsWith(".html")){let F=J.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:F}})}let{targetHost:B,targetPath:j}=Cz(J,f,w),z=f.changeOrigin?`http://${f.sourceHost}`:void 0,E=Y.body!=null&&Y.method!=="GET"&&Y.method!=="HEAD";try{return await qz({hostPort:B,method:Y.method,path:`${j}${U}`,reqHeaders:Y.headers,forwardedHost:W,originOverride:z,body:Y.body})}catch(F){if(F===hf)return G("request",`Upstream timeout for ${W}`,w),new Response("Gateway Timeout",{status:504});if(F===_1)return G("request",`Upstream pool saturated for ${W}`,w),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(F===EA||!E)try{let T=new Headers(Y.headers);if(T.set("host",B),T.set("x-forwarded-for","127.0.0.1"),T.set("x-forwarded-proto","https"),T.set("x-forwarded-host",W),z!==void 0)T.set("origin",z);return await fetch(`http://${B}${j}${U}`,{method:Y.method,headers:T,body:Y.body,redirect:"manual"})}catch(T){return G("request",`Proxy error for ${W}: ${T}`,w),new Response(`Proxy Error: ${T}`,{status:502})}return G("request",`Proxy error for ${W}: ${F}`,w),new Response(`Proxy Error: ${F}`,{status:502})}};return async(Y,X)=>{try{return await A(Y,X)}catch(J){return G("request",`Unhandled proxy handler error: ${J}`,w),new Response("Bad Gateway",{status:502})}}}function D1($){let w=new WeakMap;return{open(A){let{targetUrl:Y,forwardHeaders:X}=A.data,J;try{J=new WebSocket(Y,{headers:X})}catch(W){G("ws",`failed to open upstream ${Y}: ${W}`,$),A.close(1011,"upstream connect failed");return}J.binaryType="arraybuffer";let U={upstream:J,upstreamOpen:!1,pending:[]};w.set(A,U),J.addEventListener("open",()=>{U.upstreamOpen=!0;for(let W of U.pending)J.send(W);U.pending=[]}),J.addEventListener("message",(W)=>{A.send(W.data)}),J.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),J.addEventListener("error",()=>{G("ws",`upstream error for ${Y}`,$);try{A.close(1011,"upstream error")}catch{}})},message(A,Y){let X=w.get(A);if(!X)return;let J=typeof Y==="string"?Y:new Uint8Array(Y);if(X.upstreamOpen)X.upstream.send(J);else X.pending.push(J)},close(A,Y,X){let J=w.get(A);if(!J)return;w.delete(A);try{J.upstream.close(Y||1000,X||"")}catch{}}}}var VN;var oX=F0(()=>{Iz();KA();f0();VN=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});function TA($){return $.startsWith("*.")}function eX($,w){if(!TA(w))return!1;let A=w.slice(1);return $.length>A.length&&$.endsWith(A)}function Z1($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function SN($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function x1($){let w=new Map;for(let Y of $){let X=Z1(Y.path),J=w.get(Y.host);if(!J)J=new Map,w.set(Y.host,J);J.set(X,Y.route)}let A=new Map;for(let[Y,X]of w){let J=[];for(let[U,W]of X)J.push({path:U,route:W});J.sort((U,W)=>W.path.length-U.path.length),A.set(Y,J)}return A}function _N($,w){let A=$.get(w);if(A!==void 0)return A;let Y,X=-1;for(let[J,U]of $){if(!TA(J))continue;if(eX(w,J)){let W=J.length-1;if(W>X)X=W,Y=U}}return Y}function P1($,w,A){let Y=_N($,w);if(!Y)return;for(let X of Y)if(SN(A,X.path))return X.route;return}var $8=()=>{};import*as HA from"node:fs/promises";import*as Vf from"node:path";function kN($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function DN($,w,A,Y){try{let[X,J]=await Promise.all([HA.readFile(w,"utf8"),HA.readFile(A,"utf8")]);return{serverName:$,cert:X,key:J}}catch(X){return G("sni",`skipping ${$}: ${X.message}`,Y),null}}async function w8($,w){let A=new Map;if($.certsDir){let X=[];try{X=await HA.readdir($.certsDir)}catch(J){G("sni",`certsDir read failed (${$.certsDir}): ${J.message}`,w)}for(let J of X){let U=kN(J);if(!U)continue;let W=J.slice(0,-4);A.set(U,{certPath:Vf.join($.certsDir,J),keyPath:Vf.join($.certsDir,`${W}.key`)})}}if($.domains)for(let[X,J]of Object.entries($.domains))A.set(X,J);let Y=[];for(let[X,J]of A){let U=await DN(X,J.certPath,J.keyPath,w);if(U)Y.push(U)}return Y}var Lf=F0(()=>{f0()});import*as Tw from"node:fs/promises";import*as Of from"node:path";function xN($,w){if(!w||w.length===0)return!1;return w.some((A)=>{let Y=A.startsWith(".")?A.slice(1):A;return $===Y||$.endsWith(`.${Y}`)})}function PN($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class NA{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??JX,this.issuer=$.issuer??fU,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??ZN;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!PN($))return!1;if(xN($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return G("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;let w=this.inFlight.get($);if(w)return w;let A=this.negativeCache.get($);if(A!==void 0&&Date.now()<A)return G("on-demand",`${$} negatively cached for ${A-Date.now()}ms`,this.verbose),!1;let Y=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,Y),Y}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return G("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),!1;try{G("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let A={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,A),this.negativeCache.delete($),G("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.negativeCache.set($,Date.now()+this.negativeCacheMs),G("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}async loadFromDisk($){let{certPath:w,keyPath:A}=this.pathsFor($);try{let[Y,X]=await Promise.all([Tw.readFile(w,"utf8"),Tw.readFile(A,"utf8")]),J={serverName:$,cert:Y,key:X};return this.certs.set($,J),G("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:Of.join(this.certsDir,`${$}.crt`),keyPath:Of.join(this.certsDir,`${$}.key`)}}async persist($,w,A){await Tw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:Y,keyPath:X}=this.pathsFor($);await Promise.all([Tw.writeFile(Y,w,"utf8"),Tw.writeFile(X,A,{encoding:"utf8",mode:384})])}}var ZN=60000;var Qf=F0(()=>{CU();f0()});import*as A8 from"node:fs";import*as n0 from"node:fs/promises";import{homedir as bN}from"node:os";import*as Sf from"node:path";import*as Y8 from"node:process";function Hw(){return Sf.join(bN(),".stacks","rpx","registry.d")}function RA($){return typeof $==="string"&&$.length>0&&$.length<=128&&uN.test($)}function _f($,w){if(!RA(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return Sf.join($,`${w}.json`)}function a0($){if(!Number.isInteger($)||$<=0)return!1;try{return Y8.kill($,0),!0}catch(w){return w.code==="EPERM"}}function Vz($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&RA(w.id)&&(Y||X)&&typeof w.to==="string"&&w.to.length>0&&J&&A&&typeof w.createdAt==="string"}async function iN($){await n0.mkdir($,{recursive:!0})}async function Lz($,w=Hw(),A){if(!Vz($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await iN(w);let Y=_f(w,$.id),X=`${Y}.tmp.${Y8.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await n0.writeFile(X,J,{encoding:"utf8",mode:420}),await n0.rename(X,Y),G("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await n0.unlink(X).catch(()=>{}),U}}async function kf($,w=Hw(),A){let Y=_f(w,$);try{await n0.unlink(Y),G("registry",`removed entry ${$}`,A)}catch(X){if(X.code!=="ENOENT")throw X}}async function cN($,w=Hw(),A){let Y=_f(w,$);try{let X=await n0.readFile(Y,"utf8"),J=JSON.parse(X);if(!Vz(J))return G("registry",`entry ${$} failed validation, removing`,A),await n0.unlink(Y).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return G("registry",`entry ${$} has invalid JSON, removing`,A),await n0.unlink(Y).catch(()=>{}),null;throw X}}async function s$($=Hw(),w){let A;try{A=await n0.readdir($)}catch(X){if(X.code==="ENOENT")return[];throw X}let Y=[];for(let X of A){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!RA(J))continue;let U=await cN(J,$,w);if(U)Y.push(U)}return Y}async function b1($=Hw(),w){let A=await s$($,w),Y=0;for(let X of A){if(X.pid===void 0)continue;if(!a0(X.pid))G("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,w),await kf(X.id,$,w).catch(()=>{}),Y++}return Y}function qA($,w={}){let A=w.dir??Hw(),Y=w.debounceMs??100,X=w.pollMs??Math.max(Y*2,250),J=w.verbose;A8.mkdirSync(A,{recursive:!0});let U=null,W=!1,f=null,B=!1,j=(H)=>{return JSON.stringify(H.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})).sort((N,R)=>N.id.localeCompare(R.id)))},z=()=>{if(U=null,W)return;s$(A,J).then((H)=>{return f=j(H),$(H)}).catch((H)=>{G("registry",`watcher onChange failed: ${H}`,J)})},E=()=>{if(W)return;if(U)clearTimeout(U);U=setTimeout(z,Y)},T=setInterval(()=>{if(W||B)return;B=!0,s$(A,J).then((H)=>{if(j(H)!==f)E()}).catch((H)=>{G("registry",`watcher poll failed: ${H}`,J)}).finally(()=>{B=!1})},X),K=A8.watch(A,{persistent:!0},(H,N)=>{if(N&&/\.tmp\.\d+\.\d+$/.test(N))return;E()});return K.on("error",(H)=>{G("registry",`watcher error: ${H}`,J)}),E(),{close:()=>{if(W=!0,U)clearTimeout(U);clearInterval(T),K.close()}}}var uN;var MA=F0(()=>{f0();uN=/^[a-zA-Z0-9._-]+$/});import{spawn as vN}from"node:child_process";import*as o$ from"node:fs/promises";import{homedir as mN}from"node:os";import*as IA from"node:path";import*as L0 from"node:process";function e$(){return IA.join(mN(),".stacks","rpx")}function Qz($=e$()){return IA.join($,"daemon.pid")}async function Oz($=e$()){try{let w=await o$.readFile(Qz($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function dN($=e$()){await o$.unlink(Qz($)).catch(()=>{})}function gN(){let $=L0.execPath,w=IA.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&L0.argv[1])return[$,L0.argv[1],"daemon:start"];return[$,"daemon:start"]}async function Sz($={}){let w=$.rpxDir??e$(),A=$.verbose??!1;await $w({rpxDir:w,verbose:A}).catch((j)=>{G("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,A)});let Y=await Oz(w);if(Y!==null&&a0(Y))return G("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)G("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await dN(w);await o$.mkdir(w,{recursive:!0});let X=$.spawnCommand??gN();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");G("daemon",`spawning daemon: ${X.join(" ")}`,A);let J=vN(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??L0.cwd(),env:$.spawnEnv?{...L0.env,...$.spawnEnv}:L0.env});J.unref();let U=null;J.once("error",(j)=>{U=j});let W=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let j=await Oz(w);if(j!==null&&a0(j))return G("daemon",`daemon registered with pid=${j}`,A),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,f))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var Df=F0(()=>{fw();aX();oX();$8();Lf();Qf();KA();MA();u1();f0()});import*as Rw from"node:fs/promises";import{homedir as nN}from"node:os";import*as Zf from"node:path";function kz(){return Zf.join(nN(),".stacks","rpx")}function xf($=kz()){return Zf.join($,lN)}async function J8($=kz()){try{let w=await Rw.readFile(xf($),"utf8"),A=JSON.parse(w);if(A.version!==X8||!Array.isArray(A.resolvers))return null;return{version:X8,resolvers:A.resolvers.filter((Y)=>typeof Y==="string"),domains:Array.isArray(A.domains)?A.domains.filter((Y)=>typeof Y==="string"):[],ownerPid:typeof A.ownerPid==="number"?A.ownerPid:null,updatedAt:typeof A.updatedAt==="string"?A.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function Dz($,w){await Rw.mkdir($,{recursive:!0}),await Rw.writeFile(xf($),`${JSON.stringify(w,null,2)}
|
|
216
|
-
|
|
213
|
+
`;if(J!==void 0)B+=`origin: ${J}\r
|
|
214
|
+
`;let W=!1;for(let[j,z]of Y){let G=j.toLowerCase();if(aH.has(G))continue;if(J!==void 0&&G==="origin")continue;if(G==="content-length")W=!0;B+=`${j}: ${z}\r
|
|
215
|
+
`}if(B+=`connection: keep-alive\r
|
|
216
|
+
`,U&&!W)B+=`content-length: ${U.length}\r
|
|
217
|
+
`;return B+=`\r
|
|
218
|
+
`,tH.encode(B)}async function UR($){let w=$.getReader(),Y=[],A=0;for(;;){let{done:U,value:B}=await w.read();if(U)break;if(B){if(A+=B.length,A>K5)return w.cancel().catch(()=>{}),null;Y.push(B)}}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 PH,SY,T8,bH,BB,bw,K5=1048576,WB=30000,dH=16384,N5=262144,lH=2097152,nH=524288,pH=8192,rH=4096,tH,E5,aH,G5;var R5=o(()=>{({connect:PH}=Bun),SY=Symbol("rpx.pool.fallback"),T8=Symbol("rpx.pool.stale"),bH=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);BB=Symbol("rpx.pool.timeout"),bw=Symbol("rpx.pool.busy");tH=new TextEncoder,E5=new TextDecoder,aH=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);G5=new Map});function M5($){let w=typeof $==="string"?{to:$}:$,Y=(w.to??"").trim();if(Y&&!/^[a-z][\w+.-]*:\/\//i.test(Y))Y=`https://${Y}`;return Y=Y.replace(/\/+$/,""),{to:Y,status:w.status??301,preservePath:w.preservePath??!0}}function I5($,w,Y){if(!$.preservePath)return $.to||"/";let A=`${w}${Y}`;return A==="/"?`${$.to}/`:`${$.to}${A}`}import*as z$ from"node:path";function hY($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function BR($){let w=z$.extname($).toLowerCase();return WR[w]??"application/octet-stream"}function jR($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let Y=z$.posix.normalize(`/${w}`);if(Y.includes(".."))return null;return Y.replace(/^\/+/,"")}function zR($,w){let Y=jR($);if(Y===null)return null;let A=z$.posix.extname(Y);if(w.cleanUrls&&A===".html"){let X=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:z$.join(w.dir,Y),redirectTo:X||"/"}}if(Y===""||$.endsWith("/"))return{filePath:z$.join(w.dir,Y,"index.html")};if(A!=="")return{filePath:z$.join(w.dir,Y)};if(w.pathRewriteStyle==="flat")return{filePath:z$.join(w.dir,`${Y}.html`)};return{filePath:z$.join(w.dir,Y,"index.html")}}async function V5($,w){let Y=zR($,w);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",X=Bun.file(Y.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":BR(Y.filePath),"Cache-Control":A}});if(w.spa){let J=z$.join(w.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 WR;var ZY=o(()=>{WR={".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 FR($){let w=$.headers.get("host")||"",Y=w.indexOf(":");return Y===-1?w:w.slice(0,Y)}function C5($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let Y=$.slice(w.length);return Y===""?"/":Y}return $}function y5($,w,Y){let A=w.sourceHost??"",J=w.stripBasePathPrefix??!1?C5($,w.basePath):$,U=aW(J,w.pathRewrites);if(U)A=U.targetHost,J=U.targetPath,N("request",`Path rewrite: ${$} → ${A}${J}`,Y);return{targetHost:A,targetPath:J}}function KR($){let w=$.indexOf("://"),Y=w===-1?$.indexOf("/"):$.indexOf("/",w+3);if(Y===-1)return{pathname:"/",search:""};let A=$.indexOf("?",Y);if(A===-1)return{pathname:$.slice(Y),search:""};return{pathname:$.slice(Y,A),search:$.slice(A)}}function i1($,w,Y){let A=async(X,J)=>{let{pathname:U,search:B}=KR(X.url),W=FR(X),j=$(W,U);if(!j&&Y){let f=await Y(W,U,X);if(f instanceof Response)return f;if(f&&f.retry)j=$(W,U)}if(!j)return N("request",`No route found for host: ${W}`,w),new Response(`No proxy configured for ${W}`,{status:404});if(j.auth){let f=z5(X,U,j.auth);if(f)return N("request",`401 challenge for ${W}${U}`,w),f}if(j.redirect){let f=I5(j.redirect,U,B);return N("request",`${j.redirect.status} redirect ${W}${U} → ${f}`,w),new Response(null,{status:j.redirect.status,headers:{location:f}})}if(j.static){let E=j.stripBasePathPrefix??!0?C5(U,j.basePath):U;return V5(E,j.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!J||!j.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:f,targetPath:E}=y5(U,j,w),q=`ws://${f}${E}${B}`,T={};for(let[Q,H]of X.headers)if(!GR.has(Q.toLowerCase())&&Q.toLowerCase()!=="host")T[Q]=H;T.host=f,T["x-forwarded-for"]="127.0.0.1",T["x-forwarded-proto"]="https",T["x-forwarded-host"]=W;let M={targetUrl:q,forwardHeaders:T};if(J.upgrade(X,{data:M})){N("ws",`upgraded ${W}${E} → ${q}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}if(!j.sourceHost)return new Response(`No upstream configured for ${W}`,{status:502});if(j.cleanUrls&&U.endsWith(".html")){let f=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:f}})}let{targetHost:z,targetPath:G}=y5(U,j,w),F=j.changeOrigin?`http://${j.sourceHost}`:void 0,K=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD";try{return await T5({hostPort:z,method:X.method,path:`${G}${B}`,reqHeaders:X.headers,forwardedHost:W,originOverride:F,body:X.body})}catch(f){if(f===BB)return N("request",`Upstream timeout for ${W}`,w),new Response("Gateway Timeout",{status:504});if(f===bw)return N("request",`Upstream pool saturated for ${W}`,w),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(f===SY||!K)try{let E=new Headers(X.headers);if(E.set("host",z),E.set("x-forwarded-for","127.0.0.1"),E.set("x-forwarded-proto","https"),E.set("x-forwarded-host",W),F!==void 0)E.set("origin",F);return await fetch(`http://${z}${G}${B}`,{method:X.method,headers:E,body:X.body,redirect:"manual"})}catch(E){return N("request",`Proxy error for ${W}: ${E}`,w),new Response(`Proxy Error: ${E}`,{status:502})}return N("request",`Proxy error for ${W}: ${f}`,w),new Response(`Proxy Error: ${f}`,{status:502})}};return async(X,J)=>{try{return await A(X,J)}catch(U){return N("request",`Unhandled proxy handler error: ${U}`,w),new Response("Bad Gateway",{status:502})}}}function m1($){let w=new WeakMap;return{open(Y){let{targetUrl:A,forwardHeaders:X}=Y.data,J;try{J=new WebSocket(A,{headers:X})}catch(B){N("ws",`failed to open upstream ${A}: ${B}`,$),Y.close(1011,"upstream connect failed");return}J.binaryType="arraybuffer";let U={upstream:J,upstreamOpen:!1,pending:[]};w.set(Y,U),J.addEventListener("open",()=>{U.upstreamOpen=!0;for(let B of U.pending)J.send(B);U.pending=[]}),J.addEventListener("message",(B)=>{Y.send(B.data)}),J.addEventListener("close",(B)=>{try{Y.close(B.code||1000,B.reason||"")}catch{}}),J.addEventListener("error",()=>{N("ws",`upstream error for ${A}`,$);try{Y.close(1011,"upstream error")}catch{}})},message(Y,A){let X=w.get(Y);if(!X)return;let J=typeof A==="string"?A:new Uint8Array(A);if(X.upstreamOpen)X.upstream.send(J);else X.pending.push(J)},close(Y,A,X){let J=w.get(Y);if(!J)return;w.delete(Y);try{J.upstream.close(A||1000,X||"")}catch{}}}}var GR;var H8=o(()=>{_Y();R5();ZY();X0();GR=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});function y$($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function NR($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function g1($){let w=new Map;for(let A of $){let X=y$(A.path),J=w.get(A.host);if(!J)J=new Map,w.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of w){let J=[];for(let[U,B]of X)J.push({path:U,route:B});J.sort((U,B)=>B.path.length-U.path.length),Y.set(A,J)}return Y}function R8($,w){let Y=$.get(w);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of $){if(!U1(J))continue;if(zY(w,J)){let B=J.length-1;if(B>X)X=B,A=U}}return A}function d1($,w,Y){let A=R8($,w);if(!A)return;for(let X of A)if(NR(Y,X.path))return X.route;return}var kY=()=>{};import*as DY from"node:fs/promises";import*as jB from"node:path";function ER($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function fR($,w,Y,A){try{let[X,J]=await Promise.all([DY.readFile(w,"utf8"),DY.readFile(Y,"utf8")]);return{serverName:$,cert:X,key:J}}catch(X){return N("sni",`skipping ${$}: ${X.message}`,A),null}}async function l1($,w){let Y=new Map;if($.certsDir){let X=[];try{X=await DY.readdir($.certsDir)}catch(J){N("sni",`certsDir read failed (${$.certsDir}): ${J.message}`,w)}for(let J of X){let U=ER(J);if(!U)continue;let B=J.slice(0,-4);Y.set(U,{certPath:jB.join($.certsDir,J),keyPath:jB.join($.certsDir,`${B}.key`)})}}if($.domains)for(let[X,J]of Object.entries($.domains))Y.set(X,J);let A=[];for(let[X,J]of Y){let U=await fR(X,J.certPath,J.keyPath,w);if(U)A.push(U)}return A}var M8=o(()=>{X0()});import*as Tw from"node:fs/promises";import*as zB from"node:path";function TR($,w){if(!w||w.length===0)return!1;return w.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return $===A||$.endsWith(`.${A}`)})}function L5($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class xY{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??VX,this.issuer=$.issuer??iU,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??qR;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!L5($))return!1;if(TR($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return N("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;if(!L5($))return!1;let w=this.inFlight.get($);if(w)return w;let Y=this.negativeCache.get($);if(Y!==void 0&&Date.now()<Y)return N("on-demand",`${$} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1;let A=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,A),A}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return N("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),this.cacheNegative($),!1;try{N("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let Y={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,Y),this.negativeCache.delete($),N("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.cacheNegative($),N("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}cacheNegative($){if(this.negativeCache.size>=Q5){let w=Date.now();for(let[Y,A]of this.negativeCache)if(A<=w)this.negativeCache.delete(Y);if(this.negativeCache.size>=Q5){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set($,Date.now()+this.negativeCacheMs)}async loadFromDisk($){let{certPath:w,keyPath:Y}=this.pathsFor($);try{let[A,X]=await Promise.all([Tw.readFile(w,"utf8"),Tw.readFile(Y,"utf8")]),J={serverName:$,cert:A,key:X};return this.certs.set($,J),N("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:zB.join(this.certsDir,`${$}.crt`),keyPath:zB.join(this.certsDir,`${$}.key`)}}async persist($,w,Y){await Tw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor($);await Promise.all([Tw.writeFile(A,w,"utf8"),Tw.writeFile(X,Y,{encoding:"utf8",mode:384})])}}var qR=60000,Q5=4096;var GB=o(()=>{hX();X0()});import{existsSync as HR,readdirSync as PL,readFileSync as RR,statSync as MR}from"node:fs";import{homedir as IR}from"node:os";import{isAbsolute as VR,join as n1}from"node:path";function O5($,w){if($==="~")return w;if($.startsWith("~/"))return n1(w,$.slice(2));return $}function LR($){let w=$.indexOf(":");return(w===-1?$:$.slice(0,w)).toLowerCase()}function _5($){return $.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function OR($,w){for(let Y of w){let A=`.${Y}`;if($.endsWith(A)){let X=$.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 _R($,w){let Y=w.readText(n1($,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=w.readText(n1($,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function SR($){let w=$.selfRegisters??!1;return{command:$.command,env:$.env,urlEnv:$.urlEnv,selfRegisters:w,routes:$.routes??(w?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function hR($,w){let Y=_R($,w);if(Y?.command)return SR(Y);let A=w.fileExists(n1($,"buddy")),X=w.readText(n1($,"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 KB($,w={}){let Y={dirExists:w.dirExists??FB.dirExists,fileExists:w.fileExists??FB.fileExists,readText:w.readText??FB.readText},A=w.detect??hR,X=w.homeDir??IR(),J=$.tlds??CR,U=($.roots??yR).map((F)=>O5(F,X)),B=$.idleTimeoutMs??QR,W=new Map;for(let F of $.sites??[])W.set(F.to,F);let j=(F)=>F.idleTimeoutMs??B;function z(F){let K=bA(W,F);if(!K)return null;let f=VR(K.dir)?K.dir:O5(K.dir,X),E=K.selfRegisters??!1,q=K.routes??[];if(!E&&q.length===0)q=A(f,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let T=S5({...K.env??{}},void 0,F);return{host:F,id:_5(F),dir:f,command:K.command,env:T,routes:q,selfRegisters:E,idleTimeoutMs:j(K),source:"config"}}function G(F){let K=OR(F,J);if(!K)return null;for(let f of U){let E=n1(f,K);if(!Y.dirExists(E))continue;let q=A(E,Y);if(!q)continue;let T=q.selfRegisters??!1;return{host:F,id:_5(F),dir:E,command:q.command,env:S5({...q.env??{}},q.urlEnv,F),routes:T?[]:q.routes??[],selfRegisters:T,idleTimeoutMs:B,source:"discovered"}}return null}return{resolve(F){let K=LR(F);if(!K)return null;return z(K)??G(K)}}}function S5($,w,Y){if(!w)return $;let A=`https://${Y}`;for(let X of w)if($[X]===void 0)$[X]=A;return $}var yR,CR,QR=1800000,FB;var NB=o(()=>{yR=["~/Code"],CR=["localhost","test"],FB={dirExists:($)=>{try{return MR($).isDirectory()}catch{return!1}},fileExists:($)=>{try{return HR($)}catch{return!1}},readText:($)=>{try{return RR($,"utf8")}catch{return null}}}});import*as I8 from"node:net";function Hw($,w,Y){return N("port",`Checking if port ${$} is in use on ${w}`,Y),new Promise((A)=>{let X=I8.createServer(),J=setTimeout(()=>{N("port",`Checking port ${$} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")N("port",`Port ${$} is in use`,Y),A(!0);else N("port",`Error checking port ${$}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),N("port",`Port ${$} is available`,Y),X.close(),A(!1)});try{X.listen($,w)}catch(U){clearTimeout(J),N("port",`Exception checking port ${$}: ${U}`,Y),A(!0)}})}async function EB($,w,Y,A=50){N("port",`Finding available port starting from ${$} (max attempts: ${A})`,Y);let X=$,J=0;while(J<A){if(J++,!await Hw(X,w,Y))return N("port",`Found available port: ${X} after ${J} attempts`,Y),X;N("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 ${$}`)}function h5($,w,Y=5000,A){return N("port",`Testing connection to ${w}:${$}`,A),new Promise((X)=>{let J=I8.connect({host:w,port:$,timeout:Y});J.once("connect",()=>{N("port",`Successfully connected to ${w}:${$}`,A),J.end(),X(!0)}),J.once("timeout",()=>{N("port",`Connection to ${w}:${$} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{N("port",`Failed to connect to ${w}:${$}: ${U.message}`,A),J.destroy(),X(!1)})})}class V8{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,Y=50){this.hostname=$,this.verbose=w,this.maxRetries=Y}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Hw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await h5($,this.hostname,3000,this.verbose))return N("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let Y=await EB($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await h5(Y,this.hostname,3000,this.verbose))if(Y<$+this.maxRetries)return this.findNextAvailablePort(Y+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort($){N("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var mL;var fB=o(()=>{X0();mL=new V8});import*as y8 from"node:fs";import*as n0 from"node:fs/promises";import{homedir as ZR}from"node:os";import*as qB from"node:path";import*as C8 from"node:process";function Q$(){return qB.join(ZR(),".stacks","rpx","registry.d")}function PY($){return typeof $==="string"&&$.length>0&&$.length<=128&&kR.test($)}function TB($,w){if(!PY(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return qB.join($,`${w}.json`)}function r0($){if(!Number.isInteger($)||$<=0)return!1;try{return C8.kill($,0),!0}catch(w){return w.code==="EPERM"}}function Z5($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&PY(w.id)&&(A||X)&&typeof w.to==="string"&&w.to.length>0&&J&&Y&&typeof w.createdAt==="string"}async function DR($){await n0.mkdir($,{recursive:!0})}async function Q8($,w=Q$(),Y){if(!Z5($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await DR(w);let A=TB(w,$.id),X=`${A}.tmp.${C8.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await n0.writeFile(X,J,{encoding:"utf8",mode:420}),await n0.rename(X,A),N("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(U){throw await n0.unlink(X).catch(()=>{}),U}}async function bY($,w=Q$(),Y){let A=TB(w,$);try{await n0.unlink(A),N("registry",`removed entry ${$}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function xR($,w=Q$(),Y){let A=TB(w,$);try{let X=await n0.readFile(A,"utf8"),J=JSON.parse(X);if(!Z5(J))return N("registry",`entry ${$} failed validation, removing`,Y),await n0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return N("registry",`entry ${$} has invalid JSON, removing`,Y),await n0.unlink(A).catch(()=>{}),null;throw X}}async function C$($=Q$(),w){let Y;try{Y=await n0.readdir($)}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(!PY(J))continue;let U=await xR(J,$,w);if(U)A.push(U)}return A}async function p1($=Q$(),w){let Y=await C$($,w),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!r0(X.pid))N("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,w),await bY(X.id,$,w).catch(()=>{}),A++}return A}function uY($,w={}){let Y=w.dir??Q$(),A=w.debounceMs??100,X=w.pollMs??Math.max(A*2,250),J=w.verbose;y8.mkdirSync(Y,{recursive:!0});let U=null,B=!1,W=null,j=!1,z=(q)=>{return JSON.stringify(q.map((T)=>({id:T.id,from:T.from,to:T.to,path:T.path,pid:T.pid,pathRewrites:T.pathRewrites,cleanUrls:T.cleanUrls,changeOrigin:T.changeOrigin,static:T.static})).sort((T,M)=>T.id.localeCompare(M.id)))},G=()=>{if(U=null,B)return;C$(Y,J).then((q)=>{return W=z(q),$(q)}).catch((q)=>{N("registry",`watcher onChange failed: ${q}`,J)})},F=()=>{if(B)return;if(U)clearTimeout(U);U=setTimeout(G,A)},f=setInterval(()=>{if(B||j)return;j=!0,C$(Y,J).then((q)=>{if(z(q)!==W)F()}).catch((q)=>{N("registry",`watcher poll failed: ${q}`,J)}).finally(()=>{j=!1})},X),E=y8.watch(Y,{persistent:!0},(q,T)=>{if(T&&/\.tmp\.\d+\.\d+$/.test(T))return;F()});return E.on("error",(q)=>{N("registry",`watcher error: ${q}`,J)}),F(),{close:()=>{if(B=!0,U)clearTimeout(U);clearInterval(f),E.close()}}}var kR;var r1=o(()=>{X0();kR=/^[a-zA-Z0-9._-]+$/});import{closeSync as k5,openSync as PR,readFileSync as bR}from"node:fs";import*as D5 from"node:fs/promises";import{spawn as uR}from"node:child_process";import{homedir as cR}from"node:os";import*as cY from"node:path";import*as M$ from"node:process";class L8{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor($){this.resolver=$.resolver,this.registryDir=$.registryDir??Q$(),this.rpxDir=$.rpxDir??cY.join(cR(),".stacks","rpx"),this.verbose=$.verbose??!1,this.startupTimeoutMs=$.startupTimeoutMs??vR,this.pollIntervalMs=$.pollIntervalMs??iR,this.restartDelayMs=$.restartDelayMs??gR,this.killGraceMs=$.killGraceMs??dR,this.launch=$.launcher??nR(this.verbose),this.probePort=$.probePort??lR,this.pickPort=$.pickPort??((Y)=>EB(Y,"127.0.0.1")),this.isHostRoutable=$.isHostRoutable??(()=>!1),this.onSiteActivating=$.onSiteActivating,this.now=$.now??Date.now,this.writeEntry=$.writeEntry??Q8,this.removeEntry=$.removeEntry??bY;let w=$.reapIntervalMs??mR;if(this.reaper=setInterval(()=>{this.reapIdle()},w),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest($){if(this.stopped)return{kind:"unknown"};let w=this.sites.get($);if(w&&w.status==="failed"&&this.now()-w.failedAt>=this.restartDelayMs)this.sites.delete($),w=void 0;if(!w){let Y=this.resolver.resolve($);if(!Y)return{kind:"unknown"};w=await this.start(Y)}if(w.lastAccess=this.now(),w.status==="ready")return{kind:"ready",host:$};if(w.status==="failed")return{kind:"failed",host:$,error:w.error??"failed to start",logTail:this.readLogTail(w)};return{kind:"starting",host:$,sinceMs:this.now()-w.startedAt,source:w.site.source,logTail:this.readLogTail(w,16)}}async start($){try{this.onSiteActivating?.($.host)}catch{}let w=new Map;if(!$.selfRegisters)for(let B of $.routes){if(w.has(B.portEnv))continue;let W=await this.pickPort(B.defaultPort??3000);w.set(B.portEnv,W)}let Y=cY.join(this.rpxDir,"sites",`${$.id}.log`);await D5.mkdir(cY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv($,w),X=null,J;try{X=this.launch({command:$.command,cwd:$.dir,env:A,logPath:Y})}catch(B){J=`failed to spawn: ${B.message}`}let U={site:$,status:J?"failed":"starting",handle:X,ports:w,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($.host,U),J)return R.warn(`rpx: site ${$.host} ${J}`),U;return R.info(`rpx: booting ${$.host} → ${$.command} (${$.dir})`),X.exited.then((B)=>this.onProcessExit(U,B)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((B)=>{N("sites",`readiness loop for ${$.host} threw: ${B}`,this.verbose)}),U}async onProcessExit($,w){if($.exited=!0,this.stopped||this.sites.get($.site.host)!==$)return;if($.status==="ready"){R.warn(`rpx: ${$.site.host} exited${w!==null?` (code ${w})`:""} — will reboot on next request`),this.sites.delete($.site.host);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if($.status==="starting")this.fail($,`process exited${w!==null?` with code ${w}`:""} before becoming ready`)}async driveReadiness($){let{site:w}=$,Y=this.now()+this.startupTimeoutMs,A=w.selfRegisters?()=>this.isHostRoutable(w.host):await this.makeGateProbe(w,$.ports);while(this.now()<Y&&!this.stopped){if($.status!=="starting"||$.exited)return;if(await A()){if(await this.publishRoutes($),$.status==="starting")$.status="ready",R.success(`rpx: ${w.host} ready`);return}await HB(this.pollIntervalMs)}if($.status==="starting")this.fail($,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe($,w){let Y=$.routes.filter((X)=>X.readyGate??y$(X.path)==="/").map((X)=>w.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...w.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes($){let{site:w,ports:Y}=$;if(w.selfRegisters||w.routes.length===0)return;let A=w.routes.find((W)=>y$(W.path)==="/")??w.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let W of w.routes){if(W===A)continue;let j=Y.get(W.portEnv);if(j===void 0)continue;J.push({from:y$(W.path),to:`localhost:${j}`,stripPrefix:W.stripPrefix??!1})}let U={id:w.id,from:`localhost:${X}`,to:w.host,cwd:w.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:$.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),$.routeIds=[w.id];let B=this.now()+2000;while(this.now()<B&&!this.isHostRoutable(w.host))await HB(50)}fail($,w){$.status="failed",$.error=w,$.failedAt=this.now(),R.warn(`rpx: site ${$.site.host} failed — ${w}`),this.killProcess($)}buildEnv($,w){let Y={};for(let[A,X]of Object.entries(M$.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,$.env);for(let[A,X]of w)Y[A]=String(X);return Y.RPX_SITE_HOST=$.host,Y.RPX_SITE_URL=`https://${$.host}`,Y}readLogTail($,w=40){try{return bR($.logPath,"utf8").split(`
|
|
219
|
+
`).slice(-w).join(`
|
|
220
|
+
`).trim()}catch{return""}}async stop($){let w=this.sites.get($);if(!w)return;this.sites.delete($);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(w),R.info(`rpx: stopped ${$}`)}async killProcess($){let w=$.handle;if(!w)return;$.handle=null;try{w.stop("SIGTERM")}catch{}let Y=setTimeout(()=>{try{w.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof Y.unref==="function")Y.unref();await Promise.race([w.exited.catch(()=>{}),HB(this.killGraceMs+500)]),clearTimeout(Y)}async reapIdle(){if(this.stopped)return;let $=this.now();for(let[w,Y]of this.sites){let A=Y.site.idleTimeoutMs;if(A<=0)continue;let X=$-Y.lastAccess;if((Y.status==="ready"||$-Y.startedAt>this.startupTimeoutMs)&&X>A)N("sites",`reaping ${w} (idle ${Math.round(X/1000)}s)`,this.verbose),await this.stop(w)}}list(){let $=this.now();return[...this.sites.values()].map((w)=>({host:w.site.host,dir:w.site.dir,status:w.status,pid:w.handle?.pid??null,ports:Object.fromEntries(w.ports),uptimeMs:$-w.startedAt,idleMs:$-w.lastAccess,error:w.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map(($)=>this.stop($)))}}function HB($){return new Promise((w)=>setTimeout(w,$))}async function lR($){let w=new AbortController,Y=setTimeout(()=>w.abort(),2000);try{return await fetch(`http://127.0.0.1:${$}/`,{signal:w.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(Y)}}function nR($){let w=pR();return({command:Y,cwd:A,env:X,logPath:J})=>{let U=PR(J,"a");try{let B=uR("sh",["-c",Y],{cwd:A,env:X,detached:!0,stdio:["ignore",U,U],...w?{uid:w.uid,gid:w.gid}:{}}),W=B.pid;if(W===void 0)throw Error("spawn returned no pid");let j=new Promise((z)=>{B.once("exit",(G)=>{z(G)}),B.once("error",()=>{z(null)})}).finally(()=>{try{k5(U)}catch{}});return N("sites",`spawned pid ${W}: sh -c ${Y} (cwd ${A})`,$),{pid:W,exited:j,stop:(z="SIGTERM")=>{try{M$.kill(-W,z)}catch{try{B.kill(z)}catch{}}}}}catch(B){try{k5(U)}catch{}throw B}}}function pR(){if(M$.platform==="win32")return null;if(!(typeof M$.getuid==="function"&&M$.getuid()===0))return null;let w=Number.parseInt(M$.env.SUDO_UID??"",10),Y=Number.parseInt(M$.env.SUDO_GID??"",10);if(!Number.isInteger(w)||w<=0||!Number.isInteger(Y)||Y<=0)return null;return{uid:w,gid:Y}}var vR=120000,iR=200,mR=30000,gR=3000,dR=4000;var RB=o(()=>{kY();fB();r1();X0();u$()});function t1($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function x5($,w,Y){return`<!doctype html>
|
|
221
|
+
<html lang="en">
|
|
222
|
+
<head>
|
|
223
|
+
<meta charset="utf-8">
|
|
224
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
225
|
+
${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
|
|
226
|
+
<title>${t1($)}</title>
|
|
227
|
+
<style>${rR}</style>
|
|
228
|
+
</head>
|
|
229
|
+
<body><main class="card">${w}</main></body>
|
|
230
|
+
</html>`}function MB($){let w=Math.max(1,Math.round($.sinceMs/1000)),Y=$.logTail?`<pre>${t1($.logTail)}</pre>`:"",A=`
|
|
231
|
+
<div class="row"><div class="spinner"></div><h1>Starting ${t1($.host)}…</h1></div>
|
|
232
|
+
<p>rpx is booting this site's dev server on demand. This page reloads itself —
|
|
233
|
+
it'll switch to the app as soon as it's ready (usually a few seconds).</p>
|
|
234
|
+
<p>Booting for ${w}s.</p>
|
|
235
|
+
${Y}`;return new Response(x5(`Starting ${$.host}`,A,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function IB($){let w=$.logTail?`<pre>${t1($.logTail)}</pre>`:"<p>No output was captured.</p>",Y=`
|
|
236
|
+
<div class="row"><div class="dot"></div><h1>${t1($.host)} failed to start</h1></div>
|
|
237
|
+
<p>${t1($.error)}</p>
|
|
238
|
+
${w}
|
|
239
|
+
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(x5(`${$.host} failed`,Y,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var rR=`
|
|
240
|
+
:root { color-scheme: light dark }
|
|
241
|
+
* { box-sizing: border-box }
|
|
242
|
+
body {
|
|
243
|
+
margin: 0; min-height: 100vh; display: grid; place-items: center;
|
|
244
|
+
font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
245
|
+
background: #0b0c0f; color: #e7e9ee;
|
|
246
|
+
}
|
|
247
|
+
.card { width: min(92vw, 540px); padding: 2.25rem 2.5rem; }
|
|
248
|
+
.row { display: flex; align-items: center; gap: .75rem; }
|
|
249
|
+
h1 { font-size: 1.15rem; margin: 0; font-weight: 600; letter-spacing: -.01em }
|
|
250
|
+
p { margin: .5rem 0 0; color: #9aa1ad }
|
|
251
|
+
code { color: #cbd2dc; background: #16181d; padding: .1rem .4rem; border-radius: 5px }
|
|
252
|
+
pre {
|
|
253
|
+
margin: 1.25rem 0 0; padding: 1rem; max-height: 40vh; overflow: auto;
|
|
254
|
+
background: #16181d; border: 1px solid #23262d; border-radius: 8px;
|
|
255
|
+
font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color: #aeb6c2;
|
|
256
|
+
white-space: pre-wrap; word-break: break-word;
|
|
257
|
+
}
|
|
258
|
+
.spinner {
|
|
259
|
+
width: 16px; height: 16px; border-radius: 50%;
|
|
260
|
+
border: 2px solid #3a3f4b; border-top-color: #8ab4f8;
|
|
261
|
+
animation: spin .8s linear infinite;
|
|
262
|
+
}
|
|
263
|
+
.dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
|
|
264
|
+
@keyframes spin { to { transform: rotate(360deg) } }
|
|
265
|
+
`;import{spawn as tR}from"node:child_process";import*as $w from"node:fs/promises";import{homedir as aR}from"node:os";import*as vY from"node:path";import*as C0 from"node:process";function ww(){return vY.join(aR(),".stacks","rpx")}function b5($=ww()){return vY.join($,"daemon.pid")}async function P5($=ww()){try{let w=await $w.readFile(b5($),"utf8"),Y=Number.parseInt(w.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch(w){if(w.code==="ENOENT")return null;throw w}}async function sR($=ww()){await $w.unlink(b5($)).catch(()=>{})}function oR(){let $=C0.execPath,w=vY.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&C0.argv[1])return[$,C0.argv[1],"daemon:start"];return[$,"daemon:start"]}async function u5($={}){let w=$.rpxDir??ww(),Y=$.verbose??!1;await Yw({rpxDir:w,verbose:Y}).catch((z)=>{N("daemon",`DNS reconcile before ensureDaemonRunning: ${z}`,Y)});let A=await P5(w);if(A!==null&&r0(A))return N("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)N("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await sR(w);await $w.mkdir(w,{recursive:!0});let X=$.spawnCommand??oR();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");N("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=tR(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??C0.cwd(),env:$.spawnEnv?{...C0.env,...$.spawnEnv}:C0.env});J.unref();let U=null;J.once("error",(z)=>{U=z});let B=$.startupTimeoutMs??5000,W=$.pollIntervalMs??50,j=Date.now()+B;while(Date.now()<j){if(U)throw U;let z=await P5(w);if(z!==null&&r0(z))return N("daemon",`daemon registered with pid=${z}`,Y),{pid:z,spawned:!0};await new Promise((G)=>setTimeout(G,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${B}ms (rpxDir=${w})`)}var VB=o(()=>{u$();q8();H8();kY();M8();GB();NB();RB();ZY();_Y();r1();a1();X0()});import*as Mw from"node:fs/promises";import{homedir as eR}from"node:os";import*as yB from"node:path";function v5(){return yB.join(eR(),".stacks","rpx")}function CB($=v5()){return yB.join($,$M)}async function _8($=v5()){try{let w=await Mw.readFile(CB($),"utf8"),Y=JSON.parse(w);if(Y.version!==O8||!Array.isArray(Y.resolvers))return null;return{version:O8,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(w){if(w.code==="ENOENT")return null;throw w}}async function i5($,w){await Mw.mkdir($,{recursive:!0}),await Mw.writeFile(CB($),`${JSON.stringify(w,null,2)}
|
|
266
|
+
`,"utf8")}async function QB($){await Mw.rm(CB($),{force:!0})}function m5($){let w=$.trim().toLowerCase().replace(/\.$/,"");if(!w||w.includes("127.0.0.1"))return null;if(w==="localhost"||w.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(w))return null;if(!/^[a-z0-9.-]+$/.test(w))return null;return w}function wM($){let w=m5($);if(!w)return null;let Y=w.split(".");if(Y.length<2)return null;return Y.slice(-2).join(".")}function LB($){let w=new Set;for(let Y of $){let A=wM(Y);if(A)w.add(A)}return Array.from(w).sort()}function OB($){let w=new Set;for(let Y of $){let A=m5(Y);if(A)w.add(A)}return Array.from(w).sort()}var O8=1,$M="dns-state.json",c5;var g5=o(()=>{c5=["com","test","dev","app","page","local","localhost","example","invalid"]});var h8={};oB(h8,{tearDownDevelopmentDns:()=>Rw,syncDevelopmentDnsFromRegistry:()=>uw,stopDnsServer:()=>_B,startDnsServer:()=>s5,setupResolver:()=>GM,setupDevelopmentDns:()=>kB,resolverFilePath:()=>s1,removeResolver:()=>KM,removeLegacyTldResolvers:()=>ZB,reconcileStaleDevelopmentDns:()=>Yw,isRpxDevelopmentDnsAnswering:()=>o5,isDnsServerRunning:()=>JM,contentLooksLikeRpxResolver:()=>e5,RPX_RESOLVER_MARKER:()=>p5,DNS_PORT:()=>mY});import d5 from"node:dgram";import*as l5 from"node:fs/promises";import*as n5 from"node:path";import*as Aw from"node:process";function t5($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function a5($,w,Y=0){let A=[],X=w,J=0;while(!0){if(X>=$.length||++J>128)break;let U=$[X];if(U===0){X++;break}if((U&192)===192){if(X+1>=$.length||Y>=10)break;let B=$.readUInt16BE(X)&16383,{name:W}=a5($,B,Y+1);if(W)A.push(W);X+=2;break}if(X++,X+U>$.length)break;A.push($.subarray(X,X+U).toString("ascii")),X+=U}return{name:A.join("."),newOffset:X}}function YM($,w){let{name:Y,newOffset:A}=a5($,w),X=$.readUInt16BE(A),J=$.readUInt16BE(A+2);return{question:{name:Y,type:X,class:J},newOffset:A+4}}function iY($){let w=$.split("."),Y=[];for(let A of w)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function AM($,w,Y){let A=[],X=Buffer.alloc(12);X.writeUInt16BE($,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(iY(w.name));let J=Buffer.alloc(4);J.writeUInt16BE(w.type,0),J.writeUInt16BE(w.class,2),A.push(J),A.push(iY(w.name));let U=Buffer.alloc(10);if(U.writeUInt16BE(w.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),w.type===1){U.writeUInt16BE(4,8),A.push(U);let B=Y.split(".").map((W)=>Number.parseInt(W,10));A.push(Buffer.from(B))}else if(w.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,iY(w.name),J]);return Buffer.concat(A)}function XM($,w){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE($,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(iY(w.name));let X=Buffer.alloc(4);return X.writeUInt16BE(w.type,0),X.writeUInt16BE(w.class,2),Y.push(X),Buffer.concat(Y)}async function s5($,w){if(Aw.platform!=="darwin")return!1;let Y=OB($);if(Y.length===0)return!1;if(t0){for(let A of Y)S8.add(A);return N("dns","DNS server already running — merged domains",w),!0}return S8=new Set(Y),new Promise((A)=>{t0=d5.createSocket("udp4"),t0.on("error",(X)=>{N("dns",`DNS server error: ${X.message}`,w),t0?.close(),t0=null,A(!1)}),t0.on("message",(X,J)=>{try{let U=t5(X),{question:B}=YM(X,12);N("dns",`Query for ${B.name} type ${B.type} from ${J.address}`,w);let W=B.name.toLowerCase(),j=!1;for(let G of S8)if(W===G||W.endsWith(`.${G}`)){j=!0;break}let z;if(j&&(B.type===1||B.type===28))z=AM(U.id,B,"127.0.0.1"),N("dns",`Responding with localhost for ${B.name}`,w);else z=XM(U.id,B),N("dns",`NXDOMAIN for ${B.name}`,w);t0?.send(z,J.port,J.address)}catch(U){N("dns",`Error processing DNS query: ${U}`,w)}}),t0.on("listening",()=>{let X=t0?.address();N("dns",`DNS server listening on ${X?.address}:${X?.port}`,w),A(!0)});try{t0.bind(mY,"127.0.0.1")}catch(X){N("dns",`Failed to bind DNS server: ${X}`,w),A(!1)}})}function _B($){if(t0)N("dns","Stopping DNS server",$),t0.close(),t0=null,S8=new Set}function JM(){return t0!==null}async function o5($,w=500){let Y=$.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let X=d5.createSocket("udp4"),J=setTimeout(()=>{X.close(),A(!1)},w);X.on("message",(B)=>{clearTimeout(J),X.close();try{let W=t5(B);A(W.ancount>0)}catch{A(!1)}}),X.on("error",()=>{clearTimeout(J),X.close(),A(!1)});let U=UM(Y,1);X.send(U,mY,"127.0.0.1",(B)=>{if(B)clearTimeout(J),X.close(),A(!1)})})}function UM($,w){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([iY($),Buffer.from([0,w,0,1])]);return Buffer.concat([Y,A])}function WM(){return`${p5}
|
|
217
267
|
nameserver 127.0.0.1
|
|
218
|
-
port ${
|
|
219
|
-
`}function
|
|
268
|
+
port ${mY}
|
|
269
|
+
`}function s1($){return n5.join(r5,$)}function e5($){return $.includes("127.0.0.1")&&$.includes(String(mY))}async function BM($){try{return await l5.readFile(s1($),"utf8")}catch(w){if(w.code==="ENOENT")return null;throw w}}async function SB($){if(Aw.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),x1));if(!A()&&!Y()){N("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),N("dns","DNS cache flushed",$)}catch(X){N("dns",`Could not flush DNS cache: ${X}`,$)}}function $6($){if(!/^[a-z0-9.-]+$/.test($))throw Error(`refusing unsafe resolver basename: ${JSON.stringify($)}`)}async function jM($,w){$6($);let{execSudoSync:Y}=await Promise.resolve().then(() => (X0(),x1)),A=WM().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${r5} && printf "%b" "${A}" > ${s1($)}'`;Y(X),N("dns",`Created ${s1($)}`,w)}async function zM($,w){$6($);let{execSudoSync:Y}=await Promise.resolve().then(() => (X0(),x1));Y(`rm -f ${s1($)}`),N("dns",`Removed ${s1($)}`,w)}async function GM($,w){return kB({domains:w??[],verbose:$})}async function FM($,w){if(Aw.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),x1));if(!A()&&!Y())return N("dns","SUDO_PASSWORD not set, cannot create resolver files",w),!1;try{for(let X of $)await jM(X,w);return await SB(w),!0}catch(X){return N("dns",`Failed to create resolver file: ${X}`,w),!1}}async function hB($,w){if(Aw.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),x1));if(!A()&&!Y())return;try{for(let X of $)await zM(X,w);await SB(w)}catch(X){N("dns",`Failed to remove resolver files: ${X}`,w)}}async function ZB($){if(Aw.platform!=="darwin")return[];let w=[];for(let Y of c5){let A=await BM(Y);if(A&&e5(A))await hB([Y],$),w.push(Y)}return w}async function kB($){let w=$.rpxDir??ww(),Y=OB($.domains);if(Y.length===0)return!1;let A=LB(Y),X=await s5(Y,$.verbose);if(!X){let B=Y[0];if(B&&await o5(B))X=!0;else N("dns","Dev DNS server not available on 127.0.0.1:15353",$.verbose)}if(!X)return!1;if(!await FM(A,$.verbose))return!1;let U={version:O8,resolvers:A,domains:Y,ownerPid:$.ownerPid??Aw.pid,updatedAt:new Date().toISOString()};return await i5(w,U),!0}async function uw($,w={}){let Y=$.map((W)=>W.to).filter(Boolean),A=w.rpxDir??ww(),X=LB(Y),B=((await _8(A))?.resolvers??[]).filter((W)=>!X.includes(W));if(B.length>0)await hB(B,w.verbose);if(X.length===0){_B(w.verbose),await QB(A);return}await kB({domains:Y,rpxDir:A,verbose:w.verbose,ownerPid:w.ownerPid??Aw.pid})}async function Rw($={}){let w=$.rpxDir??ww();_B($.verbose);let A=(await _8(w))?.resolvers??[];await hB(A,$.verbose),await ZB($.verbose),await QB(w)}async function KM($){await Rw({verbose:$})}async function Yw($={}){let w=$.rpxDir??ww(),Y=await _8(w),A=Y?.ownerPid!=null&&r0(Y.ownerPid);if(Y&&!A){N("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,$.verbose),await Rw($);return}let X=await ZB($.verbose);if(X.length>0)N("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,$.verbose);await SB($.verbose)}var mY=15353,p5="# managed-by: rpx",r5="/etc/resolver",t0=null,S8;var a1=o(()=>{VB();g5();r1();X0();S8=new Set});import{dirname as iM,join as mM}from"path";import*as x0 from"process";import{fileURLToPath as gM}from"url";import{existsSync as g6}from"node:fs";import r8 from"node:fs/promises";import eB from"node:os";import t8 from"node:path";import Ow from"node:process";import{EventEmitter as d6}from"node:events";import Uw from"node:process";import $j from"node:process";import e8 from"node:process";import aY from"node:process";import AY from"node:process";import Aj from"node:tty";import hF,{stdin as j4,stdout as z4}from"node:process";import Jj,{stdin as DF,stdout as xF}from"node:process";import PF from"node:readline";class Wj{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=eB.homedir(),w=t8.join($,".config","clapp");this.configPath=t8.join(w,"telemetry.json")}async isEnabled(){if(Ow.env.DO_NOT_TRACK==="1"||Ow.env.DO_NOT_TRACK==="true")return!1;if(Ow.env.NO_TELEMETRY==="1"||Ow.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,w){if(!await this.isEnabled())return;let A={event:$,...w,timestamp:Date.now(),platform:eB.platform(),nodeVersion:Ow.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand($,w){await this.track("command",{command:$,duration:w})}async trackError($,w){await this.track("error",{error:$,command:w})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let w=await this.loadConfig();return w.lastSent=Date.now(),await this.saveConfig(w),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let w=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(w),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((w)=>setTimeout(w,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:Ow.env.DO_NOT_TRACK==="1"||Ow.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(g6(this.configPath)){let $=await r8.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let w=t8.dirname(this.configPath);await r8.mkdir(w,{recursive:!0}),await r8.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),w=Date.now().toString(36);return`${$}-${w}`}}var sM=new Wj;function l6($,w={}){let Y={_:[]},A=w.alias||{},X=new Set(w.boolean||[]),J={};for(let B of Object.keys(A))for(let W of A[B])J[W]=B;for(let B of X)if(A[B])for(let W of A[B])X.add(W);function U(B,W){let j=J[B]||B;if(Y[j]=W,A[j])for(let z of A[j])Y[z]=W;if(J[B]&&A[J[B]])for(let z of A[J[B]])Y[z]=W;Y[B]=W}for(let B=0;B<$.length;B++){let W=$[B];if(W==="--"){Y._.push(...$.slice(B+1));break}if(W.startsWith("--")){let j=W.indexOf("=");if(j!==-1){let z=W.slice(2,j),G=W.slice(j+1);U(z,G)}else{let z=W.slice(2);if(z.startsWith("no-")){let F=z.slice(3);U(F,!1);continue}let G=J[z]||z;if(X.has(G)||X.has(z))U(z,!0);else{let F=$[B+1];if(F!==void 0&&!F.startsWith("-"))U(z,F),B++;else U(z,!0)}}}else if(W.startsWith("-")&&W.length>1){let j=W.slice(1);for(let z=0;z<j.length;z++){let G=j[z],F=J[G]||G;if(z===j.length-1&&!X.has(F)&&!X.has(G)){let K=$[B+1];if(K!==void 0&&!K.startsWith("-"))U(G,K),B++;else U(G,!0)}else U(G,!0)}}else Y._.push(W)}return Y}function o8($){return $.replace(/[<[].+/,"").trim()}function n6($){let w=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(B)=>{let W=!1,j=B[1];if(j.startsWith("..."))j=j.slice(3),W=!0;return{required:B[0].startsWith("<"),value:j,variadic:W}},J;while(J=w.exec($))A.push(X(J));let U;while(U=Y.exec($))A.push(X(U));return A}function p6($){let w={alias:{},boolean:[]};for(let[Y,A]of $.entries()){if(A.names.length>1)w.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!$.some((J,U)=>{return U!==Y&&J.names.some((B)=>A.names.includes(B))&&typeof J.required==="boolean"}))w.boolean.push(A.names[0])}else w.boolean.push(A.names[0])}return w}function wj($){return $.reduce((w,Y)=>w.length>=Y.length?w:Y,"")}function a8($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function r6($){return $.replace(/([a-z])-([a-z])/g,(w,Y,A)=>{return Y+A.toUpperCase()})}function t6($,w,Y){let A=0,X=w.length,J=$,U;for(;A<X;++A)U=J[w[A]],J=J[w[A]]=A===X-1?Y:U!=null?U:!!~w[A+1].indexOf(".")||!(+w[A+1]>-1)?{}:[]}function a6($,w){for(let Y of Object.keys(w)){let A=w[Y];if(A.shouldTransform){if($[Y]=Array.prototype.concat.call([],$[Y]),typeof A.transformFunction==="function")$[Y]=$[Y].map(A.transformFunction)}}}function s6($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function Bj($){return $.split(".").map((w,Y)=>{return Y===0?r6(w):w}).join(".")}class tY extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
|
|
220
270
|
|
|
221
271
|
Stack trace:
|
|
222
|
-
${this.stack}`;return this.message}}function
|
|
223
|
-
`);let
|
|
272
|
+
${this.stack}`;return this.message}}function o6(){let{env:$}=$j,{TERM:w,TERM_PROGRAM:Y}=$;if($j.platform!=="win32")return w!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||w==="xterm-256color"||w==="alacritty"||w==="rxvt-unicode"||w==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var eY="\x1B",j0=`${eY}[`;var h$={to($,w){if(!w)return`${j0}${$+1}G`;return`${j0}${w+1};${$+1}H`},move($,w){let Y="";if($<0)Y+=`${j0}${-$}D`;else if($>0)Y+=`${j0}${$}C`;if(w<0)Y+=`${j0}${-w}A`;else if(w>0)Y+=`${j0}${w}B`;return Y},up:($=1)=>`${j0}${$}A`,down:($=1)=>`${j0}${$}B`,forward:($=1)=>`${j0}${$}C`,backward:($=1)=>`${j0}${$}D`,nextLine:($=1)=>`${j0}E`.repeat($),prevLine:($=1)=>`${j0}F`.repeat($),left:`${j0}G`,hide:`${j0}?25l`,show:`${j0}?25h`,save:`${eY}7`,restore:`${eY}8`};var s8={screen:`${j0}2J`,up:($=1)=>`${j0}1J`.repeat($),down:($=1)=>`${j0}J`.repeat($),line:`${j0}2K`,lineEnd:`${j0}K`,lineStart:`${j0}1K`,lines($){let w="";for(let Y=0;Y<$;Y++)w+=this.line+(Y<$-1?h$.up():"");if($)w+=h$.left;return w}},w4={screen:`${eY}c`};function e6($,w){let Y=[];for(let A=0;A<=w.length;A++)Y[A]=[A];for(let A=0;A<=$.length;A++)Y[0][A]=A;for(let A=1;A<=w.length;A++)for(let X=1;X<=$.length;X++)if(w.charAt(A-1)===$.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[w.length][$.length]}function jj($,w,Y=2,A=3){return w.map((X)=>({cmd:X,distance:e6($,X)})).filter(({distance:X})=>X<=Y).sort((X,J)=>X.distance-J.distance).slice(0,A).map(({cmd:X})=>X)}class zj{rawName;description;name;names;isBoolean;required;config;negated;constructor($,w,Y){if(this.rawName=$,this.description=w,this.config=Object.assign({},Y),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=o8($).split(",").map((A)=>{let X=A.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return Bj(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($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var A4=e8.argv,$F=`${e8.platform}-${e8.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,Yj=aY.argv,wF=`${aY.platform}-${aY.arch} node-${aY.version}`;class $J{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,Y,A){this.rawName=$,this.description=w,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=o8($);let X=o8($),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=n6($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,w="-v, --version"){return this.versionNumber=$,this.option(w,"Display version number"),this}example($){return this.examples.push($),this}option($,w,Y){let A=new zj($,w,Y);return this.options.push(A),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===$;return this.name===$}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof wJ}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption($){return $=$.split(".")[0],!!this.options.find((w)=>{return w.names.includes($)})}outputHelp(){let{name:$,commands:w}=this.cli,{versionNumber:Y,options:A,helpCallback:X}=this.cli.globalCommand,J=[{body:`${$}${Y?`/${Y}`:""}`}];if(J.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let W=wj(w.map((K)=>K.rawName)),j=new Map,z=[];for(let K of w)if(K.namespace){if(!j.has(K.namespace))j.set(K.namespace,[]);j.get(K.namespace).push(K)}else z.push(K);let G="";if(z.length>0)G+=z.map((K)=>{return` ${a8(K.rawName,W.length)} ${K.description}`}).join(`
|
|
273
|
+
`);let F=Array.from(j.keys()).sort();for(let K of F){let f=j.get(K);if(G.length>0)G+=`
|
|
224
274
|
|
|
225
|
-
`;
|
|
226
|
-
`,
|
|
227
|
-
`)}J.push({title:"Commands",body:
|
|
228
|
-
`)})}let
|
|
229
|
-
`)})}if(this.examples.length>0)J.push({title:"Examples",body:this.examples.map((
|
|
230
|
-
`)});if(X)J=X(J)||J;console.log(J.map((
|
|
231
|
-
${
|
|
275
|
+
`;G+=` ${K}:
|
|
276
|
+
`,G+=f.map((E)=>{return` ${a8(E.rawName,W.length-2)} ${E.description}`}).join(`
|
|
277
|
+
`)}J.push({title:"Commands",body:G}),J.push({title:"For more info, run any command with the `--help` flag",body:w.map((K)=>` $ ${$}${K.displayName===""?"":` ${K.displayName}`} --help`).join(`
|
|
278
|
+
`)})}let B=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)B=B.filter((W)=>W.name!=="version");if(B.length>0){let W=wj(B.map((j)=>j.rawName));J.push({title:"Options",body:B.map((j)=>{return` ${a8(j.rawName,W.length)} ${j.description} ${j.config.default===void 0?"":`(default: ${j.config.default})`}`}).join(`
|
|
279
|
+
`)})}if(this.examples.length>0)J.push({title:"Examples",body:this.examples.map((W)=>{if(typeof W==="function")return W($);return W}).join(`
|
|
280
|
+
`)});if(X)J=X(J)||J;console.log(J.map((W)=>{return W.title?`${W.title}:
|
|
281
|
+
${W.body}`:W.body}).join(`
|
|
232
282
|
|
|
233
|
-
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"
|
|
283
|
+
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?$F:wF}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let Y=this.args.filter((X)=>X.required).slice(this.cli.args.length),A=Y.map((X)=>`<${X.value}>`).join(" ");throw new tY(`Missing required argument${Y.length>1?"s":""}: ${A}
|
|
234
284
|
|
|
235
|
-
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let
|
|
285
|
+
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys($))if(Y!=="--"&&!this.hasOption(Y)&&!w.hasOption(Y)){let X=[...w.options,...this.options].flatMap((W)=>W.names),J=Y.length>1?`--${Y}`:`-${Y}`,U=jj(Y,X),B=`Unknown option \`${J}\``;if(U.length>0)B+=`
|
|
236
286
|
|
|
237
|
-
Did you mean one of these?`,U.forEach((
|
|
238
|
-
• ${
|
|
287
|
+
Did you mean one of these?`,U.forEach((W)=>{let j=W.length>1?`--${W}`:`-${W}`;B+=`
|
|
288
|
+
• ${j}`});throw B+=`
|
|
239
289
|
|
|
240
|
-
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new
|
|
290
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new tY(B)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,Y=[...w.options,...this.options];for(let A of Y){let X=$[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 tY(`Option \`${A.rawName}\` requires a value.
|
|
241
291
|
|
|
242
|
-
Example: ${this.cli.name} ${this.rawName} ${
|
|
292
|
+
Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class wJ extends $J{constructor($){super("@@global@@","",{},$)}}var YF=$J,Ww={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var wY={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function AF(){return!0}function XF(){let $={};$.supportsColor=AF();function w(A,X=[]){let J=A===""?[]:[...X,A],U=function(W){if(!$.supportsColor)return W;let j="",z="";for(let G of J)if(G in wY&&wY[G]in Ww){let F=wY[G];j+=Ww[F][0],z=Ww[F][1]+z}else if(G in Ww)j+=Ww[G][0],z=Ww[G][1]+z;return j+W+z},B=[...Object.keys(Ww),...Object.keys(wY)];for(let W of B)if(!(W in U))Object.defineProperty(U,W,{get(){return w(W,J)}});return U}let Y=[...Object.keys(Ww),...Object.keys(wY)];for(let A of Y)if(!(A in $))Object.defineProperty($,A,{get(){return w(A)}});return $}var YY=XF();class YJ extends d6{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new wJ(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(Y)=>{if(console.log(`
|
|
243
293
|
|
|
244
|
-
Received ${
|
|
294
|
+
Received ${Y}, cleaning up...`),$)try{await $()}catch(A){console.error("Error during cleanup:",A)}Uw.exit(0)};return Uw.on("SIGINT",()=>w("SIGINT")),Uw.on("SIGTERM",()=>w("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,w,Y){if(!Y)Y={};let A=new YF($,w||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option($,w,Y){return this.globalCommand.option($,w,Y),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,w="-v, --version"){return this.globalCommand.version($,w),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:w},Y,A){if(this.args=$,this.options=w,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(YY.red(`
|
|
245
295
|
✗ Command "${$}" not found.
|
|
246
|
-
`)),this.enableDidYouMean){let w=[];for(let
|
|
247
|
-
Run \`${this.name??"cli"} --help\` for usage.`;
|
|
248
|
-
`),
|
|
249
|
-
`),
|
|
250
|
-
`),X=[];for(let J=0;J<Math.max(
|
|
251
|
-
`),U=[];for(let
|
|
252
|
-
`)}class
|
|
253
|
-
`),
|
|
254
|
-
`).length-1;this.output.write(
|
|
255
|
-
`);this.output.write(Y
|
|
256
|
-
`).slice(
|
|
257
|
-
`)),this._prevFrame=$;return}this.output.write(
|
|
258
|
-
`)}finally{await
|
|
259
|
-
`),
|
|
260
|
-
`):E.ca}:null,T=!1,K=[];function H(S){for(let X$ of K)try{X$.kill(S)}catch{}}async function N(S){await pz(A,S,F),H("SIGHUP")}let R=$.onDemandTls,M=R?.enabled?new NA({config:R,certsDir:R.certsDir??$.productionCerts?.certsDir??h$.join(A,"on-demand-certs"),initial:z,verbose:W,onCertAdded:(S)=>{N(S)}}):null;await pz(A,M?M.sniEntries():z,F);let y=await s$(Y,W);await $w({rpxDir:A,verbose:W}).catch((S)=>{G("daemon",`DNS reconcile on start failed: ${S}`,W)}),await kw(y,{rpxDir:A,verbose:W,ownerPid:h.pid}).catch((S)=>{G("daemon",`DNS setup on start failed: ${S}`,W)}),await b1(Y,W).catch(()=>{});let I=qA((S)=>{kw(S,{rpxDir:A,verbose:W,ownerPid:h.pid}).catch((X$)=>{G("daemon",`DNS sync on registry change failed: ${X$}`,W)})},{dir:Y,verbose:W}),C=setInterval(()=>{b1(Y,W).catch(()=>{})},f);C.unref?.();let j0=null;if(J>0)j0=Bun.serve({port:J,hostname:U,fetch(S){return ez(S,M)},error(){return new Response("Bad Request",{status:400})}});function Q(){if(T)return;let S={...h.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:A,RPX_WORKER_REGISTRYDIR:Y,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:W?"1":"0"},X$=Bun.spawn(jR(),{env:S,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(_A,Iw){if(!T)G("daemon",`worker exited (code ${Iw}); respawning`,W),Q()}});K.push(X$)}for(let S=0;S<B;S++)Q();if(W)q.success(`rpx coordinator listening on https://${U}:${X} via ${B} worker(s)${j0?` (http→https on :${J})`:""}`),q.info(`pid file: ${j}`);let _,z0=new Promise((S)=>{_=S});async function t0(){if(T)return z0;if(T=!0,clearInterval(C),I.close(),j0?.stop(!1),H("SIGTERM"),await Promise.race([Promise.all(K.map((S)=>S.exited)),new Promise((S)=>setTimeout(S,3000))]),H("SIGKILL"),await Nw({rpxDir:A,verbose:W}).catch((S)=>{G("daemon",`DNS teardown failed: ${S}`,W)}),await c1(A),await b0.unlink(pf(A)).catch(()=>{}),W)q.info("rpx coordinator stopped");return _(),z0}let r0=(S)=>{G("daemon",`coordinator received ${S}, shutting down`,W),t0().catch(()=>{})};return h.once("SIGINT",r0),h.once("SIGTERM",r0),{stop:t0,done:z0,httpsPort:X,httpPort:J,pidPath:j,ensureCert:(S)=>M?M.ensureCert(S):Promise.resolve(!1)}}function ER(){let $=h.execPath,w=h$.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&h.argv[1])return[$,h.argv[1],"daemon:start"];return[$,"daemon:start"]}async function wF($={}){let w=$.rpxDir??K$(),A=$.verbose??!1;await $w({rpxDir:w,verbose:A}).catch((j)=>{G("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,A)});let Y=await qw(w);if(Y!==null&&a0(Y))return G("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)G("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await c1(w);await b0.mkdir(w,{recursive:!0});let X=$.spawnCommand??ER();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");G("daemon",`spawning daemon: ${X.join(" ")}`,A);let J=rz(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??h.cwd(),env:$.spawnEnv?{...h.env,...$.spawnEnv}:h.env});J.unref();let U=null;J.once("error",(j)=>{U=j});let W=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let j=await qw(w);if(j!==null&&a0(j))return G("daemon",`daemon registered with pid=${j}`,A),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,f))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function AF($={}){let w=$.rpxDir??K$(),A=$.verbose??!1,Y=$.timeoutMs??5000,X=$.pollIntervalMs??50,J=$.forceAfterTimeout??!0,U=await qw(w);if(U===null||!a0(U)){if(U!==null)await c1(w);return await $w({rpxDir:w,verbose:A}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{h.kill(U,"SIGTERM")}catch(f){if(f.code==="ESRCH")return await c1(w),{stopped:!1,pid:U,forced:!1};throw f}let W=Date.now()+Y;while(Date.now()<W){if(!a0(U))return G("daemon",`daemon pid=${U} stopped cleanly`,A),{stopped:!0,pid:U,forced:!1};await new Promise((f)=>setTimeout(f,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${Y}ms`);G("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,A);try{h.kill(U,"SIGKILL")}catch(f){if(f.code!=="ESRCH")throw f}return await c1(w),await Nw({rpxDir:w,verbose:A}).catch((f)=>{G("daemon",`DNS teardown after SIGKILL: ${f}`,A)}),{stopped:!0,pid:U,forced:!0}}async function YF($={}){let w=$.rpxDir??K$();if(await W8(w))return;await $w({rpxDir:w,verbose:$.verbose})}fw();f0();import{spawn as GR}from"node:child_process";import*as Dw from"node:process";class XF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){G("start",`Process ${$} is already running`,A);return}let[Y,...X]=w.command.split(" "),J=w.cwd||Dw.cwd();G("start",`Starting process ${$}:`,A),G("start",` Command: ${Y} ${X.join(" ")}`,A),G("start",` Working directory: ${J}`,A),G("start",` Environment variables: ${E$(w.env)}`,A);let U=GR(Y,X,{cwd:J,env:{...Dw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((W,f)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)G("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),f(B),Dw.emit("SIGINT")}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)G("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),f(Error(`Process ${$} exited with code ${B}`)),Dw.emit("SIGINT")}),A)U.stdout?.on("data",(B)=>{G("process",`[${$}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{G("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else G("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){G("start",`No process found for ${$}`,w);return}return G("start",`Stopping process ${$}`,w),new Promise((Y)=>{if(!A.process){Y();return}A.process.once("exit",()=>{this.processes.delete($),G("start",`Process ${$} stopped`,w),Y()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){G("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){G("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),Y()}})}async stopAll($){if(this.isShuttingDown){G("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,G("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((Y)=>{q.error(`Failed to stop process ${A}:`,Y)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var B8=new XF;f0();import*as l0 from"node:fs/promises";import{homedir as KR}from"node:os";import*as tf from"node:path";import*as rf from"node:process";var TR=/^[a-zA-Z0-9._-]+$/;function Zw(){return tf.join(KR(),".stacks","rpx","registry.d")}function v1($){return typeof $==="string"&&$.length>0&&$.length<=128&&TR.test($)}function af($,w){if(!v1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return tf.join($,`${w}.json`)}function JF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&v1(w.id)&&(Y||X)&&typeof w.to==="string"&&w.to.length>0&&J&&A&&typeof w.createdAt==="string"}async function HR($){await l0.mkdir($,{recursive:!0})}async function UF($,w=Zw(),A){if(!JF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await HR(w);let Y=af(w,$.id),X=`${Y}.tmp.${rf.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await l0.writeFile(X,J,{encoding:"utf8",mode:420}),await l0.rename(X,Y),G("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await l0.unlink(X).catch(()=>{}),U}}async function fF($,w=Zw(),A){let Y=af(w,$);try{await l0.unlink(Y),G("registry",`removed entry ${$}`,A)}catch(X){if(X.code!=="ENOENT")throw X}}async function sf($,w=Zw(),A){let Y=af(w,$);try{let X=await l0.readFile(Y,"utf8"),J=JSON.parse(X);if(!JF(J))return G("registry",`entry ${$} failed validation, removing`,A),await l0.unlink(Y).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return G("registry",`entry ${$} has invalid JSON, removing`,A),await l0.unlink(Y).catch(()=>{}),null;throw X}}async function WF($=Zw(),w){let A;try{A=await l0.readdir($)}catch(X){if(X.code==="ENOENT")return[];throw X}let Y=[];for(let X of A){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!v1(J))continue;let U=await sf(J,$,w);if(U)Y.push(U)}return Y}fw();import{execSync as LR}from"node:child_process";import*as uw from"node:http";import*as HF from"node:http2";import*as NF from"node:net";import*as Y0 from"node:process";var j8=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,V$={bold:j8(1,22),dim:j8(2,22),green:j8(32,39),cyan:j8(36,39)};OU();Df();fw();MA();f0();import*as BF from"node:fs";import*as jF from"node:path";import*as L$ from"node:process";function NR($,w){let Y=(w&&w!=="/"?`${$}${w}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return Y.length>0?Y:"rpx"}async function of($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,Y=new Set,X=$.proxies.map((E)=>{let F=E.id??NR(E.to,E.path);if(!RA(F))throw Error(`invalid registry id "${F}" derived from to="${E.to}"`);if(Y.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return Y.add(F),{...E,id:F}}),J=new Date().toISOString();for(let E of X)await Lz({id:E.id,from:E.from,to:E.to,path:E.path,pid:$.persistent?void 0:L$.pid,cwd:L$.cwd(),createdAt:J,cleanUrls:E.cleanUrls,changeOrigin:E.changeOrigin,pathRewrites:E.pathRewrites,static:E.static},A,w);let U=await Sz({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let E of X){let F=E.static?`static ${typeof E.static==="string"?E.static:E.static.dir}`:E.from;q.success(`https://${E.to} → ${F}`)}if(q.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,f=A??Hw(),B=X.map((E)=>E.id),j=async()=>{if(W)return;W=!0;for(let E of B)await kf(E,A,w).catch((F)=>{G("runner",`removeEntry(${E}) failed: ${F}`,w)})},z=(E)=>{G("runner",`received ${E}, unregistering ${B.length} entries`,w),j().finally(()=>L$.exit(0))};L$.once("SIGINT",z),L$.once("SIGTERM",z),L$.once("exit",()=>{if(W)return;for(let E of B)try{BF.unlinkSync(jF.join(f,`${E}.json`))}catch{}}),await new Promise(()=>{})}f0();import{exec as RR}from"node:child_process";import xw from"node:fs";import FF from"node:os";import $W from"node:path";import*as VA from"node:process";import{promisify as qR}from"node:util";var hA=qR(RR);function zF($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var T$=VA.platform==="win32"?$W.join(VA.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",ef=!1;async function z8($){if(VA.platform==="win32")throw Error("Administrator privileges required on Windows");if(dX()){let{stdout:Y}=await hA($);return Y}let w=Qw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:Y}=await hA(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return ef=!0,Y}if(ef)try{let{stdout:Y}=await hA(`sudo -n sh -c '${A}'`);return Y}catch(Y){G("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:Y}=await hA(`sudo -n sh -c '${A}'`);return ef=!0,Y}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(Y){throw Error(`Failed to execute sudo command: ${Y.message}`)}}async function LA($,w){let A=$.filter((X)=>!zF(X)),Y=$.filter((X)=>zF(X));if(Y.length>0)G("hosts",`Skipping /etc/hosts for loopback dev names: ${Y.join(", ")}`,w);if(A.length===0)return;G("hosts",`Adding hosts: ${A.join(", ")}`,w),G("hosts",`Using hosts file at: ${T$}`,w);try{let X;try{X=await xw.promises.readFile(T$,"utf-8")}catch{G("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{X=await z8(`cat "${T$}"`)}catch(f){throw console.log(" Could not read hosts file — skipping hosts setup"),G("hosts",`sudo read also failed: ${f}`,w),Error(`Cannot read hosts file: ${f}`)}}let J=A.filter((f)=>{let B=`127.0.0.1 ${f}`,j=`::1 ${f}`;return!X.includes(B)&&!X.includes(j)});if(J.length===0){G("hosts","All hosts already exist in hosts file",w);return}let U=J.map((f)=>`
|
|
296
|
+
`)),this.enableDidYouMean){let w=[];for(let A of this.commands){if(A.displayName)w.push(A.displayName);if(A.aliasNames)w.push(...A.aliasNames)}let Y=jj($,w);if(Y.length>0)console.log(YY.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${YY.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(YY.dim("Run"),`${this.name} --help`,YY.dim("to see all available commands")),Uw.exit(1)}async parse($=Yj,w={}){let{run:Y=!0,exitOnError:A=!1}=w;if(A)try{return await this.parse($,{run:Y})}catch(W){throw this.handleUsageError(W),W}if(this.rawArgs=$,!this.name)this.name=$[1]?s6($[1]):"cli";let X=!0,J=$.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let W of this.commands)if(W.isMatched(U)){let j=this.mri(J,W);X=!1;let z={...j,args:j.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 j=this.mri(J,W);this.setParsedInfo(j,W),this.emit("command:!",W);break}}if(X){let W=this.mri($.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 B={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 B}mri($,w){let Y=[...this.globalCommand.options,...w?w.options:[]],A=p6(Y),X=[],J=$.indexOf("--");if(J>-1)X=$.slice(J+1),$=$.slice(0,J);let U=l6($,A),B={_:U._};for(let F of Object.keys(U))if(F!=="_")B[Bj(F)]=U[F];let W=B._,j={"--":X},z=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,G=Object.create(null);for(let F of Y){if(!z&&F.config.default!==void 0)for(let K of F.names)j[K]=F.config.default;if(Array.isArray(F.config.type)){if(G[F.name]===void 0)G[F.name]={shouldTransform:!0,transformFunction:F.config.type[0]}}}for(let F of Object.keys(B))if(F!=="_"){let K=F.split(".");t6(j,K,B[F]),a6(j,G)}return{args:W,options:j}}async run($=Yj){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let A=$,X=A.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
|
|
297
|
+
Run \`${this.name??"cli"} --help\` for usage.`;Uw.stderr.write(`${J}${X}${U}
|
|
298
|
+
`),Uw.exit(A.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((B,W)=>{if(B.variadic)A.push($.slice(W));else A.push($[W])}),A.push(w);let X={command:Y,args:A,options:w};for(let B of Y.beforeHooks)await B(X);let J,U=async()=>{let B=Y.commandAction.apply(this,A);if(B instanceof Promise)J=await B;else J=B;return J};if(Y.middleware.length>0){let B=0,W=async()=>{if(B<Y.middleware.length){let j=Y.middleware[B++];await j({...X,next:W})}else await U()};await W()}else await U();for(let B of Y.afterHooks)await B(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return Uw.removeAllListeners("SIGINT"),Uw.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 Gj{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let w=this.cache.get($);if(!w){this.misses++;return}if(Date.now()-w.timestamp>w.ttl){this.cache.delete($),this.misses++;return}return this.hits++,w.value}set($,w,Y=5000){if(!this.enabled)return;this.cache.set($,{value:w,timestamp:Date.now(),ttl:Y})}has($){if(!this.enabled)return!1;let w=this.cache.get($);if(!w)return!1;if(Date.now()-w.timestamp>w.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[w,Y]of this.cache.entries())if($-Y.timestamp>Y.ttl)this.cache.delete(w)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var J4=new Gj;function JF(){if("FORCE_COLOR"in AY.env)return AY.env.FORCE_COLOR!=="0";if("NO_COLOR"in AY.env||AY.env.TERM==="dumb")return!1;if(AY.platform==="win32")return!0;return Aj.isatty(1)&&Aj.isatty(2)}var Fj=JF();function A0($,w){if(!Fj)return(Y)=>Y;return(Y)=>$+Y+w}var UF=A0("\x1B[0m","\x1B[0m"),WF=A0("\x1B[31m","\x1B[39m"),BF=A0("\x1B[32m","\x1B[39m"),jF=A0("\x1B[33m","\x1B[39m"),zF=A0("\x1B[34m","\x1B[39m"),GF=A0("\x1B[35m","\x1B[39m"),FF=A0("\x1B[36m","\x1B[39m"),KF=A0("\x1B[37m","\x1B[39m"),NF=A0("\x1B[90m","\x1B[39m"),EF=A0("\x1B[1m","\x1B[22m"),fF=A0("\x1B[3m","\x1B[23m"),qF=A0("\x1B[4m","\x1B[24m"),TF=A0("\x1B[2m","\x1B[22m"),HF=A0("\x1B[7m","\x1B[27m"),RF=A0("\x1B[8m","\x1B[28m"),MF=A0("\x1B[9m","\x1B[29m"),IF=A0("\x1B[41m","\x1B[49m"),VF=A0("\x1B[42m","\x1B[49m"),yF=A0("\x1B[43m","\x1B[49m"),CF=A0("\x1B[44m","\x1B[49m"),QF=A0("\x1B[45m","\x1B[49m"),LF=A0("\x1B[46m","\x1B[49m"),OF=A0("\x1B[47m","\x1B[49m"),_F=Fj,SF={reset:UF,red:WF,green:BF,yellow:jF,blue:zF,magenta:GF,cyan:FF,white:KF,gray:NF,bold:EF,italic:fF,underline:qF,dim:TF,inverse:HF,hidden:RF,strikethrough:MF,bgRed:IF,bgGreen:VF,bgYellow:yF,bgBlue:CF,bgMagenta:QF,bgCyan:LF,bgWhite:OF,isColorSupported:_F},sY=SF,ZF=["up","down","left","right","space","enter","cancel"],oY={actions:new Set(ZF),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function Kj($,w){if(typeof $==="string")return oY.aliases.get($)===w;for(let Y of $){if(Y===void 0)continue;if(Kj(Y,w))return!0}return!1}function kF($,w){if($===w)return[];let Y=$.split(`
|
|
299
|
+
`),A=w.split(`
|
|
300
|
+
`),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var G4=hF.platform.startsWith("win"),Xj=Symbol("clapp:cancel");function rY($,w){let Y=$;if(Y.isTTY)Y.setRawMode(w)}function bF($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function uF($){return bF($).length}function Uj($,w,Y){if(!w||w<1)return $;let A=Y?.hard??!1,X=Y?.trim??!0,J=$.split(`
|
|
301
|
+
`),U=[];for(let B of J){if(uF(B)<=w){U.push(X?B.trimEnd():B);continue}if(A){let W="",j=0,z=0;while(z<B.length){let G=B.slice(z).match(/^\x1b\[[0-9;]*m/);if(G){W+=G[0],z+=G[0].length;continue}if(j>=w)U.push(X?W.trimEnd():W),W="",j=0;W+=B[z],j++,z++}if(W)U.push(X?W.trimEnd():W)}else U.push(X?B.trimEnd():B)}return U.join(`
|
|
302
|
+
`)}class AJ{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=DF,output:A=xF,render:X,signal:J,...U}=$;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=w,this._abortSignal=J,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber($,w){let Y=this._subscribers.get($)??[];Y.push(w),this._subscribers.set($,Y)}on($,w){return this.setSubscriber($,{cb:w}),this}once($,w){return this.setSubscriber($,{cb:w,once:!0}),this}emit($,...w){let Y=this._subscribers.get($)??[],A=[];for(let X of Y)if(X.cb(...w),X.once)A.push(()=>Y.splice(Y.indexOf(X),1));for(let X of A)X();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(Xj);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=PF.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),rY(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(h$.show),this.output.off("resize",this.render),rY(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(h$.show),this.output.off("resize",this.render),rY(this.input,!1),$(Xj)})})}_isActionKey($,w){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,w){if(this.userInput=$??"",this.emit("userInput",this.userInput),w&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,w){if(this._track&&w.name!=="return"){if(w.name&&this._isActionKey($,w))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=w.name==="tab"||w.name==="escape"||w.name==="backspace"||w.name==="delete"||w.name==="enter"||w.name==="return"||w.name&&["up","down","left","right"].includes(w.name);if($&&!Y&&$.length===1&&$>=" ")this._manualLine+=$;else if(w.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(w?.name){if(!this._track&&oY.aliases.has(w.name))this.emit("cursor",oY.aliases.get(w.name));if(oY.actions.has(w.name))this.emit("cursor",w.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),w),w?.name==="return"){if(this.opts.validate){let 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(Kj([$,w?.name,w?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
303
|
+
`),rY(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 $=Uj(this._prevFrame,Jj.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
304
|
+
`).length-1;this.output.write(h$.move(-999,$*-1))}render(){let $=Uj(this._render(this)??"",Jj.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(h$.hide);else{let w=kF(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let Y=w[0];this.output.write(h$.move(0,Y)),this.output.write(s8.lines(1));let A=$.split(`
|
|
305
|
+
`);this.output.write(A[Y]),this._prevFrame=$,this.output.write(h$.move(0,A.length-Y-1));return}if(w&&w?.length>1){let Y=w[0];this.output.write(h$.move(0,Y)),this.output.write(s8.down());let X=$.split(`
|
|
306
|
+
`).slice(Y);this.output.write(X.join(`
|
|
307
|
+
`)),this._prevFrame=$;return}this.output.write(s8.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function cF($,w){if($===void 0)return 0;if(w.length===0)return 0;let A=w.findIndex((X)=>X.value===$);return A!==-1?A:0}function vF($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function iF($,w){if(!w)return;if($)return w;return w[0]}class mF extends AJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#A;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return sY.inverse(sY.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[w,...Y]=this.userInput.slice(this._cursor);return`${$}${sY.inverse(w)}${Y.join("")}`}get options(){if(typeof this.#w==="function")return this.#w();return this.#w}constructor($){super($);this.#w=$.options;let w=this.options;this.filteredOptions=[...w],this.multiple=$.multiple===!0,this.#A=$.filter??vF;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.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=w.findIndex((J)=>J.value===A);if(X!==-1)this.toggleSelected(A),this.#$=X}this.focusedValue=this.options[this.#$]?.value,this.on("key",(A,X)=>this.#X(A,X)),this.on("userInput",(A)=>this.#J(A))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#X($,w){let Y=w.name==="up",A=w.name==="down",X=w.name==="return";if(Y||A){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(X)this.value=iF(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(w.name==="tab"||this.isNavigating&&w.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((w)=>w!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#J($){if($!==this.#Y){this.#Y=$;let w=this.options;if($)this.filteredOptions=w.filter((Y)=>this.#A($,Y));else this.filteredOptions=[...w];if(this.#$=cF(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class gF extends AJ{options;cursor=0;#$;getGroupItems($){return this.options.filter((w)=>w.group===$)}isGroupSelected($){let w=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return w.every((A)=>Y.includes(A.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let w=String($.value),Y=this.getGroupItems(w);if(this.isGroupSelected(w))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 w=this.value.includes($.value);this.value=w?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:w}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(w).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((X)=>({...X,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?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.#$&&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.#$&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var dF=o6();var e=($,w)=>dF?$:w,N4=e("◆","*"),E4=e("■","x"),f4=e("▲","x"),q4=e("◇","o"),T4=e("┌","T"),lF=e("│","|"),H4=e("└","—"),R4=e("●",">"),M4=e("○"," "),I4=e("◻","[•]"),V4=e("◼","[+]"),y4=e("◻","[ ]"),C4=e("▪","•"),Q4=e("─","-"),L4=e("╮","+"),O4=e("├","+"),_4=e("╯","+"),S4=e("●","•"),h4=e("◆","*"),Z4=e("▲","!"),k4=e("■","x");var D4={light:e("─","-"),heavy:e("━","="),block:e("█","#")};function nF(){return`${sY.gray(lF)} `}var x4=nF();pJ();import{homedir as rJ}from"node:os";import{join as tJ,resolve as wN}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",P9={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:tJ(rJ(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:tJ(rJ(),".stacks","ssl","stacks.localhost.crt"),keyPath:tJ(rJ(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},aJ=null;async function b9(){if(!aJ)aJ=await nJ({name:"rpx",cwd:wN(__dirname,".."),defaultConfig:P9});return aJ}var J1=P9;import{existsSync as YN,readdirSync as AN,readFileSync as XN,statSync as JN}from"node:fs";import{homedir as c9}from"node:os";import{isAbsolute as UN,join as W1}from"node:path";var v9=["~/Code"],i9=["localhost","test"],WN=1800000,sJ={dirExists:($)=>{try{return JN($).isDirectory()}catch{return!1}},fileExists:($)=>{try{return YN($)}catch{return!1}},readText:($)=>{try{return XN($,"utf8")}catch{return null}}};function oJ($,w){if($==="~")return w;if($.startsWith("~/"))return W1(w,$.slice(2));return $}function BN($){let w=$.indexOf(":");return(w===-1?$:$.slice(0,w)).toLowerCase()}function uA($){return $.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function jN($,w){for(let Y of w){let A=`.${Y}`;if($.endsWith(A)){let X=$.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 zN($,w){let Y=w.readText(W1($,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=w.readText(W1($,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function GN($){let w=$.selfRegisters??!1;return{command:$.command,env:$.env,urlEnv:$.urlEnv,selfRegisters:w,routes:$.routes??(w?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function FN($,w){let Y=zN($,w);if(Y?.command)return GN(Y);let A=w.fileExists(W1($,"buddy")),X=w.readText(W1($,"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 KN($,w={}){let Y={dirExists:w.dirExists??sJ.dirExists,fileExists:w.fileExists??sJ.fileExists,readText:w.readText??sJ.readText},A=w.detect??FN,X=w.homeDir??c9(),J=$.tlds??i9,U=($.roots??v9).map((F)=>oJ(F,X)),B=$.idleTimeoutMs??WN,W=new Map;for(let F of $.sites??[])W.set(F.to,F);let j=(F)=>F.idleTimeoutMs??B;function z(F){let K=bA(W,F);if(!K)return null;let f=UN(K.dir)?K.dir:oJ(K.dir,X),E=K.selfRegisters??!1,q=K.routes??[];if(!E&&q.length===0)q=A(f,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let T=u9({...K.env??{}},void 0,F);return{host:F,id:uA(F),dir:f,command:K.command,env:T,routes:q,selfRegisters:E,idleTimeoutMs:j(K),source:"config"}}function G(F){let K=jN(F,J);if(!K)return null;for(let f of U){let E=W1(f,K);if(!Y.dirExists(E))continue;let q=A(E,Y);if(!q)continue;let T=q.selfRegisters??!1;return{host:F,id:uA(F),dir:E,command:q.command,env:u9({...q.env??{}},q.urlEnv,F),routes:T?[]:q.routes??[],selfRegisters:T,idleTimeoutMs:B,source:"discovered"}}return null}return{resolve(F){let K=BN(F);if(!K)return null;return z(K)??G(K)}}}function NN($){try{return AN($,{withFileTypes:!0}).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}function m9($,w={}){let Y=w.homeDir??c9(),A=$.tlds??i9,X=($.roots??v9).map((G)=>oJ(G,Y)),J=w.readdir??NN,U=KN($,w),B=[],W=new Set,j=(G)=>{if(G&&!W.has(G.host))W.add(G.host),B.push(G)};for(let G of $.sites??[])if(!G.to.includes("*"))j(U.resolve(G.to));let z=A[0]??"localhost";for(let G of X)for(let F of J(G))j(U.resolve(`${F}.${z}`));return B}function u9($,w,Y){if(!w)return $;let A=`https://${Y}`;for(let X of w)if($[X]===void 0)$[X]=A;return $}u$();q8();H8();kY();M8();GB();NB();RB();ZY();_Y();r1();a1();X0();import{spawn as X6}from"node:child_process";import*as P0 from"node:fs/promises";import{homedir as J6}from"node:os";import*as L$ from"node:path";import*as V from"node:process";var NM=5000;function w$(){return L$.join(J6(),".stacks","rpx")}function Vw($=w$()){return L$.join($,"daemon.pid")}async function Iw($=w$()){try{let w=await P0.readFile(Vw($),"utf8"),Y=Number.parseInt(w.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch(w){if(w.code==="ENOENT")return null;throw w}}async function k8($=w$()){let w=await Iw($);return w!==null&&r0(w)}async function U6($=w$()){await P0.mkdir($,{recursive:!0});let w=Vw($);while(!0){try{let A=await P0.open(w,"wx");try{await A.write(`${V.pid}
|
|
308
|
+
`)}finally{await A.close()}return w}catch(A){if(A.code!=="EEXIST")throw A}let Y=await Iw($);if(Y!==null&&r0(Y))throw Error(`rpx daemon already running (pid=${Y})`);await P0.unlink(w).catch(()=>{})}}async function o1($=w$()){await P0.unlink(Vw($)).catch(()=>{})}function W6($){let w=$.cleanUrls??!1,Y=y$($.path),A=v1($.auth);if($.static)return{static:hY($.static,w),cleanUrls:w,basePath:Y,auth:A};let X=$.from??"localhost:1";return{sourceHost:new URL(X.startsWith("http")?X:`http://${X}`).host,cleanUrls:w,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites,basePath:Y,auth:A}}function EM($){return $.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??$[0]??"rpx.localhost"}async function Z8($,w,Y=[],A=!1){let X=await C$(w,$.verbose),J=[...new Set([...X.map((z)=>z.to).filter(Boolean),...Y])],U=EM(J),B=[...new Set([U,...J,"rpx.localhost"])],W=UB(J,U,$.verbose);if(typeof $.https==="object"&&typeof W.https==="object")W.https={...W.https,...$.https};let j=await e$(W);if(j&&(A||!ZX(E8,B)))N("daemon",`regenerating shared cert for host(s): ${B.join(", ")}`,$.verbose),f8(),j=null;if(!j)N("daemon","no usable cert on disk, generating one via tlsx",$.verbose),await c1({...W,forceRegenerate:!0}),j=await e$(W);if(!j)throw Error("failed to bootstrap TLS for rpx daemon");return j}async function fM($,w,Y,A){let X=V.env.SUDO_PASSWORD,J=V.env.HOME??J6(),U=[V.execPath,...V.argv.slice(1)],B=[`HOME=${J}`,`PATH=${V.env.PATH??""}`];if(A)B.push("RPX_VERBOSE=1");for(let[f,E]of Object.entries(V.env))if(E!==void 0&&f!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(f))B.push(`${f}=${E}`);let W=X?["-S","-p","","env",...B,...U]:["-n","env",...B,...U];N("daemon",`elevating daemon via sudo for privileged ports ${w}/${Y}`,A);let j=X6("sudo",W,{detached:!0,stdio:["pipe","ignore","ignore"]}),z=null,G=null;if(j.once("error",(f)=>{z=f}),j.once("exit",(f)=>{G=f??0}),X&&j.stdin)j.stdin.write(`${X}
|
|
309
|
+
`),j.stdin.end();j.unref();let F=Vw($),K=Date.now()+15000;while(Date.now()<K){if(z)throw z;let f=await Iw($);if(f!==null&&r0(f)){if(A)R.success(`rpx daemon elevated to root (pid=${f}, https on :${w})`);return{httpsPort:w,httpPort:Y,pidPath:F,done:Promise.resolve(),stop:async()=>{try{V.kill(f,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(G!==null&&G!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${G}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((E)=>setTimeout(E,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}var w6=!1;function DB(){if(w6)return;w6=!0,V.on("uncaughtException",($)=>{R.error(`rpx daemon: uncaught exception (continuing): ${$?.stack??$}`)}),V.on("unhandledRejection",($)=>{R.error(`rpx daemon: unhandled rejection (continuing): ${$}`)})}function B6($,w){let Y;try{Y=new URL($.url)}catch{return new Response("Bad Request",{status:400})}let A=($.headers.get("host")??Y.hostname).split(":")[0];if(w&&Y.pathname.startsWith("/.well-known/acme-challenge/")){let X=w.challengeStore.handlePath(Y.pathname);if(X!==void 0)return new Response(X,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(w&&!w.hasCert(A))w.ensureCert(A).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${A}${Y.pathname}${Y.search}`}})}async function j6($={}){DB();let w=$.verbose??!1,Y=$.rpxDir??w$(),A=$.registryDir??L$.join(Y,"registry.d"),X=$.httpsPort??443,J=$.httpPort??80,U=$.hostname??"0.0.0.0",B=$.gcIntervalMs??NM;if(V.env.RPX_DAEMON_WORKER==="1")return HM({rpxDir:V.env.RPX_WORKER_RPXDIR??Y,registryDir:V.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(V.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:V.env.RPX_WORKER_HOSTNAME??U,verbose:V.env.RPX_WORKER_VERBOSE==="1"||w});let W=X>0&&X<1024||J>0&&J<1024,j=typeof V.getuid==="function"&&V.getuid()===0;if(V.platform!=="win32"&&W&&!j)return fM(Y,X,J,w);let z=Math.max(1,$.workers??(Number.parseInt(V.env.RPX_WORKERS??"",10)||1));if(z>1){if($.onDemandSites?.enabled)R.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return RM($,{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:w,gcIntervalMs:B,workers:z})}let G=await U6(Y),F=new Map,K=(C,S)=>d1(F,C,S);function f(C){F=g1(C.map((Jw)=>({host:Jw.to,path:Jw.path,route:W6(Jw)})));let S=Array.from(F.keys());N("daemon",`routing table now covers ${S.length} host(s): ${S.join(", ")||"<empty>"}`,w)}await p1(A,w).catch((C)=>{N("daemon",`initial gc failed: ${C}`,w)});let E=await C$(A,w);f(E),await Yw({rpxDir:Y,verbose:w}).catch((C)=>{N("daemon",`DNS reconcile on start failed: ${C}`,w)}),await uw(E,{rpxDir:Y,verbose:w,ownerPid:V.pid}).catch((C)=>{N("daemon",`DNS setup on start failed: ${C}`,w)});let q=[];if($.productionCerts){if(q=await l1($.productionCerts,w),w&&q.length>0)R.info(`SNI: serving ${q.length} real cert(s): ${q.map((C)=>C.serverName).join(", ")}`)}let T=new Set,M=null,y;if($.onDemandSites?.enabled){if(M=new L8({resolver:KB($.onDemandSites),registryDir:A,rpxDir:Y,verbose:w,startupTimeoutMs:$.onDemandSites.startupTimeoutMs,isHostRoutable:(C)=>R8(F,C)!==void 0,onSiteActivating:(C)=>{Lw(C)}}),y=async(C)=>{let S=await M.onRequest(C);switch(S.kind){case"ready":return{retry:!0};case"starting":return MB({host:S.host,sinceMs:S.sinceMs,logTail:S.logTail});case"failed":return IB({host:S.host,error:S.error,logTail:S.logTail});case"unknown":default:return}},w)R.info("rpx: on-demand sites enabled")}let Q=i1(K,w,y),H=m1(w),I=null;if(q.length===0)I=await Z8($,A);let _=$.onDemandTls,h=_?.enabled?new xY({config:_,certsDir:_.certsDir??$.productionCerts?.certsDir??L$.join(Y,"on-demand-certs"),initial:q,verbose:w,onCertAdded:(C)=>{gw(C)}}):null;function u0(C){if(C.length>0)return C.map((S)=>({serverName:S.serverName,cert:S.cert,key:S.key}));return{key:I.key,cert:I.cert,ca:I.ca,requestCert:!1,rejectUnauthorized:!1}}function iw(C){return Bun.serve({port:X,hostname:U,reusePort:D1(),tls:u0(C),fetch(S,Jw){return Q(S,Jw)},websocket:H,error(S){return N("daemon",`https server error: ${S}`,w),new Response(`Server Error: ${S.message}`,{status:500})}})}let yw=(C)=>[...new Set(C.map((S)=>S.to).filter(Boolean))],mw=(C)=>{if(!I)return q;return JB([...yw(C),...T,"rpx.localhost"],I)},Xw=iw(h?h.sniEntries():q.length>0?q:mw(E)),Cw=null,Qw=!1;async function gw(C){if(I$)return;if(Cw=C,Qw)return;Qw=!0;try{while(!I$&&Cw){let S=Cw;Cw=null,N("daemon",`rebuilding :443 with ${S.length} SNI cert(s)`,w),Xw.stop(!1);let Jw,aB=!1;for(let sB=0;sB<20&&!I$;sB++)try{Xw=iw(S),aB=!0;break}catch(b6){Jw=b6,await new Promise((u6)=>setTimeout(u6,25))}if(!aB)R.error(`rpx: failed to rebuild :443 after issuing cert: ${Jw?.message}`)}}finally{Qw=!1}}let S$=null;if(J>0)S$=Bun.serve({port:J,hostname:U,fetch(C){return B6(C,h)},error(){return new Response("Bad Request",{status:400})}});if(w)R.success(`rpx daemon listening on https://${U}:${X}${S$?` (http→https on :${J})`:""}`),R.info(`pid file: ${G}`),R.info(`registry: ${A}`);async function Z(C){if(I$||q.length>0||h||!I)return;try{I=await Z8($,A,[...T]),await gw(mw(C))}catch(S){N("daemon",`TLS sync on registry change failed: ${S}`,w)}}async function Lw(C){if(I$||q.length>0||h||!I||!C)return;if(T.has(C))return;T.add(C);try{I=await Z8($,A,[...T],!0);let S=await C$(A,w);await gw(mw(S))}catch(S){N("daemon",`dev cert refresh for ${C} failed: ${S}`,w)}}let n8=uY((C)=>{f(C),Z(C),uw(C,{rpxDir:Y,verbose:w,ownerPid:V.pid}).catch((S)=>{N("daemon",`DNS sync on registry change failed: ${S}`,w)})},{dir:A,verbose:w}),dw=setInterval(()=>{p1(A,w).then((C)=>{if(C>0)N("daemon",`gc reaped ${C} stale entries`,w)}).catch((C)=>{N("daemon",`periodic gc failed: ${C}`,w)})},B);if(typeof dw.unref==="function")dw.unref();let I$=!1,$Y,lw=new Promise((C)=>{$Y=C});async function p8(){if(I$)return lw;if(I$=!0,clearInterval(dw),n8.close(),await M?.stopAll().catch((C)=>{N("daemon",`site supervisor stopAll failed: ${C}`,w)}),Xw.stop(!1),S$?.stop(!1),await Rw({rpxDir:Y,verbose:w}).catch((C)=>{N("daemon",`DNS teardown failed: ${C}`,w)}),await o1(Y),w)R.info("rpx daemon stopped");return $Y(),lw}let tB=(C)=>{N("daemon",`received ${C}, shutting down`,w),p8().catch(()=>{})};return V.once("SIGINT",tB),V.once("SIGTERM",tB),{stop:p8,done:lw,httpsPort:typeof Xw.port==="number"?Xw.port:X,httpPort:S$&&typeof S$.port==="number"?S$.port:J,pidPath:G,ensureCert:(C)=>h?h.ensureCert(C):Promise.resolve(!1),listSites:()=>M?.list()??[]}}function xB($){return L$.join($,"cluster-sni.json")}async function Y6($,w,Y){let A=xB($),X=`${A}.${V.pid}.tmp`;await P0.writeFile(X,JSON.stringify({sni:w,dev:Y}),"utf8"),await P0.rename(X,A)}async function A6($){try{return JSON.parse(await P0.readFile(xB($),"utf8"))}catch{return{sni:[],dev:null}}}function qM($){if($.sni.length>0)return $.sni.map((w)=>({serverName:w.serverName,cert:w.cert,key:w.key}));if($.dev)return{key:$.dev.key,cert:$.dev.cert,ca:$.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function TM(){let $=V.execPath,w=V.env.RPX_WORKER_BIN;if(w)return[$,w,"daemon:start"];let Y=L$.basename($).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&V.argv[1])return[$,V.argv[1],"daemon:start"];return[$,"daemon:start"]}async function HM($){DB();let{rpxDir:w,registryDir:Y,httpsPort:A,hostname:X,verbose:J}=$,U=new Map,B=(H,I)=>d1(U,H,I),W=(H)=>{U=g1(H.map((I)=>({host:I.to,path:I.path,route:W6(I)})))};W(await C$(Y,J));let j=i1(B,J),z=m1(J),G=!1,F=(H)=>Bun.serve({port:A,hostname:X,reusePort:!0,tls:qM(H),fetch(I,_){return j(I,_)},websocket:z,error(I){return N("daemon",`worker https error: ${I}`,J),new Response(`Server Error: ${I.message}`,{status:500})}}),K=F(await A6(w));async function f(){if(G)return;let H=await A6(w),I=null;for(let h=0;h<20&&!G;h++)try{I=F(H);break}catch{await new Promise((u0)=>setTimeout(u0,25))}if(!I){N("daemon","worker reloadTls: could not bind new listener; keeping current",J);return}let _=K;K=I,_.stop(!1)}let E=uY((H)=>W(H),{dir:Y,verbose:J}),q=()=>{f().catch(()=>{})};V.on("SIGHUP",q);let T,M=new Promise((H)=>{T=H});async function y(){if(G)return M;return G=!0,V.off("SIGHUP",q),E.close(),K.stop(!1),T(),M}let Q=()=>{y().then(()=>V.exit(0)).catch(()=>V.exit(0))};if(V.once("SIGTERM",Q),V.once("SIGINT",Q),J)R.success(`rpx worker (pid ${V.pid}) serving :${A}`);return{stop:y,done:M,httpsPort:typeof K.port==="number"?K.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function RM($,w){DB();let{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:B,gcIntervalMs:W,workers:j}=w,z=await U6(Y),G=[];if($.productionCerts)G=await l1($.productionCerts,B);let F=null;if(G.length===0)F=await Z8($,A);let K=F?{key:F.key,cert:F.cert,ca:Array.isArray(F.ca)?F.ca.join(`
|
|
310
|
+
`):F.ca}:null,f=!1,E=[];function q(Z){for(let Lw of E)try{Lw.kill(Z)}catch{}}async function T(Z){await Y6(Y,Z,K),q("SIGHUP")}let M=$.onDemandTls,y=M?.enabled?new xY({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??L$.join(Y,"on-demand-certs"),initial:G,verbose:B,onCertAdded:(Z)=>{T(Z)}}):null;await Y6(Y,y?y.sniEntries():G,K);let Q=await C$(A,B);await Yw({rpxDir:Y,verbose:B}).catch((Z)=>{N("daemon",`DNS reconcile on start failed: ${Z}`,B)}),await uw(Q,{rpxDir:Y,verbose:B,ownerPid:V.pid}).catch((Z)=>{N("daemon",`DNS setup on start failed: ${Z}`,B)}),await p1(A,B).catch(()=>{});let H=uY((Z)=>{uw(Z,{rpxDir:Y,verbose:B,ownerPid:V.pid}).catch((Lw)=>{N("daemon",`DNS sync on registry change failed: ${Lw}`,B)})},{dir:A,verbose:B}),I=setInterval(()=>{p1(A,B).catch(()=>{})},W);I.unref?.();let _=null;if(J>0)_=Bun.serve({port:J,hostname:U,fetch(Z){return B6(Z,y)},error(){return new Response("Bad Request",{status:400})}});let h=10,u0=60000,iw=30000,yw=0,mw=Date.now();function Xw(){if(f)return;let Z={...V.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:B?"1":"0"},Lw=Bun.spawn(TM(),{env:Z,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(n8,dw){if(f)return;let I$=E.indexOf(n8);if(I$!==-1)E.splice(I$,1);let $Y=Date.now();if($Y-mw>u0)mw=$Y,yw=0;if(yw++,yw>h){R.error(`rpx: worker keeps exiting (code ${dw}); giving up after ${h} restarts in ${Math.round(u0/1000)}s`);return}let lw=Math.min(iw,100*2**Math.min(yw,8));N("daemon",`worker exited (code ${dw}); respawning in ${lw}ms (restart ${yw}/${h})`,B),setTimeout(Xw,lw).unref?.()}});E.push(Lw)}for(let Z=0;Z<j;Z++)Xw();if(B)R.success(`rpx coordinator listening on https://${U}:${X} via ${j} worker(s)${_?` (http→https on :${J})`:""}`),R.info(`pid file: ${z}`);let Cw,Qw=new Promise((Z)=>{Cw=Z});async function gw(){if(f)return Qw;if(f=!0,clearInterval(I),H.close(),_?.stop(!1),q("SIGTERM"),await Promise.race([Promise.all(E.map((Z)=>Z.exited)),new Promise((Z)=>setTimeout(Z,3000))]),q("SIGKILL"),await Rw({rpxDir:Y,verbose:B}).catch((Z)=>{N("daemon",`DNS teardown failed: ${Z}`,B)}),await o1(Y),await P0.unlink(xB(Y)).catch(()=>{}),B)R.info("rpx coordinator stopped");return Cw(),Qw}let S$=(Z)=>{N("daemon",`coordinator received ${Z}, shutting down`,B),gw().catch(()=>{})};return V.once("SIGINT",S$),V.once("SIGTERM",S$),{stop:gw,done:Qw,httpsPort:X,httpPort:J,pidPath:z,ensureCert:(Z)=>y?y.ensureCert(Z):Promise.resolve(!1),listSites:()=>[]}}function MM(){let $=V.execPath,w=L$.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&V.argv[1])return[$,V.argv[1],"daemon:start"];return[$,"daemon:start"]}async function z6($={}){let w=$.rpxDir??w$(),Y=$.verbose??!1;await Yw({rpxDir:w,verbose:Y}).catch((z)=>{N("daemon",`DNS reconcile before ensureDaemonRunning: ${z}`,Y)});let A=await Iw(w);if(A!==null&&r0(A))return N("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)N("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await o1(w);await P0.mkdir(w,{recursive:!0});let X=$.spawnCommand??MM();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");N("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=X6(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??V.cwd(),env:$.spawnEnv?{...V.env,...$.spawnEnv}:V.env});J.unref();let U=null;J.once("error",(z)=>{U=z});let B=$.startupTimeoutMs??5000,W=$.pollIntervalMs??50,j=Date.now()+B;while(Date.now()<j){if(U)throw U;let z=await Iw(w);if(z!==null&&r0(z))return N("daemon",`daemon registered with pid=${z}`,Y),{pid:z,spawned:!0};await new Promise((G)=>setTimeout(G,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${B}ms (rpxDir=${w})`)}async function G6($={}){let w=$.rpxDir??w$(),Y=$.verbose??!1,A=$.timeoutMs??5000,X=$.pollIntervalMs??50,J=$.forceAfterTimeout??!0,U=await Iw(w);if(U===null||!r0(U)){if(U!==null)await o1(w);return await Yw({rpxDir:w,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{V.kill(U,"SIGTERM")}catch(W){if(W.code==="ESRCH")return await o1(w),{stopped:!1,pid:U,forced:!1};throw W}let B=Date.now()+A;while(Date.now()<B){if(!r0(U))return N("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`);N("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{V.kill(U,"SIGKILL")}catch(W){if(W.code!=="ESRCH")throw W}return await o1(w),await Rw({rpxDir:w,verbose:Y}).catch((W)=>{N("daemon",`DNS teardown after SIGKILL: ${W}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function F6($={}){let w=$.rpxDir??w$();if(await k8(w))return;await Yw({rpxDir:w,verbose:$.verbose})}u$();X0();import{spawn as IM}from"node:child_process";import*as D8 from"node:process";class K6{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){N("start",`Process ${$} is already running`,Y);return}let[A,...X]=w.command.split(" "),J=w.cwd||D8.cwd();N("start",`Starting process ${$}:`,Y),N("start",` Command: ${A} ${X.join(" ")}`,Y),N("start",` Working directory: ${J}`,Y),N("start",` Environment variables: ${R$(w.env)}`,Y);let U=IM(A,X,{cwd:J,env:{...D8.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((B,W)=>{if(U.on("error",(j)=>{if(!this.isShuttingDown)N("start",`Process ${$} failed to start: ${j}`,Y),this.processes.delete($),W(j)}),U.on("exit",(j)=>{if(!this.isShuttingDown&&j!==null&&j!==0)N("start",`Process ${$} exited with code ${j}; leaving the proxy running`,Y),this.processes.delete($),W(Error(`Process ${$} exited with code ${j}`))}),Y)U.stdout?.on("data",(j)=>{N("process",`[${$}] ${j.toString().trim()}`,!0)}),U.stderr?.on("data",(j)=>{N("process",`[${$}] ERR: ${j.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else N("start",`Process ${$} started successfully`,Y),B()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){N("start",`No process found for ${$}`,w);return}return N("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),N("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){N("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){N("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,N("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var x8=new K6;X0();import*as p0 from"node:fs/promises";import{homedir as VM}from"node:os";import*as PB from"node:path";import*as bB from"node:process";var yM=/^[a-zA-Z0-9._-]+$/;function cw(){return PB.join(VM(),".stacks","rpx","registry.d")}function e1($){return typeof $==="string"&&$.length>0&&$.length<=128&&yM.test($)}function uB($,w){if(!e1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return PB.join($,`${w}.json`)}function N6($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&e1(w.id)&&(A||X)&&typeof w.to==="string"&&w.to.length>0&&J&&Y&&typeof w.createdAt==="string"}async function CM($){await p0.mkdir($,{recursive:!0})}async function E6($,w=cw(),Y){if(!N6($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await CM(w);let A=uB(w,$.id),X=`${A}.tmp.${bB.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await p0.writeFile(X,J,{encoding:"utf8",mode:420}),await p0.rename(X,A),N("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(U){throw await p0.unlink(X).catch(()=>{}),U}}async function f6($,w=cw(),Y){let A=uB(w,$);try{await p0.unlink(A),N("registry",`removed entry ${$}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function cB($,w=cw(),Y){let A=uB(w,$);try{let X=await p0.readFile(A,"utf8"),J=JSON.parse(X);if(!N6(J))return N("registry",`entry ${$} failed validation, removing`,Y),await p0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return N("registry",`entry ${$} has invalid JSON, removing`,Y),await p0.unlink(A).catch(()=>{}),null;throw X}}async function vB($=cw(),w){let Y;try{Y=await p0.readdir($)}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(!e1(J))continue;let U=await cB(J,$,w);if(U)A.push(U)}return A}u$();import{execSync as DM}from"node:child_process";import*as d8 from"node:http";import*as O6 from"node:net";import*as J0 from"node:process";var P8=($,w)=>(Y)=>`\x1B[${$}m${Y}\x1B[${w}m`,O$={bold:P8(1,22),dim:P8(2,22),green:P8(32,39),cyan:P8(36,39)};jW();VB();u$();r1();X0();import*as q6 from"node:fs";import*as T6 from"node:path";import*as _$ from"node:process";function QM($,w){let A=(w&&w!=="/"?`${$}${w}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function iB($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,Y=$.registryDir,A=new Set,X=$.proxies.map((F)=>{let K=F.id??QM(F.to,F.path);if(!PY(K))throw Error(`invalid registry id "${K}" derived from to="${F.to}"`);if(A.has(K))throw Error(`duplicate registry id "${K}" — set an explicit \`id\` on one of the proxies`);return A.add(K),{...F,id:K}}),J=new Date().toISOString();for(let F of X)await Q8({id:F.id,from:F.from,to:F.to,path:F.path,pid:$.persistent?void 0:_$.pid,cwd:_$.cwd(),createdAt:J,cleanUrls:F.cleanUrls,changeOrigin:F.changeOrigin,pathRewrites:F.pathRewrites,static:F.static},Y,w);let U=await u5({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let F of X){let K=F.static?`static ${typeof F.static==="string"?F.static:F.static.dir}`:F.from;R.success(`https://${F.to} → ${K}`)}if(R.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let B=!1,W=Y??Q$(),j=X.map((F)=>F.id),z=async()=>{if(B)return;B=!0;for(let F of j)await bY(F,Y,w).catch((K)=>{N("runner",`removeEntry(${F}) failed: ${K}`,w)})},G=(F)=>{N("runner",`received ${F}, unregistering ${j.length} entries`,w),z().finally(()=>_$.exit(0))};_$.once("SIGINT",G),_$.once("SIGTERM",G),_$.once("exit",()=>{if(B)return;for(let F of j)try{q6.unlinkSync(T6.join(W,`${F}.json`))}catch{}}),await new Promise(()=>{})}X0();import{exec as LM}from"node:child_process";import vw from"node:fs";import R6 from"node:os";import gB from"node:path";import*as dY from"node:process";import{promisify as OM}from"node:util";var gY=OM(LM);function H6($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var G$=dY.platform==="win32"?gB.join(dY.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",mB=!1;async function b8($){if(dY.platform==="win32")throw Error("Administrator privileges required on Windows");if(z8()){let{stdout:A}=await gY($);return A}let w=xw(),Y=$.replace(/'/g,"'\\''");try{if(w){let{stdout:A}=await gY(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`);return mB=!0,A}if(mB)try{let{stdout:A}=await gY(`sudo -n sh -c '${Y}'`);return A}catch(A){N("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await gY(`sudo -n sh -c '${Y}'`);return mB=!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}`)}}async function lY($,w){let Y=$.filter((X)=>!H6(X)),A=$.filter((X)=>H6(X));if(A.length>0)N("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,w);if(Y.length===0)return;N("hosts",`Adding hosts: ${Y.join(", ")}`,w),N("hosts",`Using hosts file at: ${G$}`,w);try{let X;try{X=await vw.promises.readFile(G$,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{X=await b8(`cat "${G$}"`)}catch(W){throw console.log(" Could not read hosts file — skipping hosts setup"),N("hosts",`sudo read also failed: ${W}`,w),Error(`Cannot read hosts file: ${W}`)}}let J=Y.filter((W)=>{let j=`127.0.0.1 ${W}`,z=`::1 ${W}`;return!X.includes(j)&&!X.includes(z)});if(J.length===0){N("hosts","All hosts already exist in hosts file",w);return}let U=J.map((W)=>`
|
|
261
311
|
# Added by rpx
|
|
262
|
-
127.0.0.1 ${
|
|
263
|
-
::1 ${
|
|
264
|
-
`),
|
|
265
|
-
`),X=!1,J=
|
|
312
|
+
127.0.0.1 ${W}
|
|
313
|
+
::1 ${W}`).join(`
|
|
314
|
+
`),B=gB.join(R6.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await vw.promises.writeFile(B,X+U,"utf8"),await b8(`cat "${B}" | tee "${G$}" > /dev/null`),console.log(` Hosts updated: ${J.join(", ")}`)}catch(W){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),J.forEach((j)=>{console.log(` 127.0.0.1 ${j}`),console.log(` ::1 ${j}`)}),console.log(` Or run: sudo nano ${G$}`)}finally{try{await vw.promises.unlink(B)}catch{}}}catch(X){N("hosts",`Failed to manage hosts file: ${X.message}`,w)}}async function M6($,w){N("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let Y;try{Y=await vw.promises.readFile(G$,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{Y=await b8(`cat "${G$}"`)}catch(W){throw N("hosts",`sudo read also failed: ${W}`,w),Error(`Cannot read hosts file: ${W}`)}}let A=Y.split(`
|
|
315
|
+
`),X=!1,J=A.filter((W)=>{if($.some((z)=>W.includes(` ${z}`)&&(W.includes("127.0.0.1")||W.includes("::1"))))return X=!0,!1;if(W.trim()==="# Added by rpx")return X=!0,!1;return!0});if(!X){N("hosts","No matching hosts found to remove",w);return}while(J[J.length-1]?.trim()==="")J.pop();let U=`${J.join(`
|
|
266
316
|
`)}
|
|
267
|
-
`,
|
|
268
|
-
`,U=(f)=>{let B=K8(f);return A.has(B)||Y.some((j)=>eX(B,j))},W=(f)=>{let B=VR(f);if(!U(B))return;let j="/";try{j=new URL(f.url).pathname}catch{}if(X.some((z)=>j.startsWith(z)))return;if(CR(f.headers.get(w),$.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return W.protects=U,W}oX();$8();KA();f0();var H8=new G8,OR="0.12.0",QR=new E8("0.0.0.0"),QA=new Set,wW=!1,T8=null,AW=null;async function N8($){if(wW)return G("cleanup","Cleanup already in progress, skipping",$?.verbose),AW||Promise.resolve();wW=!0,G("cleanup","Starting cleanup process",$?.verbose),AW=new Promise((w)=>{T8=w});try{await H8.stopAll($?.verbose),q.info("Shutting down proxy servers...");let w=[],A=Array.from(QA).map((Y)=>new Promise((X)=>{Y.close(()=>{G("cleanup","Server closed successfully",$?.verbose),X()})}));if(w.push(...A),$?.hosts&&$.domains?.length){G("cleanup","Cleaning up hosts file entries",$?.verbose),G("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let Y=$.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(G("cleanup",`Filtered domains for cleanup: ${JSON.stringify(Y)}`,$?.verbose),Y.length>0)q.info("Cleaning up hosts file entries..."),w.push(EF(Y,$?.verbose).then(()=>{G("cleanup",`Removed hosts entries for ${Y.join(", ")}`,$?.verbose)}).catch((X)=>{G("cleanup",`Failed to remove hosts entries: ${X}`,$?.verbose),q.warn(`Failed to clean up hosts file entries for ${Y.join(", ")}:`,X)}))}if($?.certs&&$.domains?.length){G("cleanup","Cleaning up SSL certificates",$?.verbose),q.info("Cleaning up SSL certificates...");let Y=$.domains.map(async(X)=>{try{await zz(X,$?.verbose),G("cleanup",`Removed certificates for ${X}`,$?.verbose)}catch(J){G("cleanup",`Failed to remove certificates for ${X}: ${J}`,$?.verbose),q.warn(`Failed to clean up certificates for ${X}:`,J)}});w.push(...Y)}await Promise.allSettled(w),G("cleanup","All cleanup tasks completed successfully",$?.verbose),q.success("All cleanup tasks completed successfully")}catch(w){G("cleanup",`Error during cleanup: ${w}`,$?.verbose),q.error("Error during cleanup:",w)}finally{if(T8)T8();T8=null,wW=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(Y0.env.NODE_ENV!=="test"&&Y0.env.BUN_ENV!=="test"&&!w)Y0.exit(0)}return AW}var YW=!1;function XW($){if(YW){G("signal",`Received second ${$} signal, forcing exit`,!0),Y0.exit(1);return}YW=!0,G("signal",`Received ${$} signal, initiating cleanup`,!0),N8().catch((w)=>{G("signal",`Cleanup failed after ${$}: ${w}`,!0),Y0.exit(1)}).finally(()=>{YW=!1})}Y0.once("SIGINT",()=>XW("SIGINT"));Y0.once("SIGTERM",()=>XW("SIGTERM"));Y0.on("uncaughtException",($)=>{G("process",`Uncaught exception: ${$}`,!0),q.error("Uncaught exception:",$),XW("uncaughtException")});async function SA($,w,A,Y=5){G("connection",`Testing connection to ${$}:${w} (retries left: ${Y})`,A);let X=15000,J=Date.now();if(Y0.env.RPX_BYPASS_CONNECTION_TEST==="true"){G("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let U=()=>new Promise((W,f)=>{let B=NF.connect({host:$,port:w,timeout:3000});B.once("connect",()=>{G("connection",`Successfully connected to ${$}:${w}`,A),B.end(),W()}),B.once("timeout",()=>{G("connection",`Connection to ${$}:${w} timed out`,A),B.destroy(),f(Error("Connection timed out"))}),B.once("error",(j)=>{G("connection",`Failed to connect to ${$}:${w}: ${j}`,A),B.destroy(),f(j)})});try{await U()}catch(W){let f=W;if(Date.now()-J>X){G("connection",`Connection test timed out after ${X}ms, but continuing anyway`,A),q.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(f.code==="ECONNREFUSED"&&Y>0)return G("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${Y} retries left)`,A),await new Promise((j)=>setTimeout(j,2000)),SA($,w,A,Y-1);if(Y>0)try{G("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((j,z)=>{let E=uw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(F)=>{G("connection",`Received HTTP response with status: ${F.statusCode}`,A),j()});E.on("error",(F)=>z(F)),E.on("timeout",()=>{E.destroy(),z(Error("HTTP request timed out"))}),E.end()}),G("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(j){return G("connection",`HTTP request to ${$}:${w} failed: ${j}`,A),G("connection",`Retrying socket connection in 2 seconds... (${Y} retries left)`,A),await new Promise((z)=>setTimeout(z,2000)),SA($,w,A,Y-1)}let B=`Failed to connect to ${$}:${w} after ${5-Y} attempts: ${f.message}`;G("connection",`${B}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),q.warn(B),q.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function RF($){G("server",`Starting server with options: ${E$($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),Y=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),X=[A.hostname];if(JW($)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){G("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await OA(X,$.verbose))[0]){q.info(`Adding ${A.hostname} to hosts file...`),q.info("This may require sudo/administrator privileges");try{await LA(X,$.verbose)}catch(W){if(q.error("Failed to add hosts entry:",W.message),q.warn("You can manually add this entry to your hosts file:"),q.warn(`127.0.0.1 ${A.hostname}`),q.warn(`::1 ${A.hostname}`),Y0.platform==="win32")q.warn("On Windows:"),q.warn("1. Run notepad as administrator"),q.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else q.warn("On Unix systems:"),q.warn("sudo nano /etc/hosts")}}else G("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(U){q.error("Failed to check hosts file:",U.message)}}try{await SA(w.hostname,Y,$.verbose)}catch(U){G("server",`Connection test failed: ${U}`,$.verbose),q.error(U.message),q.warn("Continuing with proxy setup despite connection test failure..."),q.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let J=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=FA({...$,to:A.hostname});if(J=await a$({...$,to:A.hostname,https:$.https}),!J){if(G("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await S1({...$,from:w.toString(),to:A.hostname,https:$.https}),J=await a$({...$,to:A.hostname,https:$.https}),!J)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(U){throw G("server",`SSL setup failed: ${U}`,$.verbose),U}G("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await _R({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:Y,sourceUrl:{hostname:w.hostname,host:w.host},ssl:J})}async function SR($,w,A,Y,X,J,U,W,f,B,j){G("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,f);function z(K){let H={};for(let[N,R]of Object.entries(K))if(!N.startsWith(":"))H[N]=R;return H}let E=(K,H)=>{G("request",`Incoming request: ${K.method} ${K.url}`,f);let N=K.url||"/",R=K.method||"GET";if(K instanceof HF.Http2ServerRequest){let C=K.headers;R=C[":method"]||R,N=C[":path"]||N}if(B){if(!N.match(/\.[a-z0-9]+$/i))if(N.endsWith("/"))N=`${N}index.html`;else N=`${N}.html`}let M=z(K.headers);if(j)M.host=`${J.hostname}:${A}`,G("request",`Changed origin: setting host header to ${M.host}`,f);let y={hostname:J.hostname,port:A,path:N,method:R,headers:M};G("request",`Proxy request options: ${E$(y)}`,f);let I=uw.request(y,(C)=>{if(G("response",`Proxy response received with status ${C.statusCode}`,f),B&&C.statusCode===404){let Q=[];if(N.endsWith(".html"))Q.push(N.slice(0,-5));else if(!N.match(/\.[a-z0-9]+$/i))Q.push(`${N}.html`);if(!N.endsWith("/"))Q.push(`${N}/index.html`);if(Q.length>0){G("cleanUrls",`Trying alternative paths: ${Q.join(", ")}`,f);let _=(z0)=>{if(z0.length===0){H.writeHead(C.statusCode||404,C.headers),C.pipe(H);return}let t0=z0[0],r0={...y,path:t0},S=uw.request(r0,(X$)=>{if(X$.statusCode===200)G("cleanUrls",`Found matching path: ${t0}`,f),H.writeHead(X$.statusCode,X$.headers),X$.pipe(H);else _(z0.slice(1))});S.on("error",()=>_(z0.slice(1))),S.end()};_(Q);return}}let j0={...C.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};H.writeHead(C.statusCode||500,j0),C.pipe(H)});I.on("error",(C)=>{G("request",`Proxy request failed: ${C}`,f),q.error("Proxy request failed:",C),H.writeHead(502),H.end(`Proxy Error: ${C.message}`)}),K.pipe(I)};if(G("server",`Creating server with SSL config: ${!!U}`,f),U)return new Promise((K,H)=>{try{let N=Bun.serve({port:Y,hostname:X,reusePort:Sw(),tls:{key:U.key,cert:U.cert,ca:U.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let M=new URL(R.url);if(G("request",`Bun.serve received: ${R.method} ${M.pathname}`,f),B&&M.pathname.endsWith(".html")){let C=M.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:C}})}let y=`http://${J.host}`,I=`${y}${M.pathname}${M.search}`;try{let C=new Headers(R.headers);if(C.set("host",J.host),j)C.set("origin",y);return C.set("x-forwarded-for","127.0.0.1"),C.set("x-forwarded-proto","https"),C.set("x-forwarded-host",w),await fetch(I,{method:R.method,headers:C,body:R.body,redirect:"manual"})}catch(C){return G("request",`Proxy error: ${C}`,f),new Response(`Proxy Error: ${C}`,{status:502})}},error(R){return G("server",`Bun.serve error: ${R}`,f),new Response(`Server Error: ${R.message}`,{status:500})}});QA.add(N),TF({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!0,cleanUrls:B,verbose:f}),K()}catch(N){H(N)}});let F=uw.createServer(E);function T(K){return QA.add(K),new Promise((H,N)=>{K.listen(Y,X,()=>{G("server",`Server listening on port ${Y}`,f),TF({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!!U,cleanUrls:B,verbose:f}),H()}),K.on("error",(R)=>{G("server",`Server error: ${R}`,f),N(R)})})}return T(F)}async function _R($){G("setup",`Setting up reverse proxy: ${E$($)}`,$.verbose);let{from:w,to:A,fromPort:Y,sourceUrl:X,ssl:J,verbose:U,cleanup:W,vitePluginUsage:f,changeOrigin:B,cleanUrls:j}=$,z=80,E=443,F="0.0.0.0",T=$.portManager||QR,K=JW($);try{if(K&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await OA([A],U))[0]){q.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await LA([A],U),q.success(`Added ${A} to your hosts file.`)}catch(y){q.error(`Failed to add ${A} to your hosts file: ${y}`),q.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(K&&Y0.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await OA([A],U))[0]){G("hosts",`${A} not found in hosts file, adding...`,U);try{await LA([A],U)}catch(y){G("hosts",`Failed to add ${A} to hosts file: ${y}`,U)}}}if(J&&!T.usedPorts.has(z)){if(!await Pw(z,F,U))G("setup","Starting HTTP redirect server",U),qF(U),T.usedPorts.add(z);else if(G("setup","Port 80 is in use, skipping HTTP redirect",U),U)q.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let H=J?E:z,N=await Pw(H,F,U),R;if(N){if(G("setup",`Port ${H} is already in use`,U),U)q.warn(`Port ${H} is already in use. This may be another instance of rpx or another service.`);if(H===443){if(R=await T.getNextAvailablePort(3443,!0),G("setup",`Using port ${R} instead of ${H}`,U),U)q.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await T.getNextAvailablePort(H+1000,!0),G("setup",`Using port ${R} instead of ${H}`,U),U)q.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=H,T.usedPorts.add(R),G("setup",`Using standard ${H===443?"HTTPS":"HTTP"} port ${H} for ${A}`,U);await SR(w,A,Y,R,F,X,J,f,U,j,B)}catch(H){G("setup",`Setup failed: ${H}`,U),q.error(`Failed to setup reverse proxy: ${H.message}`),N8({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:U,vitePluginUsage:f})}}function qF($){G("redirect","Starting HTTP redirect server",$);let w=uw.createServer((A,Y)=>{let X=A.headers.host||"";G("redirect",`Redirecting request from ${X}${A.url} to HTTPS`,$),Y.writeHead(301,{Location:`https://${X}${A.url}`}),Y.end()}).listen(80);QA.add(w),G("redirect","HTTP redirect server started",$)}function MF($){let w={...LU,...$};if(G("proxy",`Starting proxy with options: ${E$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){q.error("viaDaemon mode requires both `from` and `to`");return}of({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((f)=>{q.error(`Failed to register with rpx daemon: ${f.message}`),Y0.exit(1)});return}let A=w.to||"",Y=A.split(".").pop()?.toLowerCase()||"",X=Y0.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(Y)&&w?.verbose)q.warn(`The .${Y} TLD may not work reliably for local development`),q.info(` Google owns .${Y} with HSTS preloading, which can bypass local DNS`),q.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (u1(),f8)).then(({setupDevelopmentDns:f})=>{f({domains:[A],verbose:w.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(Y))q.success(`DNS server started for .${Y} domains`);else q.success(`DNS server started for .${Y} domains (hosts file entry also added)`)});else G("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((f)=>{G("dns",`Failed to start DNS server: ${f}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:FA(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};G("proxy",`Server options: ${E$(W)}`,w.verbose),RF(W).catch((f)=>{G("proxy",`Failed to start proxy: ${f}`,w.verbose),q.error(`Failed to start proxy: ${f.message}`),N8({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function kR($){return $?.verbose||!1}function JW($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function IF($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let A=kR(w),Y=JW(w);if(G("config",`Starting with config: ${E$(w,2)}`,A),G("config",`Is multi-proxy? ${"proxies"in w}`,A),G("config",`Hosts management enabled? ${Y}`,A),w.viaDaemon){let K="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({id:H.id,from:H.from,to:H.to,path:H.path,cleanUrls:H.cleanUrls??w.cleanUrls,changeOrigin:H.changeOrigin??w.changeOrigin,pathRewrites:H.pathRewrites})):[{id:w.id,from:w.from,to:w.to??"rpx.localhost",path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await of({proxies:K,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){G("servers",`Found ${w.proxies.length} proxies in config`,A);for(let T of w.proxies)if(T.start){let K=`${T.from}-${T.to}`;try{G("watch",`Starting command for ${K} with command: ${T.start.command}`,A),q.info(`Starting command for ${K}...`),await H8.startProcess(K,T.start,A);let H=new URL(T.from?.startsWith("http")?T.from:`http://${T.from}`),N=H.hostname||"localhost",R=Number(H.port)||80;try{await SA(N,R,A),G("watch",`Dev server is ready at ${N}:${R}`,A)}catch(M){G("watch",`Connection check failed, but continuing with proxy setup: ${M}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(H){throw G("watch",`Failed to start command for ${K}: ${H}`,A),Error(`Failed to start command for ${K}: ${H}`)}}else G("watch",`No start command for proxy ${T.from} -> ${T.to}`,A)}else if("start"in w&&w.start){G("watch","Found start command in single proxy config",A);let T=`${w.from}-${w.to}`;try{if(w.start)G("watch",`Starting command: ${w.start.command}`,A),await H8.startProcess(T,w.start,A);let K=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),H=K.hostname||"localhost",N=Number(K.port)||80;try{await SA(H,N,A),G("watch",`Dev server is ready at ${H}:${N}`,A)}catch(R){G("watch",`Connection check failed, but continuing with proxy setup: ${R}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(K){throw G("watch",`Failed to run start command: ${K}`,A),Error(`Failed to run start command: ${K}`)}}else G("watch","No start command found in config",A);let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(Y0.platform!=="win32"&&(w.https||Y)){if(!Qw())try{G("sudo","Pre-acquiring sudo credentials for privileged operations",A),LR("sudo -v",{stdio:"inherit"})}catch{G("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let T=await a$(w);if(!T){if(G("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,w.verbose),await S1(w),T=await a$(w),!T)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else G("ssl",`Using existing and trusted certificates for ${X}`,w.verbose);w._cachedSSLConfig=T}let J="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((T)=>({...T,https:w.https,cleanup:w.cleanup,cleanUrls:T.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:T.changeOrigin??w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig}],U=J.map((T)=>T.to||"rpx.localhost"),W=w._cachedSSLConfig,f=U.filter((T)=>T&&!T.includes("localhost")&&!T.includes("127.0.0.1")),B=["dev","app","page","new","day","foo"],j=["test","localhost","local","example","invalid"],z=[...new Set(f.map((T)=>T.split(".").pop()?.toLowerCase()))],E=z.filter((T)=>!!T&&B.includes(T));if(E.length>0&&A)q.warn(`The following TLDs may not work reliably for local development: ${E.map((T)=>`.${T}`).join(", ")}`),q.info(" These TLDs have HSTS preloading which can bypass local DNS"),q.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(Y&&Y0.platform==="darwin"&&f.length>0){let{setupDevelopmentDns:T}=await Promise.resolve().then(() => (u1(),f8));if(await T({domains:f,verbose:A})){if(A)if(z.every((N)=>!!N&&j.includes(N)))q.success(`DNS server started for ${z.map((N)=>`.${N}`).join(", ")} domains`);else q.success(`DNS server started for ${z.map((N)=>`.${N}`).join(", ")} domains (hosts file entries also added)`)}else G("dns","Could not start DNS server - custom domains may not resolve",A)}let F=async()=>{G("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:T}=await Promise.resolve().then(() => (u1(),f8));await T({verbose:w.verbose})}catch(T){G("cleanup",`Error stopping DNS server: ${T}`,w.verbose)}try{await H8.stopAll(w.verbose)}catch(T){G("cleanup",`Error stopping processes: ${T}`,w.verbose)}await N8({domains:U,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};if(Y0.on("SIGINT",F),Y0.on("SIGTERM",F),Y0.on("uncaughtException",(T)=>{G("process",`Uncaught exception: ${T}`,!0),console.error("Uncaught exception:",T),F()}),W&&J.length>1){G("proxies",`Creating shared HTTPS server for ${J.length} domains`,A);let T=[],K=new Set;for(let Q of J){let _=Q.to||"rpx.localhost",z0=Q.cleanUrls||!1,t0=Q.path,r0=Z1(t0);if(Q.static)T.push({host:_,path:t0,route:{static:GA(Q.static,z0),cleanUrls:z0,basePath:r0}}),G("proxies",`Route: ${_}${t0??""} → static ${typeof Q.static==="string"?Q.static:Q.static.dir}`,A);else{let S=new URL(Q.from?.startsWith("http")?Q.from:`http://${Q.from}`);T.push({host:_,path:t0,route:{sourceHost:S.host,cleanUrls:z0,changeOrigin:Q.changeOrigin||!1,pathRewrites:Q.pathRewrites,basePath:r0}}),G("proxies",`Route: ${_}${t0??""} → ${S.host}`,A)}if(K.has(_))continue;if(K.add(_),Y&&!TA(_)&&!_.includes("localhost")&&!_.includes("127.0.0.1"))try{if(!(await OA([_],A))[0])await LA([_],A)}catch{G("hosts",`Could not add hosts entry for ${_}`,A)}}if(!await Pw(80,"0.0.0.0",A))qF(A);let N=443;if(await Pw(N,"0.0.0.0",A)){if(G("proxies",`Port ${N} is already in use, cannot start shared proxy`,A),A)q.warn(`Port ${N} is in use. Shared HTTPS proxy cannot start.`);return}let M=x1(T),y=k1((Q,_)=>P1(M,Q,_),A),I=w.originGuard?KF(w.originGuard):null,C=I?(Q,_)=>I(Q)??y(Q,_):y,j0=D1(A);try{let Q=Bun.serve({port:N,hostname:"0.0.0.0",reusePort:Sw(),tls:{key:W.key,cert:W.cert,ca:W.ca,requestCert:!1,rejectUnauthorized:!1},fetch(_,z0){return C(_,z0)},websocket:j0,error(_){return G("server",`Shared proxy server error: ${_}`,A),new Response(`Server Error: ${_.message}`,{status:500})}});QA.add(Q),G("proxies",`Shared HTTPS proxy listening on port ${N} for ${M.size} domains`,A)}catch(Q){G("proxies",`Failed to start shared proxy: ${Q}`,A),console.error("Failed to start shared HTTPS proxy:",Q),F()}}else for(let T of J)try{let K=T.to||"rpx.localhost";G("proxy",`Starting proxy for ${K} with SSL config: ${!!W}`,T.verbose),await RF({from:T.from||"localhost:5173",to:K,cleanUrls:T.cleanUrls||!1,https:T.https||!1,cleanup:T.cleanup||!1,vitePluginUsage:T.vitePluginUsage||!1,verbose:T.verbose||!1,_cachedSSLConfig:W,changeOrigin:T.changeOrigin||!1})}catch(K){G("proxies",`Failed to start proxy for ${T.to}: ${K}`,T.verbose),console.error(`Failed to start proxy for ${T.to}:`,K),F()}}function TF($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${V$.green(V$.bold("rpx"))} ${V$.green(`v${OR}`)}`),console.log(` ${V$.green("➜")} ${V$.dim($?.from??"")} ${V$.dim("➜")} ${V$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${V$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${V$.green("➜")} Clean URLs enabled`)}Ff();var $L=new Ow("rpx",{showTags:!1});function yF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}p0.chdir(ZR(DR(xR(import.meta.url)),".."));var o0=new O8("rpx"),CF="0.12.0";o0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").action(async($)=>{if(!$?.from||!$.to)return IF(ow);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let A={command:$.startCommand};if($.startCwd)A.cwd=$.startCwd;if($.startEnv)try{A.env=JSON.parse($.startEnv)}catch(Y){console.error("Failed to parse start-env JSON:",Y),p0.exit(1)}w.start=A}return MF(w)});o0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=yF(ow)?ow.proxies.find((Y)=>Y.to===$||`${Y.from}-${Y.to}`===$):ow.to===$?ow:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),p0.exit(1);try{await B8.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(Y){console.error(`Failed to start dev server for ${$}:`,Y),p0.exit(1)}});o0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await B8.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),p0.exit(1)}});o0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await B8.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),p0.exit(1)}});o0.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("--verbose","Enable verbose logging").action(async($)=>{try{await(await $F({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,workers:$.workers===void 0?void 0:typeof $.workers==="string"?Number.parseInt($.workers,10):$.workers,verbose:$.verbose??!0})).done,p0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),p0.exit(1)}});o0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,A=await AF({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!A.stopped&&A.pid===null){console.log("rpx daemon is not running");return}if(!A.stopped){console.log(`rpx daemon pid=${A.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${A.pid} stopped${A.forced?" (SIGKILL)":""}`)});o0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??K$(),A=await qw(w),Y=await W8(w),X=$.registryDir,J=await WF(X).catch(()=>[]);if($.json){console.log(JSON.stringify({running:Y,pid:A,pidFile:Mw(w),rpxDir:w,registryDir:X??Zw(),entries:J},null,2));return}if(!Y){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Mw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Mw(w)}`);if(console.log(`registry: ${X??Zw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let W=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${W})`)}});o0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),p0.exit(1);if(!v1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),p0.exit(1);try{await UF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),p0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await wF({rpxDir:$.rpxDir,verbose:$.verbose}),A=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${A} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),p0.exit(1)}});o0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async($,w)=>{if(!v1($))console.error(`invalid id: ${JSON.stringify($)}`),p0.exit(1);let A=await sf($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await fF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});o0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??K$();if(await W8(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await YF({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});o0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(CF)});o0.version(CF);o0.help();o0.run();
|
|
317
|
+
`,B=gB.join(R6.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await vw.promises.writeFile(B,U,"utf8"),await b8(`cat "${B}" | tee "${G$}" > /dev/null`),N("hosts","Hosts removed successfully",w)}catch(W){N("hosts","Could not clean up hosts file automatically",w)}finally{try{await vw.promises.unlink(B)}catch(W){N("hosts",`Failed to remove temporary file: ${W}`,w)}}}catch(Y){N("hosts",`Failed to clean up hosts file: ${Y.message}`,w)}}async function nY($,w){N("hosts",`Checking hosts: ${$}`,w);let Y;try{Y=await vw.promises.readFile(G$,"utf-8")}catch(A){N("hosts",`Error reading hosts file: ${A}`,w);try{let X=xw(),J;if(X)J=`echo '${X}' | sudo -S cat "${G$}" 2>/dev/null`;else J=`sudo -n cat "${G$}" 2>/dev/null || cat "${G$}" 2>/dev/null || echo ""`;let{stdout:U}=await gY(J);Y=U}catch(X){return N("hosts",`Cannot read hosts file, assuming entries don't exist: ${X}`,w),$.map(()=>!1)}}return $.map((A)=>{let X=`127.0.0.1 ${A}`,J=`::1 ${A}`;return Y.includes(X)||Y.includes(J)})}q8();fB();u$();X0();import{spawn as _M}from"node:child_process";import*as u8 from"node:process";class c8{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){N("start",`Process ${$} is already running`,Y);return}let[A,...X]=w.command.split(" "),J=w.cwd||u8.cwd();N("start",`Starting process ${$}:`,Y),N("start",` Command: ${A} ${X.join(" ")}`,Y),N("start",` Working directory: ${J}`,Y),N("start",` Environment variables: ${R$(w.env)}`,Y);let U=_M(A,X,{cwd:J,env:{...u8.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((B,W)=>{if(U.on("error",(j)=>{if(!this.isShuttingDown)N("start",`Process ${$} failed to start: ${j}`,Y),this.processes.delete($),W(j)}),U.on("exit",(j)=>{if(!this.isShuttingDown&&j!==null&&j!==0)N("start",`Process ${$} exited with code ${j}; leaving the proxy running`,Y),this.processes.delete($),W(Error(`Process ${$} exited with code ${j}`))}),Y)U.stdout?.on("data",(j)=>{N("process",`[${$}] ${j.toString().trim()}`,!0)}),U.stderr?.on("data",(j)=>{N("process",`[${$}] ERR: ${j.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else N("start",`Process ${$} started successfully`,Y),B()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){N("start",`No process found for ${$}`,w);return}return N("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),N("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){N("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){N("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,N("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var E_=new c8;import{timingSafeEqual as SM}from"node:crypto";function hM($,w){if($==null)return!1;let Y=Buffer.from($),A=Buffer.from(w);if(Y.length!==A.length)return!1;return SM(Y,A)}function v8($){return $.toLowerCase().replace(/\.$/,"")}var ZM=["/.well-known/acme-challenge/"];function kM($){let w=$.headers.get("host");if(w)return v8(w.split(":")[0]);try{return v8(new URL($.url).hostname)}catch{return""}}function I6($){let w=$.header.toLowerCase(),Y=new Set,A=[];for(let W of $.hosts){let j=v8(W);if(j.startsWith("*."))A.push(j);else Y.add(j)}let X=$.exemptPaths??ZM,J=$.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
318
|
+
`,U=(W)=>{let j=v8(W);return Y.has(j)||A.some((z)=>zY(j,z))},B=(W)=>{let j=kM(W);if(!U(j))return;let z="/";try{z=new URL(W.url).pathname}catch{}if(X.some((G)=>z.startsWith(G)))return;if(hM(W.headers.get(w),$.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return B.protects=U,B}H8();import*as y6 from"node:fs";import*as C6 from"node:path";var V6="/.well-known/acme-challenge/";function Q6($,w){if(!$||!w.startsWith(V6))return null;let Y=w.slice(V6.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return y6.readFileSync(C6.join($,Y),"utf8")}catch{return null}}_Y();kY();M8();ZY();X0();var m8=new c8,xM="0.12.0",PM=new V8("0.0.0.0"),g8=new Set,dB=!1,i8=null,lB=null;async function l8($){if(dB)return N("cleanup","Cleanup already in progress, skipping",$?.verbose),lB||Promise.resolve();dB=!0,N("cleanup","Starting cleanup process",$?.verbose),lB=new Promise((w)=>{i8=w});try{await m8.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],Y=Array.from(g8).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),N("cleanup","Bun server stopped",$?.verbose),X();else if(typeof J.close==="function")J.close(()=>{N("cleanup","Server closed successfully",$?.verbose),X()});else X()}catch(U){N("cleanup",`Error stopping server: ${U}`,$?.verbose),X()}}));if(w.push(...Y),g8.clear(),$?.hosts&&$.domains?.length){N("cleanup","Cleaning up hosts file entries",$?.verbose),N("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let A=$.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(N("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,$?.verbose),A.length>0)R.info("Cleaning up hosts file entries..."),w.push(M6(A,$?.verbose).then(()=>{N("cleanup",`Removed hosts entries for ${A.join(", ")}`,$?.verbose)}).catch((X)=>{N("cleanup",`Failed to remove hosts entries: ${X}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if($?.certs&&$.domains?.length){N("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let A=$.domains.map(async(X)=>{try{await U5(X,$?.verbose),N("cleanup",`Removed certificates for ${X}`,$?.verbose)}catch(J){N("cleanup",`Failed to remove certificates for ${X}: ${J}`,$?.verbose),R.warn(`Failed to clean up certificates for ${X}:`,J)}});w.push(...A)}await Promise.allSettled(w),N("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){N("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(i8)i8();i8=null,dB=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(J0.env.NODE_ENV!=="test"&&J0.env.BUN_ENV!=="test"&&!w)J0.exit(0)}return lB}var nB=!1;function _6($){if(nB){N("signal",`Received second ${$} signal, forcing exit`,!0),J0.exit(1);return}nB=!0,N("signal",`Received ${$} signal, initiating cleanup`,!0),l8().catch((w)=>{N("signal",`Cleanup failed after ${$}: ${w}`,!0),J0.exit(1)}).finally(()=>{nB=!1})}J0.once("SIGINT",()=>_6("SIGINT"));J0.once("SIGTERM",()=>_6("SIGTERM"));J0.on("uncaughtException",($)=>{R.error("Uncaught exception (continuing):",$)});J0.on("unhandledRejection",($)=>{R.error("Unhandled rejection (continuing):",$)});async function pY($,w,Y,A=5){N("connection",`Testing connection to ${$}:${w} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(J0.env.RPX_BYPASS_CONNECTION_TEST==="true"){N("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((B,W)=>{let j=O6.connect({host:$,port:w,timeout:3000});j.once("connect",()=>{N("connection",`Successfully connected to ${$}:${w}`,Y),j.end(),B()}),j.once("timeout",()=>{N("connection",`Connection to ${$}:${w} timed out`,Y),j.destroy(),W(Error("Connection timed out"))}),j.once("error",(z)=>{N("connection",`Failed to connect to ${$}:${w}: ${z}`,Y),j.destroy(),W(z)})});try{await U()}catch(B){let W=B;if(Date.now()-J>X){N("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&A>0)return N("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),pY($,w,Y,A-1);if(A>0)try{N("connection",`Trying HTTP request to ${$}:${w}`,Y),await new Promise((z,G)=>{let F=d8.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(K)=>{N("connection",`Received HTTP response with status: ${K.statusCode}`,Y),z()});F.on("error",(K)=>G(K)),F.on("timeout",()=>{F.destroy(),G(Error("HTTP request timed out"))}),F.end()}),N("connection",`HTTP request to ${$}:${w} succeeded`,Y);return}catch(z){return N("connection",`HTTP request to ${$}:${w} failed: ${z}`,Y),N("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((G)=>setTimeout(G,2000)),pY($,w,Y,A-1)}let j=`Failed to connect to ${$}:${w} after ${5-A} attempts: ${W.message}`;N("connection",`${j}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),R.warn(j),R.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 S6($){N("server",`Starting server with options: ${R$($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),Y=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),A=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),X=[Y.hostname];if(rB($)&&!Y.hostname.includes("localhost")&&!Y.hostname.includes("127.0.0.1")){N("hosts",`Checking if hosts file entry exists for: ${Y.hostname}`,$?.verbose);try{if(!(await nY(X,$.verbose))[0]){R.info(`Adding ${Y.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await lY(X,$.verbose)}catch(B){if(R.error("Failed to add hosts entry:",B.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${Y.hostname}`),R.warn(`::1 ${Y.hostname}`),J0.platform==="win32")R.warn("On Windows:"),R.warn("1. Run notepad as administrator"),R.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else R.warn("On Unix systems:"),R.warn("sudo nano /etc/hosts")}}else N("hosts",`Host entry already exists for ${Y.hostname}`,$.verbose)}catch(U){R.error("Failed to check hosts file:",U.message)}}try{await pY(w.hostname,A,$.verbose)}catch(U){N("server",`Connection test failed: ${U}`,$.verbose),R.error(U.message),R.warn("Continuing with proxy setup despite connection test failure..."),R.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let J=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=LY({...$,to:Y.hostname});if(J=await e$({...$,to:Y.hostname,https:$.https}),!J){if(N("ssl",`Generating new certificates for ${Y.hostname}`,$.verbose),await c1({...$,from:w.toString(),to:Y.hostname,https:$.https}),J=await e$({...$,to:Y.hostname,https:$.https}),!J)throw Error(`Failed to load SSL configuration after generating certificates for ${Y.hostname}`)}}catch(U){throw N("server",`SSL setup failed: ${U}`,$.verbose),U}N("server",`Setting up reverse proxy with SSL config for ${Y.hostname}`,$.verbose),await uM({...$,from:$.from||"localhost:5173",to:Y.hostname,fromPort:A,sourceUrl:{hostname:w.hostname,host:w.host},ssl:J})}async function bM($,w,Y,A,X,J,U,B,W,j){N("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,U);let z=[{host:w,route:{sourceHost:A.host,cleanUrls:B||!1,changeOrigin:W||!1,basePath:"/",auth:j}}];if(!pB({routeEntries:z,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw Error(`Failed to start proxy server for ${w} on port ${Y}`);vM({from:$,to:w,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:B,verbose:U})}async function uM($){N("setup",`Setting up reverse proxy: ${R$($)}`,$.verbose);let{from:w,to:Y,sourceUrl:A,ssl:X,verbose:J,cleanup:U,vitePluginUsage:B,changeOrigin:W,cleanUrls:j}=$,z=80,G=443,F="0.0.0.0",K=$.portManager||PM,f=rB($);try{if(f&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1")){if(!(await nY([Y],J))[0]){R.warn(`The hostname ${Y} isn't in your hosts file. Adding it now...`);try{await lY([Y],J),R.success(`Added ${Y} to your hosts file.`)}catch(y){R.error(`Failed to add ${Y} to your hosts file: ${y}`),R.info(`You may need to manually add '127.0.0.1 ${Y}' to your /etc/hosts file.`)}}}else if(f&&J0.platform!=="darwin"&&Y&&Y.includes("localhost")&&!Y.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await nY([Y],J))[0]){N("hosts",`${Y} not found in hosts file, adding...`,J);try{await lY([Y],J)}catch(y){N("hosts",`Failed to add ${Y} to hosts file: ${y}`,J)}}}if(X&&!K.usedPorts.has(z)){if(!await Hw(z,F,J))N("setup","Starting HTTP redirect server",J),h6(J),K.usedPorts.add(z);else if(N("setup","Port 80 is in use, skipping HTTP redirect",J),J)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let E=X?G:z,q=await Hw(E,F,J),T;if(q){if(N("setup",`Port ${E} is already in use`,J),J)R.warn(`Port ${E} is already in use. This may be another instance of rpx or another service.`);if(E===443){if(T=await K.getNextAvailablePort(3443,!0),N("setup",`Using port ${T} instead of ${E}`,J),J)R.info(`Using port ${T} instead. Access your site at https://${Y}:${T}`)}else if(T=await K.getNextAvailablePort(E+1000,!0),N("setup",`Using port ${T} instead of ${E}`,J),J)R.info(`Using port ${T} instead. Access your site at http://${Y}:${T}`)}else T=E,K.usedPorts.add(T),N("setup",`Using standard ${E===443?"HTTPS":"HTTP"} port ${E} for ${Y}`,J);await bM(w,Y,T,A,X,B,J,j,W,v1($.auth))}catch(E){N("setup",`Setup failed: ${E}`,J),R.error(`Failed to setup reverse proxy: ${E.message}`),l8({domains:[Y],hosts:typeof U==="boolean"?U:U?.hosts,certs:typeof U==="boolean"?U:U?.certs,verbose:J,vitePluginUsage:B})}}function h6($,w=80,Y=443,A){N("redirect",`Starting HTTP redirect server on port ${w}`,$);let X=d8.createServer((J,U)=>{if(A&&J.url){let z=J.url.split("?",1)[0],G=Q6(A,z);if(G!=null){N("redirect",`Serving ACME challenge ${z}`,$),U.writeHead(200,{"content-type":"text/plain"}),U.end(G);return}}let B=J.headers.host||"",W=B.includes(":")?B.slice(0,B.indexOf(":")):B,j=Y===443?W:`${W}:${Y}`;N("redirect",`Redirecting request from ${B}${J.url} to https://${j}`,$),U.writeHead(301,{Location:`https://${j}${J.url}`}),U.end()}).listen(w);g8.add(X),N("redirect","HTTP redirect server started",$)}function Z6($){let w={...BW,...$};if(N("proxy",`Starting proxy with options: ${R$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}iB({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((W)=>{R.error(`Failed to register with rpx daemon: ${W.message}`),J0.exit(1)});return}let Y=w.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=J0.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)&&w?.verbose)R.warn(`The .${A} TLD may not work reliably for local development`),R.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),R.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (a1(),h8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:w.verbose}).then((j)=>{if(j)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(A))R.success(`DNS server started for .${A} domains`);else R.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else N("dns",`Could not start DNS server - ${Y} may not resolve in browser`,w.verbose)})}).catch((W)=>{N("dns",`Failed to start DNS server: ${W}`,w.verbose)});let B={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:LY(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};N("proxy",`Server options: ${R$(B)}`,w.verbose),S6(B).catch((W)=>{N("proxy",`Failed to start proxy: ${W}`,w.verbose),R.error(`Failed to start proxy: ${W.message}`),l8({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function cM($){return $?.verbose||!1}function rB($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function k6($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let Y=cM(w),A=rB(w);if(N("config",`Starting with config: ${R$(w,2)}`,Y),N("config",`Is multi-proxy? ${"proxies"in w}`,Y),N("config",`Hosts management enabled? ${A}`,Y),w.viaDaemon){let I="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((_)=>({id:_.id,from:_.from,to:_.to,path:_.path,cleanUrls:_.cleanUrls??w.cleanUrls,changeOrigin:_.changeOrigin??w.changeOrigin,pathRewrites:_.pathRewrites})):[{id:w.id,from:w.from,to:w.to??"rpx.localhost",path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await iB({proxies:I,verbose:Y});return}if("proxies"in w&&Array.isArray(w.proxies)){N("servers",`Found ${w.proxies.length} proxies in config`,Y);for(let H of w.proxies)if(H.start){let I=`${H.from}-${H.to}`;try{N("watch",`Starting command for ${I} with command: ${H.start.command}`,Y),R.info(`Starting command for ${I}...`),await m8.startProcess(I,H.start,Y);let _=new URL(H.from?.startsWith("http")?H.from:`http://${H.from}`),h=_.hostname||"localhost",u0=Number(_.port)||80;try{await pY(h,u0,Y),N("watch",`Dev server is ready at ${h}:${u0}`,Y)}catch(iw){N("watch",`Connection check failed, but continuing with proxy setup: ${iw}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(_){throw N("watch",`Failed to start command for ${I}: ${_}`,Y),Error(`Failed to start command for ${I}: ${_}`)}}else N("watch",`No start command for proxy ${H.from} -> ${H.to}`,Y)}else if("start"in w&&w.start){N("watch","Found start command in single proxy config",Y);let H=`${w.from}-${w.to}`;try{if(w.start)N("watch",`Starting command: ${w.start.command}`,Y),await m8.startProcess(H,w.start,Y);let I=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),_=I.hostname||"localhost",h=Number(I.port)||80;try{await pY(_,h,Y),N("watch",`Dev server is ready at ${_}:${h}`,Y)}catch(u0){N("watch",`Connection check failed, but continuing with proxy setup: ${u0}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw N("watch",`Failed to run start command: ${I}`,Y),Error(`Failed to run start command: ${I}`)}}else N("watch","No start command found in config",Y);let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(J0.platform!=="win32"&&(w.https||A)){if(!xw())try{N("sudo","Pre-acquiring sudo credentials for privileged operations",Y),DM("sudo -v",{stdio:"inherit"})}catch{N("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if(w.productionCerts){if(J=await l1(w.productionCerts,Y),J.length>0)N("ssl",`Using ${J.length} production SNI cert(s): ${J.map((H)=>H.serverName).join(", ")}`,Y)}if(w.https){let H=J.length>0?null:await e$(w);if(!H&&J.length===0){if(N("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,w.verbose),await c1(w),H=await e$(w),!H)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else N("ssl",`Using existing and trusted certificates for ${X}`,w.verbose);w._cachedSSLConfig=H}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({...H,https:w.https,cleanup:w.cleanup,cleanUrls:H.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:H.changeOrigin??w.changeOrigin,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,auth:"auth"in w?w.auth:void 0,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig}],B=U.map((H)=>H.to||"rpx.localhost"),W=J.length>0?J:w._cachedSSLConfig??null,j=B.filter((H)=>H&&!H.includes("localhost")&&!H.includes("127.0.0.1")),z=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"],F=[...new Set(j.map((H)=>H.split(".").pop()?.toLowerCase()))],K=F.filter((H)=>!!H&&z.includes(H));if(K.length>0&&Y)R.warn(`The following TLDs may not work reliably for local development: ${K.map((H)=>`.${H}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&J0.platform==="darwin"&&j.length>0){let{setupDevelopmentDns:H}=await Promise.resolve().then(() => (a1(),h8));if(await H({domains:j,verbose:Y})){if(Y)if(F.every((h)=>!!h&&G.includes(h)))R.success(`DNS server started for ${F.map((h)=>`.${h}`).join(", ")} domains`);else R.success(`DNS server started for ${F.map((h)=>`.${h}`).join(", ")} domains (hosts file entries also added)`)}else N("dns","Could not start DNS server - custom domains may not resolve",Y)}let f=async()=>{N("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:H}=await Promise.resolve().then(() => (a1(),h8));await H({verbose:w.verbose})}catch(H){N("cleanup",`Error stopping DNS server: ${H}`,w.verbose)}try{await m8.stopAll(w.verbose)}catch(H){N("cleanup",`Error stopping processes: ${H}`,w.verbose)}await l8({domains:B,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};J0.on("SIGINT",f),J0.on("SIGTERM",f);let E=w.singlePortMode===!0,q=w.httpsPort??443,T=w.httpPort??80,M=w.originGuard?I6(w.originGuard):null,y=!!W&&(U.length>1||E),Q=!W&&E&&U.length>0;if(y&&W){N("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${q}`,Y);let H=await L6(U,A,Y);if(!await Hw(T,"0.0.0.0",Y))h6(Y,T,q,w.acmeChallengeWebroot);if(await Hw(q,"0.0.0.0",Y)){if(N("proxies",`Port ${q} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${q} is in use. Shared HTTPS proxy cannot start.`);return}if(!pB({routeEntries:H,listenPort:q,sslConfig:W,originGuard:M,verbose:Y})){R.error(`Shared HTTPS proxy failed to bind :${q}; not exiting`);return}}else if(Q){N("proxies",`Creating shared HTTP server for ${U.length} domains on port ${T}`,Y);let H=await L6(U,A,Y);if(await Hw(T,"0.0.0.0",Y)){if(N("proxies",`Port ${T} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${T} is in use. Shared HTTP proxy cannot start.`);return}if(!pB({routeEntries:H,listenPort:T,sslConfig:null,originGuard:M,verbose:Y})){R.error(`Shared HTTP proxy failed to bind :${T}; not exiting`);return}}else for(let H of U)try{let I=H.to||"rpx.localhost";N("proxy",`Starting proxy for ${I} with SSL config: ${!!W}`,H.verbose),await S6({from:H.from||"localhost:5173",to:I,cleanUrls:H.cleanUrls||!1,https:H.https||!1,cleanup:H.cleanup||!1,vitePluginUsage:H.vitePluginUsage||!1,verbose:H.verbose||!1,_cachedSSLConfig:w._cachedSSLConfig,changeOrigin:H.changeOrigin||!1})}catch(I){N("proxies",`Failed to start proxy for ${H.to}: ${I}`,H.verbose),R.error(`Failed to start proxy for ${H.to}:`,I)}}async function L6($,w,Y){let A=[],X=new Set;for(let J of $){let U=J.to||"rpx.localhost",B=J.cleanUrls||!1,W=J.path,j=y$(W),z=v1(J.auth);if(J.redirect){let G=M5(J.redirect);A.push({host:U,path:W,route:{redirect:G,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → redirect ${G.status} ${G.to}${z?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:hY(J.static,B),cleanUrls:B,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${z?" (auth)":""}`,Y);else{let G=new URL(J.from?.startsWith("http")?J.from:`http://${J.from}`);A.push({host:U,path:W,route:{sourceHost:G.host,cleanUrls:B,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → ${G.host}${z?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),w&&!U1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await nY([U],Y))[0])await lY([U],Y)}catch{N("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function pB($){let{routeEntries:w,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=$,U=g1(w),B=i1((z,G)=>d1(U,z,G),J),W=X?(z,G)=>X(z)??B(z,G):B,j=m1(J);try{let z=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:D1(),...A?{tls:Array.isArray(A)?A.map((G)=>({serverName:G.serverName,key:G.key,cert:G.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(G,F){return W(G,F)},websocket:j,error(G){return N("server",`Shared proxy server error: ${G}`,J),new Response(`Server Error: ${G.message}`,{status:500})}});return g8.add(z),N("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),z}catch(z){return N("proxies",`Failed to start shared proxy: ${z}`,J),console.error("Failed to start shared proxy:",z),null}}function vM($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${O$.green(O$.bold("rpx"))} ${O$.green(`v${xM}`)}`),console.log(` ${O$.green("➜")} ${O$.dim($?.from??"")} ${O$.dim("➜")} ${O$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${O$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${O$.green("➜")} Clean URLs enabled`)}pW();var l_=new Dw("rpx",{showTags:!1});function D6($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}x0.chdir(mM(iM(gM(import.meta.url)),".."));var b0=new YJ("rpx"),x6="0.12.0";b0.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($)=>{if(!$?.from||!$.to)return k6(J1);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,singlePortMode:$.singlePortMode||!1,httpPort:$.httpPort!==void 0?Number($.httpPort):void 0,httpsPort:$.httpsPort!==void 0?Number($.httpsPort):void 0,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let Y={command:$.startCommand};if($.startCwd)Y.cwd=$.startCwd;if($.startEnv)try{Y.env=JSON.parse($.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),x0.exit(1)}w.start=Y}return Z6(w)});b0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let Y=D6(J1)?J1.proxies.find((A)=>A.to===$||`${A.from}-${A.to}`===$):J1.to===$?J1:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${$}`),x0.exit(1);try{await x8.startProcess($,Y.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(A){console.error(`Failed to start dev server for ${$}:`,A),x0.exit(1)}});b0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await x8.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(Y){console.error(`Failed to stop dev server for ${$}:`,Y),x0.exit(1)}});b0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await x8.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),x0.exit(1)}});async function P6($){let Y={...(await b9().catch(()=>null))?.onDemand??{},enabled:!0};if($){let A=$.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}b0.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($)=>{try{let w=$.onDemand?await P6($.roots):void 0;await(await j6({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,workers:$.workers===void 0?void 0:typeof $.workers==="string"?Number.parseInt($.workers,10):$.workers,onDemandSites:w,verbose:$.verbose??!0})).done,x0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),x0.exit(1)}});b0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,Y=await G6({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.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)":""}`)});b0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??w$(),Y=await Iw(w),A=await k8(w),X=$.registryDir,J=await vB(X).catch(()=>[]);if($.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:Vw(w),rpxDir:w,registryDir:X??cw(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${Vw(w)} \u2192 pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${Vw(w)}`);if(console.log(`registry: ${X??cw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let B=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${B})`)}});b0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),x0.exit(1);if(!e1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),x0.exit(1);try{await E6({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),x0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await z6({rpxDir:$.rpxDir,verbose:$.verbose}),Y=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${Y} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),x0.exit(1)}});b0.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(!e1($))console.error(`invalid id: ${JSON.stringify($)}`),x0.exit(1);let Y=await cB($,w.registryDir,w.verbose);if(!Y){console.log(`no registry entry for id=${$}`);return}await f6($,w.registryDir,w.verbose),console.log(`unregistered ${Y.to} (id=${$})`)});b0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??w$();if(await k8(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await F6({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});b0.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($)=>{let w=await P6($.roots),Y=m9(w),A=await vB($.registryDir).catch(()=>[]),X=new Set(A.map((B)=>B.to)),J=Y.map((B)=>({host:B.host,dir:B.dir,command:B.command,source:B.source,live:X.has(B.host)}));if($.json){console.log(JSON.stringify(J,null,2));return}let U=w.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}) \u2014 scanned ${U.join(", ")}:`);for(let B of J)console.log(` ${B.live?"\u25CF":"\u25CB"} https://${B.host} ${B.live?"(live)":"(idle)"}`),console.log(` ${B.command} ${B.dir}`)});b0.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("fs/promises"),{join:A}=await import("path"),X=w.rpxDir??w$(),J=A(X,"sites",`${uA($.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${$} (it may not have been booted yet) \u2014 looked in ${J}`);return}let B=w.lines===void 0?void 0:typeof w.lines==="string"?Number.parseInt(w.lines,10):w.lines,W=U.split(`
|
|
319
|
+
`);x0.stdout.write((B&&B>0?W.slice(-B):W).join(`
|
|
320
|
+
`))});b0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(x6)});b0.version(x6);b0.help();b0.run();
|