@stacksjs/rpx 0.11.8 → 0.11.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +137 -136
- package/dist/cert-inspect.d.ts +15 -0
- package/dist/https.d.ts +30 -2
- package/dist/index.d.ts +22 -0
- package/dist/index.js +81 -79
- package/dist/macos-trust.d.ts +40 -0
- package/package.json +1 -1
- package/src/cert-inspect.ts +69 -0
- package/src/https.ts +78 -67
- package/src/index.ts +24 -0
- package/src/macos-trust.ts +175 -0
package/dist/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{a as G,b as Rn,c as tc,d as a,e as $S,f as ei,g as sS,h as Y$,i as ic,j as g0,k as pr,l as d$,m as wS,n as z$,o as I$}from"./chunk-jpf41gb9.js";import{execSync as Aa}from"node:child_process";import*as Ri from"node:http";import*as X$ from"node:http2";import*as P$ from"node:net";import*as O from"node:process";var S={info:(...t)=>console.log("[info]",...t),success:(...t)=>console.log("[success]",...t),warn:(...t)=>console.warn("[warn]",...t),error:(...t)=>console.error("[error]",...t),debug:(...t)=>console.debug("[debug]",...t),log:(...t)=>console.log(...t),start:(...t)=>console.log("[start]",...t),box:(...t)=>console.log("[box]",...t)};var jn=(t,i)=>(n)=>`\x1B[${t}m${n}\x1B[${i}m`,jt={bold:jn(1,22),dim:jn(2,22),green:jn(32,39),cyan:jn(36,39)};import{homedir as Qf}from"node:os";import{join as te,resolve as um}from"node:path";import{existsSync as Sc,statSync as Rc}from"fs";import{existsSync as Q$,mkdirSync as _a,readdirSync as Ua,readFileSync as ts,writeFileSync as ja}from"fs";import{homedir as Bi}from"os";import{dirname as da,resolve as Bt}from"path";import lr from"process";import{existsSync as Bc,statSync as Nc}from"fs";import{existsSync as df,mkdirSync as is,readdirSync as ns,writeFileSync as rs}from"fs";import{homedir as Ni}from"os";import{dirname as Fc,resolve as wt}from"path";import ai from"process";import{join as fs,relative as es,resolve as Jc}from"path";import Xn from"process";import{existsSync as hh,mkdirSync as Da,readdirSync as Oa,writeFileSync as La}from"fs";import{homedir as uf}from"os";import{dirname as oa,resolve as st}from"path";import hn from"process";import{join as cs,relative as hs,resolve as Cc}from"path";import Pn from"process";import{existsSync as lh,mkdirSync as va,readdirSync as pa,writeFileSync as Qa}from"fs";import{dirname as iA,resolve as vn}from"path";import If from"process";import{Buffer as ci}from"buffer";import{createCipheriv as ls,createDecipheriv as $s,randomBytes as yf}from"crypto";import{closeSync as af,createReadStream as _c,createWriteStream as ss,existsSync as Af,fsyncSync as Uc,openSync as jc,writeFileSync as ws}from"fs";import{access as us,constants as Wc,mkdir as ys,readdir as Wn,rename as Yc,stat as Fi,unlink as Yn,writeFile as mf}from"fs/promises";import{join as Ji}from"path";import rt from"process";import{pipeline as as}from"stream/promises";import{createGzip as dc}from"zlib";import Ci from"process";import Lt from"process";import{Buffer as xt}from"buffer";import{createCipheriv as As,createDecipheriv as ms,randomBytes as Ef}from"crypto";import{closeSync as Tf,createReadStream as Ic,createWriteStream as Es,existsSync as dn,fsyncSync as Zc,openSync as Hc,writeFileSync as Ts}from"fs";import{access as Ss,constants as Mc,mkdir as Rs,readdir as In,rename as zc,stat as _i,unlink as Zn,writeFile as Sf}from"fs/promises";import{isAbsolute as Bs,join as Ui,resolve as Ns}from"path";import _ from"process";import{pipeline as Fs}from"stream/promises";import{createGzip as Gc}from"zlib";import ji from"process";import kt from"process";import Hn from"process";import{existsSync as Mn}from"fs";import{resolve as Rf}from"path";import{existsSync as Js}from"fs";import{existsSync as Cs,readdirSync as _s}from"fs";import{extname as Bf,resolve as Kc}from"path";import Us from"process";import{join as js,relative as Ws,resolve as qc}from"path";import pn from"process";import{Buffer as Dt}from"buffer";import{createCipheriv as Ys,createDecipheriv as ds,randomBytes as Nf}from"crypto";import{closeSync as Ff,createReadStream as xc,createWriteStream as Is,existsSync as zn,fsyncSync as Dc,openSync as Oc,writeFileSync as Zs}from"fs";import{access as Hs,constants as Lc,mkdir as Ms,readdir as Gn,rename as kc,stat as Wi,unlink as Kn,writeFile as Jf}from"fs/promises";import{isAbsolute as zs,join as Yi,resolve as Gs}from"path";import U from"process";import{pipeline as Ks}from"stream/promises";import{createGzip as Vc}from"zlib";import di from"process";import Vt from"process";import xn from"process";import{existsSync as Dn}from"fs";import{resolve as Yf}from"path";import{existsSync as fu}from"fs";class eh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Sc(t))return!0;return Rc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Sc(n)?Rc(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class ch{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var bn=new eh,Lf=new ch;var qs=Object.defineProperty,xs=(t)=>t;function Ds(t,i){this[t]=xs.bind(null,i)}var Os=(t,i)=>{for(var n in i)qs(t,n,{get:i[n],enumerable:!0,configurable:!0,set:Ds.bind(i,n)})},Ls=(t,i)=>()=>(t&&(i=t(t=0)),i),$h={};Os($h,{withErrorRecovery:()=>uh,tryLoadConfig:()=>uw,loadConfigWithResult:()=>sw,loadConfig:()=>Eh,isRetryableError:()=>fw,isConfigNotFoundError:()=>rw,isBunfigError:()=>yh,globalPerformanceMonitor:()=>sn,globalCache:()=>Ii,getEnvOrDefault:()=>ew,generateConfigTypes:()=>yw,defaultGeneratedDir:()=>Ch,defaultConfigDir:()=>Jh,deepMergeWithArrayStrategy:()=>bf,deepMerge:()=>ah,createLibraryConfig:()=>aw,config:()=>ww,bunfigPlugin:()=>Aw,applyEnvVarsToConfig:()=>cn,TypeGenerationError:()=>qf,SchemaValidationError:()=>$n,PluginError:()=>Df,PerformanceMonitor:()=>Vf,FileSystemError:()=>Kf,ErrorFactory:()=>hi,EnvVarError:()=>fr,EnvProcessor:()=>$r,ConfigValidator:()=>Xf,ConfigValidationError:()=>zf,ConfigNotFoundError:()=>rr,ConfigMergeError:()=>Gf,ConfigLoader:()=>Pf,ConfigLoadError:()=>ln,ConfigFileLoader:()=>sr,ConfigCache:()=>kf,CacheUtils:()=>Sh,BunfigError:()=>Et,BrowserConfigError:()=>xf,ArrayMergeStrategies:()=>Nh});class kf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Bc(t))return!0;return Nc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Bc(n)?Nc(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Vf{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function ks(t,i={}){let r=Object.keys(i).sort().map((f)=>`${f}:${i[f]}`).join("|");return r?`${t}:${r}`:t}function Vs(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function os(t){return t.getStats().size*2}function of(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&x(i[0])&&"id"in i[0]&&i[0].id===3&&x(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(x(i)&&x(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(x(t)&&"arr"in t&&Array.isArray(t.arr)&&x(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&x(i[0])&&x(t[0])){let r=[...i];for(let f of t)if(x(f)&&"name"in f){if(!r.find((c)=>x(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(x(f)&&"path"in f){if(!r.find((c)=>x(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((e)=>Qn(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!x(i)||!x(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(x(f)&&x(n[r]))n[r]=of(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&x(f[0])&&x(n[r][0])){let e=[...f];for(let c of n[r])if(x(c)&&"name"in c){if(!e.find((h)=>x(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(x(c)&&"path"in c){if(!e.find((h)=>x(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((l)=>Qn(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function Qn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Qn(t[n],i[n]))return!1;return!0}if(x(t)&&x(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Qn(t[f],i[f]))return!1}return!0}return!1}function x(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function gs(t,i){if(!lh(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return of(i,r)}catch{return null}}catch{return null}}async function bs({name:t="",cwd:i,defaultConfig:n}){let r=i||If.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let l of f){let h=vn(r,`${c}${l}`),$=await gs(h,n);if($!==null)return $}try{let c=vn(r,"package.json");if(lh(c)){let h=(await import(c))[t];if(h&&typeof h==="object"&&!Array.isArray(h))try{return of(n,h)}catch{}}}catch{}return n}function Xs(t,i={}){let n=Pn.cwd();while(n.includes("storage"))n=Cc(n,"..");let r=Cc(n,t||"");if(i?.relative)return hs(Pn.cwd(),r);return r}async function Ps(){try{let t=await bs({name:"clarity",defaultConfig:kn,cwd:Pn.cwd(),endpoint:"",headers:{}});return{...kn,...t}}catch{return kn}}function L(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vs(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Lt<"u"){let t=Lt.type;if(t==="renderer"||t==="worker")return!1;return!!(Lt.versions&&(Lt.versions.node||Lt.versions.bun))}return!1}class sh{async format(t){let i=await vs(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ci.pid,hostname:i(),environment:Ci.env.NODE_ENV||"development",platform:Ci.platform,version:Ci.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ci.env.NODE_ENV||Ci.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class tr{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(t,i={}){this.name=t,this.config={...Hf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new sh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??rt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Vn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Vn};return{...Vn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Hf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,l=1000;while(e<c)try{try{try{await us(this.config.logDirectory,Wc.F_OK|Wc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await ys(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ci.from(t);try{if(!Af(this.currentLogFile))await mf(this.currentLogFile,"",{mode:420});if(f=jc(this.currentLogFile,"a",420),ws(f,h,{flag:"a"}),Uc(f),f!==void 0)af(f),f=void 0;if((await Fi(this.currentLogFile)).size===0){if(await mf(this.currentLogFile,h,{flag:"w",mode:420}),(await Fi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let s=$;if(s.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(s.code)){if(e<c-1){let u=typeof s.message==="string"?s.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,u);let y=l*2**e;await new Promise((w)=>setTimeout(w,y)),e++;continue}}if(s?.code&&["ENOSPC","EDQUOT"].includes(s.code))throw Error(`Disk quota exceeded or no space left on device: ${s.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",s),s}finally{if(f!==void 0)try{af(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(h){if(e===c-1){let s=h,u=typeof s.message==="string"?s.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),h}e++;let $=l*2**(e-1);await new Promise((s)=>setTimeout(s,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ji(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 Ji(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ji(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(L())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,h])=>h.createdAt.getTime()-l.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return yf(16).toString("hex")}generateKey(){return yf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=yf(16),r=ls("aes-256-gcm",i,n),f=ci.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:ci.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=dc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(ci.from(ci.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(L())return;let t=await Fi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Wn(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Fi(n).catch(()=>null))try{if(await Yc(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await Yn(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await mf(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Fi(n).catch(()=>null))await Yc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await Wn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of e.slice(i.maxFiles))await Yn(Ji(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=_c(t),r=ss(i),f=dc();await as(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Af(this.currentLogFile))try{let t=jc(this.currentLogFile,"r+");Uc(t),af(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!L()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Wn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Yn(Ji(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?K.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=rt.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${K.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!L()){let $=Rh[t],s=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:K.gray(c),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:K.green(c),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.error(u),l){let y=l.split(`
|
|
2
|
-
`);for(let
|
|
3
|
-
`;if(l
|
|
4
|
-
`;
|
|
5
|
-
`,$=$.replace(this.ANSI_PATTERN,""),this.fancy&&!L()){let
|
|
6
|
-
`),c=Math.max(...e.map((
|
|
7
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(t){if(L())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${K.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();rt.stdin.removeListener("data",n);try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!1)}catch{}rt.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!0)}catch{}rt.stdin.resume(),rt.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,
|
|
8
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}progress(t,i=""){if(!this.enabled||!this.fancy||L()||t<=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 n=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(c,
|
|
9
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||L()||!rt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(L()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Wn(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=Ji(this.config.logDirectory,r);if(t.before)try{if((await Fi(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Yn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Ln(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&Z(i[0])&&"id"in i[0]&&i[0].id===3&&Z(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(Z(i)&&Z(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(Z(t)&&"arr"in t&&Array.isArray(t.arr)&&Z(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&Z(i[0])&&Z(t[0])){let r=[...i];for(let f of t)if(Z(f)&&"name"in f){if(!r.find((c)=>Z(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(Z(f)&&"path"in f){if(!r.find((c)=>Z(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((e)=>ir(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!Z(i)||!Z(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(Z(f)&&Z(n[r]))n[r]=Ln(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&Z(f[0])&&Z(n[r][0])){let e=[...f];for(let c of n[r])if(Z(c)&&"name"in c){if(!e.find((h)=>Z(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(Z(c)&&"path"in c){if(!e.find((h)=>Z(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((l)=>ir(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function gf(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:Ln(t,i);if(Array.isArray(t))return n==="replace"?i:Ln(t,i);if(!Z(i)||!Z(t))return i;let r={...t};for(let f of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let e=i[f],c=r[f];if(e===null||e===void 0)continue;if(Array.isArray(e)||Array.isArray(c))if(n==="replace")r[f]=e;else r[f]=Ln(c,e);else if(Z(e)&&Z(c))r[f]=gf(c,e,n);else r[f]=e}return r}function ir(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!ir(t[n],i[n]))return!1;return!0}if(Z(t)&&Z(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!ir(t[f],i[f]))return!1}return!0}return!1}function Z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function qn(t,i,n="replace"){if(!hh(t))return null;try{let r=await import(t),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return gf(i,f,n)}catch{return null}}catch{return null}}function ps(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),w=`${r}_${u.map(y).join("_")}`,m=`${r}_${u.map((A)=>A.toUpperCase()).join("_")}`;if(n)et.info(`Checking environment variable ${w} for config ${t}.${u.join(".")}`);if(typeof s==="object"&&s!==null&&!Array.isArray(s))h[$]=e(s,u);else{let A=hn.env[w]||hn.env[m];if(A!==void 0){if(n)et.info(`Using environment variable ${A?w:m} for config ${t}.${u.join(".")}`);if(typeof s==="number")h[$]=Number(A);else if(typeof s==="boolean")h[$]=A.toLowerCase()==="true";else if(Array.isArray(s))try{let T=JSON.parse(A);if(Array.isArray(T))h[$]=T;else h[$]=A.split(",").map((E)=>E.trim())}catch{h[$]=A.split(",").map((T)=>T.trim())}else h[$]=A}}}return h}return e(f)}async function Qs({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:l="replace"}){let h=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?ps(t,f,e):f,$=n||hn.cwd(),s=[".ts",".js",".mjs",".cjs",".json"];if(e)et.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${$}`);let u=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),w=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([$,st($,"config"),st($,".config"),r?st($,r):void 0].filter(Boolean)));for(let T of A){if(e)et.info(`Searching for configuration in: ${T}`);let R=[st($,"config"),st($,".config")].concat(r?[st($,r)]:[]).includes(T)?[...u,...y,...w,...m]:[...y,...u,...m,...w];for(let J of R)for(let C of s){let j=st(T,`${J}${C}`),B=await qn(j,h,l);if(B!==null){if(e)et.success(`Configuration loaded from: ${j}`);return B}}}if(t){let T=st(uf(),".config",t),E=["config",`${t}.config`];if(i)E.push(`${i}.config`);if(e)et.info(`Checking user config directory: ${T}`);for(let R of E)for(let J of s){let C=st(T,`${R}${J}`),j=await qn(C,h,l);if(j!==null){if(e)et.success(`Configuration loaded from user config directory: ${C}`);return j}}}if(t){let T=st(uf(),".config"),E=[`.${t}.config`];if(i)E.push(`.${i}.config`);if(e)et.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of E)for(let J of s){let C=st(T,`${R}${J}`),j=await qn(C,h,l);if(j!==null){if(e)et.success(`Configuration loaded from user config directory dotfile: ${C}`);return j}}}if(t){let T=uf(),E=[`.${t}.config`,`.${t}`];if(i)E.push(`.${i}.config`),E.push(`.${i}`);if(e)et.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of E)for(let J of s){let C=st(T,`${R}${J}`),j=await qn(C,h,l);if(j!==null){if(e)et.success(`Configuration loaded from user home directory: ${C}`);return j}}}try{let T=st($,"package.json");if(hh(T)){let E=await import(T),R=E[t];if(!R&&i){if(R=E[i],R&&e)et.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)et.success(`Configuration loaded from package.json: ${R===E[t]?t:i}`);return gf(h,R,l)}catch(J){if(e)et.warn("Failed to merge package.json config:",J)}}}catch(T){if(e)et.warn("Failed to load package.json:",T)}if(e)et.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return h}function tw(t,i={}){let n=Xn.cwd();while(n.includes("storage"))n=Jc(n,"..");let r=Jc(n,t||"");if(i?.relative)return es(Xn.cwd(),r);return r}async function iw(){try{let t=await Qs({name:"clarity",alias:"logging",defaultConfig:on,cwd:Xn.cwd()});return{...on,...t||{}}}catch{return on}}function g(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nw(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof kt<"u"){let t=kt.type;if(t==="renderer"||t==="worker")return!1;return!!(kt.versions&&(kt.versions.node||kt.versions.bun))}return!1}class wh{async format(t){let i=await nw(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ji.pid,hostname:i(),environment:ji.env.NODE_ENV||"development",platform:ji.platform,version:ji.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ji.env.NODE_ENV||ji.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nr{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(t,i={}){this.name=t,this.config={...Mf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new wh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...gn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...gn};return{...gn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Mf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!g()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,l=1000;while(e<c)try{try{try{await Ss(this.config.logDirectory,Mc.F_OK|Mc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Rs(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:xt.from(t);try{if(!dn(this.currentLogFile))await Sf(this.currentLogFile,"",{mode:420});if(f=Hc(this.currentLogFile,"a",420),Ts(f,h,{flag:"a"}),Zc(f),f!==void 0)Tf(f),f=void 0;if((await _i(this.currentLogFile)).size===0){if(await Sf(this.currentLogFile,h,{flag:"w",mode:420}),(await _i(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let s=$;if(s.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(s.code)){if(e<c-1){let u=typeof s.message==="string"?s.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,u);let y=l*2**e;await new Promise((w)=>setTimeout(w,y)),e++;continue}}if(s?.code&&["ENOSPC","EDQUOT"].includes(s.code))throw Error(`Disk quota exceeded or no space left on device: ${s.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",s),s}finally{if(f!==void 0)try{Tf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(h){if(e===c-1){let s=h,u=typeof s.message==="string"?s.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),h}e++;let $=l*2**(e-1);await new Promise((s)=>setTimeout(s,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ui(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 Ui(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ui(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(g())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,h])=>h.createdAt.getTime()-l.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Ef(16).toString("hex")}generateKey(){return Ef(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Ef(16),r=As("aes-256-gcm",i,n),f=xt.isBuffer(t)?t:xt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),$=xt.allocUnsafe(16+l+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),h.copy($,16+l),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Gc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(xt.from(xt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(g())return;if(!this.shouldWriteToFile())return;let t=await _i(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await In(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await _i(n).catch(()=>null))try{if(await zc(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await Zn(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await Sf(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await _i(n).catch(()=>null))await zc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await In(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of e.slice(i.maxFiles))await Zn(Ui(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=Ic(t),r=Es(i),f=Gc();await Fs(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),dn(this.currentLogFile))try{let t=Hc(this.currentLogFile,"r+");Zc(t),Tf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!g()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await In(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Zn(Ui(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?W.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||g())return!1;let t=typeof _.env.NO_COLOR<"u",i=_.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=_.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${W.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=W.underline(W.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>W.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>W.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>W.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>W.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>W.strikethrough(r)),i}supportsHyperlinks(){if(g())return!1;let t=_.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=_.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(Bs(i)||i.startsWith("./")||i.startsWith("../"))i=Ns(i);else return null;return dn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Bh[t],y=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",w;switch(t){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:W.gray(h),level:t}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:W.green(h),level:t}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.error(w),l){let m=l.split(`
|
|
10
|
-
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
11
|
-
`;if(
|
|
12
|
-
`;if(
|
|
13
|
-
`);if(this[
|
|
14
|
-
`,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let
|
|
15
|
-
`),
|
|
16
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(g())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
18
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||g()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(g()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await
|
|
1
|
+
import{a as G,b as Un,c as Fn,d as a,e as LS,f as ci,g as kS,h as X$,i as Ac,j as ya,k as wf,l as P$,m as VS,n as tw,o as v$}from"./chunk-jpf41gb9.js";import{execSync as za}from"node:child_process";import*as Bi from"node:http";import*as yw from"node:http2";import*as aw from"node:net";import*as D from"node:process";var S={info:(...t)=>console.log("[info]",...t),success:(...t)=>console.log("[success]",...t),warn:(...t)=>console.warn("[warn]",...t),error:(...t)=>console.error("[error]",...t),debug:(...t)=>console.debug("[debug]",...t),log:(...t)=>console.log(...t),start:(...t)=>console.log("[start]",...t),box:(...t)=>console.log("[box]",...t)};var Mn=(t,i)=>(n)=>`\x1B[${t}m${n}\x1B[${i}m`,dt={bold:Mn(1,22),dim:Mn(2,22),green:Mn(32,39),cyan:Mn(36,39)};import{homedir as se}from"node:os";import{join as ye,resolve as Zm}from"node:path";import{existsSync as Hc,statSync as Mc}from"fs";import{existsSync as Ew,mkdirSync as ga,readdirSync as ba,readFileSync as Tw,writeFileSync as Xa}from"fs";import{homedir as Ci}from"os";import{dirname as pa,resolve as Bt}from"path";import Ar from"process";import{existsSync as zc,statSync as Gc}from"fs";import{existsSync as kf,mkdirSync as Sw,readdirSync as Rw,writeFileSync as Bw}from"fs";import{homedir as Fi}from"os";import{dirname as Kc,resolve as ut}from"path";import Ai from"process";import{join as Cw,relative as Fw,resolve as qc}from"path";import nr from"process";import{existsSync as Cl,mkdirSync as hA,readdirSync as $A,writeFileSync as wA}from"fs";import{homedir as Jf}from"os";import{dirname as yA,resolve as wt}from"path";import wn from"process";import{join as Nw,relative as Jw,resolve as xc}from"path";import rr from"process";import{existsSync as Fl,mkdirSync as TA,readdirSync as SA,writeFileSync as RA}from"fs";import{dirname as CA,resolve as fr}from"path";import Vf from"process";import{Buffer as li}from"buffer";import{createCipheriv as _w,createDecipheriv as Uw,randomBytes as _f}from"crypto";import{closeSync as Uf,createReadStream as Oc,createWriteStream as dw,existsSync as df,fsyncSync as Dc,openSync as Lc,writeFileSync as jw}from"fs";import{access as Ww,constants as kc,mkdir as Yw,readdir as zn,rename as Vc,stat as Ni,unlink as Gn,writeFile as jf}from"fs/promises";import{join as Ji}from"path";import rt from"process";import{pipeline as Iw}from"stream/promises";import{createGzip as oc}from"zlib";import _i from"process";import Lt from"process";import{Buffer as xt}from"buffer";import{createCipheriv as Zw,createDecipheriv as Hw,randomBytes as Wf}from"crypto";import{closeSync as Yf,createReadStream as gc,createWriteStream as Mw,existsSync as Kn,fsyncSync as bc,openSync as Xc,writeFileSync as zw}from"fs";import{access as Gw,constants as Pc,mkdir as Kw,readdir as qn,rename as vc,stat as Ui,unlink as xn,writeFile as If}from"fs/promises";import{isAbsolute as qw,join as di,resolve as xw}from"path";import _ from"process";import{pipeline as Ow}from"stream/promises";import{createGzip as pc}from"zlib";import ji from"process";import kt from"process";import On from"process";import{existsSync as Dn}from"fs";import{resolve as Zf}from"path";import{existsSync as Dw}from"fs";import{existsSync as Lw,readdirSync as kw}from"fs";import{extname as Hf,resolve as Qc}from"path";import Vw from"process";import{join as ow,relative as gw,resolve as tl}from"path";import er from"process";import{Buffer as Ot}from"buffer";import{createCipheriv as bw,createDecipheriv as Xw,randomBytes as Mf}from"crypto";import{closeSync as zf,createReadStream as il,createWriteStream as Pw,existsSync as Ln,fsyncSync as nl,openSync as rl,writeFileSync as vw}from"fs";import{access as pw,constants as fl,mkdir as Qw,readdir as kn,rename as el,stat as Wi,unlink as Vn,writeFile as Gf}from"fs/promises";import{isAbsolute as tu,join as Yi,resolve as iu}from"path";import U from"process";import{pipeline as nu}from"stream/promises";import{createGzip as cl}from"zlib";import Ii from"process";import Vt from"process";import gn from"process";import{existsSync as bn}from"fs";import{resolve as Lf}from"path";import{existsSync as Cs}from"fs";class Rl{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Hc(t))return!0;return Mc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Hc(n)?Mc(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Bl{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var ir=new Rl,ne=new Bl;var ru=Object.defineProperty,fu=(t)=>t;function eu(t,i){this[t]=fu.bind(null,i)}var cu=(t,i)=>{for(var n in i)ru(t,n,{get:i[n],enumerable:!0,configurable:!0,set:eu.bind(i,n)})},lu=(t,i)=>()=>(t&&(i=t(t=0)),i),Nl={};cu(Nl,{withErrorRecovery:()=>Ul,tryLoadConfig:()=>Wu,loadConfigWithResult:()=>du,loadConfig:()=>Il,isRetryableError:()=>Cu,isConfigNotFoundError:()=>Bu,isBunfigError:()=>dl,globalPerformanceMonitor:()=>yn,globalCache:()=>Zi,getEnvOrDefault:()=>Fu,generateConfigTypes:()=>Yu,defaultGeneratedDir:()=>xl,defaultConfigDir:()=>ql,deepMergeWithArrayStrategy:()=>le,deepMerge:()=>jl,createLibraryConfig:()=>Iu,config:()=>ju,bunfigPlugin:()=>Zu,applyEnvVarsToConfig:()=>$n,TypeGenerationError:()=>pf,SchemaValidationError:()=>sn,PluginError:()=>te,PerformanceMonitor:()=>fe,FileSystemError:()=>vf,ErrorFactory:()=>hi,EnvVarError:()=>ur,EnvProcessor:()=>mr,ConfigValidator:()=>he,ConfigValidationError:()=>Xf,ConfigNotFoundError:()=>wr,ConfigMergeError:()=>Pf,ConfigLoader:()=>$e,ConfigLoadError:()=>un,ConfigFileLoader:()=>Er,ConfigCache:()=>re,CacheUtils:()=>Hl,BunfigError:()=>Et,BrowserConfigError:()=>Qf,ArrayMergeStrategies:()=>Gl});class re{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!zc(t))return!0;return Gc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=zc(n)?Gc(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class fe{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function hu(t,i={}){let r=Object.keys(i).sort().map((f)=>`${f}:${i[f]}`).join("|");return r?`${t}:${r}`:t}function $u(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function wu(t){return t.getStats().size*2}function ee(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&x(i[0])&&"id"in i[0]&&i[0].id===3&&x(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(x(i)&&x(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(x(t)&&"arr"in t&&Array.isArray(t.arr)&&x(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&x(i[0])&&x(t[0])){let r=[...i];for(let f of t)if(x(f)&&"name"in f){if(!r.find((c)=>x(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(x(f)&&"path"in f){if(!r.find((c)=>x(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((e)=>cr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!x(i)||!x(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(x(f)&&x(n[r]))n[r]=ee(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&x(f[0])&&x(n[r][0])){let e=[...f];for(let c of n[r])if(x(c)&&"name"in c){if(!e.find((l)=>x(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(x(c)&&"path"in c){if(!e.find((l)=>x(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((h)=>cr(h,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function cr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!cr(t[n],i[n]))return!1;return!0}if(x(t)&&x(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!cr(t[f],i[f]))return!1}return!0}return!1}function x(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function uu(t,i){if(!Fl(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return ee(i,r)}catch{return null}}catch{return null}}async function su({name:t="",cwd:i,defaultConfig:n}){let r=i||Vf.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let h of f){let l=fr(r,`${c}${h}`),$=await uu(l,n);if($!==null)return $}try{let c=fr(r,"package.json");if(Fl(c)){let l=(await import(c))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return ee(n,l)}catch{}}}catch{}return n}function yu(t,i={}){let n=rr.cwd();while(n.includes("storage"))n=xc(n,"..");let r=xc(n,t||"");if(i?.relative)return Jw(rr.cwd(),r);return r}async function au(){try{let t=await su({name:"clarity",defaultConfig:vn,cwd:rr.cwd(),endpoint:"",headers:{}});return{...vn,...t}}catch{return vn}}function L(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Au(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Lt<"u"){let t=Lt.type;if(t==="renderer"||t==="worker")return!1;return!!(Lt.versions&&(Lt.versions.node||Lt.versions.bun))}return!1}class Jl{async format(t){let i=await Au(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:_i.pid,hostname:i(),environment:_i.env.NODE_ENV||"development",platform:_i.platform,version:_i.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_i.env.NODE_ENV||_i.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class lr{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(t,i={}){this.name=t,this.config={...gf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Jl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??rt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...pn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...pn};return{...pn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:gf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,h=1000;while(e<c)try{try{try{await Ww(this.config.logDirectory,kc.F_OK|kc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Yw(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:li.from(t);try{if(!df(this.currentLogFile))await jf(this.currentLogFile,"",{mode:420});if(f=Lc(this.currentLogFile,"a",420),jw(f,l,{flag:"a"}),Dc(f),f!==void 0)Uf(f),f=void 0;if((await Ni(this.currentLogFile)).size===0){if(await jf(this.currentLogFile,l,{flag:"w",mode:420}),(await Ni(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let w=$;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(e<c-1){let s=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,s);let y=h*2**e;await new Promise((u)=>setTimeout(u,y)),e++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(f!==void 0)try{Uf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(l){if(e===c-1){let w=l,s=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}e++;let $=h*2**(e-1);await new Promise((w)=>setTimeout(w,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ji(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 Ji(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ji(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(L())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,h],[,l])=>l.createdAt.getTime()-h.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[h]of f.slice(c))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return _f(16).toString("hex")}generateKey(){return _f(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=_f(16),r=_w("aes-256-gcm",i,n),f=li.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:li.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=oc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(li.from(li.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(L())return;let t=await Ni(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await zn(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Ni(n).catch(()=>null))try{if(await Vc(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Gn(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await jf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ni(n).catch(()=>null))await Vc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await zn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,h)=>h.localeCompare(c));for(let c of e.slice(i.maxFiles))await Gn(Ji(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=Oc(t),r=dw(i),f=oc();await Iw(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),df(this.currentLogFile))try{let t=Lc(this.currentLogFile,"r+");Dc(t),Uf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!L()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await zn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Gn(Ji(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?K.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=rt.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${K.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!L()){let $=Ml[t],w=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",s;switch(t){case"debug":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:K.gray(c),level:t}),console.error(s);break;case"info":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s);break;case"success":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:K.green(c),level:t}),console.error(s);break;case"warning":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.warn(s);break;case"error":if(s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s),h){let y=h.split(`
|
|
2
|
+
`);for(let u of y)if(u.trim()&&!u.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:K.gray(` ${u}`),level:t,showTimestamp:!1}))}break}}else if(!L()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let l=`${e} ${this.environment}.${t.toUpperCase()}: ${c}
|
|
3
|
+
`;if(h)l+=`${h}
|
|
4
|
+
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!L()){let n=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:K.blue("◐"),tag:n,message:`${K.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
|
|
5
|
+
`,$=$.replace(this.ANSI_PATTERN,""),this.fancy&&!L()){let w=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:K.green("✓"),tag:w,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!L())console.error($.trim());await this.writeToFile($)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new lr(i,{...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(n),n}createReadStream(){if(L())throw Error("createReadStream is not supported in browser environments");if(!df(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Oc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=li.isBuffer(t)?t:li.from(t,"base64"),f=r.slice(0,16),e=r.slice(-16),c=r.slice(16,-16),h=Uw("aes-256-gcm",n,f);return h.setAuthTag(e),li.concat([h.update(c),h.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return L()}isServerMode(){return!L()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i);if(this.fancy&&!L()){let e=t.split(`
|
|
6
|
+
`),c=Math.max(...e.map((w)=>w.length))+2,h=`┌${"─".repeat(c)}┐`,l=`└${"─".repeat(c)}┘`,$=e.map((w)=>{let s=" ".repeat(c-w.length-2);return`│ ${w}${s} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:K.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(h)})),$.forEach((w)=>console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(w),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(l),showTimestamp:!1}))}else if(!L())console.error(`${r} ${this.environment}.INFO: [BOX] ${t}`);let f=`${r} ${this.environment}.INFO: [BOX] ${t}
|
|
7
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(t){if(L())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${K.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();rt.stdin.removeListener("data",n);try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!1)}catch{}rt.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!0)}catch{}rt.stdin.resume(),rt.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,h=0;if(n=t.replace(c,(l,$)=>{if($==="%")return"%";if(h>=i.length)return l;let w=i[h++];switch($){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 l}}),h<i.length)n+=` ${i.slice(h).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!L()){let c=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",h=K.blue("◐");console.error(`${h} ${c} ${K.cyan(n)}`)}let e=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}progress(t,i=""){if(!this.enabled||!this.fancy||L()||t<=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 n=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(c,h)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,c)),h!==void 0)this.activeProgressBar.message=h;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;if(this.activeProgressBar.current=this.activeProgressBar.total,c!==void 0)this.activeProgressBar.message=c;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(c,h="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||L())return;rt.stdout.write(`${"\r".padEnd(rt.stdout.columns||80)}\r`),this.log(h,c),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||L()||!rt.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=K.green("━".repeat(r)),c=K.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=i||n===100?K.green("✓"):K.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=rt.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,rt.stdout.write(t.lastRenderedLine),i)rt.stdout.write(`
|
|
9
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||L()||!rt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(L()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await zn(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=Ji(this.config.logDirectory,r);if(t.before)try{if((await Ni(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Gn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Pn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&Z(i[0])&&"id"in i[0]&&i[0].id===3&&Z(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(Z(i)&&Z(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(Z(t)&&"arr"in t&&Array.isArray(t.arr)&&Z(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&Z(i[0])&&Z(t[0])){let r=[...i];for(let f of t)if(Z(f)&&"name"in f){if(!r.find((c)=>Z(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(Z(f)&&"path"in f){if(!r.find((c)=>Z(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((e)=>hr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!Z(i)||!Z(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(Z(f)&&Z(n[r]))n[r]=Pn(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&Z(f[0])&&Z(n[r][0])){let e=[...f];for(let c of n[r])if(Z(c)&&"name"in c){if(!e.find((l)=>Z(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(Z(c)&&"path"in c){if(!e.find((l)=>Z(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((h)=>hr(h,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function ce(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:Pn(t,i);if(Array.isArray(t))return n==="replace"?i:Pn(t,i);if(!Z(i)||!Z(t))return i;let r={...t};for(let f of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let e=i[f],c=r[f];if(e===null||e===void 0)continue;if(Array.isArray(e)||Array.isArray(c))if(n==="replace")r[f]=e;else r[f]=Pn(c,e);else if(Z(e)&&Z(c))r[f]=ce(c,e,n);else r[f]=e}return r}function hr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!hr(t[n],i[n]))return!1;return!0}if(Z(t)&&Z(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!hr(t[f],i[f]))return!1}return!0}return!1}function Z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function on(t,i,n="replace"){if(!Cl(t))return null;try{let r=await import(t),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return ce(i,f,n)}catch{return null}}catch{return null}}function mu(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${r}_${s.map(y).join("_")}`,m=`${r}_${s.map((A)=>A.toUpperCase()).join("_")}`;if(n)et.info(`Checking environment variable ${u} for config ${t}.${s.join(".")}`);if(typeof w==="object"&&w!==null&&!Array.isArray(w))l[$]=e(w,s);else{let A=wn.env[u]||wn.env[m];if(A!==void 0){if(n)et.info(`Using environment variable ${A?u:m} for config ${t}.${s.join(".")}`);if(typeof w==="number")l[$]=Number(A);else if(typeof w==="boolean")l[$]=A.toLowerCase()==="true";else if(Array.isArray(w))try{let T=JSON.parse(A);if(Array.isArray(T))l[$]=T;else l[$]=A.split(",").map((E)=>E.trim())}catch{l[$]=A.split(",").map((T)=>T.trim())}else l[$]=A}}}return l}return e(f)}async function Eu({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:h="replace"}){let l=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?mu(t,f,e):f,$=n||wn.cwd(),w=[".ts",".js",".mjs",".cjs",".json"];if(e)et.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${$}`);let s=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),u=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([$,wt($,"config"),wt($,".config"),r?wt($,r):void 0].filter(Boolean)));for(let T of A){if(e)et.info(`Searching for configuration in: ${T}`);let R=[wt($,"config"),wt($,".config")].concat(r?[wt($,r)]:[]).includes(T)?[...s,...y,...u,...m]:[...y,...s,...m,...u];for(let N of R)for(let J of w){let d=wt(T,`${N}${J}`),B=await on(d,l,h);if(B!==null){if(e)et.success(`Configuration loaded from: ${d}`);return B}}}if(t){let T=wt(Jf(),".config",t),E=["config",`${t}.config`];if(i)E.push(`${i}.config`);if(e)et.info(`Checking user config directory: ${T}`);for(let R of E)for(let N of w){let J=wt(T,`${R}${N}`),d=await on(J,l,h);if(d!==null){if(e)et.success(`Configuration loaded from user config directory: ${J}`);return d}}}if(t){let T=wt(Jf(),".config"),E=[`.${t}.config`];if(i)E.push(`.${i}.config`);if(e)et.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of E)for(let N of w){let J=wt(T,`${R}${N}`),d=await on(J,l,h);if(d!==null){if(e)et.success(`Configuration loaded from user config directory dotfile: ${J}`);return d}}}if(t){let T=Jf(),E=[`.${t}.config`,`.${t}`];if(i)E.push(`.${i}.config`),E.push(`.${i}`);if(e)et.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of E)for(let N of w){let J=wt(T,`${R}${N}`),d=await on(J,l,h);if(d!==null){if(e)et.success(`Configuration loaded from user home directory: ${J}`);return d}}}try{let T=wt($,"package.json");if(Cl(T)){let E=await import(T),R=E[t];if(!R&&i){if(R=E[i],R&&e)et.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)et.success(`Configuration loaded from package.json: ${R===E[t]?t:i}`);return ce(l,R,h)}catch(N){if(e)et.warn("Failed to merge package.json config:",N)}}}catch(T){if(e)et.warn("Failed to load package.json:",T)}if(e)et.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function Tu(t,i={}){let n=nr.cwd();while(n.includes("storage"))n=qc(n,"..");let r=qc(n,t||"");if(i?.relative)return Fw(nr.cwd(),r);return r}async function Su(){try{let t=await Eu({name:"clarity",alias:"logging",defaultConfig:Qn,cwd:nr.cwd()});return{...Qn,...t||{}}}catch{return Qn}}function g(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ru(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof kt<"u"){let t=kt.type;if(t==="renderer"||t==="worker")return!1;return!!(kt.versions&&(kt.versions.node||kt.versions.bun))}return!1}class _l{async format(t){let i=await Ru(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ji.pid,hostname:i(),environment:ji.env.NODE_ENV||"development",platform:ji.platform,version:ji.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ji.env.NODE_ENV||ji.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $r{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(t,i={}){this.name=t,this.config={...bf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new _l,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...tr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...tr};return{...tr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:bf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!g()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,h=1000;while(e<c)try{try{try{await Gw(this.config.logDirectory,Pc.F_OK|Pc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Kw(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:xt.from(t);try{if(!Kn(this.currentLogFile))await If(this.currentLogFile,"",{mode:420});if(f=Xc(this.currentLogFile,"a",420),zw(f,l,{flag:"a"}),bc(f),f!==void 0)Yf(f),f=void 0;if((await Ui(this.currentLogFile)).size===0){if(await If(this.currentLogFile,l,{flag:"w",mode:420}),(await Ui(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let w=$;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(e<c-1){let s=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,s);let y=h*2**e;await new Promise((u)=>setTimeout(u,y)),e++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(f!==void 0)try{Yf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(l){if(e===c-1){let w=l,s=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}e++;let $=h*2**(e-1);await new Promise((w)=>setTimeout(w,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return di(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 di(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return di(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(g())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,h],[,l])=>l.createdAt.getTime()-h.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[h]of f.slice(c))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return Wf(16).toString("hex")}generateKey(){return Wf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Wf(16),r=Zw("aes-256-gcm",i,n),f=xt.isBuffer(t)?t:xt.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=xt.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=pc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(xt.from(xt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(g())return;if(!this.shouldWriteToFile())return;let t=await Ui(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await qn(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Ui(n).catch(()=>null))try{if(await vc(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await xn(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await If(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ui(n).catch(()=>null))await vc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await qn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,h)=>h.localeCompare(c));for(let c of e.slice(i.maxFiles))await xn(di(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=gc(t),r=Mw(i),f=pc();await Ow(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Kn(this.currentLogFile))try{let t=Xc(this.currentLogFile,"r+");bc(t),Yf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!g()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await qn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await xn(di(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?j.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||g())return!1;let t=typeof _.env.NO_COLOR<"u",i=_.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=_.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${j.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=j.underline(j.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>j.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>j.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>j.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>j.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>j.strikethrough(r)),i}supportsHyperlinks(){if(g())return!1;let t=_.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=_.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(qw(i)||i.startsWith("./")||i.startsWith("../"))i=xw(i);else return null;return Kn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":zl[t],y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:j.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:j.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
10
|
+
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:j.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!g()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
11
|
+
`;if(h)w+=`${h}
|
|
12
|
+
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(t,i=""){let n={update:(h,l)=>{},finish:(h)=>{},interrupt:(h,l)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(h,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,l="info")=>{if(!g()&&_.stdout.isTTY)_.stdout.write(`
|
|
13
|
+
`);if(this[l==="warning"?"warn":l](h),this.activeProgressBar&&this.shouldStyleConsole()&&!g()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":j.blue("◐"),tag:n,message:`${j.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
|
|
14
|
+
`,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":j.green("✓"),tag:w,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!g())console.error($.trim());if(this.shouldWriteToFile())await this.writeToFile($)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new $r(i,{...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(n),n}createReadStream(){if(g())throw Error("createReadStream is not supported in browser environments");if(!Kn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return gc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=xt.isBuffer(t)?t:xt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),h=Hw("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=xt.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return g()}isServerMode(){return!g()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let h=f.split(`
|
|
15
|
+
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:j.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:j.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:j.cyan(w),showTimestamp:!1}))}else if(!g())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
|
|
16
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(g())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${j.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();_.stdin.removeListener("data",n);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,$=0;if(n=t.replace(l,(w,s)=>{if(s==="%")return"%";if($>=i.length)return w;let y=i[$++];switch(s){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return w}}),$<i.length)n+=` ${i.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${j.blue("◐")} `;console.error(`${$}${l} ${j.cyan(r)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=j.green("━".repeat(r)),c=j.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?j.green("✓"):j.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=_.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,_.stdout.write(t.lastRenderedLine),i)_.stdout.write(`
|
|
18
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||g()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(g()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await qn(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=di(this.config.logDirectory,r);if(t.before)try{if((await Ui(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await xn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function Ul(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function dl(t){return t instanceof Et}function Bu(t){return t instanceof wr}function Cu(t){if(dl(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>t.message.toLowerCase().includes(n.toLowerCase()))}class mr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return yn.track("applyEnvironmentVariables",$,{configName:t});return $()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=On.env[l]||($?On.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=On.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof ur)throw s;throw hi.envVar(l,w,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw hi.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(On.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let n=`Environment Variables for ${i}:
|
|
19
19
|
|
|
20
20
|
`;for(let r of t)n+=`${r.key}
|
|
21
21
|
`,n+=` Type: ${r.type}
|
|
@@ -27,25 +27,25 @@ import{a as G,b as Rn,c as tc,d as a,e as $S,f as ei,g as sS,h as Y$,i as ic,j a
|
|
|
27
27
|
`;n+=`| Variable | Type | Description | Example |
|
|
28
28
|
`,n+=`|----------|------|-------------|----------|
|
|
29
29
|
`;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
30
|
-
`;return n}}function ew(t,i){let n=Th("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function ah(t,i,n={}){return Ah(t,i,n,new WeakMap)}function Ah(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return mh(t,i,f,r);if(!Nt(i)||!Nt(t))return i;return $w(t,i,n,r)}function mh(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return cw(t,i);case"smart":return hw(t,i,r);default:return i}return i}function cw(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Zf(f,r)))n.push(r);return n}function hw(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Nt(i[0])&&Nt(t[0]))return lw(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function lw(t,i,n){let r=[...i];for(let f of t){if(!Nt(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find(($)=>Nt($)&&(l in $)&&$[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function $w(t,i,n,r){let f=i;if(Nt(f)&&r.has(f))return r.get(f);let e={...t};if(Nt(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(Nt(l)&&Nt(h))e[c]=Ah(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=mh(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function bf(t,i,n="replace"){return ah(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Zf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Zf(t[n],i[n]))return!1;return!0}if(Nt(t)&&Nt(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Zf(t[f],i[f]))return!1}return!0}return!1}function Nt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class sr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let $=Ii.getWithFileCheck("file",t);if($){if(l)console.log(`Configuration loaded from cache: ${t}`);return $}}let h=async()=>{if(!Mn(t))return null;try{let $=`?t=${Date.now()}`,s=await import(t+$),u=s.default||s,y="default"in s,w=Object.keys(s).length>0;if(!y&&!w)throw new ln(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new ln(t,Error("Configuration must export a valid object"),"unknown");let T={config:bf(i,u,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Ii.setWithFileCheck("file",T,t,e);return T}catch($){throw $ instanceof Error?hi.configLoad(t,$):hi.configLoad(t,Error(String($)))}};if(c)return sn.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Rf(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(n.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)n.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return n.filter(Boolean)}checkFileAccess(t){return uh(async()=>{return Mn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Mn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=Rf(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=Rf(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(t){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((n)=>n.test(t))}async validateConfigFile(t){let i=[];try{if(!Mn(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class Xf{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,$=async()=>{let s=[],u=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(w){return s.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:s,warnings:u}}};if(l)return await sn.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Js(i))throw new $n(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new $n(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let $=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.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:Fh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Pf{fileLoader=new sr;envProcessor=new $r;validator=new Xf;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let $=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if($)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let s=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),u=!s&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),y=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if($&&(y||s))throw h;if(u&&(!$||!y))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)Wt.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){let h=Date.now()-i;throw Wt.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:$="replace",verbose:s=!1}=t,u=e||ai.cwd(),y=[],w=await this.loadLocalConfiguration(r,f,u,c,l,$,s,h,n);if(w)return y.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(w,y,h,r,s);let m=await this.loadHomeConfiguration(r,f,l,$,s,h);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,h,r,s);let A=await this.loadPackageJsonConfiguration(r,f,u,l,$,s,h);if(A)return y.push(wt(u,"package.json")),this.finalizeResult(A,y,h,r,s);if(y.push(...this.getAllSearchPaths(r,f,u,c)),i)throw hi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,l,h,s),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let $=l?cn(t,f,c):f,s=this.getLocalDirectories(n,r);for(let u of s){if(c)Wt.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),w=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(w){if(c)Wt.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?cn(t,n,f):n,l=[wt(Ni(),".config",t),wt(Ni(),".config"),Ni()];for(let h of l){if(f)Wt.info(`Checking home directory: ${h}`);let $=this.fileLoader.generateConfigPaths(t,h,i),s=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(s){if(f)Wt.success(`Configuration loaded from home directory: ${s.source.path}`);return s}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?cn(t,r,e):r;try{let h=wt(n,"package.json");if(!df(h))return null;let $=await import(h),s=$[t],u=t;if(!s&&i)s=$[i],u=i;if(s&&typeof s==="object"&&!Array.isArray(s)){if(e)Wt.success(`Configuration loaded from package.json: ${u}`);return{config:bf(l,s,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)Wt.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:cn(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw hi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Ii.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Ii.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias)n.push(`alias:${i.alias}`);if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,wt(t,"config"),wt(t,".config"),i?wt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(wt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[wt(Ni(),".config",t),wt(Ni(),".config"),Ni()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function oc(t){let n=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return n||r}async function sw(t){return ot.loadConfig({...t,__strictErrorHandling:!0})}async function Eh(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await ot.loadConfig(t);else r=await ot.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let f=r instanceof Error?r.name:"UnknownError",e=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||e.includes("config"))&&t.verbose)Wt.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ot.applyEnvironmentVariables(l.name||"",i,!0,l.verbose||!1))?.config??i;return i}}async function ww(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ot.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&oc(n)))return(await ot.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await ot.loadConfig({...t,cwd:t.cwd||ai.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&oc(i)))return(await ot.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function uw(t,i,n="replace"){let r=new sr;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function cn(t,i,n=!1){let r=new $r,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((A)=>A.toUpperCase()).join("")}`,`${f}_${u.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,m;for(let A of y)if(w=ai.env[A],w!==void 0){m=A;break}if(w!==void 0&&m)if(typeof s==="boolean")h[$]=["true","1","yes"].includes(w.toLowerCase());else if(typeof s==="number"){let A=Number(w);if(!Number.isNaN(A))h[$]=A}else if(Array.isArray(s))try{h[$]=JSON.parse(w)}catch{h[$]=w.split(",").map((A)=>A.trim())}else h[$]=w;else if(s&&typeof s==="object"&&!Array.isArray(s))h[$]=e(s,u)}return h}return e(i)}function yw(t){let i=wt(ai.cwd(),t.configDir),n=wt(ai.cwd(),t.generatedDir),r=wt(n,"config-types.ts");if(!df(Fc(r)))is(Fc(r),{recursive:!0,mode:511});let f=df(i)?ns(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${Ow}
|
|
30
|
+
`;return n}}function Fu(t,i){let n=Zl("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function jl(t,i,n={}){return Wl(t,i,n,new WeakMap)}function Wl(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return Yl(t,i,f,r);if(!Ct(i)||!Ct(t))return i;return Uu(t,i,n,r)}function Yl(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return Nu(t,i);case"smart":return Ju(t,i,r);default:return i}return i}function Nu(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>of(f,r)))n.push(r);return n}function Ju(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ct(i[0])&&Ct(t[0]))return _u(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function _u(t,i,n){let r=[...i];for(let f of t){if(!Ct(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let h of e)if(h in f){if(r.find(($)=>Ct($)&&(h in $)&&$[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function Uu(t,i,n,r){let f=i;if(Ct(f)&&r.has(f))return r.get(f);let e={...t};if(Ct(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(Ct(h)&&Ct(l))e[c]=Wl(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=Yl(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function le(t,i,n="replace"){return jl(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function of(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!of(t[n],i[n]))return!1;return!0}if(Ct(t)&&Ct(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!of(t[f],i[f]))return!1}return!0}return!1}function Ct(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Er{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:h=!1}=n;if(f){let $=Zi.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!Dn(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new un(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new un(t,Error("Configuration must export a valid object"),"unknown");let T={config:le(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Zi.setWithFileCheck("file",T,t,e);return T}catch($){throw $ instanceof Error?hi.configLoad(t,$):hi.configLoad(t,Error(String($)))}};if(c)return yn.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Zf(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(n.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)n.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return n.filter(Boolean)}checkFileAccess(t){return Ul(async()=>{return Dn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Dn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=Zf(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=Zf(t,c);if(await this.checkFileAccess(h))r.push(h)}}catch{return[]}return r}looksLikeConfigFile(t){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((n)=>n.test(t))}async validateConfigFile(t){let i=[];try{if(!Dn(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class he{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await yn.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Dw(i))throw new sn(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new sn(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),h=this.validateWithRule(c,e,e.path);if(r.push(...h),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.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:Kl},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class $e{fileLoader=new Er;envProcessor=new mr;validator=new he;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)jt.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){let l=Date.now()-i;throw jt.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||Ai.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(ut(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw hi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,h,l){let $=h?$n(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)jt.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)jt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?$n(t,n,f):n,h=[ut(Fi(),".config",t),ut(Fi(),".config"),Fi()];for(let l of h){if(f)jt.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)jt.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?$n(t,r,e):r;try{let l=ut(n,"package.json");if(!kf(l))return null;let $=await import(l),w=$[t],s=t;if(!w&&i)w=$[i],s=i;if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)jt.success(`Configuration loaded from package.json: ${s}`);return{config:le(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)jt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:$n(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw hi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Zi.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Zi.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias)n.push(`alias:${i.alias}`);if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,ut(t,"config"),ut(t,".config"),i?ut(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(ut(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[ut(Fi(),".config",t),ut(Fi(),".config"),Fi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function ll(t){let n=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return n||r}async function du(t){return ot.loadConfig({...t,__strictErrorHandling:!0})}async function Il(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await ot.loadConfig(t);else r=await ot.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let f=r instanceof Error?r.name:"UnknownError",e=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||e.includes("config"))&&t.verbose)jt.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let h=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ot.applyEnvironmentVariables(h.name||"",i,!0,h.verbose||!1))?.config??i;return i}}async function ju(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ot.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&ll(n)))return(await ot.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await ot.loadConfig({...t,cwd:t.cwd||Ai.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&ll(i)))return(await ot.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function Wu(t,i,n="replace"){let r=new Er;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function $n(t,i,n=!1){let r=new mr,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=Ai.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}function Yu(t){let i=ut(Ai.cwd(),t.configDir),n=ut(Ai.cwd(),t.generatedDir),r=ut(n,"config-types.ts");if(!kf(Kc(r)))Sw(Kc(r),{recursive:!0,mode:511});let f=kf(i)?Rw(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${cs}
|
|
31
31
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
32
|
-
`;
|
|
33
|
-
${f.map(($)=>{let
|
|
32
|
+
`;Bw(r,e,{mode:438})}function Iu(t){let i=null,n=null,r=()=>{if(!n)n=Il(t).then((e)=>{return i=e,e},(e)=>{let c="defaultConfig"in t?t.defaultConfig:{};if(i=c,"verbose"in t&&t.verbose)jt.warn("Config loading failed, using defaults:",[e instanceof Error?e:Error(String(e))]);return c});return n},f="defaultConfig"in t?t.defaultConfig:{};return i=f,r(),new Proxy({},{get(e,c){if(i)return i[c];let h=f[c];return r(),h},has(e,c){return c in(i||f)},ownKeys(){return Object.keys(i||f)},getOwnPropertyDescriptor(e,c){return Object.getOwnPropertyDescriptor(i||f,c)},set(e,c,h){if(!i)i={...f};return i[c]=h,!0}})}function Zu(t){let i=Qc(Vw.cwd(),t?.configDir||"./config");function n(){if(!Lw(i))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),e=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=kw(i).filter((l)=>f.has(Hf(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),h=new Map;for(let{base:l,file:$}of c){let w=Hf($).toLowerCase(),s=h.get(l);if(!s){h.set(l,$);continue}let y=Hf(s).toLowerCase();if(e.indexOf(w)<e.indexOf(y))h.set(l,$)}return Array.from(h.entries()).map(([l,$])=>({base:l,file:$})).sort((l,$)=>l.base.localeCompare($.base))}function r(){let f=n(),e=f.map(($)=>$.base),c=e.length?e.map(($)=>`'${$}'`).join(" | "):"string",h=f.length?`{
|
|
33
|
+
${f.map(($)=>{let w=Qc(i,$.file).replace(/\\/g,"/");return` '${$.base}': typeof import('${w}').default`}).join(`,
|
|
34
34
|
`)}
|
|
35
35
|
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
36
|
-
export type ConfigByName = ${
|
|
36
|
+
export type ConfigByName = ${h}
|
|
37
37
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
38
38
|
export type ConfigOf = Config
|
|
39
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(e)=>{return{path:e.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Th,Ii,sn,Sh,mw,Ew,gc,kn,Hf,ft,K,Tw,bc,Sw,Xc,Rw,Bw,Cf,Nw,Pc,vc,_f,Fw,Jw,Cw,_w,Vn,Rh,Uw,et,jw,Ww,pc,on,Mf,b,W,Yw,Qc,dw,th,Iw,Zw,Uf,Hw,ih,nh,Mw,jf,zw,Gw,Kw,qw,xw,gn,Bh,Dw,Ow="0.15.6",Et,rr,ln,zf,Gf,fr,Kf,qf,$n,xf,Df,hi,Nh,Fh,Wt,ot,Jh,Ch,Lw=Ls(async()=>{Th=import.meta.require,Ii=new kf,sn=new Vf,Sh={createKey:ks,isEquivalent:Vs,estimateMemoryUsage:os},mw=vn(If.cwd(),"config"),Ew=vn(If.cwd(),"src/generated"),gc=Pn.env.CLARITY_LOG_DIR||cs(Xs(),"logs"),kn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Hf=await Ps(),ft={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},K=ft,Tw=ft.red,bc=ft.green,Sw=ft.yellow,Xc=ft.blue,Rw=ft.magenta,Bw=ft.cyan,Cf=ft.white,Nw=ft.gray,Pc=ft.bgRed,vc=ft.bgYellow,_f=ft.bold,Fw=ft.dim,Jw=ft.italic,Cw=ft.underline,_w=ft.reset,Vn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Rh={debug:"\uD83D\uDD0D",info:Xc("ℹ"),success:bc("✓"),warning:vc(Cf(_f(" WARN "))),error:Pc(Cf(_f(" ERROR ")))},Uw=new tr("stacks"),et=new tr("bunfig",{showTags:!0}),jw=st(hn.cwd(),"config"),Ww=st(hn.cwd(),"src/generated"),pc=Xn.env.CLARITY_LOG_DIR||fs(tw(),"logs"),on={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:pc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Mf=await iw(),b={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},W=b,Yw=b.red,Qc=b.green,dw=b.yellow,th=b.blue,Iw=b.magenta,Zw=b.cyan,Uf=b.white,Hw=b.gray,ih=b.bgRed,nh=b.bgYellow,Mw=b.bgGray,jf=b.bold,zw=b.dim,Gw=b.italic,Kw=b.underline,qw=b.strikethrough,xw=b.reset,gn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Bh={debug:"\uD83D\uDD0D",info:th("ℹ"),success:Qc("✓"),warning:nh(Uf(jf(" WARN "))),error:ih(Uf(jf(" ERROR ")))},Dw=new nr("stacks"),Et=class extends Error{timestamp;context;constructor(i,n={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,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 i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},rr=class extends Et{code="CONFIG_NOT_FOUND";constructor(i,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:n,searchPathCount:n.length})}},ln=class extends Et{code="CONFIG_LOAD_ERROR";constructor(i,n,r){super(`Failed to load configuration from "${i}": ${n.message}`,{configPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},zf=class extends Et{code="CONFIG_VALIDATION_ERROR";constructor(i,n,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:n,errorCount:n.length})}},Gf=class extends Et{code="CONFIG_MERGE_ERROR";constructor(i,n,r,f){super(`Failed to merge configuration from "${i}" with "${n}": ${r.message}`,{sourcePath:i,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},fr=class extends Et{code="ENV_VAR_ERROR";constructor(i,n,r,f){super(`Failed to parse environment variable "${i}" with value "${n}" as ${r}`,{envKey:i,envValue:n,expectedType:r,configName:f})}},Kf=class extends Et{code="FILE_SYSTEM_ERROR";constructor(i,n,r){super(`File system ${i} failed for "${n}": ${r.message}`,{operation:i,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},qf=class extends Et{code="TYPE_GENERATION_ERROR";constructor(i,n,r){super(`Failed to generate types from "${i}" to "${n}": ${r.message}`,{configDir:i,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},$n=class extends Et{code="SCHEMA_VALIDATION_ERROR";constructor(i,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:n,errorCount:n.length})}},xf=class extends Et{code="BROWSER_CONFIG_ERROR";constructor(i,n,r,f){super(`Failed to fetch configuration from "${i}": ${n} ${r}`,{endpoint:i,status:n,statusText:r,configName:f})}},Df=class extends Et{code="PLUGIN_ERROR";constructor(i,n,r){super(`Plugin "${i}" failed during ${n}: ${r.message}`,{pluginName:i,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},hi={configNotFound(t,i,n){return new rr(t,i,n)},configLoad(t,i,n){return new ln(t,i,n)},configValidation(t,i,n){return new zf(t,i,n)},configMerge(t,i,n,r){return new Gf(t,i,n,r)},envVar(t,i,n,r){return new fr(t,i,n,r)},fileSystem(t,i,n){return new Kf(t,i,n)},typeGeneration(t,i,n){return new qf(t,i,n)},schemaValidation(t,i,n){return new $n(t,i,n)},browserConfig(t,i,n,r){return new xf(t,i,n,r)},plugin(t,i,n){return new Df(t,i,n)}},Nh={replace:"replace",concat:"concat",smart:"smart"},Fh=/^https?:\/\//,Wt=new nr("bunfig",{showTags:!0}),ot=new Pf,Jh=wt(ai.cwd(),"config"),Ch=wt(ai.cwd(),"src/generated")});function kw(t,i={}){let n=pn.cwd();while(n.includes("storage"))n=qc(n,"..");let r=qc(n,t||"");if(i?.relative)return Ws(pn.cwd(),r);return r}var Vw=pn.env.CLARITY_LOG_DIR||js(kw(),"logs"),_h={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Vw,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},er={..._h},OA=(async()=>{try{let{loadConfig:t}=await Lw().then(()=>$h),i=await t({name:"clarity",alias:"logging",defaultConfig:_h,cwd:pn.cwd()});if(i)Object.assign(er,i)}catch{}return er})();function X(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ow(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Vt<"u"){let t=Vt.type;if(t==="renderer"||t==="worker")return!1;return!!(Vt.versions&&(Vt.versions.node||Vt.versions.bun))}return!1}class Uh{async format(t){let i=await ow(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:di.pid,hostname:i(),environment:di.env.NODE_ENV||"development",platform:di.platform,version:di.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:di.env.NODE_ENV||di.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var Q={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},d=Q,LA=Q.red,gw=Q.green,kA=Q.yellow,bw=Q.blue,VA=Q.magenta,oA=Q.cyan,rh=Q.white,gA=Q.gray,Xw=Q.bgRed,Pw=Q.bgYellow,bA=Q.bgGray,fh=Q.bold,XA=Q.dim,PA=Q.italic,vA=Q.underline,pA=Q.strikethrough,QA=Q.reset,Wf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},vw={debug:"\uD83D\uDD0D",info:bw("ℹ"),success:gw("✓"),warning:Pw(rh(fh(" WARN "))),error:Xw(rh(fh(" ERROR ")))};class wr{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(t,i={}){this.name=t,this.config={...er},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Uh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??U.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Wf,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Wf};return{...Wf,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:er.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!X()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,l=1000;while(e<c)try{try{try{await Hs(this.config.logDirectory,Lc.F_OK|Lc.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Ms(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Dt.from(t);try{if(!zn(this.currentLogFile))await Jf(this.currentLogFile,"",{mode:420});if(f=Oc(this.currentLogFile,"a",420),Zs(f,h,{flag:"a"}),Dc(f),f!==void 0)Ff(f),f=void 0;if((await Wi(this.currentLogFile)).size===0){if(await Jf(this.currentLogFile,h,{flag:"w",mode:420}),(await Wi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let s=$;if(s.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(s.code)){if(e<c-1){let u=typeof s.message==="string"?s.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,u);let y=l*2**e;await new Promise((w)=>setTimeout(w,y)),e++;continue}}if(s?.code&&["ENOSPC","EDQUOT"].includes(s.code))throw Error(`Disk quota exceeded or no space left on device: ${s.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",s),s}finally{if(f!==void 0)try{Ff(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(h){if(e===c-1){let s=h,u=typeof s.message==="string"?s.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),h}e++;let $=l*2**(e-1);await new Promise((s)=>setTimeout(s,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Yi(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 Yi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Yi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(X())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,l],[,h])=>h.createdAt.getTime()-l.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[l]of f.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Nf(16).toString("hex")}generateKey(){return Nf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Nf(16),r=Ys("aes-256-gcm",i,n),f=Dt.isBuffer(t)?t:Dt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),$=Dt.allocUnsafe(16+l+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),h.copy($,16+l),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Vc(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(Dt.from(Dt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(X())return;if(!this.shouldWriteToFile())return;let t=await Wi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Gn(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Wi(n).catch(()=>null))try{if(await kc(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await Kn(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await Jf(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Wi(n).catch(()=>null))await kc(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await Gn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of e.slice(i.maxFiles))await Kn(Yi(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=xc(t),r=Is(i),f=Vc();await Ks(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),zn(this.currentLogFile))try{let t=Oc(this.currentLogFile,"r+");Dc(t),Ff(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!X()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Gn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Kn(Yi(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?d.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||X())return!1;let t=typeof U.env.NO_COLOR<"u",i=U.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof U.stderr<"u"&&U.stderr.isTTY||typeof U.stdout<"u"&&U.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=U.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${d.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=d.underline(d.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>d.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>d.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>d.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>d.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>d.strikethrough(r)),i}supportsHyperlinks(){if(X())return!1;let t=U.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=U.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(zs(i)||i.startsWith("./")||i.startsWith("../"))i=Gs(i);else return null;return zn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){if(!this.shouldLog(t))return;let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":vw[t],y=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",w;switch(t){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:d.gray(h),level:t}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:d.green(h),level:t}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.error(w),l){let m=l.split(`
|
|
40
|
-
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
41
|
-
`;if(
|
|
42
|
-
`;if(
|
|
43
|
-
`);if(this[
|
|
44
|
-
`,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let
|
|
45
|
-
`),
|
|
46
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(X())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
48
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||X()||!U.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(X()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await
|
|
39
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(e)=>{return{path:e.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Zl,Zi,yn,Hl,Hu,Mu,hl,vn,gf,ft,K,zu,$l,Gu,wl,Ku,qu,Kf,xu,ul,sl,qf,Ou,Du,Lu,ku,pn,Ml,Vu,et,ou,gu,yl,Qn,bf,b,j,bu,al,Xu,Al,Pu,vu,xf,pu,ml,El,Qu,Of,ts,is,ns,rs,fs,tr,zl,es,cs="0.15.6",Et,wr,un,Xf,Pf,ur,vf,pf,sn,Qf,te,hi,Gl,Kl,jt,ot,ql,xl,ls=lu(async()=>{Zl=import.meta.require,Zi=new re,yn=new fe,Hl={createKey:hu,isEquivalent:$u,estimateMemoryUsage:wu},Hu=fr(Vf.cwd(),"config"),Mu=fr(Vf.cwd(),"src/generated"),hl=rr.env.CLARITY_LOG_DIR||Nw(yu(),"logs"),vn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:hl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},gf=await au(),ft={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},K=ft,zu=ft.red,$l=ft.green,Gu=ft.yellow,wl=ft.blue,Ku=ft.magenta,qu=ft.cyan,Kf=ft.white,xu=ft.gray,ul=ft.bgRed,sl=ft.bgYellow,qf=ft.bold,Ou=ft.dim,Du=ft.italic,Lu=ft.underline,ku=ft.reset,pn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ml={debug:"\uD83D\uDD0D",info:wl("ℹ"),success:$l("✓"),warning:sl(Kf(qf(" WARN "))),error:ul(Kf(qf(" ERROR ")))},Vu=new lr("stacks"),et=new lr("bunfig",{showTags:!0}),ou=wt(wn.cwd(),"config"),gu=wt(wn.cwd(),"src/generated"),yl=nr.env.CLARITY_LOG_DIR||Cw(Tu(),"logs"),Qn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bf=await Su(),b={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},j=b,bu=b.red,al=b.green,Xu=b.yellow,Al=b.blue,Pu=b.magenta,vu=b.cyan,xf=b.white,pu=b.gray,ml=b.bgRed,El=b.bgYellow,Qu=b.bgGray,Of=b.bold,ts=b.dim,is=b.italic,ns=b.underline,rs=b.strikethrough,fs=b.reset,tr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},zl={debug:"\uD83D\uDD0D",info:Al("ℹ"),success:al("✓"),warning:El(xf(Of(" WARN "))),error:ml(xf(Of(" ERROR ")))},es=new $r("stacks"),Et=class extends Error{timestamp;context;constructor(i,n={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,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 i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},wr=class extends Et{code="CONFIG_NOT_FOUND";constructor(i,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:n,searchPathCount:n.length})}},un=class extends Et{code="CONFIG_LOAD_ERROR";constructor(i,n,r){super(`Failed to load configuration from "${i}": ${n.message}`,{configPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Xf=class extends Et{code="CONFIG_VALIDATION_ERROR";constructor(i,n,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:n,errorCount:n.length})}},Pf=class extends Et{code="CONFIG_MERGE_ERROR";constructor(i,n,r,f){super(`Failed to merge configuration from "${i}" with "${n}": ${r.message}`,{sourcePath:i,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},ur=class extends Et{code="ENV_VAR_ERROR";constructor(i,n,r,f){super(`Failed to parse environment variable "${i}" with value "${n}" as ${r}`,{envKey:i,envValue:n,expectedType:r,configName:f})}},vf=class extends Et{code="FILE_SYSTEM_ERROR";constructor(i,n,r){super(`File system ${i} failed for "${n}": ${r.message}`,{operation:i,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},pf=class extends Et{code="TYPE_GENERATION_ERROR";constructor(i,n,r){super(`Failed to generate types from "${i}" to "${n}": ${r.message}`,{configDir:i,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},sn=class extends Et{code="SCHEMA_VALIDATION_ERROR";constructor(i,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:n,errorCount:n.length})}},Qf=class extends Et{code="BROWSER_CONFIG_ERROR";constructor(i,n,r,f){super(`Failed to fetch configuration from "${i}": ${n} ${r}`,{endpoint:i,status:n,statusText:r,configName:f})}},te=class extends Et{code="PLUGIN_ERROR";constructor(i,n,r){super(`Plugin "${i}" failed during ${n}: ${r.message}`,{pluginName:i,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},hi={configNotFound(t,i,n){return new wr(t,i,n)},configLoad(t,i,n){return new un(t,i,n)},configValidation(t,i,n){return new Xf(t,i,n)},configMerge(t,i,n,r){return new Pf(t,i,n,r)},envVar(t,i,n,r){return new ur(t,i,n,r)},fileSystem(t,i,n){return new vf(t,i,n)},typeGeneration(t,i,n){return new pf(t,i,n)},schemaValidation(t,i,n){return new sn(t,i,n)},browserConfig(t,i,n,r){return new Qf(t,i,n,r)},plugin(t,i,n){return new te(t,i,n)}},Gl={replace:"replace",concat:"concat",smart:"smart"},Kl=/^https?:\/\//,jt=new $r("bunfig",{showTags:!0}),ot=new $e,ql=ut(Ai.cwd(),"config"),xl=ut(Ai.cwd(),"src/generated")});function hs(t,i={}){let n=er.cwd();while(n.includes("storage"))n=tl(n,"..");let r=tl(n,t||"");if(i?.relative)return gw(er.cwd(),r);return r}var $s=er.env.CLARITY_LOG_DIR||ow(hs(),"logs"),Ol={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$s,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},sr={...Ol},$m=(async()=>{try{let{loadConfig:t}=await ls().then(()=>Nl),i=await t({name:"clarity",alias:"logging",defaultConfig:Ol,cwd:er.cwd()});if(i)Object.assign(sr,i)}catch{}return sr})();function X(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ws(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Vt<"u"){let t=Vt.type;if(t==="renderer"||t==="worker")return!1;return!!(Vt.versions&&(Vt.versions.node||Vt.versions.bun))}return!1}class Dl{async format(t){let i=await ws(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ii.pid,hostname:i(),environment:Ii.env.NODE_ENV||"development",platform:Ii.platform,version:Ii.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ii.env.NODE_ENV||Ii.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var tt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},Y=tt,wm=tt.red,us=tt.green,um=tt.yellow,ss=tt.blue,sm=tt.magenta,ym=tt.cyan,Tl=tt.white,am=tt.gray,ys=tt.bgRed,as=tt.bgYellow,Am=tt.bgGray,Sl=tt.bold,mm=tt.dim,Em=tt.italic,Tm=tt.underline,Sm=tt.strikethrough,Rm=tt.reset,Df={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},As={debug:"\uD83D\uDD0D",info:ss("ℹ"),success:us("✓"),warning:as(Tl(Sl(" WARN "))),error:ys(Tl(Sl(" ERROR ")))};class Tr{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(t,i={}){this.name=t,this.config={...sr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Dl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??U.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Df,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Df};return{...Df,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:sr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!X()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let f,e=0,c=3,h=1000;while(e<c)try{try{try{await pw(this.config.logDirectory,fl.F_OK|fl.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Qw(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Ot.from(t);try{if(!Ln(this.currentLogFile))await Gf(this.currentLogFile,"",{mode:420});if(f=rl(this.currentLogFile,"a",420),vw(f,l,{flag:"a"}),nl(f),f!==void 0)zf(f),f=void 0;if((await Wi(this.currentLogFile)).size===0){if(await Gf(this.currentLogFile,l,{flag:"w",mode:420}),(await Wi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let w=$;if(w.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(w.code)){if(e<c-1){let s=typeof w.message==="string"?w.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${c}:`,s);let y=h*2**e;await new Promise((u)=>setTimeout(u,y)),e++;continue}}if(w?.code&&["ENOSPC","EDQUOT"].includes(w.code))throw Error(`Disk quota exceeded or no space left on device: ${w.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",w),w}finally{if(f!==void 0)try{zf(f)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(l){if(e===c-1){let w=l,s=typeof w.message==="string"?w.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}e++;let $=h*2**(e-1);await new Promise((w)=>setTimeout(w,$))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Yi(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 Yi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Yi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(X())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let n=typeof i.interval==="number"?i.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,h],[,l])=>l.createdAt.getTime()-h.createdAt.getTime()),e=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,e);if(f.length>c)for(let[h]of f.slice(c))this.encryptionKeys.delete(h),this.keys.delete(h)}generateKeyId(){return Mf(16).toString("hex")}generateKey(){return Mf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Mf(16),r=bw("aes-256-gcm",i,n),f=Ot.isBuffer(t)?t:Ot.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=Ot.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=cl(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(Ot.from(Ot.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(X())return;if(!this.shouldWriteToFile())return;let t=await Wi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await kn(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Wi(n).catch(()=>null))try{if(await el(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Vn(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Gf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Wi(n).catch(()=>null))await el(n,e)}if(this.currentLogFile=r,i.maxFiles){let e=(await kn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,h)=>h.localeCompare(c));for(let c of e.slice(i.maxFiles))await Vn(Yi(this.config.logDirectory,c))}}}async compressLogFile(t,i){let n=il(t),r=Pw(i),f=cl();await nu(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Ln(this.currentLogFile))try{let t=rl(this.currentLogFile,"r+");nl(t),zf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!X()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await kn(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of i)try{await Vn(Yi(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?Y.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||X())return!1;let t=typeof U.env.NO_COLOR<"u",i=U.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof U.stderr<"u"&&U.stderr.isTTY||typeof U.stdout<"u"&&U.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=U.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${Y.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=Y.underline(Y.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>Y.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Y.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Y.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Y.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>Y.strikethrough(r)),i}supportsHyperlinks(){if(X())return!1;let t=U.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=U.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(tu(i)||i.startsWith("./")||i.startsWith("../"))i=iu(i);else return null;return Ln(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){if(!this.shouldLog(t))return;let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":As[t],y=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:Y.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:Y.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
40
|
+
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:Y.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!X()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
41
|
+
`;if(h)w+=`${h}
|
|
42
|
+
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(t,i=""){let n={update:(h,l)=>{},finish:(h)=>{},interrupt:(h,l)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(h,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,h),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(h)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,h)},interrupt:(h,l="info")=>{if(!X()&&U.stdout.isTTY)U.stdout.write(`
|
|
43
|
+
`);if(this[l==="warning"?"warn":l](h),this.activeProgressBar&&this.shouldStyleConsole()&&!X()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":Y.blue("◐"),tag:n,message:`${Y.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)$+=` ${JSON.stringify(n)}`;if($+=`
|
|
44
|
+
`,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":Y.green("✓"),tag:w,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!X())console.error($.trim());if(this.shouldWriteToFile())await this.writeToFile($)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new Tr(i,{...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(n),n}createReadStream(){if(X())throw Error("createReadStream is not supported in browser environments");if(!Ln(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return il(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Ot.isBuffer(t)?t:Ot.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),h=Xw("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=Ot.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return X()}isServerMode(){return!X()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let h=f.split(`
|
|
45
|
+
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:Y.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:Y.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:Y.cyan(w),showTimestamp:!1}))}else if(!X())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
|
|
46
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(X())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${Y.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();U.stdin.removeListener("data",n);try{if(typeof U.stdin.setRawMode==="function")U.stdin.setRawMode(!1)}catch{}U.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof U.stdin.setRawMode==="function")U.stdin.setRawMode(!0)}catch{}U.stdin.resume(),U.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,$=0;if(n=t.replace(l,(w,s)=>{if(s==="%")return"%";if($>=i.length)return w;let y=i[$++];switch(s){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return w}}),$<i.length)n+=` ${i.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${Y.blue("◐")} `;console.error(`${$}${l} ${Y.cyan(r)}`)}let h=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(h)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!U.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=Y.green("━".repeat(r)),c=Y.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?Y.green("✓"):Y.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${Y.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=U.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,U.stdout.write(t.lastRenderedLine),i)U.stdout.write(`
|
|
48
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||X()||!U.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(X()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await kn(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let e=Yi(this.config.logDirectory,r);if(t.before)try{if((await Wi(e)).mtime>=t.before)continue}catch(c){console.error(`Failed to get stats for file ${e}:`,c);continue}n.push(e)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Vn(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var Bm=new Tr("stacks");class Wt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class Ll extends Wt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((e)=>`"${e}"`).join(", ")}`;super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}}class yr extends Wt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}}class kl extends Wt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class Vl extends Wt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class we extends Wt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}}class ol extends Wt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class gl extends Wt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class ar extends Wt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class bl extends Wt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}}class Xl extends Wt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}}var Hi={configNotFound(t,i,n){return new Ll(t,i,n)},configLoad(t,i,n){return new yr(t,i,n)},configValidation(t,i,n){return new kl(t,i,n)},configMerge(t,i,n,r){return new Vl(t,i,n,r)},envVar(t,i,n,r){return new we(t,i,n,r)},fileSystem(t,i,n){return new ol(t,i,n)},typeGeneration(t,i,n){return new gl(t,i,n)},schemaValidation(t,i,n){return new ar(t,i,n)},browserConfig(t,i,n,r){return new bl(t,i,n,r)},plugin(t,i,n){return new Xl(t,i,n)}};async function ms(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class ue{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return ne.track("applyEnvironmentVariables",$,{configName:t});return $()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=gn.env[l]||($?gn.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=gn.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof we)throw s;throw Hi.envVar(l,w,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw Hi.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(gn.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let n=`Environment Variables for ${i}:
|
|
49
49
|
|
|
50
50
|
`;for(let r of t)n+=`${r.key}
|
|
51
51
|
`,n+=` Type: ${r.type}
|
|
@@ -57,24 +57,24 @@ export type ConfigOf = Config
|
|
|
57
57
|
`;n+=`| Variable | Type | Description | Example |
|
|
58
58
|
`,n+=`|----------|------|-------------|----------|
|
|
59
59
|
`;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
60
|
-
`;return n}}function Qw(t,i,n={}){return Mh(t,i,n,new WeakMap)}function Mh(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return zh(t,i,f,r);if(!Ft(i)||!Ft(t))return i;return ru(t,i,n,r)}function zh(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return tu(t,i);case"smart":return iu(t,i,r);default:return i}return i}function tu(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Of(f,r)))n.push(r);return n}function iu(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ft(i[0])&&Ft(t[0]))return nu(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function nu(t,i,n){let r=[...i];for(let f of t){if(!Ft(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find(($)=>Ft($)&&(l in $)&&$[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function ru(t,i,n,r){let f=i;if(Ft(f)&&r.has(f))return r.get(f);let e={...t};if(Ft(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(Ft(l)&&Ft(h))e[c]=Mh(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=zh(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function Gh(t,i,n="replace"){return Qw(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Of(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Of(t[n],i[n]))return!1;return!0}if(Ft(t)&&Ft(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Of(t[f],i[f]))return!1}return!0}return!1}function Ft(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Kh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let $=bn.getWithFileCheck("file",t);if($){if(l)console.log(`Configuration loaded from cache: ${t}`);return $}}let h=async()=>{if(!Dn(t))return null;try{let $=`?t=${Date.now()}`,s=await import(t+$),u=s.default||s,y="default"in s,w=Object.keys(s).length>0;if(!y&&!w)throw new cr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new cr(t,Error("Configuration must export a valid object"),"unknown");let T={config:Gh(i,u,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)bn.setWithFileCheck("file",T,t,e);return T}catch($){throw $ instanceof Error?Zi.configLoad(t,$):Zi.configLoad(t,Error(String($)))}};if(c)return Lf.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Yf(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=i===void 0?[]:Array.isArray(i)?i:[i];for(let e of r){if(!e)continue;if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}let f=new Set;return n.filter((e)=>{if(!e||f.has(e))return!1;return f.add(e),!0})}checkFileAccess(t){return pw(async()=>{return Dn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Dn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=Yf(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=Yf(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(t){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((n)=>n.test(t))}async validateConfigFile(t){let i=[];try{if(!Dn(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var eu=/^https?:\/\//;class qh{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,$=async()=>{let s=[],u=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(w){return s.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:s,warnings:u}}};if(l)return await Lf.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!fu(i))throw new hr(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new hr(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let $=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.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:eu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Ot=new wr("bunfig",{showTags:!0});function cu(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`}class xh{fileLoader=new Kh;envProcessor=new pf;validator=new qh;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let $=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if($)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let s=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),u=!s&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),y=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if($&&(y||s))throw h;if(u&&(!$||!y))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)Ot.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let h=Date.now()-i;throw Ot.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:$="replace",verbose:s=!1}=t,u=e||lr.cwd(),y=[],w=await this.loadLocalConfiguration(r,f,u,c,l,$,s,h,n);if(w)return y.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(w,y,h,r,s);let m=await this.loadHomeConfiguration(r,f,l,$,s,h);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,h,r,s);let A=await this.loadPackageJsonConfiguration(r,f,u,l,$,s,h);if(A)return y.push(Bt(u,"package.json")),this.finalizeResult(A,y,h,r,s);if(y.push(...this.getAllSearchPaths(r,f,u,c)),i)throw Zi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,l,h,s),warnings:[`No configuration file found for "${r}"${cu(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let $=l?On(t,f,c):f,s=this.getLocalDirectories(n,r);for(let u of s){if(c)Ot.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),w=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(w){if(c)Ot.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?On(t,n,f):n,l=[Bt(Bi(),".config",t),Bt(Bi(),".config"),Bi()];for(let h of l){if(f)Ot.info(`Checking home directory: ${h}`);let $=this.fileLoader.generateConfigPaths(t,h,i),s=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(s){if(f)Ot.success(`Configuration loaded from home directory: ${s.source.path}`);return s}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?On(t,r,e):r;try{let h=Bt(n,"package.json");if(!Q$(h))return null;let $={};try{$=JSON.parse(ts(h,"utf8"))}catch(y){if(e)Ot.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let s=$[t],u=t;if(!s&&i){let y=Array.isArray(i)?i:[i];for(let w of y){if(!w)continue;if($[w]){s=$[w],u=w;break}}}if(s&&typeof s==="object"&&!Array.isArray(s)){if(e)Ot.success(`Configuration loaded from package.json: ${u}`);return{config:Gh(l,s,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)Ot.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:On(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Zi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return bn.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);bn.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias){let r=Array.isArray(i.alias)?i.alias.join(","):i.alias;n.push(`alias:${r}`)}if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Bt(t,"config"),Bt(t,".config"),i?Bt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(Bt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[Bt(Bi(),".config",t),Bt(Bi(),".config"),Bi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var em=new xh;function On(t,i,n=!1){let r=new pf,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((A)=>A.toUpperCase()).join("")}`,`${f}_${u.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,m;for(let A of y)if(w=lr.env[A],w!==void 0){m=A;break}if(w!==void 0&&m)if(typeof s==="boolean")h[$]=["true","1","yes"].includes(w.toLowerCase());else if(typeof s==="number"){let A=Number(w);if(!Number.isNaN(A))h[$]=A}else if(Array.isArray(s))try{h[$]=JSON.parse(w)}catch{h[$]=w.split(",").map((A)=>A.trim())}else h[$]=w;else if(s&&typeof s==="object"&&!Array.isArray(s))h[$]=e(s,u)}return h}return e(i)}var cm=Bt(lr.cwd(),"config"),hm=Bt(lr.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",hu={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:te(Qf(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:te(Qf(),".stacks","ssl","stacks.localhost.crt"),keyPath:te(Qf(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Hi=hu;import*as O$ from"node:fs";import*as L$ from"node:path";import*as qt from"node:process";import{spawn as ra}from"node:child_process";import*as Kt from"node:fs/promises";import{homedir as q$}from"node:os";import*as Gt from"node:path";import*as nt from"node:process";import{execSync as wi}from"node:child_process";import o from"node:fs/promises";import*as Qe from"node:os";import{homedir as vi}from"node:os";import{join as it}from"node:path";import*as zt from"node:process";import{createRequire as lu}from"node:module";import ie from"node:os";import ne from"node:path";import{existsSync as Dh,statSync as Oh}from"fs";import{existsSync as $u,mkdirSync as Bm,readdirSync as Nm,readFileSync as su,writeFileSync as Fm}from"fs";import{homedir as Mi}from"os";import{dirname as _m,resolve as Jt}from"path";import gr from"process";import{existsSync as Lh,statSync as kh}from"fs";import{existsSync as Ne,mkdirSync as wu,readdirSync as uu,writeFileSync as yu}from"fs";import{homedir as zi}from"os";import{dirname as Vh,resolve as yt}from"path";import Ai from"process";import{join as au,relative as Au,resolve as oh}from"path";import dr from"process";import{existsSync as Zl,mkdirSync as zm,readdirSync as Gm,writeFileSync as Km}from"fs";import{homedir as re}from"os";import{dirname as Dm,resolve as ut}from"path";import an from"process";import{join as mu,relative as Eu,resolve as gh}from"path";import Ir from"process";import{existsSync as Hl,mkdirSync as om,readdirSync as gm,writeFileSync as bm}from"fs";import{dirname as Pm,resolve as Zr}from"path";import Fe from"process";import{Buffer as li}from"buffer";import{createCipheriv as Tu,createDecipheriv as Su,randomBytes as fe}from"crypto";import{closeSync as ee,createReadStream as bh,createWriteStream as Ru,existsSync as ce,fsyncSync as Xh,openSync as Ph,writeFileSync as Bu}from"fs";import{access as Nu,constants as vh,mkdir as Fu,readdir as ur,rename as ph,stat as Gi,unlink as yr,writeFile as he}from"fs/promises";import{join as Ki}from"path";import ct from"process";import{pipeline as Ju}from"stream/promises";import{createGzip as Qh}from"zlib";import qi from"process";import Pt from"process";import{Buffer as gt}from"buffer";import{createCipheriv as Cu,createDecipheriv as _u,randomBytes as le}from"crypto";import{closeSync as $e,createReadStream as tl,createWriteStream as Uu,existsSync as ar,fsyncSync as il,openSync as nl,writeFileSync as ju}from"fs";import{access as Wu,constants as rl,mkdir as Yu,readdir as Ar,rename as fl,stat as xi,unlink as mr,writeFile as se}from"fs/promises";import{isAbsolute as du,join as Di,resolve as Iu}from"path";import H from"process";import{pipeline as Zu}from"stream/promises";import{createGzip as el}from"zlib";import Oi from"process";import vt from"process";import Er from"process";import{existsSync as Tr}from"fs";import{resolve as we}from"path";import{existsSync as Hu}from"fs";import{existsSync as Mu,readdirSync as zu}from"fs";import{extname as ue,resolve as cl}from"path";import Gu from"process";import{join as Ku,relative as qu,resolve as hl}from"path";import Hr from"process";import{Buffer as bt}from"buffer";import{createCipheriv as xu,createDecipheriv as Du,randomBytes as ye}from"crypto";import{closeSync as ae,createReadStream as ll,createWriteStream as Ou,existsSync as Sr,fsyncSync as $l,openSync as sl,writeFileSync as Lu}from"fs";import{access as ku,constants as wl,mkdir as Vu,readdir as Rr,rename as ul,stat as Li,unlink as Br,writeFile as Ae}from"fs/promises";import{isAbsolute as ou,join as ki,resolve as gu}from"path";import M from"process";import{pipeline as bu}from"stream/promises";import{createGzip as yl}from"zlib";import Vi from"process";import pt from"process";import Nr from"process";import{existsSync as Fr}from"fs";import{resolve as me}from"path";import{existsSync as Xu}from"fs";import{exec as E0}from"node:child_process";import Ul from"node:fs";import T0 from"node:os";import dt from"node:path";import m$ from"node:process";import{promisify as S0}from"node:util";import Xi from"node:crypto";import Qt from"node:fs";import ze from"node:path";import{execSync as Il}from"node:child_process";import or from"node:os";var mm=lu(import.meta.url);class Ml{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Dh(t))return!0;return Oh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Dh(n)?Oh(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class zl{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Mr=new Ml,Ge=new zl,Pu=Object.defineProperty,vu=(t)=>t;function pu(t,i){this[t]=vu.bind(null,i)}var Qu=(t,i)=>{for(var n in i)Pu(t,n,{get:i[n],enumerable:!0,configurable:!0,set:pu.bind(i,n)})},ty=(t,i)=>()=>(t&&(i=t(t=0)),i),Gl={};Qu(Gl,{withErrorRecovery:()=>xl,tryLoadConfig:()=>Fy,loadConfigWithResult:()=>By,loadConfig:()=>Vl,isRetryableError:()=>Ay,isConfigNotFoundError:()=>ay,isBunfigError:()=>Dl,globalPerformanceMonitor:()=>Tn,globalCache:()=>gi,getEnvOrDefault:()=>my,generateConfigTypes:()=>Jy,defaultGeneratedDir:()=>Ql,defaultConfigDir:()=>pl,deepMergeWithArrayStrategy:()=>Oe,deepMerge:()=>Ol,createLibraryConfig:()=>Cy,config:()=>Ny,bunfigPlugin:()=>_y,applyEnvVarsToConfig:()=>un,TypeGenerationError:()=>Ye,SchemaValidationError:()=>mn,PluginError:()=>Ie,PerformanceMonitor:()=>qe,FileSystemError:()=>We,ErrorFactory:()=>si,EnvVarError:()=>Dr,EnvProcessor:()=>br,ConfigValidator:()=>Le,ConfigValidationError:()=>Ue,ConfigNotFoundError:()=>xr,ConfigMergeError:()=>je,ConfigLoader:()=>ke,ConfigLoadError:()=>An,ConfigFileLoader:()=>Xr,ConfigCache:()=>Ke,CacheUtils:()=>gl,BunfigError:()=>Tt,BrowserConfigError:()=>de,ArrayMergeStrategies:()=>Pl});class Ke{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!Lh(t))return!0;return kh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=Lh(n)?kh(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class qe{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function iy(t,i={}){let n=Object.keys(i).sort().map((r)=>`${r}:${i[r]}`).join("|");return n?`${t}:${n}`:t}function ny(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function ry(t){return t.getStats().size*2}function xe(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&D(i[0])&&"id"in i[0]&&i[0].id===3&&D(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(D(i)&&D(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(D(t)&&"arr"in t&&Array.isArray(t.arr)&&D(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&D(i[0])&&D(t[0])){let r=[...i];for(let f of t)if(D(f)&&"name"in f){if(!r.find((e)=>D(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(D(f)&&"path"in f){if(!r.find((e)=>D(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>zr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!D(i)||!D(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(D(f)&&D(n[r]))n[r]=xe(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&D(f[0])&&D(n[r][0])){let e=[...f];for(let c of n[r])if(D(c)&&"name"in c){if(!e.find((l)=>D(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(D(c)&&"path"in c){if(!e.find((l)=>D(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((l)=>zr(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function zr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!zr(t[n],i[n]))return!1;return!0}if(D(t)&&D(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!zr(t[f],i[f]))return!1}return!0}return!1}function D(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function fy(t,i){if(!Hl(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return xe(i,r)}catch{return null}}catch{return null}}async function ey({name:t="",cwd:i,defaultConfig:n}){let r=i||Fe.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let l of f){let h=Zr(r,`${c}${l}`),$=await fy(h,n);if($!==null)return $}try{let c=Zr(r,"package.json");if(Hl(c)){let l=(await import(c))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return xe(n,l)}catch{}}}catch{}return n}function cy(t,i={}){let n=Ir.cwd();while(n.includes("storage"))n=gh(n,"..");let r=gh(n,t||"");if(i?.relative)return Eu(Ir.cwd(),r);return r}async function hy(){try{let t=await ey({name:"clarity",defaultConfig:Ur,cwd:Ir.cwd(),endpoint:"",headers:{}});return{...Ur,...t}}catch{return Ur}}function k(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ly(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Pt<"u"){let t=Pt.type;if(t==="renderer"||t==="worker")return!1;return!!(Pt.versions&&(Pt.versions.node||Pt.versions.bun))}return!1}class Kl{async format(t){let i=await ly(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:qi.pid,hostname:i(),environment:qi.env.NODE_ENV||"development",platform:qi.platform,version:qi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:qi.env.NODE_ENV||qi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Gr{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(t,i={}){this.name=t,this.config={...Ce},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Kl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??ct.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...jr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...jr};return{...jr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ce.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await Nu(this.config.logDirectory,vh.F_OK|vh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Fu(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:li.from(t);try{if(!ce(this.currentLogFile))await he(this.currentLogFile,"",{mode:420});if(r=Ph(this.currentLogFile,"a",420),Bu(r,l,{flag:"a"}),Xh(r),r!==void 0)ee(r),r=void 0;if((await Gi(this.currentLogFile)).size===0){if(await he(this.currentLogFile,l,{flag:"w",mode:420}),(await Gi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let $=h;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let s=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,s);let u=c*2**f;await new Promise((y)=>setTimeout(y,u)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{ee(r)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===e-1){let $=l,s=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}f++;let h=c*2**(f-1);await new Promise(($)=>setTimeout($,h))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ki(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 Ki(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ki(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return fe(16).toString("hex")}generateKey(){return fe(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=fe(16),r=Tu("aes-256-gcm",i,n),f=li.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:li.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Qh(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(li.from(li.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(k())return;let t=await Gi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await ur(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Gi(n).catch(()=>null))try{if(await ph(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await yr(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await he(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Gi(n).catch(()=>null))await ph(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await ur(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await yr(Ki(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=bh(t),r=Ru(i),f=Qh();await Ju(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),ce(this.currentLogFile))try{let t=Ph(this.currentLogFile,"r+");Xh(t),ee(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await ur(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await yr(Ki(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?q.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=ct.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${q.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!k()){let $=bl[t],s=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:q.gray(c),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:q.green(c),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:$,tag:s,message:c,level:t}),console.error(u),l){let y=l.split(`
|
|
61
|
-
`);for(let
|
|
62
|
-
`;if(l
|
|
63
|
-
`;
|
|
64
|
-
`,
|
|
65
|
-
`),c=Math.max(...e.map((
|
|
66
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(t){if(k())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${q.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();ct.stdin.removeListener("data",n);try{if(typeof ct.stdin.setRawMode==="function")ct.stdin.setRawMode(!1)}catch{}ct.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof ct.stdin.setRawMode==="function")ct.stdin.setRawMode(!0)}catch{}ct.stdin.resume(),ct.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let f=/%([sdijfo%])/g,e=0;if(n=t.replace(f,(c,
|
|
67
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(t,i=""){if(!this.enabled||!this.fancy||k()||t<=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 n=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,r)),f!==void 0)this.activeProgressBar.message=f;let e=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,e)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;ct.stdout.write(`${"\r".padEnd(ct.stdout.columns||80)}\r`),this.log(f,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||k()||!ct.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=q.green("━".repeat(r)),c=q.gray("━".repeat(f)),
|
|
68
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||k()||!ct.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await ur(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Ki(this.config.logDirectory,r);if(t.before)try{if((await Gi(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await yr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function _r(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&z(i[0])&&"id"in i[0]&&i[0].id===3&&z(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(z(i)&&z(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(z(t)&&"arr"in t&&Array.isArray(t.arr)&&z(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&z(i[0])&&z(t[0])){let r=[...i];for(let f of t)if(z(f)&&"name"in f){if(!r.find((e)=>z(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(z(f)&&"path"in f){if(!r.find((e)=>z(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>Kr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!z(i)||!z(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(z(f)&&z(n[r]))n[r]=_r(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&z(f[0])&&z(n[r][0])){let e=[...f];for(let c of n[r])if(z(c)&&"name"in c){if(!e.find((l)=>z(l)&&("name"in l)&&l.name===c.name))e.push(c)}else if(z(c)&&"path"in c){if(!e.find((l)=>z(l)&&("path"in l)&&l.path===c.path))e.push(c)}else if(!e.some((l)=>Kr(l,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function De(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:_r(t,i);if(Array.isArray(t))return n==="replace"?i:_r(t,i);if(!z(i)||!z(t))return i;let r={...t};for(let f of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let e=i[f],c=r[f];if(e===null||e===void 0)continue;if(Array.isArray(e)||Array.isArray(c))if(n==="replace")r[f]=e;else r[f]=_r(c,e);else if(z(e)&&z(c))r[f]=De(c,e,n);else r[f]=e}return r}function Kr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Kr(t[n],i[n]))return!1;return!0}if(z(t)&&z(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Kr(t[f],i[f]))return!1}return!0}return!1}function z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Jr(t,i,n="replace"){if(!Zl(t))return null;try{let r=await import(t),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return De(i,f,n)}catch{return null}}catch{return null}}function $y(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),w=`${r}_${u.map(y).join("_")}`,m=`${r}_${u.map((A)=>A.toUpperCase()).join("_")}`;if(n)lt.info(`Checking environment variable ${w} for config ${t}.${u.join(".")}`);if(typeof s==="object"&&s!==null&&!Array.isArray(s))h[$]=e(s,u);else{let A=an.env[w]||an.env[m];if(A!==void 0){if(n)lt.info(`Using environment variable ${A?w:m} for config ${t}.${u.join(".")}`);if(typeof s==="number")h[$]=Number(A);else if(typeof s==="boolean")h[$]=A.toLowerCase()==="true";else if(Array.isArray(s))try{let T=JSON.parse(A);if(Array.isArray(T))h[$]=T;else h[$]=A.split(",").map((E)=>E.trim())}catch{h[$]=A.split(",").map((T)=>T.trim())}else h[$]=A}}}return h}return e(f)}async function sy({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:l="replace"}){let h=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?$y(t,f,e):f,$=n||an.cwd(),s=[".ts",".js",".mjs",".cjs",".json"];if(e)lt.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${$}`);let u=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),w=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([$,ut($,"config"),ut($,".config"),r?ut($,r):void 0].filter(Boolean)));for(let T of A){if(e)lt.info(`Searching for configuration in: ${T}`);let E=[ut($,"config"),ut($,".config")].concat(r?[ut($,r)]:[]).includes(T)?[...u,...y,...w,...m]:[...y,...u,...m,...w];for(let R of E)for(let J of s){let C=ut(T,`${R}${J}`),j=await Jr(C,h,l);if(j!==null){if(e)lt.success(`Configuration loaded from: ${C}`);return j}}}if(t){let T=ut(re(),".config",t),E=["config",`${t}.config`];if(i)E.push(`${i}.config`);if(e)lt.info(`Checking user config directory: ${T}`);for(let R of E)for(let J of s){let C=ut(T,`${R}${J}`),j=await Jr(C,h,l);if(j!==null){if(e)lt.success(`Configuration loaded from user config directory: ${C}`);return j}}}if(t){let T=ut(re(),".config"),E=[`.${t}.config`];if(i)E.push(`.${i}.config`);if(e)lt.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of E)for(let J of s){let C=ut(T,`${R}${J}`),j=await Jr(C,h,l);if(j!==null){if(e)lt.success(`Configuration loaded from user config directory dotfile: ${C}`);return j}}}if(t){let T=re(),E=[`.${t}.config`,`.${t}`];if(i)E.push(`.${i}.config`),E.push(`.${i}`);if(e)lt.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of E)for(let J of s){let C=ut(T,`${R}${J}`),j=await Jr(C,h,l);if(j!==null){if(e)lt.success(`Configuration loaded from user home directory: ${C}`);return j}}}try{let T=ut($,"package.json");if(Zl(T)){let E=await import(T),R=E[t];if(!R&&i){if(R=E[i],R&&e)lt.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)lt.success(`Configuration loaded from package.json: ${R===E[t]?t:i}`);return De(h,R,l)}catch(J){if(e)lt.warn("Failed to merge package.json config:",J)}}}catch(T){if(e)lt.warn("Failed to load package.json:",T)}if(e)lt.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return h}function wy(t,i={}){let n=dr.cwd();while(n.includes("storage"))n=oh(n,"..");let r=oh(n,t||"");if(i?.relative)return Au(dr.cwd(),r);return r}async function uy(){try{let t=await sy({name:"clarity",alias:"logging",defaultConfig:Wr,cwd:dr.cwd()});return{...Wr,...t||{}}}catch{return Wr}}function P(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function yy(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vt<"u"){let t=vt.type;if(t==="renderer"||t==="worker")return!1;return!!(vt.versions&&(vt.versions.node||vt.versions.bun))}return!1}class ql{async format(t){let i=await yy(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Oi.pid,hostname:i(),environment:Oi.env.NODE_ENV||"development",platform:Oi.platform,version:Oi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Oi.env.NODE_ENV||Oi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qr{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(t,i={}){this.name=t,this.config={..._e},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new ql,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Yr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Yr};return{...Yr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:_e.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await Wu(this.config.logDirectory,rl.F_OK|rl.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Yu(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:gt.from(t);try{if(!ar(this.currentLogFile))await se(this.currentLogFile,"",{mode:420});if(r=nl(this.currentLogFile,"a",420),ju(r,l,{flag:"a"}),il(r),r!==void 0)$e(r),r=void 0;if((await xi(this.currentLogFile)).size===0){if(await se(this.currentLogFile,l,{flag:"w",mode:420}),(await xi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let $=h;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let s=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,s);let u=c*2**f;await new Promise((y)=>setTimeout(y,u)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{$e(r)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===e-1){let $=l,s=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}f++;let h=c*2**(f-1);await new Promise(($)=>setTimeout($,h))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Di(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 Di(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Di(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return le(16).toString("hex")}generateKey(){return le(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=le(16),r=Cu("aes-256-gcm",i,n),f=gt.isBuffer(t)?t:gt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),$=gt.allocUnsafe(16+l+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),h.copy($,16+l),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=el(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(gt.from(gt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let t=await xi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ar(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await xi(n).catch(()=>null))try{if(await fl(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await mr(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await se(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await xi(n).catch(()=>null))await fl(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Ar(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await mr(Di(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=tl(t),r=Uu(i),f=el();await Zu(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),ar(this.currentLogFile))try{let t=nl(this.currentLogFile,"r+");il(t),$e(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ar(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await mr(Di(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?Y.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof H.env.NO_COLOR<"u",i=H.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=H.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${Y.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=Y.underline(Y.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>Y.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Y.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Y.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Y.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>Y.strikethrough(r)),i}supportsHyperlinks(){if(P())return!1;let t=H.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=H.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(du(i)||i.startsWith("./")||i.startsWith("../"))i=Iu(i);else return null;return ar(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Xl[t],y=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",w;switch(t){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:Y.gray(h),level:t}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:Y.green(h),level:t}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.error(w),l){let m=l.split(`
|
|
69
|
-
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:
|
|
70
|
-
`;if(
|
|
71
|
-
`;if(
|
|
72
|
-
`);if(this[e==="warning"?"warn":e](f),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?
|
|
73
|
-
`,
|
|
74
|
-
`),
|
|
75
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${
|
|
76
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(e)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=
|
|
77
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await
|
|
60
|
+
`;return n}}function Es(t,i,n={}){return Pl(t,i,n,new WeakMap)}function Pl(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return vl(t,i,f,r);if(!Ft(i)||!Ft(t))return i;return Bs(t,i,n,r)}function vl(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return Ts(t,i);case"smart":return Ss(t,i,r);default:return i}return i}function Ts(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>ie(f,r)))n.push(r);return n}function Ss(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ft(i[0])&&Ft(t[0]))return Rs(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function Rs(t,i,n){let r=[...i];for(let f of t){if(!Ft(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let h of e)if(h in f){if(r.find(($)=>Ft($)&&(h in $)&&$[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function Bs(t,i,n,r){let f=i;if(Ft(f)&&r.has(f))return r.get(f);let e={...t};if(Ft(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(Ft(h)&&Ft(l))e[c]=Pl(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=vl(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function pl(t,i,n="replace"){return Es(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function ie(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!ie(t[n],i[n]))return!1;return!0}if(Ft(t)&&Ft(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!ie(t[f],i[f]))return!1}return!0}return!1}function Ft(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Ql{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:h=!1}=n;if(f){let $=ir.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!bn(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new yr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new yr(t,Error("Configuration must export a valid object"),"unknown");let T={config:pl(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)ir.setWithFileCheck("file",T,t,e);return T}catch($){throw $ instanceof Error?Hi.configLoad(t,$):Hi.configLoad(t,Error(String($)))}};if(c)return ne.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Lf(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=i===void 0?[]:Array.isArray(i)?i:[i];for(let e of r){if(!e)continue;if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}let f=new Set;return n.filter((e)=>{if(!e||f.has(e))return!1;return f.add(e),!0})}checkFileAccess(t){return ms(async()=>{return bn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!bn(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=Lf(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=Lf(t,c);if(await this.checkFileAccess(h))r.push(h)}}catch{return[]}return r}looksLikeConfigFile(t){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((n)=>n.test(t))}async validateConfigFile(t){let i=[];try{if(!bn(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var Fs=/^https?:\/\//;class th{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await ne.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Cs(i))throw new ar(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new ar(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),h=this.validateWithRule(c,e,e.path);if(r.push(...h),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.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:Fs},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Dt=new Tr("bunfig",{showTags:!0});function Ns(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`}class ih{fileLoader=new Ql;envProcessor=new ue;validator=new th;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)Dt.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){if(h instanceof Error&&h.name==="ConfigNotFoundError")throw h;let l=Date.now()-i;throw Dt.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||Ar.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(Bt(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw Hi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),warnings:[`No configuration file found for "${r}"${Ns(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,h,l){let $=h?Xn(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)Dt.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)Dt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?Xn(t,n,f):n,h=[Bt(Ci(),".config",t),Bt(Ci(),".config"),Ci()];for(let l of h){if(f)Dt.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)Dt.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?Xn(t,r,e):r;try{let l=Bt(n,"package.json");if(!Ew(l))return null;let $={};try{$=JSON.parse(Tw(l,"utf8"))}catch(y){if(e)Dt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let w=$[t],s=t;if(!w&&i){let y=Array.isArray(i)?i:[i];for(let u of y){if(!u)continue;if($[u]){w=$[u],s=u;break}}}if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)Dt.success(`Configuration loaded from package.json: ${s}`);return{config:pl(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)Dt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Xn(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Hi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return ir.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);ir.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias){let r=Array.isArray(i.alias)?i.alias.join(","):i.alias;n.push(`alias:${r}`)}if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Bt(t,"config"),Bt(t,".config"),i?Bt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(Bt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[Bt(Ci(),".config",t),Bt(Ci(),".config"),Ci()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var _m=new ih;function Xn(t,i,n=!1){let r=new ue,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=Ar.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}var Um=Bt(Ar.cwd(),"config"),dm=Bt(Ar.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Js={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:ye(se(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:ye(se(),".stacks","ssl","stacks.localhost.crt"),keyPath:ye(se(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Mi=Js;import*as cw from"node:fs";import*as lw from"node:path";import*as qt from"node:process";import{spawn as Na}from"node:child_process";import*as Kt from"node:fs/promises";import{homedir as rw}from"node:os";import*as Gt from"node:path";import*as nt from"node:process";import{execSync as tn}from"node:child_process";import o from"node:fs/promises";import*as ac from"node:os";import{homedir as uf}from"node:os";import{join as Q}from"node:path";import*as zt from"node:process";import{createRequire as _s}from"node:module";import ae from"node:os";import Ae from"node:path";import{existsSync as nh,statSync as rh}from"fs";import{existsSync as Us,mkdirSync as Dm,readdirSync as Lm,readFileSync as ds,writeFileSync as km}from"fs";import{homedir as zi}from"os";import{dirname as gm,resolve as Nt}from"path";import tf from"process";import{existsSync as fh,statSync as eh}from"fs";import{existsSync as Me,mkdirSync as js,readdirSync as Ws,writeFileSync as Ys}from"fs";import{homedir as Gi}from"os";import{dirname as ch,resolve as yt}from"path";import mi from"process";import{join as Is,relative as Zs,resolve as lh}from"path";import Kr from"process";import{existsSync as bh,mkdirSync as r1,readdirSync as f1,writeFileSync as e1}from"fs";import{homedir as me}from"os";import{dirname as h1,resolve as st}from"path";import En from"process";import{join as Hs,relative as Ms,resolve as hh}from"path";import qr from"process";import{existsSync as Xh,mkdirSync as y1,readdirSync as a1,writeFileSync as A1}from"fs";import{dirname as E1,resolve as xr}from"path";import ze from"process";import{Buffer as $i}from"buffer";import{createCipheriv as zs,createDecipheriv as Gs,randomBytes as Ee}from"crypto";import{closeSync as Te,createReadStream as $h,createWriteStream as Ks,existsSync as Se,fsyncSync as wh,openSync as uh,writeFileSync as qs}from"fs";import{access as xs,constants as sh,mkdir as Os,readdir as Sr,rename as yh,stat as Ki,unlink as Rr,writeFile as Re}from"fs/promises";import{join as qi}from"path";import ct from"process";import{pipeline as Ds}from"stream/promises";import{createGzip as ah}from"zlib";import xi from"process";import Pt from"process";import{Buffer as gt}from"buffer";import{createCipheriv as Ls,createDecipheriv as ks,randomBytes as Be}from"crypto";import{closeSync as Ce,createReadStream as Ah,createWriteStream as Vs,existsSync as Br,fsyncSync as mh,openSync as Eh,writeFileSync as os}from"fs";import{access as gs,constants as Th,mkdir as bs,readdir as Cr,rename as Sh,stat as Oi,unlink as Fr,writeFile as Fe}from"fs/promises";import{isAbsolute as Xs,join as Di,resolve as Ps}from"path";import H from"process";import{pipeline as vs}from"stream/promises";import{createGzip as Rh}from"zlib";import Li from"process";import vt from"process";import Nr from"process";import{existsSync as Jr}from"fs";import{resolve as Ne}from"path";import{existsSync as ps}from"fs";import{existsSync as Qs,readdirSync as t0}from"fs";import{extname as Je,resolve as Bh}from"path";import i0 from"process";import{join as n0,relative as r0,resolve as Ch}from"path";import Or from"process";import{Buffer as bt}from"buffer";import{createCipheriv as f0,createDecipheriv as e0,randomBytes as _e}from"crypto";import{closeSync as Ue,createReadStream as Fh,createWriteStream as c0,existsSync as _r,fsyncSync as Nh,openSync as Jh,writeFileSync as l0}from"fs";import{access as h0,constants as _h,mkdir as $0,readdir as Ur,rename as Uh,stat as ki,unlink as dr,writeFile as de}from"fs/promises";import{isAbsolute as w0,join as Vi,resolve as u0}from"path";import M from"process";import{pipeline as s0}from"stream/promises";import{createGzip as dh}from"zlib";import oi from"process";import pt from"process";import jr from"process";import{existsSync as Wr}from"fs";import{resolve as je}from"path";import{existsSync as y0}from"fs";import{exec as My}from"node:child_process";import Dh from"node:fs";import zy from"node:os";import Yt from"node:path";import Y$ from"node:process";import{promisify as Gy}from"node:util";import Pi from"node:crypto";import Qt from"node:fs";import Xe from"node:path";import{execSync as gh}from"node:child_process";import Qr from"node:os";var Gm=_s(import.meta.url);class Ph{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!nh(t))return!0;return rh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=nh(n)?rh(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class vh{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Dr=new Ph,Pe=new vh,a0=Object.defineProperty,A0=(t)=>t;function m0(t,i){this[t]=A0.bind(null,i)}var E0=(t,i)=>{for(var n in i)a0(t,n,{get:i[n],enumerable:!0,configurable:!0,set:m0.bind(i,n)})},T0=(t,i)=>()=>(t&&(i=t(t=0)),i),ph={};E0(ph,{withErrorRecovery:()=>i$,tryLoadConfig:()=>O0,loadConfigWithResult:()=>q0,loadConfig:()=>c$,isRetryableError:()=>Z0,isConfigNotFoundError:()=>I0,isBunfigError:()=>n$,globalPerformanceMonitor:()=>Bn,globalCache:()=>bi,getEnvOrDefault:()=>H0,generateConfigTypes:()=>D0,defaultGeneratedDir:()=>a$,defaultConfigDir:()=>y$,deepMergeWithArrayStrategy:()=>ic,deepMerge:()=>r$,createLibraryConfig:()=>L0,config:()=>x0,bunfigPlugin:()=>k0,applyEnvVarsToConfig:()=>An,TypeGenerationError:()=>Le,SchemaValidationError:()=>Sn,PluginError:()=>Ve,PerformanceMonitor:()=>pe,FileSystemError:()=>De,ErrorFactory:()=>ui,EnvVarError:()=>br,EnvProcessor:()=>nf,ConfigValidator:()=>nc,ConfigValidationError:()=>xe,ConfigNotFoundError:()=>gr,ConfigMergeError:()=>Oe,ConfigLoader:()=>rc,ConfigLoadError:()=>Tn,ConfigFileLoader:()=>rf,ConfigCache:()=>ve,CacheUtils:()=>h$,BunfigError:()=>Tt,BrowserConfigError:()=>ke,ArrayMergeStrategies:()=>u$});class ve{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let n=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${n}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let n=0;n<i;n++)this.cache.delete(t[n][0])}set(t,i,n,r){if(!this.options.enabled)return;let f=this.generateKey(t,n),e=r??this.options.ttl,c=this.estimateSize(i);this.cache.set(f,{value:i,timestamp:new Date,ttl:e,hits:0,size:c}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,i),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(t,i){try{if(!fh(t))return!0;return eh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let n=this.get(t,i);if(!n)return;if(this.isFileModified(i,n.fileTimestamp)){this.delete(t,i);return}return n.value}setWithFileCheck(t,i,n,r){try{let f=fh(n)?eh(n):null,e=f?f.mtime:new Date;this.set(t,{value:i,fileTimestamp:e},n,r)}catch{this.set(t,i,n,r)}}delete(t,i){let n=this.generateKey(t,i);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((r,f)=>r+f.size,0),n=t.map((r)=>r.timestamp).sort();return{size:i,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:n[0],newestEntry:n[n.length-1]}}export(){let t={};for(let[i,n]of this.cache.entries())t[i]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return t}import(t){this.cache.clear();for(let[i,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(i,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class pe{metrics=[];maxMetrics=1000;async track(t,i,n={}){let r=performance.now(),f=new Date;try{let e=await i(),c=performance.now()-r;return this.recordMetric({operation:t,duration:c,timestamp:f,...n}),e}catch(e){let c=performance.now()-r;throw this.recordMetric({operation:`${t}:error`,duration:c,timestamp:f,...n}),e}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((f)=>f.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=i.map((f)=>f.duration),r=n.reduce((f,e)=>f+e,0);return{count:i.length,averageDuration:r/i.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function S0(t,i={}){let n=Object.keys(i).sort().map((r)=>`${r}:${i[r]}`).join("|");return n?`${t}:${n}`:t}function R0(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function B0(t){return t.getStats().size*2}function Qe(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&O(i[0])&&"id"in i[0]&&i[0].id===3&&O(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(O(i)&&O(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(O(t)&&"arr"in t&&Array.isArray(t.arr)&&O(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&O(i[0])&&O(t[0])){let r=[...i];for(let f of t)if(O(f)&&"name"in f){if(!r.find((e)=>O(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(O(f)&&"path"in f){if(!r.find((e)=>O(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>Lr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!O(i)||!O(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(O(f)&&O(n[r]))n[r]=Qe(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&O(f[0])&&O(n[r][0])){let e=[...f];for(let c of n[r])if(O(c)&&"name"in c){if(!e.find((h)=>O(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(O(c)&&"path"in c){if(!e.find((h)=>O(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((h)=>Lr(h,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function Lr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Lr(t[n],i[n]))return!1;return!0}if(O(t)&&O(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Lr(t[f],i[f]))return!1}return!0}return!1}function O(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function C0(t,i){if(!Xh(t))return null;try{let n=await import(t),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return Qe(i,r)}catch{return null}}catch{return null}}async function F0({name:t="",cwd:i,defaultConfig:n}){let r=i||ze.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],e=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let c of e)for(let h of f){let l=xr(r,`${c}${h}`),$=await C0(l,n);if($!==null)return $}try{let c=xr(r,"package.json");if(Xh(c)){let h=(await import(c))[t];if(h&&typeof h==="object"&&!Array.isArray(h))try{return Qe(n,h)}catch{}}}catch{}return n}function N0(t,i={}){let n=qr.cwd();while(n.includes("storage"))n=hh(n,"..");let r=hh(n,t||"");if(i?.relative)return Ms(qr.cwd(),r);return r}async function J0(){try{let t=await F0({name:"clarity",defaultConfig:Hr,cwd:qr.cwd(),endpoint:"",headers:{}});return{...Hr,...t}}catch{return Hr}}function k(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _0(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Pt<"u"){let t=Pt.type;if(t==="renderer"||t==="worker")return!1;return!!(Pt.versions&&(Pt.versions.node||Pt.versions.bun))}return!1}class Qh{async format(t){let i=await _0(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:xi.pid,hostname:i(),environment:xi.env.NODE_ENV||"development",platform:xi.platform,version:xi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xi.env.NODE_ENV||xi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class kr{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(t,i={}){this.name=t,this.config={...Ke},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Qh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??ct.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Mr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Mr};return{...Mr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ke.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await xs(this.config.logDirectory,sh.F_OK|sh.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Os(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:$i.from(t);try{if(!Se(this.currentLogFile))await Re(this.currentLogFile,"",{mode:420});if(r=uh(this.currentLogFile,"a",420),qs(r,h,{flag:"a"}),wh(r),r!==void 0)Te(r),r=void 0;if((await Ki(this.currentLogFile)).size===0){if(await Re(this.currentLogFile,h,{flag:"w",mode:420}),(await Ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let $=l;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,w);let s=c*2**f;await new Promise((y)=>setTimeout(y,s)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{Te(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(h){if(f===e-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}f++;let l=c*2**(f-1);await new Promise(($)=>setTimeout($,l))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return qi(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 qi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return qi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,h])=>h.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ee(16).toString("hex")}generateKey(){return Ee(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Ee(16),r=zs("aes-256-gcm",i,n),f=$i.concat([r.update(t,"utf8"),r.final()]),e=r.getAuthTag();return{encrypted:$i.concat([n,f,e]),iv:n}}async compressData(t){return new Promise((i,n)=>{let r=ah(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i($i.from($i.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(k())return;let t=await Ki(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Sr(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Ki(n).catch(()=>null))try{if(await yh(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Rr(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Re(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Ki(n).catch(()=>null))await yh(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Sr(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await Rr(qi(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=$h(t),r=Ks(i),f=ah();await Ds(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Se(this.currentLogFile))try{let t=uh(this.currentLogFile,"r+");wh(t),Te(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Sr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Rr(qi(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?q.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=ct.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${q.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);if(this.fancy&&!k()){let $=$$[t],w=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",s;switch(t){case"debug":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:q.gray(c),level:t}),console.error(s);break;case"info":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s);break;case"success":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:q.green(c),level:t}),console.error(s);break;case"warning":s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.warn(s);break;case"error":if(s=this.formatConsoleMessage({timestamp:f,icon:$,tag:w,message:c,level:t}),console.error(s),h){let y=h.split(`
|
|
61
|
+
`);for(let u of y)if(u.trim()&&!u.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:q.gray(` ${u}`),level:t,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let l=`${e} ${this.environment}.${t.toUpperCase()}: ${c}
|
|
62
|
+
`;if(h)l+=`${h}
|
|
63
|
+
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!k()){let n=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:q.blue("◐"),tag:n,message:`${q.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),l=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
|
|
64
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!k()){let $=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:q.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!k())console.error(l.trim());await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new kr(i,{...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(n),n}createReadStream(){if(k())throw Error("createReadStream is not supported in browser environments");if(!Se(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $h(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=$i.isBuffer(t)?t:$i.from(t,"base64"),f=r.slice(0,16),e=r.slice(-16),c=r.slice(16,-16),h=Gs("aes-256-gcm",n,f);return h.setAuthTag(e),$i.concat([h.update(c),h.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return k()}isServerMode(){return!k()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i);if(this.fancy&&!k()){let e=t.split(`
|
|
65
|
+
`),c=Math.max(...e.map((w)=>w.length))+2,h=`┌${"─".repeat(c)}┐`,l=`└${"─".repeat(c)}┘`,$=e.map((w)=>{let s=" ".repeat(c-w.length-2);return`│ ${w}${s} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:q.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(h)})),$.forEach((w)=>console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(w),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:q.cyan(l),showTimestamp:!1}))}else if(!k())console.error(`${r} ${this.environment}.INFO: [BOX] ${t}`);let f=`${r} ${this.environment}.INFO: [BOX] ${t}
|
|
66
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(t){if(k())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${q.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();ct.stdin.removeListener("data",n);try{if(typeof ct.stdin.setRawMode==="function")ct.stdin.setRawMode(!1)}catch{}ct.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof ct.stdin.setRawMode==="function")ct.stdin.setRawMode(!0)}catch{}ct.stdin.resume(),ct.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let f=/%([sdijfo%])/g,e=0;if(n=t.replace(f,(c,h)=>{if(h==="%")return"%";if(e>=i.length)return c;let l=i[e++];switch(h){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return c}}),e<i.length)n+=` ${i.slice(e).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!k()){let f=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",e=q.blue("◐");console.error(`${e} ${f} ${q.cyan(n)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
67
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(t,i=""){if(!this.enabled||!this.fancy||k()||t<=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 n=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,r)),f!==void 0)this.activeProgressBar.message=f;let e=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,e)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;ct.stdout.write(`${"\r".padEnd(ct.stdout.columns||80)}\r`),this.log(f,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||k()||!ct.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=q.green("━".repeat(r)),c=q.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=i||n===100?q.green("✓"):q.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${q.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=ct.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,ct.stdout.write(t.lastRenderedLine),i)ct.stdout.write(`
|
|
68
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||k()||!ct.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Sr(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=qi(this.config.logDirectory,r);if(t.before)try{if((await Ki(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Rr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Zr(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&z(i[0])&&"id"in i[0]&&i[0].id===3&&z(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(z(i)&&z(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(z(t)&&"arr"in t&&Array.isArray(t.arr)&&z(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&z(i[0])&&z(t[0])){let r=[...i];for(let f of t)if(z(f)&&"name"in f){if(!r.find((e)=>z(e)&&("name"in e)&&e.name===f.name))r.push(f)}else if(z(f)&&"path"in f){if(!r.find((e)=>z(e)&&("path"in e)&&e.path===f.path))r.push(f)}else if(!r.some((e)=>Vr(e,f)))r.push(f);return r}if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}if(!z(i)||!z(t))return i;let n={...t};for(let r in i)if(Object.prototype.hasOwnProperty.call(i,r)){let f=i[r];if(f===null||f===void 0)continue;else if(z(f)&&z(n[r]))n[r]=Zr(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&z(f[0])&&z(n[r][0])){let e=[...f];for(let c of n[r])if(z(c)&&"name"in c){if(!e.find((h)=>z(h)&&("name"in h)&&h.name===c.name))e.push(c)}else if(z(c)&&"path"in c){if(!e.find((h)=>z(h)&&("path"in h)&&h.path===c.path))e.push(c)}else if(!e.some((h)=>Vr(h,c)))e.push(c);n[r]=e}else if(f.every((e)=>typeof e==="string")&&n[r].every((e)=>typeof e==="string")){let e=[...f];for(let c of n[r])if(!e.includes(c))e.push(c);n[r]=e}else n[r]=f;else n[r]=f}return n}function tc(t,i,n="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return n==="replace"?i:Zr(t,i);if(Array.isArray(t))return n==="replace"?i:Zr(t,i);if(!z(i)||!z(t))return i;let r={...t};for(let f of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,f))continue;let e=i[f],c=r[f];if(e===null||e===void 0)continue;if(Array.isArray(e)||Array.isArray(c))if(n==="replace")r[f]=e;else r[f]=Zr(c,e);else if(z(e)&&z(c))r[f]=tc(c,e,n);else r[f]=e}return r}function Vr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Vr(t[n],i[n]))return!1;return!0}if(z(t)&&z(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Vr(t[f],i[f]))return!1}return!0}return!1}function z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Yr(t,i,n="replace"){if(!bh(t))return null;try{let r=await import(t),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return tc(i,f,n)}catch{return null}}catch{return null}}function U0(t,i,n=!1){if(!t)return i;let r=t.toUpperCase().replace(/-/g,"_"),f={...i};function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=(A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${r}_${s.map(y).join("_")}`,m=`${r}_${s.map((A)=>A.toUpperCase()).join("_")}`;if(n)ht.info(`Checking environment variable ${u} for config ${t}.${s.join(".")}`);if(typeof w==="object"&&w!==null&&!Array.isArray(w))l[$]=e(w,s);else{let A=En.env[u]||En.env[m];if(A!==void 0){if(n)ht.info(`Using environment variable ${A?u:m} for config ${t}.${s.join(".")}`);if(typeof w==="number")l[$]=Number(A);else if(typeof w==="boolean")l[$]=A.toLowerCase()==="true";else if(Array.isArray(w))try{let T=JSON.parse(A);if(Array.isArray(T))l[$]=T;else l[$]=A.split(",").map((E)=>E.trim())}catch{l[$]=A.split(",").map((T)=>T.trim())}else l[$]=A}}}return l}return e(f)}async function d0({name:t="",alias:i,cwd:n,configDir:r,defaultConfig:f,verbose:e=!1,checkEnv:c=!0,arrayStrategy:h="replace"}){let l=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?U0(t,f,e):f,$=n||En.cwd(),w=[".ts",".js",".mjs",".cjs",".json"];if(e)ht.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${$}`);let s=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),u=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],A=Array.from(new Set([$,st($,"config"),st($,".config"),r?st($,r):void 0].filter(Boolean)));for(let T of A){if(e)ht.info(`Searching for configuration in: ${T}`);let E=[st($,"config"),st($,".config")].concat(r?[st($,r)]:[]).includes(T)?[...s,...y,...u,...m]:[...y,...s,...m,...u];for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from: ${J}`);return d}}}if(t){let T=st(me(),".config",t),E=["config",`${t}.config`];if(i)E.push(`${i}.config`);if(e)ht.info(`Checking user config directory: ${T}`);for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from user config directory: ${J}`);return d}}}if(t){let T=st(me(),".config"),E=[`.${t}.config`];if(i)E.push(`.${i}.config`);if(e)ht.info(`Checking user config directory for dotfile configs: ${T}`);for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from user config directory dotfile: ${J}`);return d}}}if(t){let T=me(),E=[`.${t}.config`,`.${t}`];if(i)E.push(`.${i}.config`),E.push(`.${i}`);if(e)ht.info(`Checking user home directory for dotfile configs: ${T}`);for(let R of E)for(let N of w){let J=st(T,`${R}${N}`),d=await Yr(J,l,h);if(d!==null){if(e)ht.success(`Configuration loaded from user home directory: ${J}`);return d}}}try{let T=st($,"package.json");if(bh(T)){let E=await import(T),R=E[t];if(!R&&i){if(R=E[i],R&&e)ht.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(e)ht.success(`Configuration loaded from package.json: ${R===E[t]?t:i}`);return tc(l,R,h)}catch(N){if(e)ht.warn("Failed to merge package.json config:",N)}}}catch(T){if(e)ht.warn("Failed to load package.json:",T)}if(e)ht.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function j0(t,i={}){let n=Kr.cwd();while(n.includes("storage"))n=lh(n,"..");let r=lh(n,t||"");if(i?.relative)return Zs(Kr.cwd(),r);return r}async function W0(){try{let t=await d0({name:"clarity",alias:"logging",defaultConfig:zr,cwd:Kr.cwd()});return{...zr,...t||{}}}catch{return zr}}function P(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Y0(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vt<"u"){let t=vt.type;if(t==="renderer"||t==="worker")return!1;return!!(vt.versions&&(vt.versions.node||vt.versions.bun))}return!1}class t${async format(t){let i=await Y0(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Li.pid,hostname:i(),environment:Li.env.NODE_ENV||"development",platform:Li.platform,version:Li.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Li.env.NODE_ENV||Li.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class or{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(t,i={}){this.name=t,this.config={...qe},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new t$,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Gr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Gr};return{...Gr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:qe.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await gs(this.config.logDirectory,Th.F_OK|Th.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await bs(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:gt.from(t);try{if(!Br(this.currentLogFile))await Fe(this.currentLogFile,"",{mode:420});if(r=Eh(this.currentLogFile,"a",420),os(r,h,{flag:"a"}),mh(r),r!==void 0)Ce(r),r=void 0;if((await Oi(this.currentLogFile)).size===0){if(await Fe(this.currentLogFile,h,{flag:"w",mode:420}),(await Oi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let $=l;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,w);let s=c*2**f;await new Promise((y)=>setTimeout(y,s)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{Ce(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(h){if(f===e-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}f++;let l=c*2**(f-1);await new Promise(($)=>setTimeout($,l))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Di(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 Di(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Di(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,h])=>h.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Be(16).toString("hex")}generateKey(){return Be(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=Be(16),r=Ls("aes-256-gcm",i,n),f=gt.isBuffer(t)?t:gt.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=gt.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=Rh(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(gt.from(gt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let t=await Oi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Cr(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await Oi(n).catch(()=>null))try{if(await Sh(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await Fr(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await Fe(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Oi(n).catch(()=>null))await Sh(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Cr(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await Fr(Di(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=Ah(t),r=Vs(i),f=Rh();await vs(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Br(this.currentLogFile))try{let t=Eh(this.currentLogFile,"r+");mh(t),Ce(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Cr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Fr(Di(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?W.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof H.env.NO_COLOR<"u",i=H.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=H.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${W.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=W.underline(W.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>W.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>W.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>W.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>W.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>W.strikethrough(r)),i}supportsHyperlinks(){if(P())return!1;let t=H.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=H.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(Xs(i)||i.startsWith("./")||i.startsWith("../"))i=Ps(i);else return null;return Br(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":w$[t],y=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:W.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:W.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
69
|
+
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:W.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}if(!this.shouldLog(t))return;let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
70
|
+
`;if(h)w+=`${h}
|
|
71
|
+
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(t,i=""){let n={update:(f,e)=>{},finish:(f)=>{},interrupt:(f,e)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,e)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),e!==void 0)this.activeProgressBar.message=e;if(this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,e="info")=>{if(!P()&&H.stdout.isTTY)H.stdout.write(`
|
|
72
|
+
`);if(this[e==="warning"?"warn":e](f),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":W.blue("◐"),tag:n,message:`${W.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),l=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
|
|
73
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":W.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!P())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new or(i,{...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(n),n}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!Br(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ah(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=gt.isBuffer(t)?t:gt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),h=ks("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=gt.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let h=f.split(`
|
|
74
|
+
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:W.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:W.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:W.cyan(w),showTimestamp:!1}))}else if(!P())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
|
|
75
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${W.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();H.stdin.removeListener("data",n);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,h=0;if(n=t.replace(c,(l,$)=>{if($==="%")return"%";if(h>=i.length)return l;let w=i[h++];switch($){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 l}}),h<i.length)n+=` ${i.slice(h).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${W.blue("◐")} `;console.error(`${h}${c} ${W.cyan(r)}`)}let e=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
76
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(e)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=W.green("━".repeat(r)),c=W.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?W.green("✓"):W.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${W.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=H.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,H.stdout.write(t.lastRenderedLine),i)H.stdout.write(`
|
|
77
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Cr(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Di(this.config.logDirectory,r);if(t.before)try{if((await Oi(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Fr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function i$(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function n$(t){return t instanceof Tt}function I0(t){return t instanceof gr}function Z0(t){if(n$(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((i)=>t.message.toLowerCase().includes(i.toLowerCase()))}class nf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Bn.track("applyEnvironmentVariables",$,{configName:t});return $()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=Nr.env[l]||($?Nr.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=Nr.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof br)throw s;throw ui.envVar(l,w,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw ui.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(Nr.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let n=`Environment Variables for ${i}:
|
|
78
78
|
|
|
79
79
|
`;for(let r of t)n+=`${r.key}
|
|
80
80
|
`,n+=` Type: ${r.type}
|
|
@@ -86,25 +86,25 @@ export type ConfigOf = Config
|
|
|
86
86
|
`;n+=`| Variable | Type | Description | Example |
|
|
87
87
|
`,n+=`|----------|------|-------------|----------|
|
|
88
88
|
`;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
89
|
-
`;return n}}function my(t,i){let n=ol("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function Ol(t,i,n={}){return Ll(t,i,n,new WeakMap)}function Ll(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return kl(t,i,f,r);if(!Ct(i)||!Ct(t))return i;return Ry(t,i,n,r)}function kl(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return Ey(t,i);case"smart":return Ty(t,i,r);default:return i}return i}function Ey(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Je(f,r)))n.push(r);return n}function Ty(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Ct(i[0])&&Ct(t[0]))return Sy(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function Sy(t,i,n){let r=[...i];for(let f of t){if(!Ct(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find((h)=>Ct(h)&&(l in h)&&h[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function Ry(t,i,n,r){let f=i;if(Ct(f)&&r.has(f))return r.get(f);let e={...t};if(Ct(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(Ct(l)&&Ct(h))e[c]=Ll(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=kl(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function Oe(t,i,n="replace"){return Ol(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Je(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Je(t[n],i[n]))return!1;return!0}if(Ct(t)&&Ct(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Je(t[f],i[f]))return!1}return!0}return!1}function Ct(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Xr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let $=gi.getWithFileCheck("file",t);if($){if(l)console.log(`Configuration loaded from cache: ${t}`);return $}}let h=async()=>{if(!Tr(t))return null;try{let $=`?t=${Date.now()}`,s=await import(t+$),u=s.default||s,y="default"in s,w=Object.keys(s).length>0;if(!y&&!w)throw new An(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new An(t,Error("Configuration must export a valid object"),"unknown");let m={config:Oe(i,u,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)gi.setWithFileCheck("file",m,t,e);return m}catch($){throw $ instanceof Error?si.configLoad(t,$):si.configLoad(t,Error(String($)))}};if(c)return Tn.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(we(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(n.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)n.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return n.filter(Boolean)}checkFileAccess(t){return xl(async()=>{return Tr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Tr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=we(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=we(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Tr(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class Le{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,$=async()=>{let s=[],u=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(w){return s.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:s,warnings:u}}};if(l)return await Tn.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Hu(i))throw new mn(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new mn(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let $=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.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:vl},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ke{fileLoader=new Xr;envProcessor=new br;validator=new Le;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let $=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if($)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let s=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),u=!s&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),y=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if($&&(y||s))throw h;if(u&&(!$||!y))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)It.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){let h=Date.now()-i;throw It.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:$="replace",verbose:s=!1}=t,u=e||Ai.cwd(),y=[],w=await this.loadLocalConfiguration(r,f,u,c,l,$,s,h,n);if(w)return y.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(w,y,h,r,s);let m=await this.loadHomeConfiguration(r,f,l,$,s,h);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,h,r,s);let A=await this.loadPackageJsonConfiguration(r,f,u,l,$,s,h);if(A)return y.push(yt(u,"package.json")),this.finalizeResult(A,y,h,r,s);if(y.push(...this.getAllSearchPaths(r,f,u,c)),i)throw si.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,l,h,s),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let $=l?un(t,f,c):f,s=this.getLocalDirectories(n,r);for(let u of s){if(c)It.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),w=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(w){if(c)It.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?un(t,n,f):n,l=[yt(zi(),".config",t),yt(zi(),".config"),zi()];for(let h of l){if(f)It.info(`Checking home directory: ${h}`);let $=this.fileLoader.generateConfigPaths(t,h,i),s=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(s){if(f)It.success(`Configuration loaded from home directory: ${s.source.path}`);return s}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?un(t,r,e):r;try{let h=yt(n,"package.json");if(!Ne(h))return null;let $=await import(h),s=$[t],u=t;if(!s&&i)s=$[i],u=i;if(s&&typeof s==="object"&&!Array.isArray(s)){if(e)It.success(`Configuration loaded from package.json: ${u}`);return{config:Oe(l,s,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)It.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:un(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw si.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return gi.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);gi.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias)n.push(`alias:${i.alias}`);if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,yt(t,"config"),yt(t,".config"),i?yt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(yt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[yt(zi(),".config",t),yt(zi(),".config"),zi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function al(t){let i=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||n}async function By(t){return ti.loadConfig({...t,__strictErrorHandling:!0})}async function Vl(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await ti.loadConfig(t);else r=await ti.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let f=r instanceof Error?r.name:"UnknownError",e=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||e.includes("config"))&&t.verbose)It.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let c=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ti.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function Ny(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ti.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&al(n)))return(await ti.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await ti.loadConfig({...t,cwd:t.cwd||Ai.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&al(i)))return(await ti.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function Fy(t,i,n="replace"){let r=new Xr;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function un(t,i,n=!1){let r=new br,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((A)=>A.toUpperCase()).join("")}`,`${f}_${u.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,m;for(let A of y)if(w=Ai.env[A],w!==void 0){m=A;break}if(w!==void 0&&m)if(typeof s==="boolean")h[$]=["true","1","yes"].includes(w.toLowerCase());else if(typeof s==="number"){let A=Number(w);if(!Number.isNaN(A))h[$]=A}else if(Array.isArray(s))try{h[$]=JSON.parse(w)}catch{h[$]=w.split(",").map((A)=>A.trim())}else h[$]=w;else if(s&&typeof s==="object"&&!Array.isArray(s))h[$]=e(s,u)}return h}return e(i)}function Jy(t){let i=yt(Ai.cwd(),t.configDir),n=yt(Ai.cwd(),t.generatedDir),r=yt(n,"config-types.ts");if(!Ne(Vh(r)))wu(Vh(r),{recursive:!0,mode:511});let f=Ne(i)?uu(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${Qy}
|
|
89
|
+
`;return n}}function H0(t,i){let n=l$("process");if(typeof n>"u"||!n.env)return i;let r=n.env[t];return r!==void 0?r:i}function r$(t,i,n={}){return f$(t,i,n,new WeakMap)}function f$(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return e$(t,i,f,r);if(!Jt(i)||!Jt(t))return i;return K0(t,i,n,r)}function e$(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return M0(t,i);case"smart":return z0(t,i,r);default:return i}return i}function M0(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Ge(f,r)))n.push(r);return n}function z0(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(Jt(i[0])&&Jt(t[0]))return G0(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function G0(t,i,n){let r=[...i];for(let f of t){if(!Jt(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let h of e)if(h in f){if(r.find((l)=>Jt(l)&&(h in l)&&l[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function K0(t,i,n,r){let f=i;if(Jt(f)&&r.has(f))return r.get(f);let e={...t};if(Jt(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(Jt(h)&&Jt(l))e[c]=f$(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=e$(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function ic(t,i,n="replace"){return r$(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Ge(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Ge(t[n],i[n]))return!1;return!0}if(Jt(t)&&Jt(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Ge(t[f],i[f]))return!1}return!0}return!1}function Jt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class rf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:h=!1}=n;if(f){let $=bi.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!Jr(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new Tn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new Tn(t,Error("Configuration must export a valid object"),"unknown");let m={config:ic(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)bi.setWithFileCheck("file",m,t,e);return m}catch($){throw $ instanceof Error?ui.configLoad(t,$):ui.configLoad(t,Error(String($)))}};if(c)return Bn.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(Ne(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(n.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)n.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return n.filter(Boolean)}checkFileAccess(t){return i$(async()=>{return Jr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Jr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=Ne(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=Ne(t,c);if(await this.checkFileAccess(h))r.push(h)}}catch{return[]}return r}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Jr(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class nc{async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await Bn.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!ps(i))throw new Sn(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new Sn(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),h=this.validateWithRule(c,e,e.path);if(r.push(...h),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.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:s$},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class rc{fileLoader=new rf;envProcessor=new nf;validator=new nc;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)It.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){let l=Date.now()-i;throw It.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||mi.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(yt(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw ui.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,h,l){let $=h?An(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)It.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)It.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?An(t,n,f):n,h=[yt(Gi(),".config",t),yt(Gi(),".config"),Gi()];for(let l of h){if(f)It.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)It.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?An(t,r,e):r;try{let l=yt(n,"package.json");if(!Me(l))return null;let $=await import(l),w=$[t],s=t;if(!w&&i)w=$[i],s=i;if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)It.success(`Configuration loaded from package.json: ${s}`);return{config:ic(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)It.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:An(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw ui.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return bi.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);bi.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias)n.push(`alias:${i.alias}`);if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,yt(t,"config"),yt(t,".config"),i?yt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(yt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[yt(Gi(),".config",t),yt(Gi(),".config"),Gi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}function jh(t){let i=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||n}async function q0(t){return ti.loadConfig({...t,__strictErrorHandling:!0})}async function c$(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let r;if(n)r=await ti.loadConfig(t);else r=await ti.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??i}catch(r){let f=r instanceof Error?r.name:"UnknownError",e=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||e.includes("config"))&&t.verbose)It.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let c=n?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ti.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function x0(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ti.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&jh(n)))return(await ti.applyEnvironmentVariables(t,{},!0,!1)).config;throw n}}try{return(await ti.loadConfig({...t,cwd:t.cwd||mi.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&jh(i)))return(await ti.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function O0(t,i,n="replace"){let r=new rf;try{let f=await r.loadFromPath(t,i,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function An(t,i,n=!1){let r=new nf,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=mi.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}function D0(t){let i=yt(mi.cwd(),t.configDir),n=yt(mi.cwd(),t.generatedDir),r=yt(n,"config-types.ts");if(!Me(ch(r)))js(ch(r),{recursive:!0,mode:511});let f=Me(i)?Ws(i).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],e=`// Generated by bunfig v${Ey}
|
|
90
90
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
91
|
-
`;
|
|
92
|
-
${f.map((
|
|
91
|
+
`;Ys(r,e,{mode:438})}function L0(t){let i=null,n=null,r=()=>{if(!n)n=c$(t).then((e)=>{return i=e,e},(e)=>{let c="defaultConfig"in t?t.defaultConfig:{};if(i=c,"verbose"in t&&t.verbose)It.warn("Config loading failed, using defaults:",[e instanceof Error?e:Error(String(e))]);return c});return n},f="defaultConfig"in t?t.defaultConfig:{};return i=f,r(),new Proxy({},{get(e,c){if(i)return i[c];let h=f[c];return r(),h},has(e,c){return c in(i||f)},ownKeys(){return Object.keys(i||f)},getOwnPropertyDescriptor(e,c){return Object.getOwnPropertyDescriptor(i||f,c)},set(e,c,h){if(!i)i={...f};return i[c]=h,!0}})}function k0(t){let i=Bh(i0.cwd(),t?.configDir||"./config");function n(){if(!Qs(i))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),e=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=t0(i).filter((l)=>f.has(Je(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),h=new Map;for(let{base:l,file:$}of c){let w=Je($).toLowerCase(),s=h.get(l);if(!s){h.set(l,$);continue}let y=Je(s).toLowerCase();if(e.indexOf(w)<e.indexOf(y))h.set(l,$)}return Array.from(h.entries()).map(([l,$])=>({base:l,file:$})).sort((l,$)=>l.base.localeCompare($.base))}function r(){let f=n(),e=f.map((l)=>l.base),c=e.length?e.map((l)=>`'${l}'`).join(" | "):"string",h=f.length?`{
|
|
92
|
+
${f.map((l)=>{let $=Bh(i,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${$}').default`}).join(`,
|
|
93
93
|
`)}
|
|
94
94
|
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
95
|
-
export type ConfigByName = ${
|
|
95
|
+
export type ConfigByName = ${h}
|
|
96
96
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
97
97
|
export type ConfigOf = Config
|
|
98
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(e)=>{return{path:e.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var ol,gi,Tn,gl,Uy,jy,Al,Ur,Ce,ht,q,Wy,ml,Yy,El,dy,Iy,Ee,Zy,Tl,Sl,Te,Hy,My,zy,Gy,jr,bl,Ky,lt,qy,xy,Rl,Wr,_e,v,Y,Dy,Bl,Oy,Nl,Ly,ky,Se,Vy,Fl,Jl,oy,Re,gy,by,Xy,Py,vy,Yr,Xl,py,Qy="0.15.6",Tt,xr,An,Ue,je,Dr,We,Ye,mn,de,Ie,si,Pl,vl,It,ti,pl,Ql,t0=ty(async()=>{ol=import.meta.require,gi=new Ke,Tn=new qe,gl={createKey:iy,isEquivalent:ny,estimateMemoryUsage:ry},Uy=Zr(Fe.cwd(),"config"),jy=Zr(Fe.cwd(),"src/generated"),Al=Ir.env.CLARITY_LOG_DIR||mu(cy(),"logs"),Ur={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Al,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ce=await hy(),ht={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},q=ht,Wy=ht.red,ml=ht.green,Yy=ht.yellow,El=ht.blue,dy=ht.magenta,Iy=ht.cyan,Ee=ht.white,Zy=ht.gray,Tl=ht.bgRed,Sl=ht.bgYellow,Te=ht.bold,Hy=ht.dim,My=ht.italic,zy=ht.underline,Gy=ht.reset,jr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bl={debug:"\uD83D\uDD0D",info:El("ℹ"),success:ml("✓"),warning:Sl(Ee(Te(" WARN "))),error:Tl(Ee(Te(" ERROR ")))},Ky=new Gr("stacks"),lt=new Gr("bunfig",{showTags:!0}),qy=ut(an.cwd(),"config"),xy=ut(an.cwd(),"src/generated"),Rl=dr.env.CLARITY_LOG_DIR||au(wy(),"logs"),Wr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},_e=await uy(),v={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},Y=v,Dy=v.red,Bl=v.green,Oy=v.yellow,Nl=v.blue,Ly=v.magenta,ky=v.cyan,Se=v.white,Vy=v.gray,Fl=v.bgRed,Jl=v.bgYellow,oy=v.bgGray,Re=v.bold,gy=v.dim,by=v.italic,Xy=v.underline,Py=v.strikethrough,vy=v.reset,Yr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Xl={debug:"\uD83D\uDD0D",info:Nl("ℹ"),success:Bl("✓"),warning:Jl(Se(Re(" WARN "))),error:Fl(Se(Re(" ERROR ")))},py=new qr("stacks"),Tt=class extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},xr=class extends Tt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${t}"${r} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}},An=class extends Tt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Ue=class extends Tt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}},je=class extends Tt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Dr=class extends Tt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}},We=class extends Tt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Ye=class extends Tt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}},mn=class extends Tt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}},de=class extends Tt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}},Ie=class extends Tt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}},si={configNotFound(t,i,n){return new xr(t,i,n)},configLoad(t,i,n){return new An(t,i,n)},configValidation(t,i,n){return new Ue(t,i,n)},configMerge(t,i,n,r){return new je(t,i,n,r)},envVar(t,i,n,r){return new Dr(t,i,n,r)},fileSystem(t,i,n){return new We(t,i,n)},typeGeneration(t,i,n){return new Ye(t,i,n)},schemaValidation(t,i,n){return new mn(t,i,n)},browserConfig(t,i,n,r){return new de(t,i,n,r)},plugin(t,i,n){return new Ie(t,i,n)}},Pl={replace:"replace",concat:"concat",smart:"smart"},vl=/^https?:\/\//,It=new qr("bunfig",{showTags:!0}),ti=new ke,pl=yt(Ai.cwd(),"config"),Ql=yt(Ai.cwd(),"src/generated")});function i0(t,i={}){let n=Hr.cwd();while(n.includes("storage"))n=hl(n,"..");let r=hl(n,t||"");if(i?.relative)return qu(Hr.cwd(),r);return r}var n0=Hr.env.CLARITY_LOG_DIR||Ku(i0(),"logs"),t$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:n0,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Or={...t$},D1=(async()=>{try{let{loadConfig:t}=await t0().then(()=>Gl),i=await t({name:"clarity",alias:"logging",defaultConfig:t$,cwd:Hr.cwd()});if(i)Object.assign(Or,i)}catch{}return Or})();function p(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function r0(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let t=pt.type;if(t==="renderer"||t==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class i${async format(t){let i=await r0(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Vi.pid,hostname:i(),environment:Vi.env.NODE_ENV||"development",platform:Vi.platform,version:Vi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Vi.env.NODE_ENV||Vi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var tt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},I=tt,O1=tt.red,f0=tt.green,L1=tt.yellow,e0=tt.blue,k1=tt.magenta,V1=tt.cyan,Cl=tt.white,o1=tt.gray,c0=tt.bgRed,h0=tt.bgYellow,g1=tt.bgGray,_l=tt.bold,b1=tt.dim,X1=tt.italic,P1=tt.underline,v1=tt.strikethrough,p1=tt.reset,Be={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},l0={debug:"\uD83D\uDD0D",info:e0("ℹ"),success:f0("✓"),warning:h0(Cl(_l(" WARN "))),error:c0(Cl(_l(" ERROR ")))};class Pr{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(t,i={}){this.name=t,this.config={...Or},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new i$,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Be,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Be};return{...Be,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Or.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await ku(this.config.logDirectory,wl.F_OK|wl.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Vu(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:bt.from(t);try{if(!Sr(this.currentLogFile))await Ae(this.currentLogFile,"",{mode:420});if(r=sl(this.currentLogFile,"a",420),Lu(r,l,{flag:"a"}),$l(r),r!==void 0)ae(r),r=void 0;if((await Li(this.currentLogFile)).size===0){if(await Ae(this.currentLogFile,l,{flag:"w",mode:420}),(await Li(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let $=h;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let s=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,s);let u=c*2**f;await new Promise((y)=>setTimeout(y,u)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{ae(r)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===e-1){let $=l,s=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",s),l}f++;let h=c*2**(f-1);await new Promise(($)=>setTimeout($,h))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ki(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 ki(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return ki(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ye(16).toString("hex")}generateKey(){return ye(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=ye(16),r=xu("aes-256-gcm",i,n),f=bt.isBuffer(t)?t:bt.from(t,"utf8"),e=r.update(f),c=r.final(),l=e.length+c.length,h=r.getAuthTag(),$=bt.allocUnsafe(16+l+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),h.copy($,16+l),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=yl(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(bt.from(bt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let t=await Li(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Rr(this.config.logDirectory),e=f.filter((h)=>h.startsWith(this.name)&&/\.log\.\d+$/.test(h)).sort((h,$)=>{let s=Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-s}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${c}`;if(await Li(n).catch(()=>null))try{if(await ul(n,l),i.compress)try{let h=`${l}.gz`;await this.compressLogFile(l,h),await Br(l)}catch(h){console.error("Error compressing rotated file:",h)}if(e.length===0&&!f.some((h)=>h.endsWith(".log.1")))try{let h=`${n}.1`;await Ae(h,"")}catch(h){console.error("Error creating backup file:",h)}}catch(h){console.error(`Error during rotation: ${h instanceof Error?h.message:String(h)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await Li(n).catch(()=>null))await ul(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Rr(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await Br(ki(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=ll(t),r=Ou(i),f=yl();await bu(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Sr(this.currentLogFile))try{let t=sl(this.currentLogFile,"r+");$l(t),ae(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Rr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Br(ki(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?I.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof M.env.NO_COLOR<"u",i=M.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,l=(w)=>w.replace(this.ANSI_PATTERN,"");if(!this.fancy){let w=[];if(c)w.push(i);if(e==="warning")w.push("WARN");else if(e==="error")w.push("ERROR");else if(n)w.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)w.push(r.replace(/[[\]]/g,""));return w.push(f),w.join(" ")}let h=M.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${I.cyan(f)}`;if(!c)return $.trim();let s=l($).trim().length,u=l(i).length,y=Math.max(1,h-2-s-u);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let l=Number.parseInt(c,10);return l<i[0].length?String(i[0][l]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let l=i[r++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=I.underline(I.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(c)}`,h="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${l}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>I.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>I.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>I.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>I.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>I.strikethrough(r)),i}supportsHyperlinks(){if(p())return!1;let t=M.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=M.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(ou(i)||i.startsWith("./")||i.startsWith("../"))i=gu(i);else return null;return Sr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){if(!this.shouldLog(t))return;let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,l;if(i instanceof Error)c=i.message,l=i.stack;else c=this.formatMessage(i,n);let{consoleText:h,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":l0[t],y=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",w;switch(t){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:I.gray(h),level:t}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:I.green(h),level:t}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:u,tag:y,message:h,level:t}),console.error(w),l){let m=l.split(`
|
|
99
|
-
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:I.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),
|
|
100
|
-
`;if(
|
|
101
|
-
`;if(
|
|
102
|
-
`);if(this[e==="warning"?"warn":e](f),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":I.blue("◐"),tag:n,message:`${I.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,
|
|
103
|
-
`,
|
|
104
|
-
`),
|
|
105
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(p())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${I.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();M.stdin.removeListener("data",n);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,
|
|
106
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(e)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=I.green("━".repeat(r)),c=I.gray("━".repeat(f)),
|
|
107
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await
|
|
98
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(e)=>{return{path:e.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var l$,bi,Bn,h$,V0,o0,Wh,Hr,Ke,lt,q,g0,Yh,b0,Ih,X0,P0,We,v0,Zh,Hh,Ye,p0,Q0,ty,iy,Mr,$$,ny,ht,ry,fy,Mh,zr,qe,v,W,ey,zh,cy,Gh,ly,hy,Ie,$y,Kh,qh,wy,Ze,uy,sy,yy,ay,Ay,Gr,w$,my,Ey="0.15.6",Tt,gr,Tn,xe,Oe,br,De,Le,Sn,ke,Ve,ui,u$,s$,It,ti,y$,a$,Ty=T0(async()=>{l$=import.meta.require,bi=new ve,Bn=new pe,h$={createKey:S0,isEquivalent:R0,estimateMemoryUsage:B0},V0=xr(ze.cwd(),"config"),o0=xr(ze.cwd(),"src/generated"),Wh=qr.env.CLARITY_LOG_DIR||Hs(N0(),"logs"),Hr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Wh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ke=await J0(),lt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},q=lt,g0=lt.red,Yh=lt.green,b0=lt.yellow,Ih=lt.blue,X0=lt.magenta,P0=lt.cyan,We=lt.white,v0=lt.gray,Zh=lt.bgRed,Hh=lt.bgYellow,Ye=lt.bold,p0=lt.dim,Q0=lt.italic,ty=lt.underline,iy=lt.reset,Mr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$$={debug:"\uD83D\uDD0D",info:Ih("ℹ"),success:Yh("✓"),warning:Hh(We(Ye(" WARN "))),error:Zh(We(Ye(" ERROR ")))},ny=new kr("stacks"),ht=new kr("bunfig",{showTags:!0}),ry=st(En.cwd(),"config"),fy=st(En.cwd(),"src/generated"),Mh=Kr.env.CLARITY_LOG_DIR||Is(j0(),"logs"),zr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},qe=await W0(),v={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},W=v,ey=v.red,zh=v.green,cy=v.yellow,Gh=v.blue,ly=v.magenta,hy=v.cyan,Ie=v.white,$y=v.gray,Kh=v.bgRed,qh=v.bgYellow,wy=v.bgGray,Ze=v.bold,uy=v.dim,sy=v.italic,yy=v.underline,ay=v.strikethrough,Ay=v.reset,Gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},w$={debug:"\uD83D\uDD0D",info:Gh("ℹ"),success:zh("✓"),warning:qh(Ie(Ze(" WARN "))),error:Kh(Ie(Ze(" ERROR ")))},my=new or("stacks"),Tt=class extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},gr=class extends Tt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${t}"${r} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}},Tn=class extends Tt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},xe=class extends Tt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}},Oe=class extends Tt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},br=class extends Tt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}},De=class extends Tt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Le=class extends Tt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Sn=class extends Tt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}},ke=class extends Tt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}},Ve=class extends Tt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}},ui={configNotFound(t,i,n){return new gr(t,i,n)},configLoad(t,i,n){return new Tn(t,i,n)},configValidation(t,i,n){return new xe(t,i,n)},configMerge(t,i,n,r){return new Oe(t,i,n,r)},envVar(t,i,n,r){return new br(t,i,n,r)},fileSystem(t,i,n){return new De(t,i,n)},typeGeneration(t,i,n){return new Le(t,i,n)},schemaValidation(t,i,n){return new Sn(t,i,n)},browserConfig(t,i,n,r){return new ke(t,i,n,r)},plugin(t,i,n){return new Ve(t,i,n)}},u$={replace:"replace",concat:"concat",smart:"smart"},s$=/^https?:\/\//,It=new or("bunfig",{showTags:!0}),ti=new rc,y$=yt(mi.cwd(),"config"),a$=yt(mi.cwd(),"src/generated")});function Sy(t,i={}){let n=Or.cwd();while(n.includes("storage"))n=Ch(n,"..");let r=Ch(n,t||"");if(i?.relative)return r0(Or.cwd(),r);return r}var Ry=Or.env.CLARITY_LOG_DIR||n0(Sy(),"logs"),A$={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ry,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Xr={...A$},hE=(async()=>{try{let{loadConfig:t}=await Ty().then(()=>ph),i=await t({name:"clarity",alias:"logging",defaultConfig:A$,cwd:Or.cwd()});if(i)Object.assign(Xr,i)}catch{}return Xr})();function p(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function By(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let t=pt.type;if(t==="renderer"||t==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class m${async format(t){let i=await By(),n=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:n})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:oi.pid,hostname:i(),environment:oi.env.NODE_ENV||"development",platform:oi.platform,version:oi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:oi.env.NODE_ENV||oi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var it={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},I=it,$E=it.red,Cy=it.green,wE=it.yellow,Fy=it.blue,uE=it.magenta,sE=it.cyan,xh=it.white,yE=it.gray,Ny=it.bgRed,Jy=it.bgYellow,aE=it.bgGray,Oh=it.bold,AE=it.dim,mE=it.italic,EE=it.underline,TE=it.strikethrough,SE=it.reset,He={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_y={debug:"\uD83D\uDD0D",info:Fy("ℹ"),success:Cy("✓"),warning:Jy(xh(Oh(" WARN "))),error:Ny(xh(Oh(" ERROR ")))};class ff{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(t,i={}){this.name=t,this.config={...Xr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new m$,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let n={...i},r=i.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),e=this.generateKey();this.currentKeyId=f,this.keys.set(f,e),this.encryptionKeys.set(f,{key:e,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...He,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...He};return{...He,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Xr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...i,...Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=i.level;return n}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let r,f=0,e=3,c=1000;while(f<e)try{try{try{await h0(this.config.logDirectory,_h.F_OK|_h.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await $0(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let h=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:bt.from(t);try{if(!_r(this.currentLogFile))await de(this.currentLogFile,"",{mode:420});if(r=Jh(this.currentLogFile,"a",420),l0(r,h,{flag:"a"}),Nh(r),r!==void 0)Ue(r),r=void 0;if((await ki(this.currentLogFile)).size===0){if(await de(this.currentLogFile,h,{flag:"w",mode:420}),(await ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let $=l;if($.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes($.code)){if(f<e-1){let w=typeof $.message==="string"?$.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${e}:`,w);let s=c*2**f;await new Promise((y)=>setTimeout(y,s)),f++;continue}}if($?.code&&["ENOSPC","EDQUOT"].includes($.code))throw Error(`Disk quota exceeded or no space left on device: ${$.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",$),$}finally{if(r!==void 0)try{Ue(r)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(h){if(f===e-1){let $=h,w=typeof $.message==="string"?$.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),h}f++;let l=c*2**(f-1);await new Promise(($)=>setTimeout($,l))}})();this.pendingOperations.push(i);let n=this.pendingOperations.length-1;try{await i}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Vi(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 Vi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Vi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,n=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,h])=>h.createdAt.getTime()-c.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,e=Math.max(1,f);if(r.length>e)for(let[c]of r.slice(e))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return _e(16).toString("hex")}generateKey(){return _e(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),n=_e(16),r=f0("aes-256-gcm",i,n),f=bt.isBuffer(t)?t:bt.from(t,"utf8"),e=r.update(f),c=r.final(),h=e.length+c.length,l=r.getAuthTag(),$=bt.allocUnsafe(16+h+16);return n.copy($,0),e.copy($,16),c.copy($,16+e.length),l.copy($,16+h),{encrypted:$,iv:n}}async compressData(t){return new Promise((i,n)=>{let r=dh(),f=[];r.on("data",(e)=>f.push(e)),r.on("end",()=>i(bt.from(bt.concat(f)))),r.on("error",n),r.write(t),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let t=await ki(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ur(this.config.logDirectory),e=f.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,$)=>{let w=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0")-w}),c=e.length>0?Number.parseInt(e[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,h=`${n}.${c}`;if(await ki(n).catch(()=>null))try{if(await Uh(n,h),i.compress)try{let l=`${h}.gz`;await this.compressLogFile(h,l),await dr(h)}catch(l){console.error("Error compressing rotated file:",l)}if(e.length===0&&!f.some((l)=>l.endsWith(".log.1")))try{let l=`${n}.1`;await de(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),e=n.replace(/\.log$/,`-${f}.log`);if(await ki(n).catch(()=>null))await Uh(n,e)}if(this.currentLogFile=r,i.maxFiles){let f=(await Ur(this.config.logDirectory)).filter((e)=>e.startsWith(this.name)).sort((e,c)=>c.localeCompare(e));for(let e of f.slice(i.maxFiles))await dr(Vi(this.config.logDirectory,e))}}}async compressLogFile(t,i){let n=Fh(t),r=c0(i),f=dh();await s0(n,f,r)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),_r(this.currentLogFile))try{let t=Jh(this.currentLogFile,"r+");Nh(t),Ue(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ur(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await dr(Vi(this.config.logDirectory,i))}catch(n){console.error(`Failed to delete temp file ${i}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?I.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof M.env.NO_COLOR<"u",i=M.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:n="",tag:r="",message:f,level:e,showTimestamp:c=!0}=t,h=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(c)u.push(i);if(e==="warning")u.push("WARN");else if(e==="error")u.push("ERROR");else if(n)u.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)u.push(r.replace(/[[\]]/g,""));return u.push(f),u.join(" ")}let l=M.stdout.columns||120,$="";if(e==="warning"||e==="error")$=`${n} ${f}`;else if(e==="info"||e==="success")$=`${n} ${r} ${f}`;else $=`${n} ${r} ${I.cyan(f)}`;if(!c)return $.trim();let w=h($).trim().length,s=h(i).length,y=Math.max(1,l-2-w-s);return`${$.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(e,c)=>{let h=Number.parseInt(c,10);return h<i[0].length?String(i[0][h]):e});let n=/%([sdijfo%])/g,r=0,f=t.replace(n,(e,c)=>{if(c==="%")return"%";if(r>=i.length)return e;let h=i[r++];switch(c){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return e}});if(r<i.length)f+=` ${i.slice(r).map((e)=>typeof e==="object"?JSON.stringify(e,null,2):String(e)).join(" ")}`;return f}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let e=I.underline(I.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let h=`file://${encodeURI(c)}`,l="\x1B]8;;",$="\x1B\\";return`\x1B]8;;${h}\x1B\\${e}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${e}\x1B]8;;\x1B\\`;return e}),i=i.replace(/`([^`]+)`/g,(n,r)=>I.bgGray(r)),i=i.replace(/\*\*([^*]+)\*\*/g,(n,r)=>I.bold(r)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>I.italic(r)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>I.italic(r)),i=i.replace(/~([^~]+)~/g,(n,r)=>I.strikethrough(r)),i}supportsHyperlinks(){if(p())return!1;let t=M.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let n=M.env.HOME||"";if(n)i=i.replace(/^~(?=$|\/)/,n)}if(w0(i)||i.startsWith("./")||i.startsWith("../"))i=u0(i);else return null;return _r(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:n}}async log(t,i,...n){if(!this.shouldLog(t))return;let r=new Date,f=this.formatConsoleTimestamp(r),e=this.formatFileTimestamp(r),c,h;if(i instanceof Error)c=i.message,h=i.stack;else c=this.formatMessage(i,n);let{consoleText:l,fileText:$}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let s=this.options.showIcons===!1?"":_y[t],y=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:I.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:I.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:s,tag:y,message:l,level:t}),console.error(u),h){let m=h.split(`
|
|
99
|
+
`);for(let A of m)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:I.gray(` ${A}`),level:t,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${e} ${this.environment}.${t.toUpperCase()}: ${c}`),h)console.error(h)}let w=`${e} ${this.environment}.${t.toUpperCase()}: ${$}
|
|
100
|
+
`;if(h)w+=`${h}
|
|
101
|
+
`;if(w=w.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(w)}progress(t,i=""){let n={update:(f,e)=>{},finish:(f)=>{},interrupt:(f,e)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,e)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),e!==void 0)this.activeProgressBar.message=e;if(this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,e="info")=>{if(!p()&&M.stdout.isTTY)M.stdout.write(`
|
|
102
|
+
`);if(this[e==="warning"?"warn":e](f),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":I.blue("◐"),tag:n,message:`${I.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-i),e=`${t} completed in ${f}ms`,c=new Date,h=this.formatConsoleTimestamp(c),l=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${e}`;if(n)l+=` ${JSON.stringify(n)}`;if(l+=`
|
|
103
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:h,icon:this.options.showIcons===!1?"":I.green("✓"),tag:$,message:`${e}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!p())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,n=new ff(i,{...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(n),n}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!_r(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Fh(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=bt.isBuffer(t)?t:bt.from(t,"base64"),f=r.subarray(0,16),e=r.subarray(r.length-16),c=r.subarray(16,r.length-16),h=e0("aes-256-gcm",n,f);h.setAuthTag(e);let l=h.update(c),$=h.final(),w=l.length+$.length,s=bt.allocUnsafe(w);return l.copy(s,0),$.copy(s,l.length),s.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return p()}isServerMode(){return!p()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,n=this.formatConsoleTimestamp(i),r=this.formatFileTimestamp(i),{consoleText:f,fileText:e}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let h=f.split(`
|
|
104
|
+
`),l=Math.max(...h.map((y)=>y.length))+2,$=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,s=h.map((y)=>{return this.formatConsoleMessage({timestamp:n,message:I.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:I.cyan($),showTimestamp:!1})),s.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:n,message:I.cyan(w),showTimestamp:!1}))}else if(!p())console.error(`${r} ${this.environment}.INFO: [BOX] ${e}`);let c=`${r} ${this.environment}.INFO: [BOX] ${e}
|
|
105
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(t){if(p())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${I.cyan("?")} ${t} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();M.stdin.removeListener("data",n);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),i(f==="y"||f==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let n=t;if(i&&i.length>0){let c=/%([sdijfo%])/g,h=0;if(n=t.replace(c,(l,$)=>{if($==="%")return"%";if(h>=i.length)return l;let w=i[h++];switch($){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 l}}),h<i.length)n+=` ${i.slice(h).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${I.blue("◐")} `;console.error(`${h}${c} ${I.cyan(r)}`)}let e=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
106
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(e)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),r=Math.round(t.barLength*n/100),f=t.barLength-r,e=I.green("━".repeat(r)),c=I.gray("━".repeat(f)),h=`[${e}${c}]`,l=`${n}%`.padStart(4),$=t.message?` ${t.message}`:"",w=this.options.showIcons===!1?"":i||n===100?I.green("✓"):I.blue("▶"),s=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",y=`\r${w}${s} ${h} ${l}${$}`,u=M.stdout.columns||80,m=" ".repeat(Math.max(0,u-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,M.stdout.write(t.lastRenderedLine),i)M.stdout.write(`
|
|
107
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Ur(this.config.logDirectory),n=[];for(let r of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Vi(this.config.logDirectory,r);if(t.before)try{if((await ki(f)).mtime>=t.before)continue}catch(e){console.error(`Failed to get stats for file ${f}:`,e);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await dr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var RE=new ff("stacks");class Mt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,n])=>`${i}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class E$ extends Mt{code="CONFIG_NOT_FOUND";constructor(t,i,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((e)=>`"${e}"`).join(", ")}`;super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:i,searchPathCount:i.length})}}class Pr extends Mt{code="CONFIG_LOAD_ERROR";constructor(t,i,n){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}}class T$ extends Mt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class S$ extends Mt{code="CONFIG_MERGE_ERROR";constructor(t,i,n,r){super(`Failed to merge configuration from "${t}" with "${i}": ${n.message}`,{sourcePath:t,targetPath:i,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class fc extends Mt{code="ENV_VAR_ERROR";constructor(t,i,n,r){super(`Failed to parse environment variable "${t}" with value "${i}" as ${n}`,{envKey:t,envValue:i,expectedType:n,configName:r})}}class R$ extends Mt{code="FILE_SYSTEM_ERROR";constructor(t,i,n){super(`File system ${t} failed for "${i}": ${n.message}`,{operation:t,path:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class B$ extends Mt{code="TYPE_GENERATION_ERROR";constructor(t,i,n){super(`Failed to generate types from "${t}" to "${i}": ${n.message}`,{configDir:t,outputPath:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class vr extends Mt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:i,errorCount:i.length})}}class C$ extends Mt{code="BROWSER_CONFIG_ERROR";constructor(t,i,n,r){super(`Failed to fetch configuration from "${t}": ${i} ${n}`,{endpoint:t,status:i,statusText:n,configName:r})}}class F$ extends Mt{code="PLUGIN_ERROR";constructor(t,i,n){super(`Plugin "${t}" failed during ${i}: ${n.message}`,{pluginName:t,operation:i,originalError:n.name,originalMessage:n.message});this.cause=n}}var Xi={configNotFound(t,i,n){return new E$(t,i,n)},configLoad(t,i,n){return new Pr(t,i,n)},configValidation(t,i,n){return new T$(t,i,n)},configMerge(t,i,n,r){return new S$(t,i,n,r)},envVar(t,i,n,r){return new fc(t,i,n,r)},fileSystem(t,i,n){return new R$(t,i,n)},typeGeneration(t,i,n){return new B$(t,i,n)},schemaValidation(t,i,n){return new vr(t,i,n)},browserConfig(t,i,n,r){return new C$(t,i,n,r)},plugin(t,i,n){return new F$(t,i,n)}};async function Uy(t,i={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:e}=i,c=Error("Unknown error occurred");for(let h=0;h<=n;h++)try{return await t()}catch(l){if(c=l instanceof Error?l:Error(String(l)),h===n||!f(c))break;if(r>0)await new Promise(($)=>setTimeout($,r))}if(e!==void 0)return e;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class ec{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:e=!0,customParsers:c={},verbose:h=!1,trackPerformance:l=!0}=n,$=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let w=r||this.generateEnvPrefix(t),s={...i};return this.processObject(s,[],w,{useCamelCase:f,useBackwardCompatibility:e,customParsers:c,verbose:h,configName:t}),{config:s,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Pe.track("applyEnvironmentVariables",$,{configName:t});return $()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=c.map((w)=>this.formatEnvKey(w,r.useCamelCase)),l=`${n}_${h.join("_")}`,$=r.useBackwardCompatibility?`${n}_${c.map((w)=>w.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.processObject(e,c,n,r);else{let w=jr.env[l]||($?jr.env[$]:void 0);if(w!==void 0){if(r.verbose){let s=jr.env[l]?l:$}try{t[f]=this.parseEnvironmentValue(w,typeof e,l,r.customParsers,r.configName)}catch(s){if(s instanceof fc)throw s;throw Xi.envVar(l,w,typeof e,r.configName)}}}}}parseEnvironmentValue(t,i,n,r,f){for(let[e,c]of Object.entries(r))try{return c(t)}catch{continue}for(let e of this.defaultParsers)if(e.canParse(t,i))try{return e.parse(t)}catch{throw Xi.envVar(n,t,`${i} (via ${e.name} parser)`,f)}return t}getEnvironmentVariables(t){let i={},n=t.toUpperCase();for(let[r,f]of Object.entries(jr.env))if(r.startsWith(n)&&f!==void 0)i[r]=f;return i}validateEnvironmentVariable(t,i,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))r.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,i,n,{})}catch(f){r.push(`Cannot parse value "${i}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(t,i,n={}){let{prefix:r,format:f="text"}=n,e=r||this.generateEnvPrefix(t),c=[];switch(this.extractEnvVarInfo(i,[],e,c),f){case"markdown":return this.formatAsMarkdown(c,t);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,t)}}extractEnvVarInfo(t,i,n,r){for(let[f,e]of Object.entries(t)){let c=[...i,f],h=`${n}_${c.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof e==="object"&&e!==null&&!Array.isArray(e))this.extractEnvVarInfo(e,c,n,r);else r.push({key:h,type:Array.isArray(e)?"array":typeof e,description:`Configuration for ${c.join(".")}`,example:this.generateExample(e)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let n=`Environment Variables for ${i}:
|
|
108
108
|
|
|
109
109
|
`;for(let r of t)n+=`${r.key}
|
|
110
110
|
`,n+=` Type: ${r.type}
|
|
@@ -116,41 +116,43 @@ export type ConfigOf = Config
|
|
|
116
116
|
`;n+=`| Variable | Type | Description | Example |
|
|
117
117
|
`,n+=`|----------|------|-------------|----------|
|
|
118
118
|
`;for(let r of t)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
119
|
-
`;return n}}function s0(t,i,n={}){return $$(t,i,n,new WeakMap)}function $$(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let l=c(t,i);if(l!==void 0)return l}if(Array.isArray(i)||Array.isArray(t))return s$(t,i,f,r);if(!_t(i)||!_t(t))return i;return a0(t,i,n,r)}function s$(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return w0(t,i);case"smart":return u0(t,i,r);default:return i}return i}function w0(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>Ze(f,r)))n.push(r);return n}function u0(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(_t(i[0])&&_t(t[0]))return y0(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function y0(t,i,n){let r=[...i];for(let f of t){if(!_t(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let l of e)if(l in f){if(r.find((h)=>_t(h)&&(l in h)&&h[l]===f[l])){c=!0;break}}if(!c)r.push(f)}return r}function a0(t,i,n,r){let f=i;if(_t(f)&&r.has(f))return r.get(f);let e={...t};if(_t(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let l=f[c],h=e[c];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){e[c]=l;continue}if(_t(l)&&_t(h))e[c]=$$(h,l,n,r);else if(Array.isArray(l)||Array.isArray(h))e[c]=s$(h,l,n.arrayMergeMode||"smart",r);else e[c]=l}return e}function w$(t,i,n="replace"){return s0(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Ze(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!Ze(t[n],i[n]))return!1;return!0}if(_t(t)&&_t(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!Ze(t[f],i[f]))return!1}return!0}return!1}function _t(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class u${extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:l=!1}=n;if(f){let $=Mr.getWithFileCheck("file",t);if($){if(l)console.log(`Configuration loaded from cache: ${t}`);return $}}let h=async()=>{if(!Fr(t))return null;try{let $=`?t=${Date.now()}`,s=await import(t+$),u=s.default||s,y="default"in s,w=Object.keys(s).length>0;if(!y&&!w)throw new Lr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Lr(t,Error("Configuration must export a valid object"),"unknown");let m={config:w$(i,u,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Mr.setWithFileCheck("file",m,t,e);return m}catch($){throw $ instanceof Error?bi.configLoad(t,$):bi.configLoad(t,Error(String($)))}};if(c)return Ge.track("loadFromPath",h,{path:t});return h()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(me(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=i===void 0?[]:Array.isArray(i)?i:[i];for(let e of r){if(!e)continue;if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}let f=new Set;return n.filter((e)=>{if(!e||f.has(e))return!1;return f.add(e),!0})}checkFileAccess(t){return $0(async()=>{return Fr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Fr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let l=me(t,`${e}${c}`);if(await this.checkFileAccess(l))r.push(l)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let l=me(t,c);if(await this.checkFileAccess(l))r.push(l)}}catch{return[]}return r}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Fr(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var A0=/^https?:\/\//;class y${async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:l=!0,verbose:h=!1}=n,$=async()=>{let s=[],u=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:l,verbose:h};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(w){return s.push({path:"",message:`Validation failed: ${w}`,rule:"system"}),{isValid:!1,errors:s,warnings:u}}};if(l)return await Ge.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!Xu(i))throw new kr(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new kr(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,l=Array.isArray(i.type)?i.type:[i.type];if(!l.includes(c)){if(r.push({path:n,message:`Expected type ${l.join(" or ")}, got ${c}`,expected:l.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let l=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,l,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let l of i.required)if(!(l in c)){if(r.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[l,h]of Object.entries(i.properties))if(l in c){let $=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(c[l],h,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let l=new Set(Object.keys(i.properties||{}));for(let h of Object.keys(c))if(!l.has(h))f.push({path:n?`${n}.${h}`:h,message:`Additional property '${h}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),l=this.validateWithRule(c,e,e.path);if(r.push(...l),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.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:A0},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Xt=new Pr("bunfig",{showTags:!0});function m0(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`}class a${fileLoader=new u$;envProcessor=new oe;validator=new y$;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let h=this.checkCache(c.name||"",c);if(h)return h}let l;try{l=await this.loadConfigurationStrategies(c,!0,n)}catch(h){let $=c.__strictErrorHandling;if(h instanceof Error&&h.name==="ConfigNotFoundError"){if($)throw h;l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(h instanceof Error&&h.name==="ConfigLoadError"){let s=h.message.includes("EACCES")||h.message.includes("EPERM")||h.message.includes("permission denied"),u=!s&&(h.message.includes("syntax")||h.message.includes("Expected")||h.message.includes("Unexpected")||h.message.includes("BuildMessage")||h.message.includes("errors building")),y=h.message.includes("Configuration must export a valid object")||h.message.includes("Configuration file is empty and exports nothing");if($&&(y||s))throw h;if(u&&(!$||!y))l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${h.message}`]};else throw h}else l={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${h instanceof Error?h.message:String(h)}`]}}if(f||e)await this.validateConfiguration(l.config,f,e,c.name);if(n?.enabled&&l)this.cacheResult(c.name||"",l,n,c);if(r?.enabled){let h={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(h);if(r.slowThreshold&&h.duration>r.slowThreshold)Xt.warn(`Slow configuration loading detected: ${h.duration}ms for ${c.name}`);l.metrics=h}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let h=Date.now()-i;throw Xt.error(`Configuration loading failed after ${h}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:l,checkEnv:h=!0,arrayStrategy:$="replace",verbose:s=!1}=t,u=e||gr.cwd(),y=[],w=await this.loadLocalConfiguration(r,f,u,c,l,$,s,h,n);if(w)return y.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(w,y,h,r,s);let m=await this.loadHomeConfiguration(r,f,l,$,s,h);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,h,r,s);let A=await this.loadPackageJsonConfiguration(r,f,u,l,$,s,h);if(A)return y.push(Jt(u,"package.json")),this.finalizeResult(A,y,h,r,s);if(y.push(...this.getAllSearchPaths(r,f,u,c)),i)throw bi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,l,h,s),warnings:[`No configuration file found for "${r}"${m0(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,l,h){let $=l?Cr(t,f,c):f,s=this.getLocalDirectories(n,r);for(let u of s){if(c)Xt.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),w=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:h?.ttl,useCache:!h?.ttl||h.ttl>100});if(w){if(c)Xt.success(`Configuration loaded from: ${w.source.path}`);return w}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?Cr(t,n,f):n,l=[Jt(Mi(),".config",t),Jt(Mi(),".config"),Mi()];for(let h of l){if(f)Xt.info(`Checking home directory: ${h}`);let $=this.fileLoader.generateConfigPaths(t,h,i),s=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(s){if(f)Xt.success(`Configuration loaded from home directory: ${s.source.path}`);return s}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let l=c?Cr(t,r,e):r;try{let h=Jt(n,"package.json");if(!$u(h))return null;let $={};try{$=JSON.parse(su(h,"utf8"))}catch(y){if(e)Xt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let s=$[t],u=t;if(!s&&i){let y=Array.isArray(i)?i:[i];for(let w of y){if(!w)continue;if($[w]){s=$[w],u=w;break}}}if(s&&typeof s==="object"&&!Array.isArray(s)){if(e)Xt.success(`Configuration loaded from package.json: ${u}`);return{config:w$(l,s,f),source:{type:"package.json",path:h,priority:30,timestamp:new Date}}}}catch(h){if(e)Xt.warn("Failed to load package.json:",[h instanceof Error?h:Error(String(h))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Cr(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw bi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Mr.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Mr.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias){let r=Array.isArray(i.alias)?i.alias.join(","):i.alias;n.push(`alias:${r}`)}if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Jt(t,"config"),Jt(t,".config"),i?Jt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(Jt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[Jt(Mi(),".config",t),Jt(Mi(),".config"),Mi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var tE=new a$;function Cr(t,i,n=!1){let r=new oe,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,l=[]){let h={...c};for(let[$,s]of Object.entries(c)){let u=[...l,$],y=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((A)=>A.toUpperCase()).join("")}`,`${f}_${u.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],w,m;for(let A of y)if(w=gr.env[A],w!==void 0){m=A;break}if(w!==void 0&&m)if(typeof s==="boolean")h[$]=["true","1","yes"].includes(w.toLowerCase());else if(typeof s==="number"){let A=Number(w);if(!Number.isNaN(A))h[$]=A}else if(Array.isArray(s))try{h[$]=JSON.parse(w)}catch{h[$]=w.split(",").map((A)=>A.trim())}else h[$]=w;else if(s&&typeof s==="object"&&!Array.isArray(s))h[$]=e(s,u)}return h}return e(i)}var iE=Jt(gr.cwd(),"config"),nE=Jt(gr.cwd(),"src/generated"),A$={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:ne.join(ie.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:ne.join(ie.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:ne.join(ie.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},V=A$,Zt={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var F={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},oi={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function He(t,i){let n=[];function r(f){let e;try{e=Ul.readdirSync(f)}catch{return}for(let c of e){let l=dt.join(f,c);try{if(Ul.statSync(l).isDirectory())r(l);else if(c===i)n.push(f)}catch{continue}}}return r(t),n}function N(t,i,n){if(n||V.verbose)console.debug(`[tlsx:${t}] ${i}`)}var R0=S0(E0);function E$(){return m$.env.SUDO_PASSWORD}var jl="[redacted]",B0=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),N0=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function F0(t){let i=t.toLowerCase();return B0.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function Vr(t){if(Array.isArray(t))return t.map((n)=>Vr(n));if(typeof t==="string")return N0.test(t)?jl:t;if(!t||typeof t!=="object")return t;let i={};for(let[n,r]of Object.entries(t)){if(F0(n)){i[n]=jl;continue}i[n]=Vr(r)}return i}function vr(t){return JSON.stringify(Vr(t))}function J0(t){let i=E$();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let n=i.replace(/'/g,"'\\''"),r=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function $i(t,i={}){let n=J0(t);try{let{stdout:r,stderr:f}=await R0(n,{cwd:i.cwd||m$.cwd(),timeout:i.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${t}
|
|
120
|
-
Error: ${r.message}`);throw f.stack=r.stack,f}}function
|
|
119
|
+
`;return n}}function dy(t,i,n={}){return N$(t,i,n,new WeakMap)}function N$(t,i,n,r){let{arrayMergeMode:f="replace",skipNullish:e=!1,customMerger:c}=n;if(i===null||i===void 0)return e?t:i;if(c){let h=c(t,i);if(h!==void 0)return h}if(Array.isArray(i)||Array.isArray(t))return J$(t,i,f,r);if(!_t(i)||!_t(t))return i;return Iy(t,i,n,r)}function J$(t,i,n,r){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(n){case"replace":return i;case"concat":return jy(t,i);case"smart":return Wy(t,i,r);default:return i}return i}function jy(t,i){let n=[...i];for(let r of t)if(!n.some((f)=>oe(f,r)))n.push(r);return n}function Wy(t,i,n){if(i.length===0)return t;if(t.length===0)return i;if(_t(i[0])&&_t(t[0]))return Yy(t,i,n);if(i.every((r)=>typeof r==="string")&&t.every((r)=>typeof r==="string")){let r=[...i];for(let f of t)if(!r.includes(f))r.push(f);return r}return i}function Yy(t,i,n){let r=[...i];for(let f of t){if(!_t(f)){r.push(f);continue}let e=["id","name","key","path","type"],c=!1;for(let h of e)if(h in f){if(r.find((l)=>_t(l)&&(h in l)&&l[h]===f[h])){c=!0;break}}if(!c)r.push(f)}return r}function Iy(t,i,n,r){let f=i;if(_t(f)&&r.has(f))return r.get(f);let e={...t};if(_t(f))r.set(f,e);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let h=f[c],l=e[c];if(n.skipNullish&&(h===null||h===void 0))continue;if(h===null||h===void 0){e[c]=h;continue}if(_t(h)&&_t(l))e[c]=N$(l,h,n,r);else if(Array.isArray(h)||Array.isArray(l))e[c]=J$(l,h,n.arrayMergeMode||"smart",r);else e[c]=h}return e}function _$(t,i,n="replace"){return dy(t,i,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function oe(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let n=0;n<t.length;n++)if(!oe(t[n],i[n]))return!1;return!0}if(_t(t)&&_t(i)){let n=Object.keys(t),r=Object.keys(i);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(i,f))return!1;if(!oe(t[f],i[f]))return!1}return!0}return!1}function _t(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class U${extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:e,trackPerformance:c=!0,verbose:h=!1}=n;if(f){let $=Dr.getWithFileCheck("file",t);if($){if(h)console.log(`Configuration loaded from cache: ${t}`);return $}}let l=async()=>{if(!Wr(t))return null;try{let $=`?t=${Date.now()}`,w=await import(t+$),s=w.default||w,y="default"in w,u=Object.keys(w).length>0;if(!y&&!u)throw new Pr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof s!=="object"||s===null||Array.isArray(s))throw new Pr(t,Error("Configuration must export a valid object"),"unknown");let m={config:_$(i,s,r),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(f)Dr.setWithFileCheck("file",m,t,e);return m}catch($){throw $ instanceof Error?Xi.configLoad(t,$):Xi.configLoad(t,Error(String($)))}};if(c)return Pe.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,n={}){for(let r of t)try{let f=await this.loadFromPath(r,i,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(t,i,n){let r=this.generateNamePatterns(t,n),f=[];for(let e of r)for(let c of this.extensions)f.push(je(i,`${e}${c}`));return f}generateNamePatterns(t,i){let n=[];if(n.push("config",".config"),t)n.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let r=i===void 0?[]:Array.isArray(i)?i:[i];for(let e of r){if(!e)continue;if(n.push(e,`.${e}.config`,`${e}.config`,`.${e}`),t)n.push(`${t}.${e}.config`,`.${t}.${e}.config`)}let f=new Set;return n.filter((e)=>{if(!e||f.has(e))return!1;return f.add(e),!0})}checkFileAccess(t){return Uy(async()=>{return Wr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,n){let r=[];if(!Wr(t))return r;if(i||n){let f=this.generateNamePatterns(i||"",n);for(let e of f)for(let c of this.extensions){let h=je(t,`${e}${c}`);if(await this.checkFileAccess(h))r.push(h)}}else try{let{readdirSync:f}=await import("fs"),e=f(t);for(let c of e)if(this.looksLikeConfigFile(c)){let h=je(t,c);if(await this.checkFileAccess(h))r.push(h)}}catch{return[]}return r}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Wr(t))return i.push("Configuration file does not exist"),i;let n=await import(t),r=n.default||n;if(r===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)i.push("Configuration must be an object");else if(Array.isArray(r))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),e=f(t,"utf8");JSON.parse(e)}catch(f){i.push(`Invalid JSON syntax: ${f}`)}}catch(n){i.push(`Failed to load configuration file: ${n}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let n=new Map;return await Promise.allSettled(t.map(async(r)=>{try{let f=await this.loadFromPath(r,{},i);if(f)n.set(r,f.config)}catch(f){if(i.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var Zy=/^https?:\/\//;class d${async validateConfiguration(t,i,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:e=!0,customRules:c=[],trackPerformance:h=!0,verbose:l=!1}=n,$=async()=>{let w=[],s=[],y={stopOnFirstError:r,validateRequired:f,validateTypes:e,customRules:c,trackPerformance:h,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...c],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return w.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:w,warnings:s}}};if(h)return await Pe.track("validateConfiguration",$);return $()}async validateWithSchemaFile(t,i,n){try{if(!y0(i))throw new vr(i,[{path:"",message:"Schema file does not exist"}]);let r=await import(i),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(t,f,n);else return this.validateWithJSONSchema(t,f,n)}catch(r){throw new vr(i,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(t,i,n){let r=[],f=[];return this.validateObjectAgainstSchema(t,i,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(t,i,n,r,f,e){if(e.validateTypes&&i.type){let c=Array.isArray(t)?"array":typeof t,h=Array.isArray(i.type)?i.type:[i.type];if(!h.includes(c)){if(r.push({path:n,message:`Expected type ${h.join(" or ")}, got ${c}`,expected:h.join(" or "),actual:c,rule:"type"}),e.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(r.push({path:n,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),e.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)r.push({path:n,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)r.push({path:n,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))r.push({path:n,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)r.push({path:n,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)r.push({path:n,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let c=0;c<t.length;c++){let h=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(t[c],i.items,h,r,f,e),e.stopOnFirstError&&r.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let c=t;if(e.validateRequired&&i.required){for(let h of i.required)if(!(h in c)){if(r.push({path:n?`${n}.${h}`:h,message:`Missing required property '${h}'`,expected:"required",rule:"required"}),e.stopOnFirstError)return}}if(i.properties){for(let[h,l]of Object.entries(i.properties))if(h in c){let $=n?`${n}.${h}`:h;if(this.validateObjectAgainstSchema(c[h],l,$,r,f,e),e.stopOnFirstError&&r.length>0)return}}if(i.additionalProperties===!1){let h=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(c))if(!h.has(l))f.push({path:n?`${n}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,n){let r=[],f=[];for(let e of i)try{let c=this.getValueByPath(t,e.path),h=this.validateWithRule(c,e,e.path);if(r.push(...h),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:e.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(t,i,n){let r=[];if(i.required&&(t===void 0||t===null))return r.push({path:n,message:i.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(t===void 0||t===null)return r;if(i.type){let f=Array.isArray(t)?"array":typeof t;if(f!==i.type)r.push({path:n,message:i.message||`Expected type ${i.type}, got ${f}`,expected:i.type,actual:f,rule:"type"})}if(i.min!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f<i.min)r.push({path:n,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:f,rule:"min"})}if(i.max!==void 0){let f=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(f>i.max)r.push({path:n,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:f,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))r.push({path:n,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))r.push({path:n,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let f=i.validator(t);if(f)r.push({path:n,message:i.message||f,rule:"custom"})}return r}getValueByPath(t,i){if(!i)return t;let n=i.split("."),r=t;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(t){let i=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,e,c]=r;i.push({path:f,required:!e,type:this.mapTypeScriptType(c)})}return i}mapTypeScriptType(t){switch(t.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:Zy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Xt=new ff("bunfig",{showTags:!0});function Hy(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`}class j${fileLoader=new U$;envProcessor=new ec;validator=new d$;async loadConfig(t){let i=Date.now(),{cache:n,performance:r,schema:f,validate:e,...c}=t;try{if(n?.enabled){let l=this.checkCache(c.name||"",c);if(l)return l}let h;try{h=await this.loadConfigurationStrategies(c,!0,n)}catch(l){let $=c.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if($)throw l;h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let w=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),s=!w&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if($&&(y||w))throw l;if(s&&(!$||!y))h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!$)h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else h={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(f||e)await this.validateConfiguration(h.config,f,e,c.name);if(n?.enabled&&h)this.cacheResult(c.name||"",h,n,c);if(r?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(l);if(r.slowThreshold&&l.duration>r.slowThreshold)Xt.warn(`Slow configuration loading detected: ${l.duration}ms for ${c.name}`);h.metrics=l}return h}catch(h){if(h instanceof Error&&h.name==="ConfigNotFoundError")throw h;let l=Date.now()-i;throw Xt.error(`Configuration loading failed after ${l}ms:`,[h instanceof Error?h:Error(String(h))]),h}}async loadConfigurationStrategies(t,i=!1,n){let{name:r="",alias:f,cwd:e,configDir:c,defaultConfig:h,checkEnv:l=!0,arrayStrategy:$="replace",verbose:w=!1}=t,s=e||tf.cwd(),y=[],u=await this.loadLocalConfiguration(r,f,s,c,h,$,w,l,n);if(u)return y.push(...this.getLocalSearchPaths(r,f,s,c)),this.finalizeResult(u,y,l,r,w);let m=await this.loadHomeConfiguration(r,f,h,$,w,l);if(m)return y.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(m,y,l,r,w);let A=await this.loadPackageJsonConfiguration(r,f,s,h,$,w,l);if(A)return y.push(Nt(s,"package.json")),this.finalizeResult(A,y,l,r,w);if(y.push(...this.getAllSearchPaths(r,f,s,c)),i)throw Xi.configNotFound(r,y,f);return{...await this.applyEnvironmentVariables(r,h,l,w),warnings:[`No configuration file found for "${r}"${Hy(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,n,r,f,e,c,h,l){let $=h?Ir(t,f,c):f,w=this.getLocalDirectories(n,r);for(let s of w){if(c)Xt.info(`Searching for configuration in: ${s}`);let y=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(y,$,{arrayStrategy:e,verbose:c,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(c)Xt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,n,r,f,e){if(!t)return null;let c=e?Ir(t,n,f):n,h=[Nt(zi(),".config",t),Nt(zi(),".config"),zi()];for(let l of h){if(f)Xt.info(`Checking home directory: ${l}`);let $=this.fileLoader.generateConfigPaths(t,l,i),w=await this.fileLoader.tryLoadFromPaths($,c,{arrayStrategy:r,verbose:f});if(w){if(f)Xt.success(`Configuration loaded from home directory: ${w.source.path}`);return w}}return null}async loadPackageJsonConfiguration(t,i,n,r,f,e,c){let h=c?Ir(t,r,e):r;try{let l=Nt(n,"package.json");if(!Us(l))return null;let $={};try{$=JSON.parse(ds(l,"utf8"))}catch(y){if(e)Xt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let w=$[t],s=t;if(!w&&i){let y=Array.isArray(i)?i:[i];for(let u of y){if(!u)continue;if($[u]){w=$[u],s=u;break}}}if(w&&typeof w==="object"&&!Array.isArray(w)){if(e)Xt.success(`Configuration loaded from package.json: ${s}`);return{config:_$(h,w,f),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(e)Xt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,n,r){if(!n||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ir(t,i,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,n,r,f){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,n,r){let f=[];if(n){let e=n(t);if(e)f.push(...e)}if(i){let e=await this.validator.validateConfiguration(t,i);if(!e.isValid)f.push(...e.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Xi.configValidation(r||"unknown",f,r)}checkCache(t,i){let n=this.generateCacheKey(t,i);return Dr.get(n)||null}cacheResult(t,i,n,r){let f=this.generateCacheKey(t,r);Dr.set(f,i,void 0,n.ttl)}generateCacheKey(t,i){let n=[t];if(i.alias){let r=Array.isArray(i.alias)?i.alias.join(","):i.alias;n.push(`alias:${r}`)}if(i.cwd)n.push(`cwd:${i.cwd}`);if(i.configDir)n.push(`configDir:${i.configDir}`);if("checkEnv"in i)n.push(`checkEnv:${i.checkEnv}`);return n.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Nt(t,"config"),Nt(t,".config"),i?Nt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,n,r){let f=[];return f.push(...this.getLocalSearchPaths(t,i,n,r)),f.push(...this.getHomeSearchPaths(t,i)),f.push(Nt(n,"package.json")),f}getLocalSearchPaths(t,i,n,r){let f=this.getLocalDirectories(n,r),e=[];for(let c of f)e.push(...this.fileLoader.generateConfigPaths(t,c,i));return e}getHomeSearchPaths(t,i){if(!t)return[];let n=[Nt(zi(),".config",t),Nt(zi(),".config"),zi()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(t,f,i));return r}async loadConfigWithResult(t){return this.loadConfig(t)}}var BE=new j$;function Ir(t,i,n=!1){let r=new ec,f=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function e(c,h=[]){let l={...c};for(let[$,w]of Object.entries(c)){let s=[...h,$],y=[`${f}_${s.join("_").toUpperCase()}`,`${f}_${s.map((A)=>A.toUpperCase()).join("")}`,`${f}_${s.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let A of y)if(u=tf.env[A],u!==void 0){m=A;break}if(u!==void 0&&m)if(typeof w==="boolean")l[$]=["true","1","yes"].includes(u.toLowerCase());else if(typeof w==="number"){let A=Number(u);if(!Number.isNaN(A))l[$]=A}else if(Array.isArray(w))try{l[$]=JSON.parse(u)}catch{l[$]=u.split(",").map((A)=>A.trim())}else l[$]=u;else if(w&&typeof w==="object"&&!Array.isArray(w))l[$]=e(w,s)}return l}return e(i)}var CE=Nt(tf.cwd(),"config"),FE=Nt(tf.cwd(),"src/generated"),W$={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:Ae.join(ae.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:Ae.join(ae.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:Ae.join(ae.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},V=W$,Zt={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var F={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},gi={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function ge(t,i){let n=[];function r(f){let e;try{e=Dh.readdirSync(f)}catch{return}for(let c of e){let h=Yt.join(f,c);try{if(Dh.statSync(h).isDirectory())r(h);else if(c===i)n.push(f)}catch{continue}}}return r(t),n}function C(t,i,n){if(n||V.verbose)console.debug(`[tlsx:${t}] ${i}`)}var Ky=Gy(My);function I$(){return Y$.env.SUDO_PASSWORD}var Lh="[redacted]",qy=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),xy=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function Oy(t){let i=t.toLowerCase();return qy.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function pr(t){if(Array.isArray(t))return t.map((n)=>pr(n));if(typeof t==="string")return xy.test(t)?Lh:t;if(!t||typeof t!=="object")return t;let i={};for(let[n,r]of Object.entries(t)){if(Oy(n)){i[n]=Lh;continue}i[n]=pr(r)}return i}function ef(t){return JSON.stringify(pr(t))}function Dy(t){let i=I$();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let n=i.replace(/'/g,"'\\''"),r=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function wi(t,i={}){let n=Dy(t);try{let{stdout:r,stderr:f}=await Ky(n,{cwd:i.cwd||Y$.cwd(),timeout:i.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${t}
|
|
120
|
+
Error: ${r.message}`);throw f.stack=r.stack,f}}function Z$(t){if(t.domain)return t.domain;if(t.domains?.length)return t.domains[0];throw Error("Either domain or domains must be specified")}function cc(t){let i=Yt.join(zy.homedir(),".stacks","ssl"),n=t.basePath&&t.basePath.trim()!==""?t.basePath:V.basePath&&V.basePath.trim()!==""?V.basePath:i,r=t.certPath?Yt.isAbsolute(t.certPath)?t.certPath:Yt.join(n,t.certPath):Yt.join(n,V.certPath),f=t.keyPath?Yt.isAbsolute(t.keyPath)?t.keyPath:Yt.join(n,t.keyPath):Yt.join(n,V.keyPath),e=t.caCertPath?Yt.isAbsolute(t.caCertPath)?t.caCertPath:Yt.join(n,t.caCertPath):Yt.join(n,V.caCertPath);return{certPath:r,keyPath:f,caCertPath:e,basePath:n}}function H$(t){let i=[],n=new Set;if(t.domain)n.add(t.domain);if(t.domains?.length)t.domains.forEach((r)=>n.add(r));for(let r of n)i.push({type:2,value:r});if(t.altNameIPs?.length)for(let r of t.altNameIPs)i.push({type:7,ip:r});if(t.altNameURIs?.length)for(let r of t.altNameURIs)i.push({type:6,value:r});if(t.subjectAltNames?.length)i.push(...t.subjectAltNames);return C(F.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function lc(t){let i=t.notBeforeDays??Zt.DEFAULT_NOT_BEFORE_DAYS,n=t.validityDays??(t.validityYears?t.validityYears*365:Zt.DEFAULT_VALIDITY_DAYS);C(F.CERT,"Calculating certificate validity dates",t.verbose);let r=new Date(Date.now()-86400*i*1000),f=new Date(r.getTime()+n*24*60*60*1000);return r.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),C(F.CERT,`Validity period: ${r.toISOString()} to ${f.toISOString()}`,t.verbose),{notBefore:r,notAfter:f}}var Ht={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},at={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};function mn(t){if(t<128)return Buffer.from([t]);let i=[],n=t;while(n>0)i.unshift(n&255),n>>=8;return Buffer.from([128|i.length,...i])}function Rt(t,i){let n=mn(i.length);return Buffer.concat([Buffer.from([t]),n,i])}function Rn(t){let i=t.split(".").map(Number),n=[];n.push(40*i[0]+i[1]);for(let r=2;r<i.length;r++){let f=i[r],e=[];e.unshift(f&127),f>>=7;while(f>0)e.unshift(f&127|128),f>>=7;n.push(...e)}return Rt(Ht.OID,Buffer.from(n))}function be(t){let i;if(typeof t==="bigint"){let n=t.toString(16).padStart(2,"0");i=Buffer.from(n.length%2?`0${n}`:n,"hex")}else if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let n=t.toString(16).padStart(2,"0");i=Buffer.from(n.length%2?`0${n}`:n,"hex")}else i=t;if(i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return Rt(Ht.INTEGER,i)}function M$(t,i=0){return Rt(Ht.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function z$(t){return Rt(Ht.OCTET_STRING,t)}function St(...t){return Rt(Ht.SEQUENCE,Buffer.concat(t))}function Ly(...t){return Rt(Ht.SET,Buffer.concat(t))}function ky(t){return Rt(Ht.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function Vy(t){return Rt(Ht.UTF8_STRING,Buffer.from(t,"utf8"))}function oy(){return Buffer.from([Ht.NULL,0])}function kh(t,i,n=!0){let r=160|t|(n?0:0),f=mn(i.length);return Buffer.concat([Buffer.from([r]),f,i])}function Vh(t){let i=t.getUTCFullYear();if(i>=2050){let n=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Rt(Ht.GENERALIZED_TIME,Buffer.from(n,"ascii"))}else{let n=(i%100).toString().padStart(2,"0"),r=(t.getUTCMonth()+1).toString().padStart(2,"0"),f=t.getUTCDate().toString().padStart(2,"0"),e=t.getUTCHours().toString().padStart(2,"0"),c=t.getUTCMinutes().toString().padStart(2,"0"),h=t.getUTCSeconds().toString().padStart(2,"0"),l=`${n}${r}${f}${e}${c}${h}Z`;return Rt(Ht.UTC_TIME,Buffer.from(l,"ascii"))}}function gy(t,i){return St(Vh(t),Vh(i))}function oh(t){let i=[];for(let n of t){let r;switch(n.shortName){case"CN":r=at.COMMON_NAME;break;case"C":r=at.COUNTRY;break;case"L":r=at.LOCALITY;break;case"ST":r=at.STATE;break;case"O":r=at.ORGANIZATION;break;case"OU":r=at.ORGANIZATIONAL_UNIT;break;default:continue}let f=n.shortName==="C"?ky(n.value):Vy(n.value),e=St(Rn(r),f);i.push(Ly(e))}return St(...i)}function G$(t){return St(Rn(t),oy())}function by(t){return t.export({type:"spki",format:"der"})}function Xy(t){if(t.includes(":")){let i=t;if(t.includes("::")){let f=t.split("::"),e=f[0]?f[0].split(":"):[],c=f[1]?f[1].split(":"):[],h=8-e.length-c.length,l=Array.from({length:h},()=>"0");i=[...e,...l,...c].join(":")}let n=i.split(":"),r=Buffer.alloc(16);for(let f=0;f<8;f++){let e=Number.parseInt(n[f]||"0",16);r.writeUInt16BE(e,f*2)}return r}else{let i=t.split(".").map((n)=>Number.parseInt(n,10));return Buffer.from(i)}}function Py(t){let i=[];for(let n of t)if(n.type===2&&n.value){let r=mn(n.value.length);i.push(Buffer.concat([Buffer.from([130]),r,Buffer.from(n.value,"ascii")]))}else if(n.type===7&&n.ip){let r=Xy(n.ip),f=mn(r.length);i.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=mn(n.value.length);i.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return St(...i)}function vy(t,i){if(t){if(i!==void 0)return St(Rt(1,Buffer.from([255])),be(i));return St(Rt(1,Buffer.from([255])))}return St()}function py(t){let i=0;if(t.digitalSignature)i|=128;if(t.keyEncipherment)i|=32;if(t.keyCertSign)i|=4;if(t.cRLSign)i|=2;let n=0,r=i;while(r>0&&(r&1)===0)n++,r>>=1;if(i===0)n=7;return M$(Buffer.from([i]),n)}function Qy(t){let i=[];if(t.serverAuth)i.push(Rn(at.SERVER_AUTH));if(t.clientAuth)i.push(Rn(at.CLIENT_AUTH));return St(...i)}function an(t,i,n){let r=[Rn(t)];if(i)r.push(Rt(1,Buffer.from([255])));return r.push(z$(n)),St(...r)}function ta(t){let i=[];if(i.push(kh(0,be(2))),i.push(be(t.serialNumber)),i.push(G$(at.SHA256_WITH_RSA)),i.push(oh(t.issuer)),i.push(gy(t.notBefore,t.notAfter)),i.push(oh(t.subject)),i.push(by(t.publicKey)),t.extensions){let n=[];if(t.extensions.basicConstraints)n.push(an(at.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,vy(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)n.push(an(at.KEY_USAGE,t.extensions.keyUsage.critical??!0,py(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)n.push(an(at.EXTENDED_KEY_USAGE,!1,Qy(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)n.push(an(at.SUBJECT_ALT_NAME,!1,Py(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)n.push(an(at.SUBJECT_KEY_IDENTIFIER,!1,z$(t.extensions.subjectKeyIdentifier)));if(n.length>0)i.push(kh(3,St(...n)))}return St(...i)}function ia(t,i){let n=Pi.createSign("SHA256");n.update(t);let r=n.sign(i);return St(t,G$(at.SHA256_WITH_RSA),M$(r))}function na(t,i){let n=t.toString("base64"),r=[];for(let f=0;f<n.length;f+=64)r.push(n.slice(f,f+64));return`-----BEGIN ${i}-----
|
|
121
121
|
${r.join(`
|
|
122
122
|
`)}
|
|
123
123
|
-----END ${i}-----
|
|
124
|
-
`}function
|
|
125
|
-
`);for(let e of f){let[c,...l]=e.split("="),h=l.join("=");if(c&&h)r.push({shortName:c.trim(),value:h.trim()})}return{publicKey:n,subject:r}}async function Pe(t={}){N("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||Zt.DEFAULT_KEY_SIZE;N("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:n,publicKey:r}=F$(i),f=[{shortName:"C",value:t.countryName||V.countryName},{shortName:"ST",value:t.stateName||V.stateName},{shortName:"L",value:t.localityName||V.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:e,notAfter:c}=be({validityYears:t.validityYears||Zt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:l}=J$({serialNumber:Xe(),notBefore:e,notAfter:c,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:l,privateKey:C$(n),notBefore:e,notAfter:c}}async function ve(t){if(N("ca","Generating new certificate",t.verbose),N("ca",`Options: ${vr(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=D0(t.rootCA.certificate),n=x0(t.rootCA.privateKey);N("ca",`Generating ${Zt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let r=Zt.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:e}=F$(r),c=t.commonName||T$(t),l=t.certificateAttributes||[{shortName:"C",value:t.countryName||V.countryName},{shortName:"ST",value:t.stateName||V.stateName},{shortName:"L",value:t.localityName||V.localityName},{shortName:"O",value:t.organizationName||V.organizationName},{shortName:"CN",value:c}],{notBefore:h,notAfter:$}=be({validityDays:t.validityDays||Zt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),s=S$(t),u=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},y=t.extKeyUsage||{serverAuth:!0},{certificate:w}=J$({serialNumber:Xe(),notBefore:h,notAfter:$,subject:l,issuer:i,publicKey:e,signingKey:n,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:u,extendedKeyUsage:y,subjectAltName:s});return{certificate:w,privateKey:C$(f),notBefore:h,notAfter:$}}function _$(t,i){N(F.STORAGE,`Storing certificate and private key with options: ${vr(i)}`,i?.verbose);let{certPath:n,keyPath:r}=ge({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});N(F.STORAGE,`Certificate path: ${n}`,i?.verbose),N(F.STORAGE,`Private key path: ${r}`,i?.verbose);let f=ze.dirname(n);if(!Qt.existsSync(f))N(F.STORAGE,`Creating certificate directory: ${f}`,i?.verbose),Qt.mkdirSync(f,{recursive:!0});N(F.STORAGE,"Writing certificate file",i?.verbose),Qt.writeFileSync(n,t.certificate);let e=ze.dirname(r);if(!Qt.existsSync(e))N(F.STORAGE,`Creating private key directory: ${e}`,i?.verbose),Qt.mkdirSync(e,{recursive:!0});return N(F.STORAGE,"Writing private key file",i?.verbose),Qt.writeFileSync(r,t.privateKey),N(F.STORAGE,"Certificate and private key stored successfully",i?.verbose),n}function U$(t,i){N(F.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:n}=ge({basePath:i?.basePath,caCertPath:i?.caCertPath});N(F.STORAGE,`CA certificate path: ${n}`,i?.verbose);let r=ze.dirname(n);if(!Qt.existsSync(r))N(F.STORAGE,`Creating CA certificate directory: ${r}`,i?.verbose),Qt.mkdirSync(r,{recursive:!0});return N(F.STORAGE,"Writing CA certificate file",i?.verbose),Qt.writeFileSync(n,t),N(F.STORAGE,"CA certificate stored successfully",i?.verbose),n}async function O0(t,i){if(or.platform()!=="darwin")return!1;try{let n=Il(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!n)return N(F.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(Il("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(n))return N(F.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return N(F.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(n){return N(F.TRUST,`Error checking certificate trust: ${n}`,i),!1}}var L0={platform:"darwin",async addCertificate(t,i){if(await O0(t,i?.verbose)){N(F.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),oi.success("Certificate is already trusted in system keychain");return}N(F.TRUST,"Adding certificate to macOS keychain",i?.verbose),await $i(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,n){let r=n||V.commonName;N(F.TRUST,`Removing certificate ${r} from macOS keychain`,i?.verbose);try{await $i(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),N(F.TRUST,`Removed certificate ${r} from macOS keychain`,i?.verbose)}catch(f){throw N(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},k0={platform:"win32",async addCertificate(t,i){N(F.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await $i(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,n){let r=n||V.commonName;N(F.TRUST,`Removing certificate ${r} from Windows certificate store`,i?.verbose);try{await $i(`certutil -delstore -enterprise Root "${r}"`),N(F.TRUST,`Removed certificate ${r} from Windows certificate store`,i?.verbose)}catch(f){throw N(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},V0={platform:"linux",async addCertificate(t,i){N(F.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let n=or.homedir(),r=Zt.LINUX_CERT_DB_FILENAME,f=Zt.LINUX_TRUST_ARGS;N(F.TRUST,`Searching for certificate databases in ${n}`,i?.verbose);let e=He(n,r);if(e.length===0){oi.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of e){N(F.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{N(F.TRUST,`Attempting to delete existing cert for ${V.commonName}`,i?.verbose),await $i(`certutil -d sql:${c} -D -n ${V.commonName}`)}catch(l){N(F.TRUST,`Warning: Error deleting existing cert: ${l}`,i?.verbose),console.warn(`Error deleting existing cert: ${l}`)}N(F.TRUST,`Adding new certificate to ${c}`,i?.verbose),await $i(`certutil -d sql:${c} -A -t ${f} -n ${V.commonName} -i ${t}`),oi.info(`Cert added to ${c}`)}},async removeCertificate(t,i,n){let r=n||V.commonName;N(F.TRUST,`Removing certificate ${r} from Linux certificate store`,i?.verbose);let f=or.homedir(),e=Zt.LINUX_CERT_DB_FILENAME;N(F.TRUST,`Searching for certificate databases in ${f}`,i?.verbose);let c=He(f,e);if(c.length===0){oi.warn("No certificate databases found. Cannot remove certificate.");return}for(let l of c){N(F.TRUST,`Processing certificate database in ${l}`,i?.verbose);try{await $i(`certutil -d sql:${l} -D -n "${r}"`),oi.info(`Cert removed from ${l}`)}catch(h){N(F.TRUST,`Error removing cert from ${l}: ${h}`,i?.verbose),console.warn(`Error removing cert from ${l}: ${h}`)}}}},o0={darwin:L0,win32:k0,linux:V0};async function pe(t,i,n){N(F.TRUST,`Adding certificate to system trust store with options: ${vr(n)}`,n?.verbose),N(F.TRUST,"Storing certificate and private key",n?.verbose);let r=_$(t,n);N(F.TRUST,"Storing CA certificate",n?.verbose);let f=U$(i,n),e=or.platform();N(F.TRUST,`Detected platform: ${e}`,n?.verbose);let c=o0[e];if(!c){let l=`Unsupported platform: ${e}`;throw N(F.TRUST,`Error: ${l}`,n?.verbose),Error(l)}return await c.addCertificate(f,n),N(F.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}var ui=null,b0="rpx-root-ca.crt",X0="rpx-root-ca.key";function Z$(t){return{caCertPath:it(t,b0),caKeyPath:it(t,X0)}}async function P0(t,i){try{let[n,r]=await Promise.all([o.readFile(t.caCertPath,"utf8"),o.readFile(t.caKeyPath,"utf8")]);if(!n.includes("-----BEGIN CERTIFICATE-----")||!r.includes("PRIVATE KEY-----"))return a("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:n,privateKey:r}}catch(n){return a("ssl",`No existing Root CA at ${t.caCertPath} (${n.code||n}), will create one`,i),null}}function j$(t){let i=new Set;i.add(t);let n=t.split(".");if(n.length>=2)i.add(`*.${n.slice(1).join(".")}`);return Array.from(i)}function H$(t){let n=ic(t).replace(/\*/g,"wildcard"),r=it(vi(),".stacks","ssl"),f=r;if(typeof t?.https==="object")return f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:r,{caCertPath:t.https.caCertPath||it(f,`${n}.ca.crt`),certPath:t.https.certPath||it(f,`${n}.crt`),keyPath:t.https.keyPath||it(f,`${n}.key`)};return{caCertPath:it(f,`${n}.ca.crt`),certPath:it(f,`${n}.crt`),keyPath:it(f,`${n}.key`)}}function W$(t){let i=new Set;if(pr(t))t.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";j$(r).forEach((f)=>i.add(f))});else if(d$(t)){let n=t.to||"rpx.localhost";j$(n).forEach((r)=>i.add(r))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function v0(t){a("ssl","Loading SSL configuration",t.verbose);let i={...Hi,...t};if(t.https=mi(i),!t.https?.keyPath&&!t.https?.certPath)return a("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let n=!t.https?.keyPath?"keyPath":"certPath";throw a("ssl",`Invalid SSL configuration - missing ${n}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${n}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{a("ssl","Reading SSL certificate files",t.verbose);let n=await o.readFile(t.https?.keyPath,"utf8"),r=await o.readFile(t.https?.certPath,"utf8");return a("ssl","SSL configuration loaded successfully",t.verbose),{key:n,cert:r}}catch(n){return a("ssl",`Failed to read certificates: ${n}`,t.verbose),null}}catch(n){throw a("ssl",`SSL configuration error: ${n}`,t.verbose),n}}async function p0(t){if(zt.platform==="darwin")return Q0(t);if(zt.platform==="linux")try{let{exec:i}=await import("node:child_process");return await new Promise((n)=>{i(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(r)=>{if(!r)n(!0);else i(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(f)=>{n(!f)})})})}catch{return!1}return!1}async function Q0(t){if(zt.platform!=="darwin")return!1;try{if(await Pi(t,{verbose:!1,regenerateUntrustedCerts:!0}))return a("ssl","Certificate is already trusted, skipping trust operation",!1),!0;a("ssl","Trusting certificate via macOS security command",!1);let n=it(vi(),"Library/Keychains/login.keychain-db");try{if(wi(`security add-trusted-cert -d -r trustRoot -p ssl -p basic -k "${n}" "${t}"`,{stdio:"ignore"}),await Pi(t,{verbose:!1,regenerateUntrustedCerts:!0}))return!0}catch{}try{return tc(`security add-trusted-cert -d -r trustRoot -p ssl -p basic -k /Library/Keychains/System.keychain "${t}"`),await Pi(t,{verbose:!1,regenerateUntrustedCerts:!0})}catch{return!1}}catch{return!1}}async function pi(t){if(ui&&!t.forceRegenerate){a("ssl","Using cached SSL configuration",t.verbose);return}M$();let i=pr(t)?t.proxies.map((s)=>s.to):[t.to];a("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let n=mi(t,t.verbose),r=n.basePath||it(vi(),".stacks","ssl");await o.mkdir(r,{recursive:!0});let f=Z$(r),e=await P0(f,t.verbose),c=!1;if(!e){if(t.verbose)S.info("Generating Root CA certificate (one-time)...");e=await Pe(n);try{await Promise.all([o.writeFile(f.caCertPath,e.certificate),o.writeFile(f.caKeyPath,e.privateKey,{mode:384})]),c=!0,a("ssl",`Persisted Root CA at ${f.caCertPath}`,t.verbose)}catch(s){throw a("ssl",`Error saving Root CA files: ${s}`,t.verbose),Error(`Failed to save Root CA files: ${s}`)}}else a("ssl",`Reusing existing Root CA from ${f.caCertPath}`,t.verbose);if(t.verbose)S.info(`Generating host certificate for: ${i.join(", ")}`);let l=await ve({...n,rootCA:{certificate:e.certificate,privateKey:e.privateKey}});try{await Promise.all([o.writeFile(n.certPath,l.certificate),o.writeFile(n.keyPath,l.privateKey),o.writeFile(n.caCertPath,e.certificate)]),a("ssl","Certificate files saved successfully",t.verbose)}catch(s){throw a("ssl",`Error saving certificate files: ${s}`,t.verbose),Error(`Failed to save certificate files: ${s}`)}if(c?!1:await Pi(f.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(a("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)S.success("Root CA is already trusted in system trust store");if(ui={key:l.privateKey,cert:l.certificate,ca:e.certificate},t.verbose)S.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)S.info("Adding certificate to system trust store (may require sudo permission)...");let $=!1;if(zt.platform==="darwin")try{if(tc(`security add-trusted-cert -d -r trustRoot -p ssl -p basic -k /Library/Keychains/System.keychain "${f.caCertPath}"`),t.verbose)S.success("Successfully added Root CA to system trust store");$=!0;let s=it(r,"trust-rpx-cert.sh"),u=`#!/bin/bash
|
|
124
|
+
`}function hc(){return Pi.randomBytes(20)}function K$(t=2048){let{privateKey:i,publicKey:n}=Pi.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:n}}function ra(t){let i=t.export({type:"spki",format:"der"});return Pi.createHash("sha1").update(i).digest()}function q$(t){let i={serialNumber:t.serialNumber||hc(),notBefore:t.notBefore,notAfter:t.notAfter,subject:t.subject,issuer:t.issuer||t.subject,publicKey:t.publicKey,extensions:{basicConstraints:{isCA:t.isCA??!1,critical:!0,pathLenConstraint:t.pathLenConstraint},subjectKeyIdentifier:ra(t.publicKey)}};if(t.keyUsage)i.extensions.keyUsage={...t.keyUsage,critical:!0};if(t.extendedKeyUsage)i.extensions.extendedKeyUsage=t.extendedKeyUsage;if(t.subjectAltName?.length)i.extensions.subjectAltName=t.subjectAltName;let n=ta(i),r=ia(n,t.signingKey);return{certificate:na(r,"CERTIFICATE"),certificateDer:r}}function x$(t){return t.export({type:"pkcs8",format:"pem"})}function fa(t){return Pi.createPrivateKey(t)}function ea(t){let i=new Pi.X509Certificate(t),n=i.publicKey,r=[],f=i.subject.split(`
|
|
125
|
+
`);for(let e of f){let[c,...h]=e.split("="),l=h.join("=");if(c&&l)r.push({shortName:c.trim(),value:l.trim()})}return{publicKey:n,subject:r}}async function $c(t={}){C("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||Zt.DEFAULT_KEY_SIZE;C("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:n,publicKey:r}=K$(i),f=[{shortName:"C",value:t.countryName||V.countryName},{shortName:"ST",value:t.stateName||V.stateName},{shortName:"L",value:t.localityName||V.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:e,notAfter:c}=lc({validityYears:t.validityYears||Zt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:h}=q$({serialNumber:hc(),notBefore:e,notAfter:c,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:h,privateKey:x$(n),notBefore:e,notAfter:c}}async function wc(t){if(C("ca","Generating new certificate",t.verbose),C("ca",`Options: ${ef(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=ea(t.rootCA.certificate),n=fa(t.rootCA.privateKey);C("ca",`Generating ${Zt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let r=Zt.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:e}=K$(r),c=t.commonName||Z$(t),h=t.certificateAttributes||[{shortName:"C",value:t.countryName||V.countryName},{shortName:"ST",value:t.stateName||V.stateName},{shortName:"L",value:t.localityName||V.localityName},{shortName:"O",value:t.organizationName||V.organizationName},{shortName:"CN",value:c}],{notBefore:l,notAfter:$}=lc({validityDays:t.validityDays||Zt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),w=H$(t),s=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},y=t.extKeyUsage||{serverAuth:!0},{certificate:u}=q$({serialNumber:hc(),notBefore:l,notAfter:$,subject:h,issuer:i,publicKey:e,signingKey:n,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:s,extendedKeyUsage:y,subjectAltName:w});return{certificate:u,privateKey:x$(f),notBefore:l,notAfter:$}}function O$(t,i){C(F.STORAGE,`Storing certificate and private key with options: ${ef(i)}`,i?.verbose);let{certPath:n,keyPath:r}=cc({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});C(F.STORAGE,`Certificate path: ${n}`,i?.verbose),C(F.STORAGE,`Private key path: ${r}`,i?.verbose);let f=Xe.dirname(n);if(!Qt.existsSync(f))C(F.STORAGE,`Creating certificate directory: ${f}`,i?.verbose),Qt.mkdirSync(f,{recursive:!0});C(F.STORAGE,"Writing certificate file",i?.verbose),Qt.writeFileSync(n,t.certificate);let e=Xe.dirname(r);if(!Qt.existsSync(e))C(F.STORAGE,`Creating private key directory: ${e}`,i?.verbose),Qt.mkdirSync(e,{recursive:!0});return C(F.STORAGE,"Writing private key file",i?.verbose),Qt.writeFileSync(r,t.privateKey),C(F.STORAGE,"Certificate and private key stored successfully",i?.verbose),n}function D$(t,i){C(F.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:n}=cc({basePath:i?.basePath,caCertPath:i?.caCertPath});C(F.STORAGE,`CA certificate path: ${n}`,i?.verbose);let r=Xe.dirname(n);if(!Qt.existsSync(r))C(F.STORAGE,`Creating CA certificate directory: ${r}`,i?.verbose),Qt.mkdirSync(r,{recursive:!0});return C(F.STORAGE,"Writing CA certificate file",i?.verbose),Qt.writeFileSync(n,t),C(F.STORAGE,"CA certificate stored successfully",i?.verbose),n}async function ca(t,i){if(Qr.platform()!=="darwin")return!1;try{let n=gh(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!n)return C(F.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(gh("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(n))return C(F.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return C(F.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(n){return C(F.TRUST,`Error checking certificate trust: ${n}`,i),!1}}var la={platform:"darwin",async addCertificate(t,i){if(await ca(t,i?.verbose)){C(F.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),gi.success("Certificate is already trusted in system keychain");return}C(F.TRUST,"Adding certificate to macOS keychain",i?.verbose),await wi(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,n){let r=n||V.commonName;C(F.TRUST,`Removing certificate ${r} from macOS keychain`,i?.verbose);try{await wi(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),C(F.TRUST,`Removed certificate ${r} from macOS keychain`,i?.verbose)}catch(f){throw C(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},ha={platform:"win32",async addCertificate(t,i){C(F.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await wi(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,n){let r=n||V.commonName;C(F.TRUST,`Removing certificate ${r} from Windows certificate store`,i?.verbose);try{await wi(`certutil -delstore -enterprise Root "${r}"`),C(F.TRUST,`Removed certificate ${r} from Windows certificate store`,i?.verbose)}catch(f){throw C(F.TRUST,`Error removing certificate: ${f}`,i?.verbose),f}}},$a={platform:"linux",async addCertificate(t,i){C(F.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let n=Qr.homedir(),r=Zt.LINUX_CERT_DB_FILENAME,f=Zt.LINUX_TRUST_ARGS;C(F.TRUST,`Searching for certificate databases in ${n}`,i?.verbose);let e=ge(n,r);if(e.length===0){gi.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of e){C(F.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{C(F.TRUST,`Attempting to delete existing cert for ${V.commonName}`,i?.verbose),await wi(`certutil -d sql:${c} -D -n ${V.commonName}`)}catch(h){C(F.TRUST,`Warning: Error deleting existing cert: ${h}`,i?.verbose),console.warn(`Error deleting existing cert: ${h}`)}C(F.TRUST,`Adding new certificate to ${c}`,i?.verbose),await wi(`certutil -d sql:${c} -A -t ${f} -n ${V.commonName} -i ${t}`),gi.info(`Cert added to ${c}`)}},async removeCertificate(t,i,n){let r=n||V.commonName;C(F.TRUST,`Removing certificate ${r} from Linux certificate store`,i?.verbose);let f=Qr.homedir(),e=Zt.LINUX_CERT_DB_FILENAME;C(F.TRUST,`Searching for certificate databases in ${f}`,i?.verbose);let c=ge(f,e);if(c.length===0){gi.warn("No certificate databases found. Cannot remove certificate.");return}for(let h of c){C(F.TRUST,`Processing certificate database in ${h}`,i?.verbose);try{await wi(`certutil -d sql:${h} -D -n "${r}"`),gi.info(`Cert removed from ${h}`)}catch(l){C(F.TRUST,`Error removing cert from ${h}: ${l}`,i?.verbose),console.warn(`Error removing cert from ${h}: ${l}`)}}}},wa={darwin:la,win32:ha,linux:$a};async function uc(t,i,n){C(F.TRUST,`Adding certificate to system trust store with options: ${ef(n)}`,n?.verbose),C(F.TRUST,"Storing certificate and private key",n?.verbose);let r=O$(t,n);C(F.TRUST,"Storing CA certificate",n?.verbose);let f=D$(i,n),e=Qr.platform();C(F.TRUST,`Detected platform: ${e}`,n?.verbose);let c=wa[e];if(!c){let h=`Unsupported platform: ${e}`;throw C(F.TRUST,`Error: ${h}`,n?.verbose),Error(h)}return await c.addCertificate(f,n),C(F.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{execSync as Nn}from"node:child_process";import{homedir as ua}from"node:os";import{join as sa}from"node:path";import{execSync as cf}from"node:child_process";function sc(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Cn(t){try{let i=cf(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`,{encoding:"utf8"});return sc(i)}catch{return null}}function L$(t){try{return cf(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function k$(t,i){try{let n=cf(`openssl x509 -in "${t}" -noout -text`,{encoding:"utf8"});return i.every((r)=>n.includes(`DNS:${r}`))}catch{return!1}}function V$(t,i,n=443){try{return cf(`echo | openssl s_client -connect ${t}:${n} -servername ${t} -CAfile "${i}" 2>/dev/null | grep "Verify return code"`,{encoding:"utf8",timeout:4000}).includes(": 0 (ok)")}catch{return!1}}function o$(t){let i=[];for(let n of t.split(`
|
|
126
|
+
`)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)i.push(r[1].toUpperCase())}return i}var ii="-d -r trustRoot -p ssl -p basic",si="/Library/Keychains/System.keychain",lf="rpx.localhost";function vi(){return sa(ua(),"Library/Keychains/login.keychain-db")}function hf(){return[si,vi()]}function yc(t,i=lf){let n=Nn(`security find-certificate -a -c "${i}" -Z "${t}" 2>/dev/null || true`,{encoding:"utf8"}),r=[];for(let f of n.split(`
|
|
127
|
+
`)){let e=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(e)r.push(e[1].toUpperCase())}return r}function Jn(t){if(process.platform!=="darwin")return;let i=Cn(t.caPath);if(!i)return;let n=t.commonName??lf,r=t.keychains??hf();for(let f of r)for(let e of yc(f,n)){if(e===i)continue;try{if(f.startsWith("/Library"))Fn(`security delete-certificate -Z ${e} "${f}"`);else Nn(`security delete-certificate -Z ${e} "${f}"`,{stdio:"ignore"});a("ssl",`Removed stale Root CA ${e} from ${f}`,t.verbose)}catch{}}}function pi(t,i,n){if(process.platform!=="darwin")return Qi(t,n);try{let f=Nn(`security verify-cert -c "${t}" -s "${i}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return a("ssl",`verify-cert ${i}: ${f?"trusted":"not trusted"}`,n?.verbose),f}catch{return!1}}function Qi(t,i){let n=Cn(t);if(!n)return!1;for(let r of hf())try{let f=Nn(`security find-certificate -a -Z "${r}" 2>/dev/null || true`,{encoding:"utf8"});for(let e of f.split(`
|
|
128
|
+
`))if(e.toUpperCase().includes("SHA-256")){if(e.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===n)return a("ssl",`Root CA fingerprint found in ${r}`,i?.verbose),!0}}catch{}return!1}function $f(t,i){if(process.platform!=="darwin")return!1;let n=i.serverName;Jn({caPath:t,commonName:i.commonName,verbose:i.verbose});let r=vi();try{Nn(`security add-trusted-cert ${ii} -k "${r}" "${t}"`,{stdio:"ignore"})}catch{}try{Fn(`security add-trusted-cert ${ii} -k ${si} "${t}"`)}catch{return!1}return pi(t,n,{verbose:i.verbose})||Qi(t,{verbose:i.verbose})}var yi=null,aa="rpx-root-ca.crt",Aa="rpx-root-ca.key";function sf(t){return{caCertPath:Q(t,aa),caKeyPath:Q(t,Aa)}}function ma(t){return{certPath:Q(t,"rpx.localhost.crt"),keyPath:Q(t,"rpx.localhost.key"),caCertPath:Q(t,"rpx.localhost.ca.crt"),rootCA:sf(t)}}async function Ea(t,i){try{let[n,r]=await Promise.all([o.readFile(t.caCertPath,"utf8"),o.readFile(t.caKeyPath,"utf8")]);if(!n.includes("-----BEGIN CERTIFICATE-----")||!r.includes("PRIVATE KEY-----"))return a("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:n,privateKey:r}}catch(n){return a("ssl",`No existing Root CA at ${t.caCertPath} (${n.code||n}), will create one`,i),null}}function g$(t){let i=new Set;i.add(t);let n=t.split(".");if(n.length>=2)i.add(`*.${n.slice(1).join(".")}`);return Array.from(i)}function p$(t){let n=Ac(t).replace(/\*/g,"wildcard"),r=Q(uf(),".stacks","ssl"),f=r;if(typeof t?.https==="object")return f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:r,{caCertPath:t.https.caCertPath||Q(f,`${n}.ca.crt`),certPath:t.https.certPath||Q(f,`${n}.crt`),keyPath:t.https.keyPath||Q(f,`${n}.key`)};return{caCertPath:Q(f,`${n}.ca.crt`),certPath:Q(f,`${n}.crt`),keyPath:Q(f,`${n}.key`)}}function b$(t){let i=new Set;if(wf(t))t.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";g$(r).forEach((f)=>i.add(f))});else if(P$(t)){let n=t.to||"rpx.localhost";g$(n).forEach((r)=>i.add(r))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function Ta(t){a("ssl","Loading SSL configuration",t.verbose);let i={...Mi,...t};if(t.https=Ei(i),!t.https?.keyPath&&!t.https?.certPath)return a("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let n=!t.https?.keyPath?"keyPath":"certPath";throw a("ssl",`Invalid SSL configuration - missing ${n}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${n}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{a("ssl","Reading SSL certificate files",t.verbose);let n=await o.readFile(t.https?.keyPath,"utf8"),r=await o.readFile(t.https?.certPath,"utf8");return a("ssl","SSL configuration loaded successfully",t.verbose),{key:n,cert:r}}catch(n){return a("ssl",`Failed to read certificates: ${n}`,t.verbose),null}}catch(n){throw a("ssl",`SSL configuration error: ${n}`,t.verbose),n}}async function Sa(t,i){if(zt.platform==="darwin")return Ra(t,i);if(zt.platform==="linux")try{let{exec:n}=await import("node:child_process");return await new Promise((r)=>{n(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)r(!0);else n(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(e)=>{r(!e)})})})}catch{return!1}return!1}async function Ra(t,i){if(zt.platform!=="darwin")return!1;let n=i?.serverName??"rpx.localhost",r=i?.verbose??!1;try{if(pi(t,n,{verbose:r}))return a("ssl","Root CA already trusted for SSL, skipping trust operation",r),!0;return a("ssl","Trusting Root CA for browsers (login + system keychains)",r),$f(t,{serverName:n,verbose:r})}catch{return!1}}async function nn(t){if(yi&&!t.forceRegenerate){a("ssl","Using cached SSL configuration",t.verbose);return}Q$();let i=wf(t)?t.proxies.map((w)=>w.to):[t.to];a("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let n=Ei(t,t.verbose),r=n.basePath||Q(uf(),".stacks","ssl");await o.mkdir(r,{recursive:!0});let f=sf(r),e=await Ea(f,t.verbose),c=!1;if(!e){if(t.verbose)S.info("Generating Root CA certificate (one-time)...");e=await $c(n);try{await Promise.all([o.writeFile(f.caCertPath,e.certificate),o.writeFile(f.caKeyPath,e.privateKey,{mode:384})]),c=!0,a("ssl",`Persisted Root CA at ${f.caCertPath}`,t.verbose)}catch(w){throw a("ssl",`Error saving Root CA files: ${w}`,t.verbose),Error(`Failed to save Root CA files: ${w}`)}}else a("ssl",`Reusing existing Root CA from ${f.caCertPath}`,t.verbose);if(t.verbose)S.info(`Generating host certificate for: ${i.join(", ")}`);let h=await wc({...n,rootCA:{certificate:e.certificate,privateKey:e.privateKey}});try{await Promise.all([o.writeFile(n.certPath,h.certificate),o.writeFile(n.keyPath,h.privateKey),o.writeFile(n.caCertPath,e.certificate)]),a("ssl","Certificate files saved successfully",t.verbose)}catch(w){throw a("ssl",`Error saving certificate files: ${w}`,t.verbose),Error(`Failed to save certificate files: ${w}`)}if(c?!1:await Ec(f.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(a("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)S.success("Root CA is already trusted in system trust store");if(yi={key:h.privateKey,cert:h.certificate,ca:e.certificate},t.verbose)S.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)S.info("Adding certificate to system trust store (may require sudo permission)...");let $=!1;if(zt.platform==="darwin")try{Jn({caPath:f.caCertPath,verbose:t.verbose});let w=vi();try{tn(`security add-trusted-cert ${ii} -k "${w}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Fn(`security add-trusted-cert ${ii} -k ${si} "${f.caCertPath}"`),t.verbose)S.success("Successfully added Root CA to system trust store");$=!0;let s=Q(r,"trust-rpx-cert.sh"),y=`#!/bin/bash
|
|
126
129
|
echo "Trusting RPX Root CA"
|
|
127
|
-
sudo security add-trusted-cert
|
|
130
|
+
sudo security add-trusted-cert ${ii} -k ${si} "${f.caCertPath}"
|
|
128
131
|
echo "Root CA trusted! Please restart your browser."
|
|
129
132
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
130
|
-
`;await o.writeFile(s,
|
|
133
|
+
`;await o.writeFile(s,y,{mode:493})}catch(w){if(t.verbose)S.warn(`Could not add Root CA to trust store automatically: ${w}`);let s=Q(r,"trust-rpx-cert.sh"),y=`#!/bin/bash
|
|
131
134
|
echo "Trusting RPX Root CA"
|
|
132
|
-
sudo security add-trusted-cert
|
|
135
|
+
sudo security add-trusted-cert ${ii} -k ${si} "${f.caCertPath}"
|
|
133
136
|
echo "Root CA trusted! Please restart your browser."
|
|
134
137
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
135
|
-
`;if(await o.writeFile(
|
|
138
|
+
`;if(await o.writeFile(s,y,{mode:493}),t.verbose)S.info(`Created a trust helper script at: ${s}`),S.info(`If you're still having certificate issues, run: sh ${s}`)}else if(zt.platform==="linux")try{let{exec:w}=await import("node:child_process"),s="/usr/local/share/ca-certificates/rpx",y=`
|
|
136
139
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
137
140
|
cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
138
141
|
update-ca-certificates
|
|
139
142
|
echo "RPX Root CA installed. Please restart your browser."
|
|
140
|
-
`,
|
|
143
|
+
`,u=Q(ac.tmpdir(),`rpx-trust-${Date.now()}.sh`);await o.writeFile(u,y,{mode:493}),await new Promise((m)=>{w(`sudo bash "${u}"`,(A)=>{if(A){if(t.verbose)S.warn(`Could not trust certificates: ${A}`);m(!1)}else{if(t.verbose)S.success("Successfully added certificates to system trust store");m(!0)}})}),await o.unlink(u).catch(()=>{}),$=!0}catch(w){if(t.verbose)S.warn(`Failed to trust certificates: ${w}`)}else if(zt.platform==="win32")try{let w=`
|
|
141
144
|
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
|
|
142
145
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
143
146
|
$store.Open("ReadWrite")
|
|
144
147
|
$store.Add($cert)
|
|
145
148
|
$store.Close()
|
|
146
149
|
Write-Host "Root CA trusted successfully!"
|
|
147
|
-
`,u=it(Qe.tmpdir(),"rpx-trust.ps1");if(await o.writeFile(u,s),wi(`powershell -ExecutionPolicy Bypass -File "${u}"`),t.verbose)S.success("Successfully added certificate to Windows trust store");$=!0}catch(s){if(t.verbose)S.warn(`Could not trust certificate: ${s}`)}else try{await pe(l,e.certificate,n),$=!0}catch(s){if(t.verbose)S.warn(`Could not add certificate to trust store: ${s}`)}if(ui={key:l.privateKey,cert:l.certificate,ca:e.certificate},t.verbose)S.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!$&&t.verbose)S.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),S.warn("This will bypass the warning and you should only need to do it once")}function M$(){ui=null}async function ii(t){if(!t)return null;if(ui)return ui;let i=mi(t);try{let[n,r,f]=await Promise.all([o.access(i.keyPath).then(()=>!0).catch(()=>!1),o.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?o.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!n||!r)return a("ssl",`Certificate files don't exist: key=${n}, cert=${r}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let e="regenerateUntrustedCerts"in t,c=t.regenerateUntrustedCerts,l=e?c!==!1:!0;a("ssl",`Trust check: hasFlag=${e}, flagValue=${c}, shouldCheckTrust=${l}`,t.verbose);let h=i.basePath||it(vi(),".stacks","ssl"),$=Z$(h);if(!(l?await Pi($.caCertPath,t):!0))return a("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[u,y,w]=await Promise.all([o.readFile(i.keyPath,"utf8"),o.readFile(i.certPath,"utf8"),f&&i.caCertPath?o.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(w&&!w.includes("-----BEGIN CERTIFICATE-----"))return a("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(pr(t))try{let{X509Certificate:m}=await import("node:crypto"),T=new m(y).subjectAltName||"",R=t.proxies.map((J)=>J.to).filter((J)=>!T.includes(`DNS:${J}`));if(R.length>0)return a("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,t.verbose),null}catch(m){a("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return a("ssl","Successfully loaded existing certificates",t.verbose),ui={key:u,cert:y,ca:w},ui}catch(n){return a("ssl",`Error checking existing certificates: ${n}`,t.verbose),null}}function mi(t,i){let n=ic(t);a("ssl",`Primary domain: ${n}`,i);let r=H$(t),f=it(vi(),".stacks","ssl");if(typeof t.https==="object"){let e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:f,c={domain:n,hostCertCN:n,basePath:e,caCertPath:t.https.caCertPath||r.caCertPath,certPath:t.https.certPath||r.certPath,keyPath:t.https.keyPath||r.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||n,organizationName:t.https.organizationName||"Local Development",countryName:t.https.countryName||"US",stateName:t.https.stateName||"California",localityName:t.https.localityName||"Playa Vista",validityDays:t.https.validityDays||825,verbose:i||!1,subjectAltNames:Array.from(W$(t)).map((l)=>({type:2,value:l}))};if(Y$(t.https.rootCA))c.rootCA=t.https.rootCA;return c}return{domain:n,hostCertCN:n,basePath:f,...r,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:n,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(W$(t)).map((e)=>({type:2,value:e}))}}async function nc(t,i){let n=H$({to:t,verbose:i}),r=[n.caCertPath,n.certPath,n.keyPath];a("certificates","Attempting to clean up relating certificates",i),await Promise.all(r.map((f)=>I$(f,i)))}async function Pi(t,i){try{if(a("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),zt.platform==="darwin")try{let n=wi(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim(),r=(c)=>c.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase(),f=r(n);if(!f)return a("ssl","Could not extract certificate fingerprint",i?.verbose),!1;let e=["/Library/Keychains/System.keychain",it(vi(),"Library/Keychains/login.keychain-db")];for(let c of e)try{let l=wi(`security find-certificate -a -Z "${c}" 2>/dev/null || true`).toString();for(let h of l.split(`
|
|
148
|
-
`))if(
|
|
149
|
-
`)}finally{await r.close()}return i}catch(r){if(r.code!=="EEXIST")throw r}let n=await nn(t);if(n!==null&&ri(n))throw Error(`rpx daemon already running (pid=${n})`);await Kt.unlink(i).catch(()=>{})}}async function tn(t=fi()){await Kt.unlink(ff(t)).catch(()=>{})}function ca(t){return{sourceHost:new URL(t.from.startsWith("http")?t.from:`http://${t.from}`).host,cleanUrls:t.cleanUrls??!1,changeOrigin:t.changeOrigin??!1,pathRewrites:t.pathRewrites}}function ha(t){return t.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??t[0]??"rpx.localhost"}async function la(t,i){let n=await Ei(i,t.verbose),r=[...new Set(n.map((s)=>s.to))],f=ha(r),e=[...new Set([f,...r,"rpx.localhost"])],c=Gt.join(q$(),".stacks","ssl"),l=Gt.join(c,"rpx.localhost.crt"),h={https:typeof t.https==="object"?{...t.https,certPath:l,keyPath:Gt.join(c,"rpx.localhost.key"),commonName:f}:{certPath:l,keyPath:Gt.join(c,"rpx.localhost.key"),caCertPath:Gt.join(c,"rpx.localhost.ca.crt"),commonName:f},verbose:t.verbose,regenerateUntrustedCerts:!0,...e.length>1?{proxies:e.map((s)=>({from:"localhost:1",to:s}))}:{to:f,from:"localhost:1"}},$=await ii(h);if(!$)a("daemon","no usable cert on disk, generating one",t.verbose),await pi(h),$=await ii(h);if(!$)throw Error("failed to bootstrap TLS for rpx daemon");return $}async function $a(t={}){let i=t.verbose??!1,n=t.rpxDir??fi(),r=t.registryDir??Gt.join(n,"registry.d"),f=t.httpsPort??443,e=t.httpPort??80,c=t.hostname??"0.0.0.0",l=t.gcIntervalMs??fa,h=await x$(n),$=new Map,s=(B)=>$.get(B);function u(B){let $t=new Map;for(let mt of B)$t.set(mt.to,ca(mt));$=$t,a("daemon",`routing table now covers ${$t.size} host(s): ${Array.from($t.keys()).join(", ")||"<empty>"}`,i)}await rf(r,i).catch((B)=>{a("daemon",`initial gc failed: ${B}`,i)}),u(await Ei(r,i));let y=await la(t,r),w=Bun.serve({port:f,hostname:c,tls:{key:y.key,cert:y.cert,ca:y.ca,requestCert:!1,rejectUnauthorized:!1},fetch:Sn(s,i),error(B){return a("daemon",`https server error: ${B}`,i),new Response(`Server Error: ${B.message}`,{status:500})}}),m=null;if(e>0)m=Bun.serve({port:e,hostname:c,fetch(B){let $t=new URL(B.url),mt=(B.headers.get("host")??$t.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${mt}${$t.pathname}${$t.search}`}})}});if(i)S.success(`rpx daemon listening on https://${c}:${f}${m?` (http→https on :${e})`:""}`),S.info(`pid file: ${h}`),S.info(`registry: ${r}`);let A=cc((B)=>{u(B)},{dir:r,verbose:i}),T=setInterval(()=>{rf(r,i).then((B)=>{if(B>0)a("daemon",`gc reaped ${B} stale entries`,i)}).catch((B)=>{a("daemon",`periodic gc failed: ${B}`,i)})},l);if(typeof T.unref==="function")T.unref();let E=!1,R,J=new Promise((B)=>{R=B});async function C(){if(E)return J;if(E=!0,clearInterval(T),A.close(),w.stop(!1),m?.stop(!1),await tn(n),i)S.info("rpx daemon stopped");return R(),J}let j=(B)=>{a("daemon",`received ${B}, shutting down`,i),C().catch(()=>{})};return nt.once("SIGINT",j),nt.once("SIGTERM",j),{stop:C,done:J,httpsPort:typeof w.port==="number"?w.port:f,httpPort:m&&typeof m.port==="number"?m.port:e,pidPath:h}}function D$(){let t=nt.execPath,i=Gt.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&nt.argv[1])return[t,nt.argv[1],"daemon:start"];return[t,"daemon:start"]}async function hc(t={}){let i=t.rpxDir??fi(),n=t.verbose??!1,r=await nn(i);if(r!==null&&ri(r))return a("daemon",`ensureDaemonRunning: already running pid=${r}`,n),{pid:r,spawned:!1};if(r!==null)a("daemon",`ensureDaemonRunning: clearing stale pid=${r}`,n),await tn(i);await Kt.mkdir(i,{recursive:!0});let f=t.spawnCommand??D$();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");a("daemon",`spawning daemon: ${f.join(" ")}`,n);let e=ra(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??nt.cwd(),env:t.spawnEnv?{...nt.env,...t.spawnEnv}:nt.env});e.unref();let c=null;e.once("error",(s)=>{c=s});let l=t.startupTimeoutMs??5000,h=t.pollIntervalMs??50,$=Date.now()+l;while(Date.now()<$){if(c)throw c;let s=await nn(i);if(s!==null&&ri(s))return a("daemon",`daemon registered with pid=${s}`,n),{pid:s,spawned:!0};await new Promise((u)=>setTimeout(u,h))}if(c)throw c;throw Error(`rpx daemon failed to start within ${l}ms (rpxDir=${i})`)}async function sa(t={}){let i=t.rpxDir??fi(),n=t.verbose??!1,r=t.timeoutMs??5000,f=t.pollIntervalMs??50,e=t.forceAfterTimeout??!0,c=await nn(i);if(c===null||!ri(c)){if(c!==null)await tn(i);return{stopped:!1,pid:c,forced:!1}}try{nt.kill(c,"SIGTERM")}catch(h){if(h.code==="ESRCH")return await tn(i),{stopped:!1,pid:c,forced:!1};throw h}let l=Date.now()+r;while(Date.now()<l){if(!ri(c))return a("daemon",`daemon pid=${c} stopped cleanly`,n),{stopped:!0,pid:c,forced:!1};await new Promise((h)=>setTimeout(h,f))}if(!e)throw Error(`rpx daemon (pid=${c}) did not exit within ${r}ms`);a("daemon",`daemon pid=${c} did not exit, escalating to SIGKILL`,n);try{nt.kill(c,"SIGKILL")}catch(h){if(h.code!=="ESRCH")throw h}return await tn(i),{stopped:!0,pid:c,forced:!0}}function k$(t){let i=t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return i.length>0?i:"rpx"}async function ef(t){if(t.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let i=t.verbose??!1,n=t.registryDir,r=new Set,f=t.proxies.map((y)=>{let w=y.id??k$(y.to);if(!Qi(w))throw Error(`invalid registry id "${w}" derived from to="${y.to}"`);if(r.has(w))throw Error(`duplicate registry id "${w}" — set an explicit \`id\` on one of the proxies`);return r.add(w),{...y,id:w}}),e=new Date().toISOString();for(let y of f)await ec({id:y.id,from:y.from,to:y.to,pid:t.persistent?void 0:qt.pid,cwd:qt.cwd(),createdAt:e,cleanUrls:y.cleanUrls,changeOrigin:y.changeOrigin,pathRewrites:y.pathRewrites},n,i);let c=await hc({rpxDir:t.rpxDir,verbose:i,spawnCommand:t.spawnCommand,startupTimeoutMs:t.startupTimeoutMs,spawnEnv:t.spawnEnv});for(let y of f)S.success(`https://${y.to} → ${y.from}`);if(S.info(`(via rpx daemon pid=${c.pid}; \`rpx daemon:status\` to inspect)`),t.detached)return;let l=!1,h=n??ni(),$=f.map((y)=>y.id),s=async()=>{if(l)return;l=!0;for(let y of $)await nf(y,n,i).catch((w)=>{a("runner",`removeEntry(${y}) failed: ${w}`,i)})},u=(y)=>{a("runner",`received ${y}, unregistering ${$.length} entries`,i),s().finally(()=>qt.exit(0))};qt.once("SIGINT",u),qt.once("SIGTERM",u),qt.once("exit",()=>{if(l)return;for(let y of $)try{O$.unlinkSync(L$.join(h,`${y}.json`))}catch{}}),await new Promise(()=>{})}import{exec as wa}from"node:child_process";import Ti from"node:fs";import V$ from"node:os";import $c from"node:path";import*as Bn from"node:process";import{promisify as ua}from"node:util";var cf=ua(wa),Ut=Bn.platform==="win32"?$c.join(Bn.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",lc=!1;async function hf(t){if(Bn.platform==="win32")throw Error("Administrator privileges required on Windows");let i=Rn(),n=t.replace(/'/g,"'\\''");try{if(i){let{stdout:f}=await cf(`echo '${i}' | sudo -S sh -c '${n}' 2>/dev/null`);return lc=!0,f}if(lc)try{let{stdout:f}=await cf(`sudo -n sh -c '${n}'`);return f}catch(f){a("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:r}=await cf(`sudo sh -c '${n}'`);return lc=!0,r}catch(r){throw Error(`Failed to execute sudo command: ${r.message}`)}}async function rn(t,i){a("hosts",`Adding hosts: ${t.join(", ")}`,i),a("hosts",`Using hosts file at: ${Ut}`,i);try{let n;try{n=await Ti.promises.readFile(Ut,"utf-8")}catch{a("hosts","Reading hosts file requires elevated permissions, using sudo",i);try{n=await hf(`cat "${Ut}"`)}catch(c){throw console.log(" Could not read hosts file — skipping hosts setup"),a("hosts",`sudo read also failed: ${c}`,i),Error(`Cannot read hosts file: ${c}`)}}let r=t.filter((c)=>{let l=`127.0.0.1 ${c}`,h=`::1 ${c}`;return!n.includes(l)&&!n.includes(h)});if(r.length===0){a("hosts","All hosts already exist in hosts file",i);return}let f=r.map((c)=>`
|
|
150
|
+
`,s=Q(ac.tmpdir(),"rpx-trust.ps1");if(await o.writeFile(s,w),tn(`powershell -ExecutionPolicy Bypass -File "${s}"`),t.verbose)S.success("Successfully added certificate to Windows trust store");$=!0}catch(w){if(t.verbose)S.warn(`Could not trust certificate: ${w}`)}else try{await uc(h,e.certificate,n),$=!0}catch(w){if(t.verbose)S.warn(`Could not add certificate to trust store: ${w}`)}if(yi={key:h.privateKey,cert:h.certificate,ca:e.certificate},t.verbose)S.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!$&&t.verbose)S.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),S.warn("This will bypass the warning and you should only need to do it once")}function Q$(){yi=null}async function ni(t){if(!t)return null;if(yi)return yi;let i=Ei(t);try{let[n,r,f]=await Promise.all([o.access(i.keyPath).then(()=>!0).catch(()=>!1),o.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?o.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!n||!r)return a("ssl",`Certificate files don't exist: key=${n}, cert=${r}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let e="regenerateUntrustedCerts"in t,c=t.regenerateUntrustedCerts,h=e?c!==!1:!0;a("ssl",`Trust check: hasFlag=${e}, flagValue=${c}, shouldCheckTrust=${h}`,t.verbose);let l=i.basePath||Q(uf(),".stacks","ssl"),$=sf(l);if(!(h?await Ec($.caCertPath,t):!0))return a("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[s,y,u]=await Promise.all([o.readFile(i.keyPath,"utf8"),o.readFile(i.certPath,"utf8"),f&&i.caCertPath?o.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(u&&!u.includes("-----BEGIN CERTIFICATE-----"))return a("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(wf(t))try{let{X509Certificate:m}=await import("node:crypto"),T=new m(y).subjectAltName||"",R=t.proxies.map((N)=>N.to).filter((N)=>!T.includes(`DNS:${N}`));if(R.length>0)return a("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,t.verbose),null}catch(m){a("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return a("ssl","Successfully loaded existing certificates",t.verbose),yi={key:s,cert:y,ca:u},yi}catch(n){return a("ssl",`Error checking existing certificates: ${n}`,t.verbose),null}}function Ei(t,i){let n=Ac(t);a("ssl",`Primary domain: ${n}`,i);let r=p$(t),f=Q(uf(),".stacks","ssl");if(typeof t.https==="object"){let e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:f,c={domain:n,hostCertCN:n,basePath:e,caCertPath:t.https.caCertPath||r.caCertPath,certPath:t.https.certPath||r.certPath,keyPath:t.https.keyPath||r.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||n,organizationName:t.https.organizationName||"Local Development",countryName:t.https.countryName||"US",stateName:t.https.stateName||"California",localityName:t.https.localityName||"Playa Vista",validityDays:t.https.validityDays||825,verbose:i||!1,subjectAltNames:Array.from(b$(t)).map((h)=>({type:2,value:h}))};if(X$(t.https.rootCA))c.rootCA=t.https.rootCA;return c}return{domain:n,hostCertCN:n,basePath:f,...r,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:n,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(b$(t)).map((e)=>({type:2,value:e}))}}async function mc(t,i){let n=p$({to:t,verbose:i}),r=[n.caCertPath,n.certPath,n.keyPath];a("certificates","Attempting to clean up relating certificates",i),await Promise.all(r.map((f)=>v$(f,i)))}async function Ec(t,i){try{if(a("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),zt.platform==="darwin"){if(i?.serverName)return pi(t,i.serverName,{verbose:i.verbose});return Qi(t,{verbose:i.verbose})}else if(zt.platform==="win32")try{let r=tn(`openssl x509 -noout -subject -in "${t}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!r)return a("ssl","Could not extract certificate subject",i?.verbose),!1;let f=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(tn(f).toString().includes(r))return a("ssl","Certificate found in trusted root store",i?.verbose),!0;return a("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(n){return a("ssl",`Error checking certificate trust on Windows: ${n}`,i?.verbose),!1}else if(zt.platform==="linux")try{let r=tn(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"",f=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let e of f)try{if(tn(`find ${e} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${r}"`).toString().includes(r))return a("ssl",`Certificate fingerprint found in ${e}`,i?.verbose),!0}catch{}return a("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(n){return a("ssl",`Error checking certificate trust on Linux: ${n}`,i?.verbose),!1}return a("ssl",`Platform ${zt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(n){return a("ssl",`Error checking if certificate is trusted: ${n}`,i?.verbose),!1}}function _n(t,i){return async(n)=>{let r=new URL(n.url),e=(n.headers.get("host")||"").split(":")[0],c=t(e);if(!c)return a("request",`No route found for host: ${e}`,i),new Response(`No proxy configured for ${e}`,{status:404});let h=c.sourceHost,l=r.pathname,$=tw(r.pathname,c.pathRewrites);if($)h=$.targetHost,l=$.targetPath,a("request",`Path rewrite: ${r.pathname} → ${h}${l}`,i);let w=`http://${h}${l}${r.search}`;try{let s=new Headers(n.headers);if(s.set("host",h),c.changeOrigin)s.set("origin",`http://${c.sourceHost}`);s.set("x-forwarded-for","127.0.0.1"),s.set("x-forwarded-proto","https"),s.set("x-forwarded-host",e);let y=await fetch(w,{method:n.method,headers:s,body:n.body,redirect:"manual"});if(c.cleanUrls&&r.pathname.endsWith(".html")){let m=r.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let u=new Headers(y.headers);return new Response(y.body,{status:y.status,statusText:y.statusText,headers:u})}catch(s){return a("request",`Proxy error for ${e}: ${s}`,i),new Response(`Proxy Error: ${s}`,{status:502})}}}import*as yf from"node:fs";import*as At from"node:fs/promises";import{homedir as Ba}from"node:os";import*as Tc from"node:path";import*as af from"node:process";var Ca=/^[a-zA-Z0-9._-]+$/;function ri(){return Tc.join(Ba(),".stacks","rpx","registry.d")}function rn(t){return typeof t==="string"&&t.length>0&&t.length<=128&&Ca.test(t)}function Sc(t,i){if(!rn(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return Tc.join(t,`${i}.json`)}function fi(t){if(!Number.isInteger(t)||t<=0)return!1;try{return af.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function iw(t){if(!t||typeof t!=="object")return!1;let i=t,n=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0;return typeof i.id==="string"&&rn(i.id)&&typeof i.from==="string"&&i.from.length>0&&typeof i.to==="string"&&i.to.length>0&&n&&typeof i.createdAt==="string"}async function Fa(t){await At.mkdir(t,{recursive:!0})}async function Rc(t,i=ri(),n){if(!iw(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await Fa(i);let r=Sc(i,t.id),f=`${r}.tmp.${af.pid}.${Date.now()}`,e=JSON.stringify(t,null,2);try{await At.writeFile(f,e,{encoding:"utf8",mode:420}),await At.rename(f,r),a("registry",`wrote entry ${t.id} → ${r}`,n)}catch(c){throw await At.unlink(f).catch(()=>{}),c}}async function Af(t,i=ri(),n){let r=Sc(i,t);try{await At.unlink(r),a("registry",`removed entry ${t}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function nw(t,i=ri(),n){let r=Sc(i,t);try{let f=await At.readFile(r,"utf8"),e=JSON.parse(f);if(!iw(e))return a("registry",`entry ${t} failed validation, removing`,n),await At.unlink(r).catch(()=>{}),null;return e}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return a("registry",`entry ${t} has invalid JSON, removing`,n),await At.unlink(r).catch(()=>{}),null;throw f}}async function Ti(t=ri(),i){let n;try{n=await At.readdir(t)}catch(f){if(f.code==="ENOENT")return[];throw f}let r=[];for(let f of n){if(!f.endsWith(".json"))continue;let e=f.slice(0,-5);if(!rn(e))continue;let c=await nw(e,t,i);if(c)r.push(c)}return r}async function mf(t=ri(),i){let n=await Ti(t,i),r=0;for(let f of n){if(f.pid===void 0)continue;if(!fi(f.pid))a("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,i),await Af(f.id,t,i).catch(()=>{}),r++}return r}function Bc(t,i={}){let n=i.dir??ri(),r=i.debounceMs??100,f=i.pollMs??Math.max(r*2,250),e=i.verbose;yf.mkdirSync(n,{recursive:!0});let c=null,h=!1,l=null,$=!1,w=(T)=>{return JSON.stringify(T.map((E)=>({id:E.id,from:E.from,to:E.to,pid:E.pid,pathRewrites:E.pathRewrites,cleanUrls:E.cleanUrls,changeOrigin:E.changeOrigin})).sort((E,R)=>E.id.localeCompare(R.id)))},s=()=>{if(c=null,h)return;Ti(n,e).then((T)=>{return l=w(T),t(T)}).catch((T)=>{a("registry",`watcher onChange failed: ${T}`,e)})},y=()=>{if(h)return;if(c)clearTimeout(c);c=setTimeout(s,r)},m=setInterval(()=>{if(h||$)return;$=!0,Ti(n,e).then((T)=>{if(w(T)!==l)y()}).catch((T)=>{a("registry",`watcher poll failed: ${T}`,e)}).finally(()=>{$=!1})},f),A=yf.watch(n,{persistent:!0},(T,E)=>{if(E&&/\.tmp\.\d+\.\d+$/.test(E))return;y()});return A.on("error",(T)=>{a("registry",`watcher error: ${T}`,e)}),y(),{close:()=>{if(h=!0,c)clearTimeout(c);clearInterval(m),A.close()}}}var Ja=5000;function ei(){return Gt.join(rw(),".stacks","rpx")}function Ef(t=ei()){return Gt.join(t,"daemon.pid")}async function en(t=ei()){try{let i=await Kt.readFile(Ef(t),"utf8"),n=Number.parseInt(i.trim(),10);if(!Number.isFinite(n)||n<=0)return null;return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _a(t=ei()){let i=await en(t);return i!==null&&fi(i)}async function fw(t=ei()){await Kt.mkdir(t,{recursive:!0});let i=Ef(t);while(!0){try{let r=await Kt.open(i,"wx");try{await r.write(`${nt.pid}
|
|
151
|
+
`)}finally{await r.close()}return i}catch(r){if(r.code!=="EEXIST")throw r}let n=await en(t);if(n!==null&&fi(n))throw Error(`rpx daemon already running (pid=${n})`);await Kt.unlink(i).catch(()=>{})}}async function fn(t=ei()){await Kt.unlink(Ef(t)).catch(()=>{})}function Ua(t){return{sourceHost:new URL(t.from.startsWith("http")?t.from:`http://${t.from}`).host,cleanUrls:t.cleanUrls??!1,changeOrigin:t.changeOrigin??!1,pathRewrites:t.pathRewrites}}function da(t){return t.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??t[0]??"rpx.localhost"}async function ja(t,i){let n=await Ti(i,t.verbose),r=[...new Set(n.map((w)=>w.to))],f=da(r),e=[...new Set([f,...r,"rpx.localhost"])],c=Gt.join(rw(),".stacks","ssl"),h=Gt.join(c,"rpx.localhost.crt"),l={https:typeof t.https==="object"?{...t.https,certPath:h,keyPath:Gt.join(c,"rpx.localhost.key"),commonName:f}:{certPath:h,keyPath:Gt.join(c,"rpx.localhost.key"),caCertPath:Gt.join(c,"rpx.localhost.ca.crt"),commonName:f},verbose:t.verbose,regenerateUntrustedCerts:!0,...e.length>1?{proxies:e.map((w)=>({from:"localhost:1",to:w}))}:{to:f,from:"localhost:1"}},$=await ni(l);if(!$)a("daemon","no usable cert on disk, generating one",t.verbose),await nn(l),$=await ni(l);if(!$)throw Error("failed to bootstrap TLS for rpx daemon");return $}async function Wa(t={}){let i=t.verbose??!1,n=t.rpxDir??ei(),r=t.registryDir??Gt.join(n,"registry.d"),f=t.httpsPort??443,e=t.httpPort??80,c=t.hostname??"0.0.0.0",h=t.gcIntervalMs??Ja,l=await fw(n),$=new Map,w=(B)=>$.get(B);function s(B){let $t=new Map;for(let mt of B)$t.set(mt.to,Ua(mt));$=$t,a("daemon",`routing table now covers ${$t.size} host(s): ${Array.from($t.keys()).join(", ")||"<empty>"}`,i)}await mf(r,i).catch((B)=>{a("daemon",`initial gc failed: ${B}`,i)}),s(await Ti(r,i));let y=await ja(t,r),u=Bun.serve({port:f,hostname:c,tls:{key:y.key,cert:y.cert,ca:y.ca,requestCert:!1,rejectUnauthorized:!1},fetch:_n(w,i),error(B){return a("daemon",`https server error: ${B}`,i),new Response(`Server Error: ${B.message}`,{status:500})}}),m=null;if(e>0)m=Bun.serve({port:e,hostname:c,fetch(B){let $t=new URL(B.url),mt=(B.headers.get("host")??$t.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${mt}${$t.pathname}${$t.search}`}})}});if(i)S.success(`rpx daemon listening on https://${c}:${f}${m?` (http→https on :${e})`:""}`),S.info(`pid file: ${l}`),S.info(`registry: ${r}`);let A=Bc((B)=>{s(B)},{dir:r,verbose:i}),T=setInterval(()=>{mf(r,i).then((B)=>{if(B>0)a("daemon",`gc reaped ${B} stale entries`,i)}).catch((B)=>{a("daemon",`periodic gc failed: ${B}`,i)})},h);if(typeof T.unref==="function")T.unref();let E=!1,R,N=new Promise((B)=>{R=B});async function J(){if(E)return N;if(E=!0,clearInterval(T),A.close(),u.stop(!1),m?.stop(!1),await fn(n),i)S.info("rpx daemon stopped");return R(),N}let d=(B)=>{a("daemon",`received ${B}, shutting down`,i),J().catch(()=>{})};return nt.once("SIGINT",d),nt.once("SIGTERM",d),{stop:J,done:N,httpsPort:typeof u.port==="number"?u.port:f,httpPort:m&&typeof m.port==="number"?m.port:e,pidPath:l}}function ew(){let t=nt.execPath,i=Gt.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&nt.argv[1])return[t,nt.argv[1],"daemon:start"];return[t,"daemon:start"]}async function Cc(t={}){let i=t.rpxDir??ei(),n=t.verbose??!1,r=await en(i);if(r!==null&&fi(r))return a("daemon",`ensureDaemonRunning: already running pid=${r}`,n),{pid:r,spawned:!1};if(r!==null)a("daemon",`ensureDaemonRunning: clearing stale pid=${r}`,n),await fn(i);await Kt.mkdir(i,{recursive:!0});let f=t.spawnCommand??ew();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");a("daemon",`spawning daemon: ${f.join(" ")}`,n);let e=Na(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??nt.cwd(),env:t.spawnEnv?{...nt.env,...t.spawnEnv}:nt.env});e.unref();let c=null;e.once("error",(w)=>{c=w});let h=t.startupTimeoutMs??5000,l=t.pollIntervalMs??50,$=Date.now()+h;while(Date.now()<$){if(c)throw c;let w=await en(i);if(w!==null&&fi(w))return a("daemon",`daemon registered with pid=${w}`,n),{pid:w,spawned:!0};await new Promise((s)=>setTimeout(s,l))}if(c)throw c;throw Error(`rpx daemon failed to start within ${h}ms (rpxDir=${i})`)}async function Ya(t={}){let i=t.rpxDir??ei(),n=t.verbose??!1,r=t.timeoutMs??5000,f=t.pollIntervalMs??50,e=t.forceAfterTimeout??!0,c=await en(i);if(c===null||!fi(c)){if(c!==null)await fn(i);return{stopped:!1,pid:c,forced:!1}}try{nt.kill(c,"SIGTERM")}catch(l){if(l.code==="ESRCH")return await fn(i),{stopped:!1,pid:c,forced:!1};throw l}let h=Date.now()+r;while(Date.now()<h){if(!fi(c))return a("daemon",`daemon pid=${c} stopped cleanly`,n),{stopped:!0,pid:c,forced:!1};await new Promise((l)=>setTimeout(l,f))}if(!e)throw Error(`rpx daemon (pid=${c}) did not exit within ${r}ms`);a("daemon",`daemon pid=${c} did not exit, escalating to SIGKILL`,n);try{nt.kill(c,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}return await fn(i),{stopped:!0,pid:c,forced:!0}}function hw(t){let i=t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return i.length>0?i:"rpx"}async function Tf(t){if(t.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let i=t.verbose??!1,n=t.registryDir,r=new Set,f=t.proxies.map((y)=>{let u=y.id??hw(y.to);if(!rn(u))throw Error(`invalid registry id "${u}" derived from to="${y.to}"`);if(r.has(u))throw Error(`duplicate registry id "${u}" — set an explicit \`id\` on one of the proxies`);return r.add(u),{...y,id:u}}),e=new Date().toISOString();for(let y of f)await Rc({id:y.id,from:y.from,to:y.to,pid:t.persistent?void 0:qt.pid,cwd:qt.cwd(),createdAt:e,cleanUrls:y.cleanUrls,changeOrigin:y.changeOrigin,pathRewrites:y.pathRewrites},n,i);let c=await Cc({rpxDir:t.rpxDir,verbose:i,spawnCommand:t.spawnCommand,startupTimeoutMs:t.startupTimeoutMs,spawnEnv:t.spawnEnv});for(let y of f)S.success(`https://${y.to} → ${y.from}`);if(S.info(`(via rpx daemon pid=${c.pid}; \`rpx daemon:status\` to inspect)`),t.detached)return;let h=!1,l=n??ri(),$=f.map((y)=>y.id),w=async()=>{if(h)return;h=!0;for(let y of $)await Af(y,n,i).catch((u)=>{a("runner",`removeEntry(${y}) failed: ${u}`,i)})},s=(y)=>{a("runner",`received ${y}, unregistering ${$.length} entries`,i),w().finally(()=>qt.exit(0))};qt.once("SIGINT",s),qt.once("SIGTERM",s),qt.once("exit",()=>{if(h)return;for(let y of $)try{cw.unlinkSync(lw.join(l,`${y}.json`))}catch{}}),await new Promise(()=>{})}import{exec as Ia}from"node:child_process";import Si from"node:fs";import $w from"node:os";import Nc from"node:path";import*as dn from"node:process";import{promisify as Za}from"node:util";var Sf=Za(Ia),Ut=dn.platform==="win32"?Nc.join(dn.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",Fc=!1;async function Rf(t){if(dn.platform==="win32")throw Error("Administrator privileges required on Windows");let i=Un(),n=t.replace(/'/g,"'\\''");try{if(i){let{stdout:f}=await Sf(`echo '${i}' | sudo -S sh -c '${n}' 2>/dev/null`);return Fc=!0,f}if(Fc)try{let{stdout:f}=await Sf(`sudo -n sh -c '${n}'`);return f}catch(f){a("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:r}=await Sf(`sudo sh -c '${n}'`);return Fc=!0,r}catch(r){throw Error(`Failed to execute sudo command: ${r.message}`)}}async function cn(t,i){a("hosts",`Adding hosts: ${t.join(", ")}`,i),a("hosts",`Using hosts file at: ${Ut}`,i);try{let n;try{n=await Si.promises.readFile(Ut,"utf-8")}catch{a("hosts","Reading hosts file requires elevated permissions, using sudo",i);try{n=await Rf(`cat "${Ut}"`)}catch(c){throw console.log(" Could not read hosts file — skipping hosts setup"),a("hosts",`sudo read also failed: ${c}`,i),Error(`Cannot read hosts file: ${c}`)}}let r=t.filter((c)=>{let h=`127.0.0.1 ${c}`,l=`::1 ${c}`;return!n.includes(h)&&!n.includes(l)});if(r.length===0){a("hosts","All hosts already exist in hosts file",i);return}let f=r.map((c)=>`
|
|
150
152
|
# Added by rpx
|
|
151
153
|
127.0.0.1 ${c}
|
|
152
154
|
::1 ${c}`).join(`
|
|
153
|
-
`),e
|
|
154
|
-
`),f=!1,e=r.filter((
|
|
155
|
+
`),e=Nc.join($w.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Si.promises.writeFile(e,n+f,"utf8"),await Rf(`cat "${e}" | tee "${Ut}" > /dev/null`),console.log(` Hosts updated: ${r.join(", ")}`)}catch(c){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),r.forEach((h)=>{console.log(` 127.0.0.1 ${h}`),console.log(` ::1 ${h}`)}),console.log(` Or run: sudo nano ${Ut}`)}finally{try{await Si.promises.unlink(e)}catch{}}}catch(n){a("hosts",`Failed to manage hosts file: ${n.message}`,i)}}async function Jc(t,i){a("hosts",`Removing hosts: ${t.join(", ")}`,i);try{let n;try{n=await Si.promises.readFile(Ut,"utf-8")}catch{a("hosts","Reading hosts file requires elevated permissions, using sudo",i);try{n=await Rf(`cat "${Ut}"`)}catch(l){throw a("hosts",`sudo read also failed: ${l}`,i),Error(`Cannot read hosts file: ${l}`)}}let r=n.split(`
|
|
156
|
+
`),f=!1,e=r.filter((l)=>{if(t.some((w)=>l.includes(` ${w}`)&&(l.includes("127.0.0.1")||l.includes("::1"))))return f=!0,!1;if(l.trim()==="# Added by rpx")return f=!0,!1;return!0});if(!f){a("hosts","No matching hosts found to remove",i);return}while(e[e.length-1]?.trim()==="")e.pop();let c=`${e.join(`
|
|
155
157
|
`)}
|
|
156
|
-
`,l=$c.join(V$.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Ti.promises.writeFile(l,c,"utf8"),await hf(`cat "${l}" | tee "${Ut}" > /dev/null`),a("hosts","Hosts removed successfully",i)}catch(h){a("hosts","Could not clean up hosts file automatically",i)}finally{try{await Ti.promises.unlink(l)}catch(h){a("hosts",`Failed to remove temporary file: ${h}`,i)}}}catch(n){a("hosts",`Failed to clean up hosts file: ${n.message}`,i)}}async function fn(t,i){a("hosts",`Checking hosts: ${t}`,i);let n;try{n=await Ti.promises.readFile(Ut,"utf-8")}catch(r){a("hosts",`Error reading hosts file: ${r}`,i);try{let f=Rn(),e;if(f)e=`echo '${f}' | sudo -S cat "${Ut}" 2>/dev/null`;else e=`sudo -n cat "${Ut}" 2>/dev/null || cat "${Ut}" 2>/dev/null || echo ""`;let{stdout:c}=await cf(e);n=c}catch(f){return a("hosts",`Cannot read hosts file, assuming entries don't exist: ${f}`,i),t.map(()=>!1)}}return t.map((r)=>{let f=`127.0.0.1 ${r}`,e=`::1 ${r}`;return n.includes(f)||n.includes(e)})}import*as lf from"node:net";function yi(t,i,n){return a("port",`Checking if port ${t} is in use on ${i}`,n),new Promise((r)=>{let f=lf.createServer(),e=setTimeout(()=>{a("port",`Checking port ${t} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(c)=>{if(clearTimeout(e),c.code==="EADDRINUSE")a("port",`Port ${t} is in use`,n),r(!0);else a("port",`Error checking port ${t}: ${c.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout(e),a("port",`Port ${t} is available`,n),f.close(),r(!1)});try{f.listen(t,i)}catch(c){clearTimeout(e),a("port",`Exception checking port ${t}: ${c}`,n),r(!0)}})}async function g$(t,i,n,r=50){a("port",`Finding available port starting from ${t} (max attempts: ${r})`,n);let f=t,e=0;while(e<r){if(e++,!await yi(f,i,n))return a("port",`Found available port: ${f} after ${e} attempts`,n),f;a("port",`Port ${f} is in use, trying ${f+1} (attempt ${e}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${t}`)}function o$(t,i,n=5000,r){return a("port",`Testing connection to ${i}:${t}`,r),new Promise((f)=>{let e=lf.connect({host:i,port:t,timeout:n});e.once("connect",()=>{a("port",`Successfully connected to ${i}:${t}`,r),e.end(),f(!0)}),e.once("timeout",()=>{a("port",`Connection to ${i}:${t} timed out`,r),e.destroy(),f(!1)}),e.once("error",(c)=>{a("port",`Failed to connect to ${i}:${t}: ${c.message}`,r),e.destroy(),f(!1)})})}class Nn{usedPorts=new Set;hostname;verbose;maxRetries;constructor(t="0.0.0.0",i,n=50){this.hostname=t,this.verbose=i,this.maxRetries=n}async getNextAvailablePort(t,i=!1){if(this.usedPorts.has(t))return this.findNextAvailablePort(t+1,i);if(await yi(t,this.hostname,this.verbose))return this.findNextAvailablePort(t+1,i);if(i){if(!await o$(t,this.hostname,3000,this.verbose))return a("port",`Port ${t} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(t+1,i)}return this.usedPorts.add(t),t}async findNextAvailablePort(t,i=!1){let n=await g$(t,this.hostname,this.verbose,this.maxRetries);if(i){if(!await o$(n,this.hostname,3000,this.verbose))if(n<t+this.maxRetries)return this.findNextAvailablePort(n+1,i);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(t){a("port",`Releasing port ${t}`,this.verbose),this.usedPorts.delete(t)}}var ya=new Nn;import{spawn as aa}from"node:child_process";import*as Si from"node:process";class $f{processes=new Map;isShuttingDown=!1;async startProcess(t,i,n){if(this.processes.has(t)){a("start",`Process ${t} is already running`,n);return}let[r,...f]=i.command.split(" "),e=i.cwd||Si.cwd();a("start",`Starting process ${t}:`,n),a("start",` Command: ${r} ${f.join(" ")}`,n),a("start",` Working directory: ${e}`,n),a("start",` Environment variables: ${ei(i.env)}`,n);let c=aa(r,f,{cwd:e,env:{...Si.env,...i.env},shell:!0,stdio:"inherit"});return this.processes.set(t,{command:i.command,cwd:e,process:c,env:i.env}),new Promise((l,h)=>{if(c.on("error",($)=>{if(!this.isShuttingDown)a("start",`Process ${t} failed to start: ${$}`,n),this.processes.delete(t),h($),Si.emit("SIGINT")}),c.on("exit",($)=>{if(!this.isShuttingDown&&$!==null&&$!==0)a("start",`Process ${t} exited with code ${$}`,n),this.processes.delete(t),h(Error(`Process ${t} exited with code ${$}`)),Si.emit("SIGINT")}),n)c.stdout?.on("data",($)=>{a("process",`[${t}] ${$.toString().trim()}`,!0)}),c.stderr?.on("data",($)=>{a("process",`[${t}] ERR: ${$.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&c.killed)this.processes.delete(t),h(Error(`Process ${t} was killed during startup`));else a("start",`Process ${t} started successfully`,n),l()},1000)})}async stopProcess(t,i){let n=this.processes.get(t);if(!n?.process){a("start",`No process found for ${t}`,i);return}return a("start",`Stopping process ${t}`,i),new Promise((r)=>{if(!n.process){r();return}n.process.once("exit",()=>{this.processes.delete(t),a("start",`Process ${t} stopped`,i),r()});try{n.process.kill("SIGTERM"),setTimeout(()=>{if(n.process){a("start",`Force killing process ${t}`,i);try{n.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){a("start",`Error stopping process ${t}: ${f}`,i),this.processes.delete(t),r()}})}async stopAll(t){if(this.isShuttingDown){a("start","Already shutting down, skipping duplicate stopAll call",t);return}this.isShuttingDown=!0,a("start","Stopping all processes",t);let i=Array.from(this.processes.keys()).map((n)=>this.stopProcess(n,t).catch((r)=>{S.error(`Failed to stop process ${n}:`,r)}));await Promise.allSettled(i),this.processes.clear(),this.isShuttingDown=!1}isRunning(t){let i=this.processes.get(t);return!!i?.process&&!i.process.killed}}var YT=new $f;var wf=new $f,ma="0.12.0",Ea=new Nn("0.0.0.0"),Fn=new Set,wc=!1,sf=null,uc=null;async function Cn(t){if(wc)return a("cleanup","Cleanup already in progress, skipping",t?.verbose),uc||Promise.resolve();wc=!0,a("cleanup","Starting cleanup process",t?.verbose),uc=new Promise((i)=>{sf=i});try{await wf.stopAll(t?.verbose),S.info("Shutting down proxy servers...");let i=[],n=Array.from(Fn).map((r)=>new Promise((f)=>{r.close(()=>{a("cleanup","Server closed successfully",t?.verbose),f()})}));if(i.push(...n),t?.hosts&&t.domains?.length){a("cleanup","Cleaning up hosts file entries",t?.verbose),a("cleanup",`Original domains for cleanup: ${JSON.stringify(t.domains)}`,t?.verbose);let r=t.domains.filter((f)=>{if(f==="test.local")return!0;return f!=="localhost"&&!f.startsWith("localhost.")&&f!=="127.0.0.1"});if(a("cleanup",`Filtered domains for cleanup: ${JSON.stringify(r)}`,t?.verbose),r.length>0)S.info("Cleaning up hosts file entries..."),i.push(sc(r,t?.verbose).then(()=>{a("cleanup",`Removed hosts entries for ${r.join(", ")}`,t?.verbose)}).catch((f)=>{a("cleanup",`Failed to remove hosts entries: ${f}`,t?.verbose),S.warn(`Failed to clean up hosts file entries for ${r.join(", ")}:`,f)}))}if(t?.certs&&t.domains?.length){a("cleanup","Cleaning up SSL certificates",t?.verbose),S.info("Cleaning up SSL certificates...");let r=t.domains.map(async(f)=>{try{await nc(f,t?.verbose),a("cleanup",`Removed certificates for ${f}`,t?.verbose)}catch(e){a("cleanup",`Failed to remove certificates for ${f}: ${e}`,t?.verbose),S.warn(`Failed to clean up certificates for ${f}:`,e)}});i.push(...r)}await Promise.allSettled(i),a("cleanup","All cleanup tasks completed successfully",t?.verbose),S.success("All cleanup tasks completed successfully")}catch(i){a("cleanup",`Error during cleanup: ${i}`,t?.verbose),S.error("Error during cleanup:",i)}finally{if(sf)sf();sf=null,wc=!1;let i=t&&"vitePluginUsage"in t&&t.vitePluginUsage===!0;if(O.env.NODE_ENV!=="test"&&O.env.BUN_ENV!=="test"&&!i)O.exit(0)}return uc}var yc=!1;function ac(t){if(yc){a("signal",`Received second ${t} signal, forcing exit`,!0),O.exit(1);return}yc=!0,a("signal",`Received ${t} signal, initiating cleanup`,!0),Cn().catch((i)=>{a("signal",`Cleanup failed after ${t}: ${i}`,!0),O.exit(1)}).finally(()=>{yc=!1})}O.once("SIGINT",()=>ac("SIGINT"));O.once("SIGTERM",()=>ac("SIGTERM"));O.on("uncaughtException",(t)=>{a("process",`Uncaught exception: ${t}`,!0),S.error("Uncaught exception:",t),ac("uncaughtException")});async function Jn(t,i,n,r=5){a("connection",`Testing connection to ${t}:${i} (retries left: ${r})`,n);let f=15000,e=Date.now();if(O.env.RPX_BYPASS_CONNECTION_TEST==="true"){a("connection",`Bypassing connection test for ${t}:${i} due to RPX_BYPASS_CONNECTION_TEST flag`,n);return}let c=()=>new Promise((l,h)=>{let $=P$.connect({host:t,port:i,timeout:3000});$.once("connect",()=>{a("connection",`Successfully connected to ${t}:${i}`,n),$.end(),l()}),$.once("timeout",()=>{a("connection",`Connection to ${t}:${i} timed out`,n),$.destroy(),h(Error("Connection timed out"))}),$.once("error",(s)=>{a("connection",`Failed to connect to ${t}:${i}: ${s}`,n),$.destroy(),h(s)})});try{await c()}catch(l){if(Date.now()-e>f){a("connection",`Connection test timed out after ${f}ms, but continuing anyway`,n),S.warn(`Connection test to ${t}:${i} timed out, but RPX will try to proceed anyway.`);return}if(l.code==="ECONNREFUSED"&&r>0)return a("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${r} retries left)`,n),await new Promise(($)=>setTimeout($,2000)),Jn(t,i,n,r-1);if(r>0)try{a("connection",`Trying HTTP request to ${t}:${i}`,n),await new Promise(($,s)=>{let u=Ri.request({hostname:t,port:i,path:"/",method:"HEAD",timeout:5000},(y)=>{a("connection",`Received HTTP response with status: ${y.statusCode}`,n),$()});u.on("error",(y)=>s(y)),u.on("timeout",()=>{u.destroy(),s(Error("HTTP request timed out"))}),u.end()}),a("connection",`HTTP request to ${t}:${i} succeeded`,n);return}catch($){return a("connection",`HTTP request to ${t}:${i} failed: ${$}`,n),a("connection",`Retrying socket connection in 2 seconds... (${r} retries left)`,n),await new Promise((s)=>setTimeout(s,2000)),Jn(t,i,n,r-1)}let h=`Failed to connect to ${t}:${i} after ${5-r} attempts: ${l.message}`;a("connection",`${h}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,n),S.warn(h),S.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 Ac(t){a("server",`Starting server with options: ${ei(t)}`,t.verbose);let i=new URL((t.from?.startsWith("http")?t.from:`http://${t.from}`)||"localhost:5173"),n=new URL((t.to?.startsWith("http")?t.to:`http://${t.to}`)||"rpx.localhost"),r=Number.parseInt(i.port)||(i.protocol.includes("https:")?443:80),f=[n.hostname];if(!n.hostname.includes("localhost")&&!n.hostname.includes("127.0.0.1")){a("hosts",`Checking if hosts file entry exists for: ${n.hostname}`,t?.verbose);try{if(!(await fn(f,t.verbose))[0]){S.info(`Adding ${n.hostname} to hosts file...`),S.info("This may require sudo/administrator privileges");try{await rn(f,t.verbose)}catch(l){if(S.error("Failed to add hosts entry:",l.message),S.warn("You can manually add this entry to your hosts file:"),S.warn(`127.0.0.1 ${n.hostname}`),S.warn(`::1 ${n.hostname}`),O.platform==="win32")S.warn("On Windows:"),S.warn("1. Run notepad as administrator"),S.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else S.warn("On Unix systems:"),S.warn("sudo nano /etc/hosts")}}else a("hosts",`Host entry already exists for ${n.hostname}`,t.verbose)}catch(c){S.error("Failed to check hosts file:",c.message)}}try{await Jn(i.hostname,r,t.verbose)}catch(c){a("server",`Connection test failed: ${c}`,t.verbose),S.error(c.message),S.warn("Continuing with proxy setup despite connection test failure..."),S.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let e=t._cachedSSLConfig||null;if(t.https)try{if(t.https===!0)t.https=mi({...t,to:n.hostname});if(e=await ii({...t,to:n.hostname,https:t.https}),!e){if(a("ssl",`Generating new certificates for ${n.hostname}`,t.verbose),await pi({...t,from:i.toString(),to:n.hostname,https:t.https}),e=await ii({...t,to:n.hostname,https:t.https}),!e)throw Error(`Failed to load SSL configuration after generating certificates for ${n.hostname}`)}}catch(c){throw a("server",`SSL setup failed: ${c}`,t.verbose),c}a("server",`Setting up reverse proxy with SSL config for ${n.hostname}`,t.verbose),await Sa({...t,from:t.from||"localhost:5173",to:n.hostname,fromPort:r,sourceUrl:{hostname:i.hostname,host:i.host},ssl:e})}async function Ta(t,i,n,r,f,e,c,l,h,$,s){a("proxy",`Creating proxy server ${t} -> ${i} with cleanUrls: ${$}`,h);function u(A){let T={};for(let[E,R]of Object.entries(A))if(!E.startsWith(":"))T[E]=R;return T}let y=(A,T)=>{a("request",`Incoming request: ${A.method} ${A.url}`,h);let E=A.url||"/",R=A.method||"GET";if(A instanceof X$.Http2ServerRequest){let B=A.headers;R=B[":method"]||R,E=B[":path"]||E}if($){if(!E.match(/\.[a-z0-9]+$/i))if(E.endsWith("/"))E=`${E}index.html`;else E=`${E}.html`}let J=u(A.headers);if(s)J.host=`${e.hostname}:${n}`,a("request",`Changed origin: setting host header to ${J.host}`,h);let C={hostname:e.hostname,port:n,path:E,method:R,headers:J};a("request",`Proxy request options: ${ei(C)}`,h);let j=Ri.request(C,(B)=>{if(a("response",`Proxy response received with status ${B.statusCode}`,h),$&&B.statusCode===404){let mt=[];if(E.endsWith(".html"))mt.push(E.slice(0,-5));else if(!E.match(/\.[a-z0-9]+$/i))mt.push(`${E}.html`);if(!E.endsWith("/"))mt.push(`${E}/index.html`);if(mt.length>0){a("cleanUrls",`Trying alternative paths: ${mt.join(", ")}`,h);let en=(_n)=>{if(_n.length===0){T.writeHead(B.statusCode||404,B.headers),B.pipe(T);return}let Ec=_n[0],p$={...C,path:Ec},Tc=Ri.request(p$,(Un)=>{if(Un.statusCode===200)a("cleanUrls",`Found matching path: ${Ec}`,h),T.writeHead(Un.statusCode,Un.headers),Un.pipe(T);else en(_n.slice(1))});Tc.on("error",()=>en(_n.slice(1))),Tc.end()};en(mt);return}}let $t={...B.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};T.writeHead(B.statusCode||500,$t),B.pipe(T)});j.on("error",(B)=>{a("request",`Proxy request failed: ${B}`,h),S.error("Proxy request failed:",B),T.writeHead(502),T.end(`Proxy Error: ${B.message}`)}),A.pipe(j)};if(a("server",`Creating server with SSL config: ${!!c}`,h),c)return new Promise((A,T)=>{try{let E=Bun.serve({port:r,hostname:f,tls:{key:c.key,cert:c.cert,ca:c.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let J=new URL(R.url);a("request",`Bun.serve received: ${R.method} ${J.pathname}`,h);let C=`http://${e.host}`,j=new URL(J.pathname+J.search,C);try{let B=new Headers(R.headers);if(B.set("host",e.host),s)B.set("origin",C);B.set("x-forwarded-for","127.0.0.1"),B.set("x-forwarded-proto","https"),B.set("x-forwarded-host",i);let $t=await fetch(j.toString(),{method:R.method,headers:B,body:R.body,redirect:"manual"}),mt=new Headers($t.headers);if($&&J.pathname.endsWith(".html")){let en=J.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:en}})}return new Response($t.body,{status:$t.status,statusText:$t.statusText,headers:mt})}catch(B){return a("request",`Proxy error: ${B}`,h),new Response(`Proxy Error: ${B}`,{status:502})}},error(R){return a("server",`Bun.serve error: ${R}`,h),new Response(`Server Error: ${R.message}`,{status:500})}});Fn.add(E),b$({from:t,to:i,vitePluginUsage:l,listenPort:r,ssl:!0,cleanUrls:$,verbose:h}),A()}catch(E){T(E)}});let w=Ri.createServer(y);function m(A){return Fn.add(A),new Promise((T,E)=>{A.listen(r,f,()=>{a("server",`Server listening on port ${r}`,h),b$({from:t,to:i,vitePluginUsage:l,listenPort:r,ssl:!!c,cleanUrls:$,verbose:h}),T()}),A.on("error",(R)=>{a("server",`Server error: ${R}`,h),E(R)})})}return m(w)}async function Sa(t){a("setup",`Setting up reverse proxy: ${ei(t)}`,t.verbose);let{from:i,to:n,fromPort:r,sourceUrl:f,ssl:e,verbose:c,cleanup:l,vitePluginUsage:h,changeOrigin:$,cleanUrls:s}=t,u=80,y=443,w="0.0.0.0",m=t.portManager||Ea;try{if(n&&!n.includes("localhost")&&!n.includes("127.0.0.1")){if(!(await fn([n],c))[0]){S.warn(`The hostname ${n} isn't in your hosts file. Adding it now...`);try{await rn([n],c),S.success(`Added ${n} to your hosts file.`)}catch(J){S.error(`Failed to add ${n} to your hosts file: ${J}`),S.info(`You may need to manually add '127.0.0.1 ${n}' to your /etc/hosts file.`)}}}else if(O.platform!=="darwin"&&n&&n.includes("localhost")&&!n.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await fn([n],c))[0]){a("hosts",`${n} not found in hosts file, adding...`,c);try{await rn([n],c)}catch(J){a("hosts",`Failed to add ${n} to hosts file: ${J}`,c)}}}if(e&&!m.usedPorts.has(u)){if(!await yi(u,w,c))a("setup","Starting HTTP redirect server",c),v$(c),m.usedPorts.add(u);else if(a("setup","Port 80 is in use, skipping HTTP redirect",c),c)S.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let A=e?y:u,T=await yi(A,w,c),E;if(T){if(a("setup",`Port ${A} is already in use`,c),c)S.warn(`Port ${A} is already in use. This may be another instance of rpx or another service.`);if(A===443){if(E=await m.getNextAvailablePort(3443,!0),a("setup",`Using port ${E} instead of ${A}`,c),c)S.info(`Using port ${E} instead. Access your site at https://${n}:${E}`)}else if(E=await m.getNextAvailablePort(A+1000,!0),a("setup",`Using port ${E} instead of ${A}`,c),c)S.info(`Using port ${E} instead. Access your site at http://${n}:${E}`)}else E=A,m.usedPorts.add(E),a("setup",`Using standard ${A===443?"HTTPS":"HTTP"} port ${A} for ${n}`,c);await Ta(i,n,r,E,w,f,e,h,c,s,$)}catch(A){a("setup",`Setup failed: ${A}`,c),S.error(`Failed to setup reverse proxy: ${A.message}`),Cn({domains:[n],hosts:typeof l==="boolean"?l:l?.hosts,certs:typeof l==="boolean"?l:l?.certs,verbose:c,vitePluginUsage:h})}}function v$(t){a("redirect","Starting HTTP redirect server",t);let i=Ri.createServer((n,r)=>{let f=n.headers.host||"";a("redirect",`Redirecting request from ${f}${n.url} to HTTPS`,t),r.writeHead(301,{Location:`https://${f}${n.url}`}),r.end()}).listen(80);Fn.add(i),a("redirect","HTTP redirect server started",t)}function Ra(t){let i={...Hi,...t};if(a("proxy",`Starting proxy with options: ${ei(i)}`,i?.verbose),i.viaDaemon){if(!i.from||!i.to){S.error("viaDaemon mode requires both `from` and `to`");return}ef({proxies:[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}],verbose:i.verbose}).catch((h)=>{S.error(`Failed to register with rpx daemon: ${h.message}`),O.exit(1)});return}let n=i.to||"",r=n.split(".").pop()?.toLowerCase()||"",f=O.platform==="darwin"&&n&&!n.includes("localhost")&&!n.includes("127.0.0.1"),e=["dev","app","page","new","day","foo"],c=["test","localhost","local","example","invalid"];if(f&&e.includes(r)&&i?.verbose)S.warn(`The .${r} TLD may not work reliably for local development`),S.info(` Google owns .${r} with HSTS preloading, which can bypass local DNS`),S.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(f)import("./chunk-6z1nzq0x.js").then(({startDnsServer:h,setupResolver:$})=>{h([n],i.verbose).then((s)=>{if(s)$(i.verbose,[n]).then(()=>{if(i.verbose)if(c.includes(r))S.success(`DNS server started for .${r} domains`);else S.success(`DNS server started for .${r} domains (hosts file entry also added)`)});else a("dns",`Could not start DNS server - ${n} may not resolve in browser`,i.verbose)})}).catch((h)=>{a("dns",`Failed to start DNS server: ${h}`,i.verbose)});let l={from:i.from,to:i.to,cleanUrls:i.cleanUrls,https:mi(i),cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,changeOrigin:i.changeOrigin,verbose:i.verbose,regenerateUntrustedCerts:i.regenerateUntrustedCerts};a("proxy",`Server options: ${ei(l)}`,i.verbose),Ac(l).catch((h)=>{a("proxy",`Failed to start proxy: ${h}`,i.verbose),S.error(`Failed to start proxy: ${h.message}`),Cn({domains:[i.to],hosts:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.hosts,certs:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.certs,verbose:i.verbose})})}function Ba(t){return t?.verbose||!1}async function mc(t){let i={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(t)i={...i,...t};let n=Ba(i);if(a("config",`Starting with config: ${ei(i,2)}`,n),a("config",`Is multi-proxy? ${"proxies"in i}`,n),i.viaDaemon){let m="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((A)=>({id:A.id,from:A.from,to:A.to,cleanUrls:A.cleanUrls??i.cleanUrls,changeOrigin:A.changeOrigin??i.changeOrigin,pathRewrites:A.pathRewrites})):[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}];await ef({proxies:m,verbose:n});return}if("proxies"in i&&Array.isArray(i.proxies)){a("servers",`Found ${i.proxies.length} proxies in config`,n);for(let w of i.proxies)if(w.start){let m=`${w.from}-${w.to}`;try{a("watch",`Starting command for ${m} with command: ${w.start.command}`,n),S.info(`Starting command for ${m}...`),await wf.startProcess(m,w.start,n);let A=new URL(w.from.startsWith("http")?w.from:`http://${w.from}`),T=A.hostname||"localhost",E=Number(A.port)||80;try{await Jn(T,E,n),a("watch",`Dev server is ready at ${T}:${E}`,n)}catch(R){a("watch",`Connection check failed, but continuing with proxy setup: ${R}`,n),S.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(A){throw a("watch",`Failed to start command for ${m}: ${A}`,n),Error(`Failed to start command for ${m}: ${A}`)}}else a("watch",`No start command for proxy ${w.from} -> ${w.to}`,n)}else if("start"in i&&i.start){a("watch","Found start command in single proxy config",n);let w=`${i.from}-${i.to}`;try{if(i.start)a("watch",`Starting command: ${i.start.command}`,n),await wf.startProcess(w,i.start,n);let m=new URL(i.from?.startsWith("http")?i.from:`http://${i.from}`),A=m.hostname||"localhost",T=Number(m.port)||80;try{await Jn(A,T,n),a("watch",`Dev server is ready at ${A}:${T}`,n)}catch(E){a("watch",`Connection check failed, but continuing with proxy setup: ${E}`,n),S.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(m){throw a("watch",`Failed to run start command: ${m}`,n),Error(`Failed to run start command: ${m}`)}}else a("watch","No start command found in config",n);let r="proxies"in i&&Array.isArray(i.proxies)?i.proxies[0]?.to:("to"in i)?i.to:"rpx.localhost";if(O.platform!=="win32"&&(i.https||i.cleanup?.hosts!==!1)){if(!Rn())try{a("sudo","Pre-acquiring sudo credentials for privileged operations",n),Aa("sudo -v",{stdio:"inherit"})}catch{a("sudo","Could not pre-acquire sudo credentials",n)}}if(i.https){let w=await ii(i);if(!w){if(a("ssl",`No valid or trusted certificates found for ${r}, generating new ones`,i.verbose),await pi(i),w=await ii(i),!w)throw Error(`Failed to load SSL certificates after generation for ${r}`)}else a("ssl",`Using existing and trusted certificates for ${r}`,i.verbose);i._cachedSSLConfig=w}let f="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((w)=>({...w,https:i.https,cleanup:i.cleanup,cleanUrls:w.cleanUrls??("cleanUrls"in i?i.cleanUrls:!1),vitePluginUsage:i.vitePluginUsage,changeOrigin:w.changeOrigin??i.changeOrigin,verbose:n,_cachedSSLConfig:i._cachedSSLConfig})):[{from:"from"in i?i.from:"localhost:5173",to:"to"in i?i.to:"rpx.localhost",cleanUrls:"cleanUrls"in i?i.cleanUrls:!1,https:i.https,cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,start:"start"in i?i.start:void 0,changeOrigin:i.changeOrigin,verbose:n,_cachedSSLConfig:i._cachedSSLConfig}],e=f.map((w)=>w.to||"rpx.localhost"),c=i._cachedSSLConfig,l=e.filter((w)=>w&&!w.includes("localhost")&&!w.includes("127.0.0.1")),h=["dev","app","page","new","day","foo"],$=["test","localhost","local","example","invalid"],s=[...new Set(l.map((w)=>w.split(".").pop()?.toLowerCase()))],u=s.filter((w)=>!!w&&h.includes(w));if(u.length>0&&n)S.warn(`The following TLDs may not work reliably for local development: ${u.map((w)=>`.${w}`).join(", ")}`),S.info(" These TLDs have HSTS preloading which can bypass local DNS"),S.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(O.platform==="darwin"&&l.length>0){let{startDnsServer:w,setupResolver:m}=await import("./chunk-6z1nzq0x.js");if(await w(l,n)){if(await m(n,l),n)if(s.every((E)=>!!E&&$.includes(E)))S.success(`DNS server started for ${s.map((E)=>`.${E}`).join(", ")} domains`);else S.success(`DNS server started for ${s.map((E)=>`.${E}`).join(", ")} domains (hosts file entries also added)`)}else a("dns","Could not start DNS server - custom domains may not resolve",n)}let y=async()=>{a("cleanup","Starting cleanup handler",i.verbose);try{let{stopDnsServer:w,removeResolver:m}=await import("./chunk-6z1nzq0x.js");w(i.verbose),await m(i.verbose)}catch(w){a("cleanup",`Error stopping DNS server: ${w}`,i.verbose)}try{await wf.stopAll(i.verbose)}catch(w){a("cleanup",`Error stopping processes: ${w}`,i.verbose)}await Cn({domains:e,hosts:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.hosts,certs:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.certs,verbose:i.verbose||!1})};if(O.on("SIGINT",y),O.on("SIGTERM",y),O.on("uncaughtException",(w)=>{a("process",`Uncaught exception: ${w}`,!0),console.error("Uncaught exception:",w),y()}),c&&f.length>1){a("proxies",`Creating shared HTTPS server for ${f.length} domains`,n);let w=new Map;for(let E of f){let R=E.to||"rpx.localhost",J=new URL(E.from?.startsWith("http")?E.from:`http://${E.from}`);if(w.set(R,{sourceHost:J.host,cleanUrls:E.cleanUrls||!1,changeOrigin:E.changeOrigin||!1,pathRewrites:E.pathRewrites}),a("proxies",`Route: ${R} → ${J.host}`,n),!R.includes("localhost")&&!R.includes("127.0.0.1"))try{if(!(await fn([R],n))[0])await rn([R],n)}catch{a("hosts",`Could not add hosts entry for ${R}`,n)}}if(!await yi(80,"0.0.0.0",n))v$(n);let A=443;if(await yi(A,"0.0.0.0",n)){if(a("proxies",`Port ${A} is already in use, cannot start shared proxy`,n),n)S.warn(`Port ${A} is in use. Shared HTTPS proxy cannot start.`);return}try{let E=Bun.serve({port:A,hostname:"0.0.0.0",tls:{key:c.key,cert:c.cert,ca:c.ca,requestCert:!1,rejectUnauthorized:!1},fetch:Sn((R)=>w.get(R),n),error(R){return a("server",`Shared proxy server error: ${R}`,n),new Response(`Server Error: ${R.message}`,{status:500})}});Fn.add(E),a("proxies",`Shared HTTPS proxy listening on port ${A} for ${w.size} domains`,n)}catch(E){a("proxies",`Failed to start shared proxy: ${E}`,n),console.error("Failed to start shared HTTPS proxy:",E),y()}}else for(let w of f)try{let m=w.to||"rpx.localhost";a("proxy",`Starting proxy for ${m} with SSL config: ${!!c}`,w.verbose),await Ac({from:w.from||"localhost:5173",to:m,cleanUrls:w.cleanUrls||!1,https:w.https||!1,cleanup:w.cleanup||!1,vitePluginUsage:w.vitePluginUsage||!1,verbose:w.verbose||!1,_cachedSSLConfig:c,changeOrigin:w.changeOrigin||!1})}catch(m){a("proxies",`Failed to start proxy for ${w.to}: ${m}`,w.verbose),console.error(`Failed to start proxy for ${w.to}:`,m),y()}}function b$(t){if(t?.vitePluginUsage||!t?.verbose)return;if(console.log(""),console.log(` ${jt.green(jt.bold("rpx"))} ${jt.green(`v${ma}`)}`),console.log(` ${jt.green("➜")} ${jt.dim(t?.from??"")} ${jt.dim("➜")} ${jt.cyan(t?.ssl?`https://${t?.to}`:`http://${t?.to}`)}`),t?.listenPort!==(t?.ssl?443:80))console.log(` ${jt.green("➜")} Listening on port ${t?.listenPort}`);if(t?.cleanUrls)console.log(` ${jt.green("➜")} Clean URLs enabled`)}var lS=mc;export{ec as writeEntry,cc as watchRegistry,sa as stopDaemon,Ac as startServer,Ra as startProxy,mc as startProxies,ei as safeStringify,I$ as safeDeleteFile,ef as runViaDaemon,$a as runDaemon,z$ as resolvePathRewrite,sc as removeHosts,nf as removeEntry,tn as releaseDaemonLock,$S as redactSensitive,K$ as readEntry,nn as readDaemonPid,Ei as readAll,ya as portManager,v0 as loadSSLConfig,Y$ as isValidRootCA,Qi as isValidId,d$ as isSingleProxyOptions,wS as isSingleProxyConfig,yi as isPortInUse,ri as isPidAlive,pr as isMultiProxyOptions,g0 as isMultiProxyConfig,ea as isDaemonRunning,Pi as isCertTrusted,mi as httpsConfig,Rn as getSudoPassword,ni as getRegistryDir,ic as getPrimaryDomain,fi as getDaemonRpxDir,ff as getDaemonPidPath,pi as generateCertificate,rf as gcStaleEntries,p0 as forceTrustCertificate,g$ as findAvailablePort,sS as extractHostname,tc as execSudoSync,hc as ensureDaemonRunning,k$ as deriveIdFromTarget,D$ as defaultDaemonSpawnCommand,Hi as defaultConfig,lS as default,a as debugLog,Sn as createProxyFetchHandler,Hi as config,jt as colors,M$ as clearSslConfigCache,nc as cleanupCertificates,Cn as cleanup,fn as checkHosts,ii as checkExistingCertificates,rn as addHosts,x$ as acquireDaemonLock,Nn as DefaultPortManager};
|
|
158
|
+
`,h=Nc.join($w.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Si.promises.writeFile(h,c,"utf8"),await Rf(`cat "${h}" | tee "${Ut}" > /dev/null`),a("hosts","Hosts removed successfully",i)}catch(l){a("hosts","Could not clean up hosts file automatically",i)}finally{try{await Si.promises.unlink(h)}catch(l){a("hosts",`Failed to remove temporary file: ${l}`,i)}}}catch(n){a("hosts",`Failed to clean up hosts file: ${n.message}`,i)}}async function ln(t,i){a("hosts",`Checking hosts: ${t}`,i);let n;try{n=await Si.promises.readFile(Ut,"utf-8")}catch(r){a("hosts",`Error reading hosts file: ${r}`,i);try{let f=Un(),e;if(f)e=`echo '${f}' | sudo -S cat "${Ut}" 2>/dev/null`;else e=`sudo -n cat "${Ut}" 2>/dev/null || cat "${Ut}" 2>/dev/null || echo ""`;let{stdout:c}=await Sf(e);n=c}catch(f){return a("hosts",`Cannot read hosts file, assuming entries don't exist: ${f}`,i),t.map(()=>!1)}}return t.map((r)=>{let f=`127.0.0.1 ${r}`,e=`::1 ${r}`;return n.includes(f)||n.includes(e)})}import*as Bf from"node:net";function ai(t,i,n){return a("port",`Checking if port ${t} is in use on ${i}`,n),new Promise((r)=>{let f=Bf.createServer(),e=setTimeout(()=>{a("port",`Checking port ${t} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(c)=>{if(clearTimeout(e),c.code==="EADDRINUSE")a("port",`Port ${t} is in use`,n),r(!0);else a("port",`Error checking port ${t}: ${c.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout(e),a("port",`Port ${t} is available`,n),f.close(),r(!1)});try{f.listen(t,i)}catch(c){clearTimeout(e),a("port",`Exception checking port ${t}: ${c}`,n),r(!0)}})}async function uw(t,i,n,r=50){a("port",`Finding available port starting from ${t} (max attempts: ${r})`,n);let f=t,e=0;while(e<r){if(e++,!await ai(f,i,n))return a("port",`Found available port: ${f} after ${e} attempts`,n),f;a("port",`Port ${f} is in use, trying ${f+1} (attempt ${e}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${t}`)}function ww(t,i,n=5000,r){return a("port",`Testing connection to ${i}:${t}`,r),new Promise((f)=>{let e=Bf.connect({host:i,port:t,timeout:n});e.once("connect",()=>{a("port",`Successfully connected to ${i}:${t}`,r),e.end(),f(!0)}),e.once("timeout",()=>{a("port",`Connection to ${i}:${t} timed out`,r),e.destroy(),f(!1)}),e.once("error",(c)=>{a("port",`Failed to connect to ${i}:${t}: ${c.message}`,r),e.destroy(),f(!1)})})}class jn{usedPorts=new Set;hostname;verbose;maxRetries;constructor(t="0.0.0.0",i,n=50){this.hostname=t,this.verbose=i,this.maxRetries=n}async getNextAvailablePort(t,i=!1){if(this.usedPorts.has(t))return this.findNextAvailablePort(t+1,i);if(await ai(t,this.hostname,this.verbose))return this.findNextAvailablePort(t+1,i);if(i){if(!await ww(t,this.hostname,3000,this.verbose))return a("port",`Port ${t} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(t+1,i)}return this.usedPorts.add(t),t}async findNextAvailablePort(t,i=!1){let n=await uw(t,this.hostname,this.verbose,this.maxRetries);if(i){if(!await ww(n,this.hostname,3000,this.verbose))if(n<t+this.maxRetries)return this.findNextAvailablePort(n+1,i);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(t){a("port",`Releasing port ${t}`,this.verbose),this.usedPorts.delete(t)}}var Ha=new jn;import{spawn as Ma}from"node:child_process";import*as Ri from"node:process";class Cf{processes=new Map;isShuttingDown=!1;async startProcess(t,i,n){if(this.processes.has(t)){a("start",`Process ${t} is already running`,n);return}let[r,...f]=i.command.split(" "),e=i.cwd||Ri.cwd();a("start",`Starting process ${t}:`,n),a("start",` Command: ${r} ${f.join(" ")}`,n),a("start",` Working directory: ${e}`,n),a("start",` Environment variables: ${ci(i.env)}`,n);let c=Ma(r,f,{cwd:e,env:{...Ri.env,...i.env},shell:!0,stdio:"inherit"});return this.processes.set(t,{command:i.command,cwd:e,process:c,env:i.env}),new Promise((h,l)=>{if(c.on("error",($)=>{if(!this.isShuttingDown)a("start",`Process ${t} failed to start: ${$}`,n),this.processes.delete(t),l($),Ri.emit("SIGINT")}),c.on("exit",($)=>{if(!this.isShuttingDown&&$!==null&&$!==0)a("start",`Process ${t} exited with code ${$}`,n),this.processes.delete(t),l(Error(`Process ${t} exited with code ${$}`)),Ri.emit("SIGINT")}),n)c.stdout?.on("data",($)=>{a("process",`[${t}] ${$.toString().trim()}`,!0)}),c.stderr?.on("data",($)=>{a("process",`[${t}] ERR: ${$.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&c.killed)this.processes.delete(t),l(Error(`Process ${t} was killed during startup`));else a("start",`Process ${t} started successfully`,n),h()},1000)})}async stopProcess(t,i){let n=this.processes.get(t);if(!n?.process){a("start",`No process found for ${t}`,i);return}return a("start",`Stopping process ${t}`,i),new Promise((r)=>{if(!n.process){r();return}n.process.once("exit",()=>{this.processes.delete(t),a("start",`Process ${t} stopped`,i),r()});try{n.process.kill("SIGTERM"),setTimeout(()=>{if(n.process){a("start",`Force killing process ${t}`,i);try{n.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){a("start",`Error stopping process ${t}: ${f}`,i),this.processes.delete(t),r()}})}async stopAll(t){if(this.isShuttingDown){a("start","Already shutting down, skipping duplicate stopAll call",t);return}this.isShuttingDown=!0,a("start","Stopping all processes",t);let i=Array.from(this.processes.keys()).map((n)=>this.stopProcess(n,t).catch((r)=>{S.error(`Failed to stop process ${n}:`,r)}));await Promise.allSettled(i),this.processes.clear(),this.isShuttingDown=!1}isRunning(t){let i=this.processes.get(t);return!!i?.process&&!i.process.killed}}var hS=new Cf;var Nf=new Cf,Ga="0.12.0",Ka=new jn("0.0.0.0"),Wn=new Set,_c=!1,Ff=null,Uc=null;async function In(t){if(_c)return a("cleanup","Cleanup already in progress, skipping",t?.verbose),Uc||Promise.resolve();_c=!0,a("cleanup","Starting cleanup process",t?.verbose),Uc=new Promise((i)=>{Ff=i});try{await Nf.stopAll(t?.verbose),S.info("Shutting down proxy servers...");let i=[],n=Array.from(Wn).map((r)=>new Promise((f)=>{r.close(()=>{a("cleanup","Server closed successfully",t?.verbose),f()})}));if(i.push(...n),t?.hosts&&t.domains?.length){a("cleanup","Cleaning up hosts file entries",t?.verbose),a("cleanup",`Original domains for cleanup: ${JSON.stringify(t.domains)}`,t?.verbose);let r=t.domains.filter((f)=>{if(f==="test.local")return!0;return f!=="localhost"&&!f.startsWith("localhost.")&&f!=="127.0.0.1"});if(a("cleanup",`Filtered domains for cleanup: ${JSON.stringify(r)}`,t?.verbose),r.length>0)S.info("Cleaning up hosts file entries..."),i.push(Jc(r,t?.verbose).then(()=>{a("cleanup",`Removed hosts entries for ${r.join(", ")}`,t?.verbose)}).catch((f)=>{a("cleanup",`Failed to remove hosts entries: ${f}`,t?.verbose),S.warn(`Failed to clean up hosts file entries for ${r.join(", ")}:`,f)}))}if(t?.certs&&t.domains?.length){a("cleanup","Cleaning up SSL certificates",t?.verbose),S.info("Cleaning up SSL certificates...");let r=t.domains.map(async(f)=>{try{await mc(f,t?.verbose),a("cleanup",`Removed certificates for ${f}`,t?.verbose)}catch(e){a("cleanup",`Failed to remove certificates for ${f}: ${e}`,t?.verbose),S.warn(`Failed to clean up certificates for ${f}:`,e)}});i.push(...r)}await Promise.allSettled(i),a("cleanup","All cleanup tasks completed successfully",t?.verbose),S.success("All cleanup tasks completed successfully")}catch(i){a("cleanup",`Error during cleanup: ${i}`,t?.verbose),S.error("Error during cleanup:",i)}finally{if(Ff)Ff();Ff=null,_c=!1;let i=t&&"vitePluginUsage"in t&&t.vitePluginUsage===!0;if(D.env.NODE_ENV!=="test"&&D.env.BUN_ENV!=="test"&&!i)D.exit(0)}return Uc}var dc=!1;function jc(t){if(dc){a("signal",`Received second ${t} signal, forcing exit`,!0),D.exit(1);return}dc=!0,a("signal",`Received ${t} signal, initiating cleanup`,!0),In().catch((i)=>{a("signal",`Cleanup failed after ${t}: ${i}`,!0),D.exit(1)}).finally(()=>{dc=!1})}D.once("SIGINT",()=>jc("SIGINT"));D.once("SIGTERM",()=>jc("SIGTERM"));D.on("uncaughtException",(t)=>{a("process",`Uncaught exception: ${t}`,!0),S.error("Uncaught exception:",t),jc("uncaughtException")});async function Yn(t,i,n,r=5){a("connection",`Testing connection to ${t}:${i} (retries left: ${r})`,n);let f=15000,e=Date.now();if(D.env.RPX_BYPASS_CONNECTION_TEST==="true"){a("connection",`Bypassing connection test for ${t}:${i} due to RPX_BYPASS_CONNECTION_TEST flag`,n);return}let c=()=>new Promise((h,l)=>{let $=aw.connect({host:t,port:i,timeout:3000});$.once("connect",()=>{a("connection",`Successfully connected to ${t}:${i}`,n),$.end(),h()}),$.once("timeout",()=>{a("connection",`Connection to ${t}:${i} timed out`,n),$.destroy(),l(Error("Connection timed out"))}),$.once("error",(w)=>{a("connection",`Failed to connect to ${t}:${i}: ${w}`,n),$.destroy(),l(w)})});try{await c()}catch(h){if(Date.now()-e>f){a("connection",`Connection test timed out after ${f}ms, but continuing anyway`,n),S.warn(`Connection test to ${t}:${i} timed out, but RPX will try to proceed anyway.`);return}if(h.code==="ECONNREFUSED"&&r>0)return a("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${r} retries left)`,n),await new Promise(($)=>setTimeout($,2000)),Yn(t,i,n,r-1);if(r>0)try{a("connection",`Trying HTTP request to ${t}:${i}`,n),await new Promise(($,w)=>{let s=Bi.request({hostname:t,port:i,path:"/",method:"HEAD",timeout:5000},(y)=>{a("connection",`Received HTTP response with status: ${y.statusCode}`,n),$()});s.on("error",(y)=>w(y)),s.on("timeout",()=>{s.destroy(),w(Error("HTTP request timed out"))}),s.end()}),a("connection",`HTTP request to ${t}:${i} succeeded`,n);return}catch($){return a("connection",`HTTP request to ${t}:${i} failed: ${$}`,n),a("connection",`Retrying socket connection in 2 seconds... (${r} retries left)`,n),await new Promise((w)=>setTimeout(w,2000)),Yn(t,i,n,r-1)}let l=`Failed to connect to ${t}:${i} after ${5-r} attempts: ${h.message}`;a("connection",`${l}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,n),S.warn(l),S.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 Wc(t){a("server",`Starting server with options: ${ci(t)}`,t.verbose);let i=new URL((t.from?.startsWith("http")?t.from:`http://${t.from}`)||"localhost:5173"),n=new URL((t.to?.startsWith("http")?t.to:`http://${t.to}`)||"rpx.localhost"),r=Number.parseInt(i.port)||(i.protocol.includes("https:")?443:80),f=[n.hostname];if(!n.hostname.includes("localhost")&&!n.hostname.includes("127.0.0.1")){a("hosts",`Checking if hosts file entry exists for: ${n.hostname}`,t?.verbose);try{if(!(await ln(f,t.verbose))[0]){S.info(`Adding ${n.hostname} to hosts file...`),S.info("This may require sudo/administrator privileges");try{await cn(f,t.verbose)}catch(h){if(S.error("Failed to add hosts entry:",h.message),S.warn("You can manually add this entry to your hosts file:"),S.warn(`127.0.0.1 ${n.hostname}`),S.warn(`::1 ${n.hostname}`),D.platform==="win32")S.warn("On Windows:"),S.warn("1. Run notepad as administrator"),S.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else S.warn("On Unix systems:"),S.warn("sudo nano /etc/hosts")}}else a("hosts",`Host entry already exists for ${n.hostname}`,t.verbose)}catch(c){S.error("Failed to check hosts file:",c.message)}}try{await Yn(i.hostname,r,t.verbose)}catch(c){a("server",`Connection test failed: ${c}`,t.verbose),S.error(c.message),S.warn("Continuing with proxy setup despite connection test failure..."),S.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let e=t._cachedSSLConfig||null;if(t.https)try{if(t.https===!0)t.https=Ei({...t,to:n.hostname});if(e=await ni({...t,to:n.hostname,https:t.https}),!e){if(a("ssl",`Generating new certificates for ${n.hostname}`,t.verbose),await nn({...t,from:i.toString(),to:n.hostname,https:t.https}),e=await ni({...t,to:n.hostname,https:t.https}),!e)throw Error(`Failed to load SSL configuration after generating certificates for ${n.hostname}`)}}catch(c){throw a("server",`SSL setup failed: ${c}`,t.verbose),c}a("server",`Setting up reverse proxy with SSL config for ${n.hostname}`,t.verbose),await xa({...t,from:t.from||"localhost:5173",to:n.hostname,fromPort:r,sourceUrl:{hostname:i.hostname,host:i.host},ssl:e})}async function qa(t,i,n,r,f,e,c,h,l,$,w){a("proxy",`Creating proxy server ${t} -> ${i} with cleanUrls: ${$}`,l);function s(A){let T={};for(let[E,R]of Object.entries(A))if(!E.startsWith(":"))T[E]=R;return T}let y=(A,T)=>{a("request",`Incoming request: ${A.method} ${A.url}`,l);let E=A.url||"/",R=A.method||"GET";if(A instanceof yw.Http2ServerRequest){let B=A.headers;R=B[":method"]||R,E=B[":path"]||E}if($){if(!E.match(/\.[a-z0-9]+$/i))if(E.endsWith("/"))E=`${E}index.html`;else E=`${E}.html`}let N=s(A.headers);if(w)N.host=`${e.hostname}:${n}`,a("request",`Changed origin: setting host header to ${N.host}`,l);let J={hostname:e.hostname,port:n,path:E,method:R,headers:N};a("request",`Proxy request options: ${ci(J)}`,l);let d=Bi.request(J,(B)=>{if(a("response",`Proxy response received with status ${B.statusCode}`,l),$&&B.statusCode===404){let mt=[];if(E.endsWith(".html"))mt.push(E.slice(0,-5));else if(!E.match(/\.[a-z0-9]+$/i))mt.push(`${E}.html`);if(!E.endsWith("/"))mt.push(`${E}/index.html`);if(mt.length>0){a("cleanUrls",`Trying alternative paths: ${mt.join(", ")}`,l);let hn=(Zn)=>{if(Zn.length===0){T.writeHead(B.statusCode||404,B.headers),B.pipe(T);return}let Ic=Zn[0],mw={...J,path:Ic},Zc=Bi.request(mw,(Hn)=>{if(Hn.statusCode===200)a("cleanUrls",`Found matching path: ${Ic}`,l),T.writeHead(Hn.statusCode,Hn.headers),Hn.pipe(T);else hn(Zn.slice(1))});Zc.on("error",()=>hn(Zn.slice(1))),Zc.end()};hn(mt);return}}let $t={...B.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};T.writeHead(B.statusCode||500,$t),B.pipe(T)});d.on("error",(B)=>{a("request",`Proxy request failed: ${B}`,l),S.error("Proxy request failed:",B),T.writeHead(502),T.end(`Proxy Error: ${B.message}`)}),A.pipe(d)};if(a("server",`Creating server with SSL config: ${!!c}`,l),c)return new Promise((A,T)=>{try{let E=Bun.serve({port:r,hostname:f,tls:{key:c.key,cert:c.cert,ca:c.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let N=new URL(R.url);a("request",`Bun.serve received: ${R.method} ${N.pathname}`,l);let J=`http://${e.host}`,d=new URL(N.pathname+N.search,J);try{let B=new Headers(R.headers);if(B.set("host",e.host),w)B.set("origin",J);B.set("x-forwarded-for","127.0.0.1"),B.set("x-forwarded-proto","https"),B.set("x-forwarded-host",i);let $t=await fetch(d.toString(),{method:R.method,headers:B,body:R.body,redirect:"manual"}),mt=new Headers($t.headers);if($&&N.pathname.endsWith(".html")){let hn=N.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:hn}})}return new Response($t.body,{status:$t.status,statusText:$t.statusText,headers:mt})}catch(B){return a("request",`Proxy error: ${B}`,l),new Response(`Proxy Error: ${B}`,{status:502})}},error(R){return a("server",`Bun.serve error: ${R}`,l),new Response(`Server Error: ${R.message}`,{status:500})}});Wn.add(E),sw({from:t,to:i,vitePluginUsage:h,listenPort:r,ssl:!0,cleanUrls:$,verbose:l}),A()}catch(E){T(E)}});let u=Bi.createServer(y);function m(A){return Wn.add(A),new Promise((T,E)=>{A.listen(r,f,()=>{a("server",`Server listening on port ${r}`,l),sw({from:t,to:i,vitePluginUsage:h,listenPort:r,ssl:!!c,cleanUrls:$,verbose:l}),T()}),A.on("error",(R)=>{a("server",`Server error: ${R}`,l),E(R)})})}return m(u)}async function xa(t){a("setup",`Setting up reverse proxy: ${ci(t)}`,t.verbose);let{from:i,to:n,fromPort:r,sourceUrl:f,ssl:e,verbose:c,cleanup:h,vitePluginUsage:l,changeOrigin:$,cleanUrls:w}=t,s=80,y=443,u="0.0.0.0",m=t.portManager||Ka;try{if(n&&!n.includes("localhost")&&!n.includes("127.0.0.1")){if(!(await ln([n],c))[0]){S.warn(`The hostname ${n} isn't in your hosts file. Adding it now...`);try{await cn([n],c),S.success(`Added ${n} to your hosts file.`)}catch(N){S.error(`Failed to add ${n} to your hosts file: ${N}`),S.info(`You may need to manually add '127.0.0.1 ${n}' to your /etc/hosts file.`)}}}else if(D.platform!=="darwin"&&n&&n.includes("localhost")&&!n.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await ln([n],c))[0]){a("hosts",`${n} not found in hosts file, adding...`,c);try{await cn([n],c)}catch(N){a("hosts",`Failed to add ${n} to hosts file: ${N}`,c)}}}if(e&&!m.usedPorts.has(s)){if(!await ai(s,u,c))a("setup","Starting HTTP redirect server",c),Aw(c),m.usedPorts.add(s);else if(a("setup","Port 80 is in use, skipping HTTP redirect",c),c)S.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let A=e?y:s,T=await ai(A,u,c),E;if(T){if(a("setup",`Port ${A} is already in use`,c),c)S.warn(`Port ${A} is already in use. This may be another instance of rpx or another service.`);if(A===443){if(E=await m.getNextAvailablePort(3443,!0),a("setup",`Using port ${E} instead of ${A}`,c),c)S.info(`Using port ${E} instead. Access your site at https://${n}:${E}`)}else if(E=await m.getNextAvailablePort(A+1000,!0),a("setup",`Using port ${E} instead of ${A}`,c),c)S.info(`Using port ${E} instead. Access your site at http://${n}:${E}`)}else E=A,m.usedPorts.add(E),a("setup",`Using standard ${A===443?"HTTPS":"HTTP"} port ${A} for ${n}`,c);await qa(i,n,r,E,u,f,e,l,c,w,$)}catch(A){a("setup",`Setup failed: ${A}`,c),S.error(`Failed to setup reverse proxy: ${A.message}`),In({domains:[n],hosts:typeof h==="boolean"?h:h?.hosts,certs:typeof h==="boolean"?h:h?.certs,verbose:c,vitePluginUsage:l})}}function Aw(t){a("redirect","Starting HTTP redirect server",t);let i=Bi.createServer((n,r)=>{let f=n.headers.host||"";a("redirect",`Redirecting request from ${f}${n.url} to HTTPS`,t),r.writeHead(301,{Location:`https://${f}${n.url}`}),r.end()}).listen(80);Wn.add(i),a("redirect","HTTP redirect server started",t)}function Oa(t){let i={...Mi,...t};if(a("proxy",`Starting proxy with options: ${ci(i)}`,i?.verbose),i.viaDaemon){if(!i.from||!i.to){S.error("viaDaemon mode requires both `from` and `to`");return}Tf({proxies:[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}],verbose:i.verbose}).catch((l)=>{S.error(`Failed to register with rpx daemon: ${l.message}`),D.exit(1)});return}let n=i.to||"",r=n.split(".").pop()?.toLowerCase()||"",f=D.platform==="darwin"&&n&&!n.includes("localhost")&&!n.includes("127.0.0.1"),e=["dev","app","page","new","day","foo"],c=["test","localhost","local","example","invalid"];if(f&&e.includes(r)&&i?.verbose)S.warn(`The .${r} TLD may not work reliably for local development`),S.info(` Google owns .${r} with HSTS preloading, which can bypass local DNS`),S.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(f)import("./chunk-6z1nzq0x.js").then(({startDnsServer:l,setupResolver:$})=>{l([n],i.verbose).then((w)=>{if(w)$(i.verbose,[n]).then(()=>{if(i.verbose)if(c.includes(r))S.success(`DNS server started for .${r} domains`);else S.success(`DNS server started for .${r} domains (hosts file entry also added)`)});else a("dns",`Could not start DNS server - ${n} may not resolve in browser`,i.verbose)})}).catch((l)=>{a("dns",`Failed to start DNS server: ${l}`,i.verbose)});let h={from:i.from,to:i.to,cleanUrls:i.cleanUrls,https:Ei(i),cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,changeOrigin:i.changeOrigin,verbose:i.verbose,regenerateUntrustedCerts:i.regenerateUntrustedCerts};a("proxy",`Server options: ${ci(h)}`,i.verbose),Wc(h).catch((l)=>{a("proxy",`Failed to start proxy: ${l}`,i.verbose),S.error(`Failed to start proxy: ${l.message}`),In({domains:[i.to],hosts:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.hosts,certs:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.certs,verbose:i.verbose})})}function Da(t){return t?.verbose||!1}async function Yc(t){let i={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(t)i={...i,...t};let n=Da(i);if(a("config",`Starting with config: ${ci(i,2)}`,n),a("config",`Is multi-proxy? ${"proxies"in i}`,n),i.viaDaemon){let m="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((A)=>({id:A.id,from:A.from,to:A.to,cleanUrls:A.cleanUrls??i.cleanUrls,changeOrigin:A.changeOrigin??i.changeOrigin,pathRewrites:A.pathRewrites})):[{id:i.id,from:i.from,to:i.to,cleanUrls:i.cleanUrls,changeOrigin:i.changeOrigin,pathRewrites:i.pathRewrites}];await Tf({proxies:m,verbose:n});return}if("proxies"in i&&Array.isArray(i.proxies)){a("servers",`Found ${i.proxies.length} proxies in config`,n);for(let u of i.proxies)if(u.start){let m=`${u.from}-${u.to}`;try{a("watch",`Starting command for ${m} with command: ${u.start.command}`,n),S.info(`Starting command for ${m}...`),await Nf.startProcess(m,u.start,n);let A=new URL(u.from.startsWith("http")?u.from:`http://${u.from}`),T=A.hostname||"localhost",E=Number(A.port)||80;try{await Yn(T,E,n),a("watch",`Dev server is ready at ${T}:${E}`,n)}catch(R){a("watch",`Connection check failed, but continuing with proxy setup: ${R}`,n),S.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(A){throw a("watch",`Failed to start command for ${m}: ${A}`,n),Error(`Failed to start command for ${m}: ${A}`)}}else a("watch",`No start command for proxy ${u.from} -> ${u.to}`,n)}else if("start"in i&&i.start){a("watch","Found start command in single proxy config",n);let u=`${i.from}-${i.to}`;try{if(i.start)a("watch",`Starting command: ${i.start.command}`,n),await Nf.startProcess(u,i.start,n);let m=new URL(i.from?.startsWith("http")?i.from:`http://${i.from}`),A=m.hostname||"localhost",T=Number(m.port)||80;try{await Yn(A,T,n),a("watch",`Dev server is ready at ${A}:${T}`,n)}catch(E){a("watch",`Connection check failed, but continuing with proxy setup: ${E}`,n),S.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(m){throw a("watch",`Failed to run start command: ${m}`,n),Error(`Failed to run start command: ${m}`)}}else a("watch","No start command found in config",n);let r="proxies"in i&&Array.isArray(i.proxies)?i.proxies[0]?.to:("to"in i)?i.to:"rpx.localhost";if(D.platform!=="win32"&&(i.https||i.cleanup?.hosts!==!1)){if(!Un())try{a("sudo","Pre-acquiring sudo credentials for privileged operations",n),za("sudo -v",{stdio:"inherit"})}catch{a("sudo","Could not pre-acquire sudo credentials",n)}}if(i.https){let u=await ni(i);if(!u){if(a("ssl",`No valid or trusted certificates found for ${r}, generating new ones`,i.verbose),await nn(i),u=await ni(i),!u)throw Error(`Failed to load SSL certificates after generation for ${r}`)}else a("ssl",`Using existing and trusted certificates for ${r}`,i.verbose);i._cachedSSLConfig=u}let f="proxies"in i&&Array.isArray(i.proxies)?i.proxies.map((u)=>({...u,https:i.https,cleanup:i.cleanup,cleanUrls:u.cleanUrls??("cleanUrls"in i?i.cleanUrls:!1),vitePluginUsage:i.vitePluginUsage,changeOrigin:u.changeOrigin??i.changeOrigin,verbose:n,_cachedSSLConfig:i._cachedSSLConfig})):[{from:"from"in i?i.from:"localhost:5173",to:"to"in i?i.to:"rpx.localhost",cleanUrls:"cleanUrls"in i?i.cleanUrls:!1,https:i.https,cleanup:i.cleanup,vitePluginUsage:i.vitePluginUsage,start:"start"in i?i.start:void 0,changeOrigin:i.changeOrigin,verbose:n,_cachedSSLConfig:i._cachedSSLConfig}],e=f.map((u)=>u.to||"rpx.localhost"),c=i._cachedSSLConfig,h=e.filter((u)=>u&&!u.includes("localhost")&&!u.includes("127.0.0.1")),l=["dev","app","page","new","day","foo"],$=["test","localhost","local","example","invalid"],w=[...new Set(h.map((u)=>u.split(".").pop()?.toLowerCase()))],s=w.filter((u)=>!!u&&l.includes(u));if(s.length>0&&n)S.warn(`The following TLDs may not work reliably for local development: ${s.map((u)=>`.${u}`).join(", ")}`),S.info(" These TLDs have HSTS preloading which can bypass local DNS"),S.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(D.platform==="darwin"&&h.length>0){let{startDnsServer:u,setupResolver:m}=await import("./chunk-6z1nzq0x.js");if(await u(h,n)){if(await m(n,h),n)if(w.every((E)=>!!E&&$.includes(E)))S.success(`DNS server started for ${w.map((E)=>`.${E}`).join(", ")} domains`);else S.success(`DNS server started for ${w.map((E)=>`.${E}`).join(", ")} domains (hosts file entries also added)`)}else a("dns","Could not start DNS server - custom domains may not resolve",n)}let y=async()=>{a("cleanup","Starting cleanup handler",i.verbose);try{let{stopDnsServer:u,removeResolver:m}=await import("./chunk-6z1nzq0x.js");u(i.verbose),await m(i.verbose)}catch(u){a("cleanup",`Error stopping DNS server: ${u}`,i.verbose)}try{await Nf.stopAll(i.verbose)}catch(u){a("cleanup",`Error stopping processes: ${u}`,i.verbose)}await In({domains:e,hosts:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.hosts,certs:typeof i.cleanup==="boolean"?i.cleanup:i.cleanup?.certs,verbose:i.verbose||!1})};if(D.on("SIGINT",y),D.on("SIGTERM",y),D.on("uncaughtException",(u)=>{a("process",`Uncaught exception: ${u}`,!0),console.error("Uncaught exception:",u),y()}),c&&f.length>1){a("proxies",`Creating shared HTTPS server for ${f.length} domains`,n);let u=new Map;for(let E of f){let R=E.to||"rpx.localhost",N=new URL(E.from?.startsWith("http")?E.from:`http://${E.from}`);if(u.set(R,{sourceHost:N.host,cleanUrls:E.cleanUrls||!1,changeOrigin:E.changeOrigin||!1,pathRewrites:E.pathRewrites}),a("proxies",`Route: ${R} → ${N.host}`,n),!R.includes("localhost")&&!R.includes("127.0.0.1"))try{if(!(await ln([R],n))[0])await cn([R],n)}catch{a("hosts",`Could not add hosts entry for ${R}`,n)}}if(!await ai(80,"0.0.0.0",n))Aw(n);let A=443;if(await ai(A,"0.0.0.0",n)){if(a("proxies",`Port ${A} is already in use, cannot start shared proxy`,n),n)S.warn(`Port ${A} is in use. Shared HTTPS proxy cannot start.`);return}try{let E=Bun.serve({port:A,hostname:"0.0.0.0",tls:{key:c.key,cert:c.cert,ca:c.ca,requestCert:!1,rejectUnauthorized:!1},fetch:_n((R)=>u.get(R),n),error(R){return a("server",`Shared proxy server error: ${R}`,n),new Response(`Server Error: ${R.message}`,{status:500})}});Wn.add(E),a("proxies",`Shared HTTPS proxy listening on port ${A} for ${u.size} domains`,n)}catch(E){a("proxies",`Failed to start shared proxy: ${E}`,n),console.error("Failed to start shared HTTPS proxy:",E),y()}}else for(let u of f)try{let m=u.to||"rpx.localhost";a("proxy",`Starting proxy for ${m} with SSL config: ${!!c}`,u.verbose),await Wc({from:u.from||"localhost:5173",to:m,cleanUrls:u.cleanUrls||!1,https:u.https||!1,cleanup:u.cleanup||!1,vitePluginUsage:u.vitePluginUsage||!1,verbose:u.verbose||!1,_cachedSSLConfig:c,changeOrigin:u.changeOrigin||!1})}catch(m){a("proxies",`Failed to start proxy for ${u.to}: ${m}`,u.verbose),console.error(`Failed to start proxy for ${u.to}:`,m),y()}}function sw(t){if(t?.vitePluginUsage||!t?.verbose)return;if(console.log(""),console.log(` ${dt.green(dt.bold("rpx"))} ${dt.green(`v${Ga}`)}`),console.log(` ${dt.green("➜")} ${dt.dim(t?.from??"")} ${dt.dim("➜")} ${dt.cyan(t?.ssl?`https://${t?.to}`:`http://${t?.to}`)}`),t?.listenPort!==(t?.ssl?443:80))console.log(` ${dt.green("➜")} Listening on port ${t?.listenPort}`);if(t?.cleanUrls)console.log(` ${dt.green("➜")} Clean URLs enabled`)}var DS=Yc;export{Rc as writeEntry,Bc as watchRegistry,V$ as verifyHttpsChain,$f as trustRootCaForBrowsers,Ya as stopDaemon,Wc as startServer,Oa as startProxy,Yc as startProxies,ci as safeStringify,v$ as safeDeleteFile,Tf as runViaDaemon,Wa as runDaemon,tw as resolvePathRewrite,Jc as removeHosts,Af as removeEntry,fn as releaseDaemonLock,LS as redactSensitive,nw as readEntry,en as readDaemonPid,Cn as readCertSha256Fingerprint,L$ as readCertCommonName,Ti as readAll,Jn as pruneStaleRootCas,Ha as portManager,o$ as parseSha256HashesFromSecurityListing,sc as normalizeSha256Fingerprint,Ta as loadSSLConfig,yc as listCertSha256HashesByCommonName,X$ as isValidRootCA,rn as isValidId,P$ as isSingleProxyOptions,VS as isSingleProxyConfig,pi as isRootCaTrustedForSsl,Qi as isRootCaFingerprintInKeychains,ai as isPortInUse,fi as isPidAlive,wf as isMultiProxyOptions,ya as isMultiProxyConfig,_a as isDaemonRunning,Ec as isCertTrusted,Ei as httpsConfig,Un as getSudoPassword,ma as getSharedDaemonCertPaths,sf as getRootCAPaths,ri as getRegistryDir,Ac as getPrimaryDomain,hf as getMacosTrustKeychains,vi as getMacosLoginKeychainPath,ei as getDaemonRpxDir,Ef as getDaemonPidPath,nn as generateCertificate,mf as gcStaleEntries,Sa as forceTrustCertificate,uw as findAvailablePort,kS as extractHostname,Fn as execSudoSync,Cc as ensureDaemonRunning,hw as deriveIdFromTarget,ew as defaultDaemonSpawnCommand,Mi as defaultConfig,DS as default,a as debugLog,_n as createProxyFetchHandler,Mi as config,dt as colors,Q$ as clearSslConfigCache,mc as cleanupCertificates,In as cleanup,ln as checkHosts,ni as checkExistingCertificates,k$ as certIncludesSanHostnames,cn as addHosts,fw as acquireDaemonLock,lf as RPX_ROOT_CA_COMMON_NAME,si as MACOS_SYSTEM_KEYCHAIN,ii as MACOS_CA_TRUST_FLAGS,jn as DefaultPortManager};
|