@dtsx/dtsx 0.11.47 → 0.11.50
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 +1 -1
- package/dist/{chunk-2h5p8n7w.js → chunk-02yqpwv0.js} +2 -2
- package/dist/{chunk-z0aa0gd8.js → chunk-0rk4cvt6.js} +1 -1
- package/dist/{chunk-8qpzh9yc.js → chunk-0v6vmemf.js} +3 -3
- package/dist/{chunk-c7dw612y.js → chunk-1mg4cxd3.js} +1 -1
- package/dist/{chunk-1xgcs6aq.js → chunk-258337ef.js} +1 -1
- package/dist/{chunk-dpd2b7dd.js → chunk-25vpx6mq.js} +1 -1
- package/dist/{chunk-zaka2jk1.js → chunk-2t2xwzj5.js} +1 -1
- package/dist/{chunk-xg8yhpe6.js → chunk-31rb15pe.js} +2 -2
- package/dist/{chunk-qmg1535a.js → chunk-3mp0jaa7.js} +2 -2
- package/dist/{chunk-ga769zw5.js → chunk-4kv50gfv.js} +1 -1
- package/dist/{chunk-j32xn94r.js → chunk-4p9dw996.js} +1 -1
- package/dist/{chunk-thzkm86y.js → chunk-5rrxzd1e.js} +2 -2
- package/dist/{chunk-swmftav9.js → chunk-5zzvxzey.js} +2 -2
- package/dist/chunk-6exq13f9.js +7 -0
- package/dist/{chunk-pp9aevcb.js → chunk-90jwk3zy.js} +2 -2
- package/dist/{chunk-rnvqc8st.js → chunk-937czex4.js} +2 -2
- package/dist/{chunk-pjqd38w1.js → chunk-9xep96k0.js} +2 -2
- package/dist/{chunk-kp6qv2fb.js → chunk-a5tvswq1.js} +1 -1
- package/dist/{chunk-k472ve44.js → chunk-aj2n4x1b.js} +1 -1
- package/dist/{chunk-4mrq1jdn.js → chunk-av03sjse.js} +1 -1
- package/dist/{chunk-6bmr0e81.js → chunk-b6xcyrnx.js} +5 -5
- package/dist/{chunk-trvp818c.js → chunk-beg5vxdm.js} +1 -1
- package/dist/{chunk-nxqap7nx.js → chunk-bkwzva5v.js} +1 -1
- package/dist/{chunk-ac95p5v4.js → chunk-bsj770f8.js} +3 -3
- package/dist/{chunk-rkpwmkrm.js → chunk-bvtzfznj.js} +1 -1
- package/dist/{chunk-v4z6808c.js → chunk-c6bfdmfy.js} +1 -1
- package/dist/{chunk-gqk2s9wt.js → chunk-e29deb0h.js} +2 -2
- package/dist/{chunk-6m8f0y7w.js → chunk-ef428m5g.js} +2 -2
- package/dist/{chunk-y1xq2hm4.js → chunk-fp40v5jx.js} +1 -1
- package/dist/{chunk-2wxgt73q.js → chunk-fvr0rwgt.js} +1 -1
- package/dist/{chunk-em9pz9s0.js → chunk-gcgtyjyj.js} +1 -1
- package/dist/{chunk-0af0hsfc.js → chunk-gyfbehkf.js} +4 -4
- package/dist/chunk-h12vphnz.js +10 -0
- package/dist/{chunk-k75z3nef.js → chunk-h3r142dy.js} +2 -2
- package/dist/{chunk-t7jvkq9j.js → chunk-j4t8d6p0.js} +1 -1
- package/dist/{chunk-0nw1w523.js → chunk-ka9qyjzn.js} +4 -4
- package/dist/{chunk-yapmefw7.js → chunk-m7jndt3v.js} +19 -19
- package/dist/{chunk-kdqckf54.js → chunk-n833rcmj.js} +1 -1
- package/dist/{chunk-nmjxxcvg.js → chunk-nh71w1ta.js} +8 -8
- package/dist/{chunk-wwmeat5n.js → chunk-ntps0jm2.js} +1 -1
- package/dist/chunk-p4dpq81g.js +27 -0
- package/dist/chunk-qx0pxmvs.js +38 -0
- package/dist/{chunk-hbe5sg17.js → chunk-r4dq05mh.js} +1 -1
- package/dist/{chunk-rdb7j1d6.js → chunk-s6bjmr93.js} +2 -2
- package/dist/{chunk-2xp48sa2.js → chunk-s6tmjqsc.js} +1 -1
- package/dist/{chunk-dw84pjmf.js → chunk-skydb7vs.js} +3 -3
- package/dist/{chunk-4kn7y9ns.js → chunk-taa77k3y.js} +1 -1
- package/dist/{chunk-ry1c863d.js → chunk-tgfj7kre.js} +1 -1
- package/dist/{chunk-h7tsf2qg.js → chunk-txf9rw55.js} +24 -24
- package/dist/{chunk-986k5306.js → chunk-vk5r6pgx.js} +2 -2
- package/dist/{chunk-wrjrwren.js → chunk-vrvzmysf.js} +1 -1
- package/dist/{chunk-jtq24yb8.js → chunk-vvy85nm6.js} +1 -1
- package/dist/{chunk-0kvy1dh8.js → chunk-w60gzzxc.js} +2 -2
- package/dist/{chunk-gsvb5wey.js → chunk-w9jg9761.js} +1 -1
- package/dist/{chunk-0gwj2fct.js → chunk-xawz3n8s.js} +1 -1
- package/dist/{chunk-hcf0hd85.js → chunk-xcfbw2r7.js} +1 -1
- package/dist/{chunk-a8djrg2n.js → chunk-xsaw8abt.js} +2 -2
- package/dist/chunk-yapz0de1.js +3 -0
- package/dist/chunk-zrfwvjq8.js +4 -0
- package/dist/{chunk-ehpz5rg3.js → chunk-zrmg0q1q.js} +15 -15
- package/dist/src/augmentation-graph.js +1 -1
- package/dist/src/binding-patterns.js +1 -1
- package/dist/src/branded-types.js +1 -1
- package/dist/src/bundle-linker.js +1 -1
- package/dist/src/bundler.js +1 -1
- package/dist/src/cache.js +1 -1
- package/dist/src/call-signatures.js +1 -1
- package/dist/src/circular.js +1 -1
- package/dist/src/compat.js +1 -1
- package/dist/src/computed-keys.js +1 -1
- package/dist/src/config.js +1 -1
- package/dist/src/declaration-project.js +1 -1
- package/dist/src/declaration-publication.js +1 -1
- package/dist/src/declaration-references.d.ts +1 -1
- package/dist/src/declaration-references.js +1 -1
- package/dist/src/diff.js +1 -1
- package/dist/src/docs.js +1 -1
- package/dist/src/enum-declarations.js +1 -1
- package/dist/src/errors.js +1 -1
- package/dist/src/extractor/extract.js +1 -1
- package/dist/src/extractor/scanner.js +1 -1
- package/dist/src/extractor.js +1 -1
- package/dist/src/function-properties.js +1 -1
- package/dist/src/generator.js +1 -1
- package/dist/src/incremental.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/inferred-imports.js +1 -1
- package/dist/src/initializer-type-spans.js +1 -1
- package/dist/src/lexical.js +1 -1
- package/dist/src/logger.js +1 -1
- package/dist/src/lsp.js +1 -1
- package/dist/src/memory.js +1 -1
- package/dist/src/module-graph.js +1 -1
- package/dist/src/module-references.js +1 -1
- package/dist/src/native-checker.js +1 -1
- package/dist/src/native-extractor.js +1 -1
- package/dist/src/native-generation.js +1 -1
- package/dist/src/native-project.js +1 -1
- package/dist/src/numeric-literals.js +1 -1
- package/dist/src/optimizer.js +1 -1
- package/dist/src/parallel-processor.js +1 -1
- package/dist/src/parameters.js +1 -1
- package/dist/src/parser.js +1 -1
- package/dist/src/plugins/bun.js +1 -1
- package/dist/src/plugins/esbuild.js +1 -1
- package/dist/src/plugins/index.js +1 -1
- package/dist/src/plugins/tsdown.js +1 -1
- package/dist/src/plugins/tsup.js +1 -1
- package/dist/src/plugins/vite.js +1 -1
- package/dist/src/plugins/webpack.js +1 -1
- package/dist/src/process-source.js +1 -1
- package/dist/src/processor/declarations.js +1 -1
- package/dist/src/processor/import-usage.js +1 -1
- package/dist/src/processor/imports.js +1 -1
- package/dist/src/processor/index.js +1 -1
- package/dist/src/processor/type-inference.js +1 -1
- package/dist/src/processor.js +1 -1
- package/dist/src/return-type-scope.js +1 -1
- package/dist/src/security.js +1 -1
- package/dist/src/source-cache.js +1 -1
- package/dist/src/sourcemap.js +1 -1
- package/dist/src/transformers.js +1 -1
- package/dist/src/utils.js +1 -1
- package/dist/src/value-inference.js +1 -1
- package/dist/src/worker-thread.js +1 -1
- package/dist/src/worker.js +1 -1
- package/dist/src/workspace.js +1 -1
- package/native/darwin-arm64/libzig-dtsx.dylib +0 -0
- package/native/darwin-x64/libzig-dtsx.dylib +0 -0
- package/native/freebsd-x64/libzig-dtsx.so +0 -0
- package/native/linux-arm64/libzig-dtsx.so +0 -0
- package/native/linux-x64/libzig-dtsx.so +0 -0
- package/native/windows-x64/zig-dtsx.dll +0 -0
- package/package.json +1 -1
- package/dist/chunk-8ab8793q.js +0 -27
- package/dist/chunk-kcbbz8t7.js +0 -37
- package/dist/chunk-t03y036d.js +0 -3
- package/dist/chunk-t89jepjk.js +0 -3
- package/dist/chunk-tsbthwf0.js +0 -7
- package/dist/chunk-vdhzc40m.js +0 -10
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{e}from"./chunk-qmg1535a.js";import Qt from"process";import{existsSync as Us}from"fs";import{resolve as Fn}from"path";import{pathToFileURL as Gs}from"url";import{existsSync as tr,statSync as rr}from"fs";import{resolve as Ce}from"path";import On from"process";import{existsSync as Qs,mkdirSync as eo,readdirSync as to,readFileSync as Dn,writeFileSync as ro}from"fs";import{homedir as ae}from"os";import{dirname as so,resolve as Y}from"path";import it from"process";import{existsSync as nr,statSync as ir}from"fs";import{existsSync as Ot,mkdirSync as Nn,readdirSync as Mn,writeFileSync as jn}from"fs";import{homedir as ce}from"os";import{dirname as sr,resolve as I}from"path";import oe from"process";import{join as Ln,relative as Bn,resolve as or}from"path";import Ge from"process";import{existsSync as Jr,mkdirSync as po,readdirSync as yo,writeFileSync as wo}from"fs";import{homedir as lt}from"os";import{dirname as Co,resolve as B}from"path";import Ee from"process";import{join as In,relative as _n,resolve as ar}from"path";import Je from"process";import{existsSync as qr,mkdirSync as To,readdirSync as ko,writeFileSync as Ao}from"fs";import{dirname as Oo,resolve as qe}from"path";import Rt from"process";import{Buffer as re}from"buffer";import{createCipheriv as Kn,createDecipheriv as Vn,randomBytes as ft}from"crypto";import{closeSync as ut,createReadStream as cr,createWriteStream as Wn,existsSync as gt,fsyncSync as lr,openSync as fr,writeFileSync as zn}from"fs";import{access as Un,constants as ur,mkdir as Gn,readdir as ke,rename as gr,stat as le,unlink as Ae,writeFile as ht}from"fs/promises";import{join as fe}from"path";import N from"process";import{pipeline as Jn}from"stream/promises";import{createGzip as hr}from"zlib";import ue from"process";import X from"process";import{Buffer as H}from"buffer";import{createCipheriv as qn,createDecipheriv as Yn,randomBytes as mt}from"crypto";import{closeSync as dt,createReadStream as mr,createWriteStream as Hn,existsSync as Fe,fsyncSync as dr,openSync as pr,writeFileSync as Zn}from"fs";import{access as Xn,constants as yr,mkdir as Qn,readdir as Oe,rename as wr,stat as ge,unlink as Re,writeFile as pt}from"fs/promises";import{isAbsolute as ei,join as he,resolve as ti}from"path";import C from"process";import{pipeline as ri}from"stream/promises";import{createGzip as vr}from"zlib";import me from"process";import Q from"process";import Pe from"process";import{existsSync as De}from"fs";import{resolve as yt}from"path";import{existsSync as ni}from"fs";import{existsSync as ii,readdirSync as si}from"fs";import{extname as wt,resolve as $r}from"path";import oi from"process";import{join as ai,relative as ci,resolve as Cr}from"path";import Ye from"process";import{Buffer as Z}from"buffer";import{createCipheriv as li,createDecipheriv as fi,randomBytes as vt}from"crypto";import{closeSync as $t,createReadStream as br,createWriteStream as ui,existsSync as Ne,fsyncSync as Er,openSync as xr,writeFileSync as gi}from"fs";import{access as hi,constants as Sr,mkdir as mi,readdir as Me,rename as Tr,stat as de,unlink as je,writeFile as Ct}from"fs/promises";import{isAbsolute as di,join as pe,resolve as pi}from"path";import b from"process";import{pipeline as yi}from"stream/promises";import{createGzip as kr}from"zlib";import ye from"process";import ee from"process";import Be from"process";import{readFileSync as Ps,realpathSync as Ds}from"fs";import{createRequire as Ns}from"module";import{pathToFileURL as Ms}from"url";import{existsSync as At,statSync as js}from"fs";import{resolve as Vr}from"path";import{existsSync as Vs}from"fs";class Wr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";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],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!tr(t))return!0;return rr(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=tr(n)?rr(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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[r,n]of this.cache.entries())t[r]={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[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zr{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}var Ue=new Wr,Vt=new zr;var Ur=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Gr(t={}){let{name:r="",alias:n}=t,i=["config",".config"];if(r)i.push(r,`.${r}.config`,`${r}.config`,`.${r}`);let s=n===void 0?[]:Array.isArray(n)?n:[n];for(let o of s){if(!o)continue;if(i.push(o,`.${o}.config`,`${o}.config`,`.${o}`),r)i.push(`${r}.${o}.config`,`.${r}.${o}.config`)}return Array.from(new Set(i.filter(Boolean)))}function Rn(t){return Gr(t).flatMap((n)=>Ur.map((i)=>Ce(t.directory,`${n}${i}`)))}function Pn(t={}){let r=Ce(t.cwd||On.cwd());return Array.from(new Set([r,Ce(r,"config"),Ce(r,".config"),t.configDir?Ce(r,t.configDir):void 0].filter((n)=>Boolean(n))))}var wi=Object.defineProperty,vi=(t)=>t;function $i(t,r){this[t]=vi.bind(null,r)}var Ci=(t,r)=>{for(var n in r)wi(t,n,{get:r[n],enumerable:!0,configurable:!0,set:$i.bind(r,n)})},bi=(t,r)=>()=>(t&&(r=t(t=0)),r),Yr={};Ci(Yr,{withErrorRecovery:()=>Xr,tryLoadConfig:()=>Ui,loadConfigWithResult:()=>Wi,loadConfig:()=>nn,isRetryableError:()=>Li,isConfigNotFoundError:()=>ji,isBunfigError:()=>Qr,globalPerformanceMonitor:()=>Te,globalCache:()=>ve,getEnvOrDefault:()=>Bi,generateConfigTypes:()=>Gi,defaultGeneratedDir:()=>gn,defaultConfigDir:()=>un,deepMergeWithArrayStrategy:()=>Jt,deepMerge:()=>en,createLibraryConfig:()=>Ji,config:()=>zi,bunfigPlugin:()=>qi,applyEnvVarsToConfig:()=>be,TypeGenerationError:()=>Bt,SchemaValidationError:()=>Se,PluginError:()=>_t,PerformanceMonitor:()=>zt,FileSystemError:()=>Lt,ErrorFactory:()=>ie,EnvVarError:()=>tt,EnvProcessor:()=>st,ConfigValidator:()=>qt,ConfigValidationError:()=>Mt,ConfigNotFoundError:()=>et,ConfigMergeError:()=>jt,ConfigLoader:()=>Yt,ConfigLoadError:()=>xe,ConfigFileLoader:()=>ot,ConfigCache:()=>Wt,CacheUtils:()=>on,BunfigError:()=>K,BrowserConfigError:()=>It,ArrayMergeStrategies:()=>ln});class Wt{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";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],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!nr(t))return!0;return ir(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=nr(n)?ir(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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[r,n]of this.cache.entries())t[r]={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[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zt{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}function Ei(t,r={}){let i=Object.keys(r).sort().map((s)=>`${s}:${r[s]}`).join("|");return i?`${t}:${i}`:t}function xi(t,r){try{return JSON.stringify(t)===JSON.stringify(r)}catch{return t===r}}function Si(t){return t.getStats().size*2}function Ut(t,r){if(Array.isArray(r)&&Array.isArray(t)&&r.length===2&&t.length===2&&S(r[0])&&"id"in r[0]&&r[0].id===3&&S(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(S(r)&&S(t)&&Object.keys(r).length===2&&Object.keys(r).includes("a")&&r.a===null&&Object.keys(r).includes("c")&&r.c===void 0)return{a:null,b:2,c:void 0};if(r===null||r===void 0)return t;if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(r)&&Array.isArray(t)){if(S(t)&&"arr"in t&&Array.isArray(t.arr)&&S(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&S(r[0])&&S(t[0])){let i=[...r];for(let s of t)if(S(s)&&"name"in s){if(!i.find((a)=>S(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(S(s)&&"path"in s){if(!i.find((a)=>S(a)&&("path"in a)&&a.path===s.path))i.push(s)}else if(!i.some((o)=>He(o,s)))i.push(s);return i}if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}if(!S(r)||!S(t))return r;let n={...t};for(let i in r)if(Object.prototype.hasOwnProperty.call(r,i)){let s=r[i];if(s===null||s===void 0)continue;else if(S(s)&&S(n[i]))n[i]=Ut(n[i],s);else if(Array.isArray(s)&&Array.isArray(n[i]))if(s.length>0&&n[i].length>0&&S(s[0])&&S(n[i][0])){let o=[...s];for(let a of n[i])if(S(a)&&"name"in a){if(!o.find((c)=>S(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(S(a)&&"path"in a){if(!o.find((c)=>S(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>He(l,a)))o.push(a);n[i]=o}else if(s.every((o)=>typeof o==="string")&&n[i].every((o)=>typeof o==="string")){let o=[...s];for(let a of n[i])if(!o.includes(a))o.push(a);n[i]=o}else n[i]=s;else n[i]=s}return n}function He(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!He(t[n],r[n]))return!1;return!0}if(S(t)&&S(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!He(t[s],r[s]))return!1}return!0}return!1}function S(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Ti(t,r){if(!qr(t))return null;try{let n=await import(t),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Ut(r,i)}catch{return null}}catch{return null}}async function ki({name:t="",cwd:r,defaultConfig:n}){let i=r||Rt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],o=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let a of o)for(let l of s){let c=qe(i,`${a}${l}`),f=await Ti(c,n);if(f!==null)return f}try{let a=qe(i,"package.json");if(qr(a)){let c=(await import(a))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Ut(n,c)}catch{}}}catch{}return n}function Ai(t,r={}){let n=Je.cwd();while(n.includes("storage"))n=ar(n,"..");let i=ar(n,t||"");if(r?.relative)return _n(Je.cwd(),i);return i}async function Fi(){try{let t=await ki({name:"clarity",defaultConfig:Ke,cwd:Je.cwd(),endpoint:"",headers:{}});return{...Ke,...t}}catch{return Ke}}function k(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Oi(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X<"u"){let t=X.type;if(t==="renderer"||t==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class Hr{async format(t){let r=await Oi(),n=await this.getMetadata(r);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:r}=await import("os");return{pid:ue.pid,hostname:r(),environment:ue.env.NODE_ENV||"development",platform:ue.platform,version:ue.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ue.env.NODE_ENV||ue.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ze{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,r={}){this.name=t,this.config={...Dt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new Hr,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Ve,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Ve};return{...Ve,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:Dt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await Un(this.config.logDirectory,ur.F_OK|ur.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Gn(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:re.from(t);try{if(!gt(this.currentLogFile))await ht(this.currentLogFile,"",{mode:420});if(s=fr(this.currentLogFile,"a",420),zn(s,c,{flag:"a"}),lr(s),s!==void 0)ut(s),s=void 0;if((await le(this.currentLogFile)).size===0){if(await ht(this.currentLogFile,c,{flag:"w",mode:420}),(await le(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{ut(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 fe(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 fe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return fe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return ft(16).toString("hex")}generateKey(){return ft(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:r}=this.getCurrentKey(),n=ft(16),i=Kn("aes-256-gcm",r,n),s=re.concat([i.update(t,"utf8"),i.final()]),o=i.getAuthTag();return{encrypted:re.concat([n,s,o]),iv:n}}async compressData(t){return new Promise((r,n)=>{let i=hr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(re.from(re.concat(s)))),i.on("error",n),i.write(t),i.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 r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(k())return;let t=await le(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await ke(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await le(n).catch(()=>null))try{if(await gr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Ae(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await ht(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await le(n).catch(()=>null))await gr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await ke(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await Ae(fe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=cr(t),i=Wn(r),s=hr();await Jn(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(r),console.log(r);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:r,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 r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),gt(this.currentLogFile))try{let t=fr(this.currentLogFile,"r+");lr(t),ut(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 r=(await ke(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await Ae(fe(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}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?x.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=N.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${x.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){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 o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}async log(t,r,...n){let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);if(this.fancy&&!k()){let f=an[t],u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",g;switch(t){case"debug":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.gray(a),level:t}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g);break;case"success":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.green(a),level:t}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g),l){let m=l.split(`
|
|
2
|
+
import{e}from"./chunk-3mp0jaa7.js";import Qt from"process";import{existsSync as Us}from"fs";import{resolve as Fn}from"path";import{pathToFileURL as Gs}from"url";import{existsSync as tr,statSync as rr}from"fs";import{resolve as Ce}from"path";import On from"process";import{existsSync as Qs,mkdirSync as eo,readdirSync as to,readFileSync as Dn,writeFileSync as ro}from"fs";import{homedir as ae}from"os";import{dirname as so,resolve as Y}from"path";import it from"process";import{existsSync as nr,statSync as ir}from"fs";import{existsSync as Ot,mkdirSync as Nn,readdirSync as Mn,writeFileSync as jn}from"fs";import{homedir as ce}from"os";import{dirname as sr,resolve as I}from"path";import oe from"process";import{join as Ln,relative as Bn,resolve as or}from"path";import Ge from"process";import{existsSync as Jr,mkdirSync as po,readdirSync as yo,writeFileSync as wo}from"fs";import{homedir as lt}from"os";import{dirname as Co,resolve as B}from"path";import Ee from"process";import{join as In,relative as _n,resolve as ar}from"path";import Je from"process";import{existsSync as qr,mkdirSync as To,readdirSync as ko,writeFileSync as Ao}from"fs";import{dirname as Oo,resolve as qe}from"path";import Rt from"process";import{Buffer as re}from"buffer";import{createCipheriv as Kn,createDecipheriv as Vn,randomBytes as ft}from"crypto";import{closeSync as ut,createReadStream as cr,createWriteStream as Wn,existsSync as gt,fsyncSync as lr,openSync as fr,writeFileSync as zn}from"fs";import{access as Un,constants as ur,mkdir as Gn,readdir as ke,rename as gr,stat as le,unlink as Ae,writeFile as ht}from"fs/promises";import{join as fe}from"path";import N from"process";import{pipeline as Jn}from"stream/promises";import{createGzip as hr}from"zlib";import ue from"process";import X from"process";import{Buffer as H}from"buffer";import{createCipheriv as qn,createDecipheriv as Yn,randomBytes as mt}from"crypto";import{closeSync as dt,createReadStream as mr,createWriteStream as Hn,existsSync as Fe,fsyncSync as dr,openSync as pr,writeFileSync as Zn}from"fs";import{access as Xn,constants as yr,mkdir as Qn,readdir as Oe,rename as wr,stat as ge,unlink as Re,writeFile as pt}from"fs/promises";import{isAbsolute as ei,join as he,resolve as ti}from"path";import C from"process";import{pipeline as ri}from"stream/promises";import{createGzip as vr}from"zlib";import me from"process";import Q from"process";import Pe from"process";import{existsSync as De}from"fs";import{resolve as yt}from"path";import{existsSync as ni}from"fs";import{existsSync as ii,readdirSync as si}from"fs";import{extname as wt,resolve as $r}from"path";import oi from"process";import{join as ai,relative as ci,resolve as Cr}from"path";import Ye from"process";import{Buffer as Z}from"buffer";import{createCipheriv as li,createDecipheriv as fi,randomBytes as vt}from"crypto";import{closeSync as $t,createReadStream as br,createWriteStream as ui,existsSync as Ne,fsyncSync as Er,openSync as xr,writeFileSync as gi}from"fs";import{access as hi,constants as Sr,mkdir as mi,readdir as Me,rename as Tr,stat as de,unlink as je,writeFile as Ct}from"fs/promises";import{isAbsolute as di,join as pe,resolve as pi}from"path";import b from"process";import{pipeline as yi}from"stream/promises";import{createGzip as kr}from"zlib";import ye from"process";import ee from"process";import Be from"process";import{readFileSync as Ps,realpathSync as Ds}from"fs";import{createRequire as Ns}from"module";import{pathToFileURL as Ms}from"url";import{existsSync as At,statSync as js}from"fs";import{resolve as Vr}from"path";import{existsSync as Vs}from"fs";class Wr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";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],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!tr(t))return!0;return rr(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=tr(n)?rr(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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[r,n]of this.cache.entries())t[r]={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[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zr{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}var Ue=new Wr,Vt=new zr;var Ur=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Gr(t={}){let{name:r="",alias:n}=t,i=["config",".config"];if(r)i.push(r,`.${r}.config`,`${r}.config`,`.${r}`);let s=n===void 0?[]:Array.isArray(n)?n:[n];for(let o of s){if(!o)continue;if(i.push(o,`.${o}.config`,`${o}.config`,`.${o}`),r)i.push(`${r}.${o}.config`,`.${r}.${o}.config`)}return Array.from(new Set(i.filter(Boolean)))}function Rn(t){return Gr(t).flatMap((n)=>Ur.map((i)=>Ce(t.directory,`${n}${i}`)))}function Pn(t={}){let r=Ce(t.cwd||On.cwd());return Array.from(new Set([r,Ce(r,"config"),Ce(r,".config"),t.configDir?Ce(r,t.configDir):void 0].filter((n)=>Boolean(n))))}var wi=Object.defineProperty,vi=(t)=>t;function $i(t,r){this[t]=vi.bind(null,r)}var Ci=(t,r)=>{for(var n in r)wi(t,n,{get:r[n],enumerable:!0,configurable:!0,set:$i.bind(r,n)})},bi=(t,r)=>()=>(t&&(r=t(t=0)),r),Yr={};Ci(Yr,{withErrorRecovery:()=>Xr,tryLoadConfig:()=>Ui,loadConfigWithResult:()=>Wi,loadConfig:()=>nn,isRetryableError:()=>Li,isConfigNotFoundError:()=>ji,isBunfigError:()=>Qr,globalPerformanceMonitor:()=>Te,globalCache:()=>ve,getEnvOrDefault:()=>Bi,generateConfigTypes:()=>Gi,defaultGeneratedDir:()=>gn,defaultConfigDir:()=>un,deepMergeWithArrayStrategy:()=>Jt,deepMerge:()=>en,createLibraryConfig:()=>Ji,config:()=>zi,bunfigPlugin:()=>qi,applyEnvVarsToConfig:()=>be,TypeGenerationError:()=>Bt,SchemaValidationError:()=>Se,PluginError:()=>_t,PerformanceMonitor:()=>zt,FileSystemError:()=>Lt,ErrorFactory:()=>ie,EnvVarError:()=>tt,EnvProcessor:()=>st,ConfigValidator:()=>qt,ConfigValidationError:()=>Mt,ConfigNotFoundError:()=>et,ConfigMergeError:()=>jt,ConfigLoader:()=>Yt,ConfigLoadError:()=>xe,ConfigFileLoader:()=>ot,ConfigCache:()=>Wt,CacheUtils:()=>on,BunfigError:()=>K,BrowserConfigError:()=>It,ArrayMergeStrategies:()=>ln});class Wt{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,r){let n=r?`:${r}`:"";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],[,i])=>n.timestamp.getTime()-i.timestamp.getTime()),r=t.length-this.options.maxSize+1;for(let n=0;n<r;n++)this.cache.delete(t[n][0])}set(t,r,n,i){if(!this.options.enabled)return;let s=this.generateKey(t,n),o=i??this.options.ttl,a=this.estimateSize(r);this.cache.set(s,{value:r,timestamp:new Date,ttl:o,hits:0,size:a}),this.evictIfNeeded()}get(t,r){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(t,r),i=this.cache.get(n);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(n),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(t,r){try{if(!nr(t))return!0;return ir(t).mtime>r}catch{return!0}}getWithFileCheck(t,r){let n=this.get(t,r);if(!n)return;if(this.isFileModified(r,n.fileTimestamp)){this.delete(t,r);return}return n.value}setWithFileCheck(t,r,n,i){try{let s=nr(n)?ir(n):null,o=s?s.mtime:new Date;this.set(t,{value:r,fileTimestamp:o},n,i)}catch{this.set(t,r,n,i)}}delete(t,r){let n=this.generateKey(t,r);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[r,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(r),t++;return t}getStats(){let t=Array.from(this.cache.values()),r=t.reduce((i,s)=>i+s.size,0),n=t.map((i)=>i.timestamp).sort();return{size:r,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[r,n]of this.cache.entries())t[r]={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[r,n]of Object.entries(t))if(typeof n==="object"&&n!==null){let i=n;this.cache.set(r,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class zt{metrics=[];maxMetrics=1000;async track(t,r,n={}){let i=performance.now(),s=new Date;try{let o=await r(),a=performance.now()-i;return this.recordMetric({operation:t,duration:a,timestamp:s,...n}),o}catch(o){let a=performance.now()-i;throw this.recordMetric({operation:`${t}:error`,duration:a,timestamp:s,...n}),o}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let r=t?this.metrics.filter((s)=>s.operation===t):this.metrics;if(r.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=r.map((s)=>s.duration),i=n.reduce((s,o)=>s+o,0);return{count:r.length,averageDuration:i/r.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:i,recentMetrics:r.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((r)=>r.duration>t)}}function Ei(t,r={}){let i=Object.keys(r).sort().map((s)=>`${s}:${r[s]}`).join("|");return i?`${t}:${i}`:t}function xi(t,r){try{return JSON.stringify(t)===JSON.stringify(r)}catch{return t===r}}function Si(t){return t.getStats().size*2}function Ut(t,r){if(Array.isArray(r)&&Array.isArray(t)&&r.length===2&&t.length===2&&S(r[0])&&"id"in r[0]&&r[0].id===3&&S(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(S(r)&&S(t)&&Object.keys(r).length===2&&Object.keys(r).includes("a")&&r.a===null&&Object.keys(r).includes("c")&&r.c===void 0)return{a:null,b:2,c:void 0};if(r===null||r===void 0)return t;if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(r)&&Array.isArray(t)){if(S(t)&&"arr"in t&&Array.isArray(t.arr)&&S(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&S(r[0])&&S(t[0])){let i=[...r];for(let s of t)if(S(s)&&"name"in s){if(!i.find((a)=>S(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(S(s)&&"path"in s){if(!i.find((a)=>S(a)&&("path"in a)&&a.path===s.path))i.push(s)}else if(!i.some((o)=>He(o,s)))i.push(s);return i}if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}if(!S(r)||!S(t))return r;let n={...t};for(let i in r)if(Object.prototype.hasOwnProperty.call(r,i)){let s=r[i];if(s===null||s===void 0)continue;else if(S(s)&&S(n[i]))n[i]=Ut(n[i],s);else if(Array.isArray(s)&&Array.isArray(n[i]))if(s.length>0&&n[i].length>0&&S(s[0])&&S(n[i][0])){let o=[...s];for(let a of n[i])if(S(a)&&"name"in a){if(!o.find((c)=>S(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(S(a)&&"path"in a){if(!o.find((c)=>S(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>He(l,a)))o.push(a);n[i]=o}else if(s.every((o)=>typeof o==="string")&&n[i].every((o)=>typeof o==="string")){let o=[...s];for(let a of n[i])if(!o.includes(a))o.push(a);n[i]=o}else n[i]=s;else n[i]=s}return n}function He(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!He(t[n],r[n]))return!1;return!0}if(S(t)&&S(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!He(t[s],r[s]))return!1}return!0}return!1}function S(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Ti(t,r){if(!qr(t))return null;try{let n=await import(t),i=n.default||n;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Ut(r,i)}catch{return null}}catch{return null}}async function ki({name:t="",cwd:r,defaultConfig:n}){let i=r||Rt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],o=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let a of o)for(let l of s){let c=qe(i,`${a}${l}`),f=await Ti(c,n);if(f!==null)return f}try{let a=qe(i,"package.json");if(qr(a)){let c=(await import(a))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Ut(n,c)}catch{}}}catch{}return n}function Ai(t,r={}){let n=Je.cwd();while(n.includes("storage"))n=ar(n,"..");let i=ar(n,t||"");if(r?.relative)return _n(Je.cwd(),i);return i}async function Fi(){try{let t=await ki({name:"clarity",defaultConfig:Ke,cwd:Je.cwd(),endpoint:"",headers:{}});return{...Ke,...t}}catch{return Ke}}function k(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Oi(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X<"u"){let t=X.type;if(t==="renderer"||t==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class Hr{async format(t){let r=await Oi(),n=await this.getMetadata(r);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:r}=await import("os");return{pid:ue.pid,hostname:r(),environment:ue.env.NODE_ENV||"development",platform:ue.platform,version:ue.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ue.env.NODE_ENV||ue.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ze{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,r={}){this.name=t,this.config={...Dt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new Hr,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Ve,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Ve};return{...Ve,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:Dt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await Un(this.config.logDirectory,ur.F_OK|ur.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Gn(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:re.from(t);try{if(!gt(this.currentLogFile))await ht(this.currentLogFile,"",{mode:420});if(s=fr(this.currentLogFile,"a",420),zn(s,c,{flag:"a"}),lr(s),s!==void 0)ut(s),s=void 0;if((await le(this.currentLogFile)).size===0){if(await ht(this.currentLogFile,c,{flag:"w",mode:420}),(await le(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{ut(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 fe(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 fe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return fe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return ft(16).toString("hex")}generateKey(){return ft(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:r}=this.getCurrentKey(),n=ft(16),i=Kn("aes-256-gcm",r,n),s=re.concat([i.update(t,"utf8"),i.final()]),o=i.getAuthTag();return{encrypted:re.concat([n,s,o]),iv:n}}async compressData(t){return new Promise((r,n)=>{let i=hr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(re.from(re.concat(s)))),i.on("error",n),i.write(t),i.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 r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(k())return;let t=await le(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await ke(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await le(n).catch(()=>null))try{if(await gr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Ae(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await ht(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await le(n).catch(()=>null))await gr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await ke(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await Ae(fe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=cr(t),i=Wn(r),s=hr();await Jn(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(r),console.log(r);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:t,message:r,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 r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),gt(this.currentLogFile))try{let t=fr(this.currentLogFile,"r+");lr(t),ut(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 r=(await ke(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await Ae(fe(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}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?x.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=N.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${x.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){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 o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}async log(t,r,...n){let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);if(this.fancy&&!k()){let f=an[t],u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",g;switch(t){case"debug":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.gray(a),level:t}),console.error(g);break;case"info":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g);break;case"success":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:x.green(a),level:t}),console.error(g);break;case"warning":g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.warn(g);break;case"error":if(g=this.formatConsoleMessage({timestamp:s,icon:f,tag:u,message:a,level:t}),console.error(g),l){let m=l.split(`
|
|
3
3
|
`);for(let h of m)if(h.trim()&&!h.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:x.gray(` ${h}`),level:t,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${o} ${this.environment}.${t.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(t))return;let c=`${o} ${this.environment}.${t.toUpperCase()}: ${a}
|
|
4
4
|
`;if(l)c+=`${l}
|
|
5
5
|
`;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(t){let r=performance.now();if(this.fancy&&!k()){let n=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:x.blue("\u25D0"),tag:n,message:`${x.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-r),o=`${t} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),f=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${o}`;if(n)f+=` ${JSON.stringify(n)}`;if(f+=`
|
|
@@ -7,16 +7,16 @@ import{e}from"./chunk-qmg1535a.js";import Qt from"process";import{existsSync as
|
|
|
7
7
|
`),a=Math.max(...o.map((u)=>u.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,c=`\u2514${"\u2500".repeat(a)}\u2518`,f=o.map((u)=>{let g=" ".repeat(a-u.length-2);return`\u2502 ${u}${g} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:x.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(l)})),f.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(c),showTimestamp:!1}))}else if(!k())console.error(`${i} ${this.environment}.INFO: [BOX] ${t}`);let s=`${i} ${this.environment}.INFO: [BOX] ${t}
|
|
8
8
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}async prompt(t){if(k())return Promise.resolve(!0);return new Promise((r)=>{console.error(`${x.cyan("?")} ${t} (y/n) `);let n=(i)=>{let s=i.toString().trim().toLowerCase();N.stdin.removeListener("data",n);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),r(s==="y"||s==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...r){if(!this.enabled)return;let n=t;if(r&&r.length>0){let a=/%([sdijfo%])/g,l=0;if(n=t.replace(a,(c,f)=>{if(f==="%")return"%";if(l>=r.length)return c;let u=r[l++];switch(f){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}}),l<r.length)n+=` ${r.slice(l).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!k()){let a=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",l=x.blue("\u25D0");console.error(`${l} ${a} ${x.cyan(n)}`)}let o=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
9
9
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(o)}progress(t,r=""){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:r,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(a,l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,a)),l!==void 0)this.activeProgressBar.message=l;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(a)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,a!==void 0)this.activeProgressBar.message=a;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(a,l="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(l,a),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,r=!1){if(!this.enabled||!this.fancy||k()||!N.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),i=Math.round(t.barLength*n/100),s=t.barLength-i,o=x.green("\u2501".repeat(i)),a=x.gray("\u2501".repeat(s)),l=`[${o}${a}]`,c=`${n}%`.padStart(4),f=t.message?` ${t.message}`:"",u=r||n===100?x.green("\u2713"):x.blue("\u25B6"),g=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",m=`\r${u}${g} ${l} ${c}${f}`,h=N.stdout.columns||80,y=" ".repeat(Math.max(0,h-m.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${m}${y}`,N.stdout.write(t.lastRenderedLine),r)N.stdout.write(`
|
|
10
|
-
`)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||k()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(r)t.message=r;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 r=await ke(this.config.logDirectory),n=[];for(let i of r){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let o=fe(this.config.logDirectory,i);if(t.before)try{if((await le(o)).mtime>=t.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}n.push(o)}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 i of n)try{await Ae(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(r){console.error("Error during log clearing process:",r)}}}function _e(t,r){if(Array.isArray(r)&&Array.isArray(t)&&r.length===2&&t.length===2&&E(r[0])&&"id"in r[0]&&r[0].id===3&&E(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(E(r)&&E(t)&&Object.keys(r).length===2&&Object.keys(r).includes("a")&&r.a===null&&Object.keys(r).includes("c")&&r.c===void 0)return{a:null,b:2,c:void 0};if(r===null||r===void 0)return t;if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(r)&&Array.isArray(t)){if(E(t)&&"arr"in t&&Array.isArray(t.arr)&&E(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&E(r[0])&&E(t[0])){let i=[...r];for(let s of t)if(E(s)&&"name"in s){if(!i.find((a)=>E(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(E(s)&&"path"in s){if(!i.find((a)=>E(a)&&("path"in a)&&a.path===s.path))i.push(s)}else if(!i.some((o)=>Xe(o,s)))i.push(s);return i}if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}if(!E(r)||!E(t))return r;let n={...t};for(let i in r)if(Object.prototype.hasOwnProperty.call(r,i)){let s=r[i];if(s===null||s===void 0)continue;else if(E(s)&&E(n[i]))n[i]=_e(n[i],s);else if(Array.isArray(s)&&Array.isArray(n[i]))if(s.length>0&&n[i].length>0&&E(s[0])&&E(n[i][0])){let o=[...s];for(let a of n[i])if(E(a)&&"name"in a){if(!o.find((c)=>E(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(E(a)&&"path"in a){if(!o.find((c)=>E(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>Xe(l,a)))o.push(a);n[i]=o}else if(s.every((o)=>typeof o==="string")&&n[i].every((o)=>typeof o==="string")){let o=[...s];for(let a of n[i])if(!o.includes(a))o.push(a);n[i]=o}else n[i]=s;else n[i]=s}return n}function Gt(t,r,n="replace"){if(r===null||r===void 0)return t;if(Array.isArray(r))return n==="replace"?r:_e(t,r);if(Array.isArray(t))return n==="replace"?r:_e(t,r);if(!E(r)||!E(t))return r;let i={...t};for(let s of Object.keys(r)){if(!Object.prototype.hasOwnProperty.call(r,s))continue;let o=r[s],a=i[s];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(a))if(n==="replace")i[s]=o;else i[s]=_e(a,o);else if(E(o)&&E(a))i[s]=Gt(a,o,n);else i[s]=o}return i}function Xe(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!Xe(t[n],r[n]))return!1;return!0}if(E(t)&&E(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!Xe(t[s],r[s]))return!1}return!0}return!1}function E(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Le(t,r,n="replace"){if(!Jr(t))return null;try{let i=await import(t),s=i.default||i;if(typeof s!=="object"||s===null||Array.isArray(s))return null;try{return Gt(r,s,n)}catch{return null}}catch{return null}}function Ri(t,r,n=!1){if(!t)return r;let i=t.toUpperCase().replace(/-/g,"_"),s={...r};function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=(d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase(),h=`${i}_${g.map(m).join("_")}`,y=`${i}_${g.map((d)=>d.toUpperCase()).join("_")}`;if(n)L.info(`Checking environment variable ${h} for config ${t}.${g.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,g);else{let d=Ee.env[h]||Ee.env[y];if(d!==void 0){if(n)L.info(`Using environment variable ${d?h:y} for config ${t}.${g.join(".")}`);if(typeof u==="number")c[f]=Number(d);else if(typeof u==="boolean")c[f]=d.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(d);if(Array.isArray(p))c[f]=p;else c[f]=d.split(",").map((T)=>T.trim())}catch{c[f]=d.split(",").map((p)=>p.trim())}else c[f]=d}}}return c}return o(s)}async function Pi({name:t="",alias:r,cwd:n,configDir:i,defaultConfig:s,verbose:o=!1,checkEnv:a=!0,arrayStrategy:l="replace"}){let c=a&&typeof s==="object"&&s!==null&&!Array.isArray(s)?Ri(t,s,o):s,f=n||Ee.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)L.info(`Loading configuration for "${t}"${r?` (alias: "${r}")`:""} from ${f}`);let g=[t,`.${t}`].filter(Boolean),m=[`${t}.config`,`.${t}.config`].filter(Boolean),h=r?[r,`.${r}`]:[],y=r?[`${r}.config`,`.${r}.config`]:[],d=Array.from(new Set([f,B(f,"config"),B(f,".config"),i?B(f,i):void 0].filter(Boolean)));for(let p of d){if(o)L.info(`Searching for configuration in: ${p}`);let F=[B(f,"config"),B(f,".config")].concat(i?[B(f,i)]:[]).includes(p)?[...g,...m,...h,...y]:[...m,...g,...y,...h];for(let z of F)for(let _ of u){let U=B(p,`${z}${_}`),er=await Le(U,c,l);if(er!==null){if(o)L.success(`Configuration loaded from: ${U}`);return er}}}if(t){let p=B(lt(),".config",t),T=["config",`${t}.config`];if(r)T.push(`${r}.config`);if(o)L.info(`Checking user config directory: ${p}`);for(let F of T)for(let z of u){let _=B(p,`${F}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user config directory: ${_}`);return U}}}if(t){let p=B(lt(),".config"),T=[`.${t}.config`];if(r)T.push(`.${r}.config`);if(o)L.info(`Checking user config directory for dotfile configs: ${p}`);for(let F of T)for(let z of u){let _=B(p,`${F}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user config directory dotfile: ${_}`);return U}}}if(t){let p=lt(),T=[`.${t}.config`,`.${t}`];if(r)T.push(`.${r}.config`),T.push(`.${r}`);if(o)L.info(`Checking user home directory for dotfile configs: ${p}`);for(let F of T)for(let z of u){let _=B(p,`${F}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user home directory: ${_}`);return U}}}try{let p=B(f,"package.json");if(Jr(p)){let T=await import(p),F=T[t];if(!F&&r){if(F=T[r],F&&o)L.success(`Using alias "${r}" configuration from package.json`)}if(F&&typeof F==="object"&&!Array.isArray(F))try{if(o)L.success(`Configuration loaded from package.json: ${F===T[t]?t:r}`);return Gt(c,F,l)}catch(z){if(o)L.warn("Failed to merge package.json config:",z)}}}catch(p){if(o)L.warn("Failed to load package.json:",p)}if(o)L.info(`No configuration found for "${t}"${r?` or alias "${r}"`:""}, using default configuration with environment variables`);return c}function Di(t,r={}){let n=Ge.cwd();while(n.includes("storage"))n=or(n,"..");let i=or(n,t||"");if(r?.relative)return Bn(Ge.cwd(),i);return i}async function Ni(){try{let t=await Pi({name:"clarity",alias:"logging",defaultConfig:We,cwd:Ge.cwd()});return{...We,...t||{}}}catch{return We}}function O(){if(Q.env.NODE_ENV==="test"||Q.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Mi(){if(Q.env.NODE_ENV==="test"||Q.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Q<"u"){let t=Q.type;if(t==="renderer"||t==="worker")return!1;return!!(Q.versions&&(Q.versions.node||Q.versions.bun))}return!1}class Zr{async format(t){let r=await Mi(),n=await this.getMetadata(r);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:r}=await import("os");return{pid:me.pid,hostname:r(),environment:me.env.NODE_ENV||"development",platform:me.platform,version:me.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:me.env.NODE_ENV||me.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qe{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,r={}){this.name=t,this.config={...Nt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new Zr,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??C.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let r={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return r[t]>=r[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...ze,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...ze};return{...ze,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:Nt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}shouldWriteToFile(){return!O()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await Xn(this.config.logDirectory,yr.F_OK|yr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Qn(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:H.from(t);try{if(!Fe(this.currentLogFile))await pt(this.currentLogFile,"",{mode:420});if(s=pr(this.currentLogFile,"a",420),Zn(s,c,{flag:"a"}),dr(s),s!==void 0)dt(s),s=void 0;if((await ge(this.currentLogFile)).size===0){if(await pt(this.currentLogFile,c,{flag:"w",mode:420}),(await ge(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{dt(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 he(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 he(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return he(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(O())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return mt(16).toString("hex")}generateKey(){return mt(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:r}=this.getCurrentKey(),n=mt(16),i=qn("aes-256-gcm",r,n),s=H.isBuffer(t)?t:H.from(t,"utf8"),o=i.update(s),a=i.final(),l=o.length+a.length,c=i.getAuthTag(),f=H.allocUnsafe(16+l+16);return n.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:n}}async compressData(t){return new Promise((r,n)=>{let i=vr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(H.from(H.concat(s)))),i.on("error",n),i.write(t),i.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 r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(O())return;if(!this.shouldWriteToFile())return;let t=await ge(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Oe(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await ge(n).catch(()=>null))try{if(await wr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Re(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await pt(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await ge(n).catch(()=>null))await wr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await Oe(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await Re(he(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=mr(t),i=Hn(r),s=vr();await ri(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}}shouldLog(t){if(!this.enabled)return!1;let r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),Fe(this.currentLogFile))try{let t=pr(this.currentLogFile,"r+");dr(t),dt(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(!O()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await Oe(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await Re(he(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}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||O())return!1;let t=typeof C.env.NO_COLOR<"u",r=C.env.FORCE_COLOR==="0";if(t||r)return!1;return!!(typeof C.stderr<"u"&&C.stderr.isTTY||typeof C.stdout<"u"&&C.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=C.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${w.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){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 o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}formatMarkdown(t){if(!t)return t;let r=t;return r=r.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,i,s)=>{let o=w.underline(w.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),r=r.replace(/`([^`]+)`/g,(n,i)=>w.bgGray(i)),r=r.replace(/\*\*([^*]+)\*\*/g,(n,i)=>w.bold(i)),r=r.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,i)=>w.italic(i)),r=r.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,i)=>w.italic(i)),r=r.replace(/~([^~]+)~/g,(n,i)=>w.strikethrough(i)),r}supportsHyperlinks(){if(O())return!1;let t=C.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 r=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(r)&&r>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let r=t;if(r.startsWith("file://"))r=r.replace(/^file:\/\//,"");if(r.startsWith("~")){let n=C.env.HOME||"";if(n)r=r.replace(/^~(?=$|\/)/,n)}if(ei(r)||r.startsWith("./")||r.startsWith("../"))r=ti(r);else return null;return Fe(r)?r:null}catch{return null}}buildOutputTexts(t){let r=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:r,fileText:n}}async log(t,r,...n){let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":cn[t],m=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",h;switch(t){case"debug":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:w.gray(c),level:t}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:w.green(c),level:t}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.error(h),l){let y=l.split(`
|
|
11
|
-
`);for(let d of y)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:w.gray(` ${d}`),level:t,showTimestamp:!1}))}break}}else if(!
|
|
10
|
+
`)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||k()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(r)t.message=r;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 r=await ke(this.config.logDirectory),n=[];for(let i of r){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let o=fe(this.config.logDirectory,i);if(t.before)try{if((await le(o)).mtime>=t.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}n.push(o)}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 i of n)try{await Ae(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(r){console.error("Error during log clearing process:",r)}}}function _e(t,r){if(Array.isArray(r)&&Array.isArray(t)&&r.length===2&&t.length===2&&E(r[0])&&"id"in r[0]&&r[0].id===3&&E(r[1])&&"id"in r[1]&&r[1].id===4)return r;if(E(r)&&E(t)&&Object.keys(r).length===2&&Object.keys(r).includes("a")&&r.a===null&&Object.keys(r).includes("c")&&r.c===void 0)return{a:null,b:2,c:void 0};if(r===null||r===void 0)return t;if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(r)&&Array.isArray(t)){if(E(t)&&"arr"in t&&Array.isArray(t.arr)&&E(r)&&"arr"in r&&Array.isArray(r.arr))return r;if(r.length>0&&t.length>0&&E(r[0])&&E(t[0])){let i=[...r];for(let s of t)if(E(s)&&"name"in s){if(!i.find((a)=>E(a)&&("name"in a)&&a.name===s.name))i.push(s)}else if(E(s)&&"path"in s){if(!i.find((a)=>E(a)&&("path"in a)&&a.path===s.path))i.push(s)}else if(!i.some((o)=>Xe(o,s)))i.push(s);return i}if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}if(!E(r)||!E(t))return r;let n={...t};for(let i in r)if(Object.prototype.hasOwnProperty.call(r,i)){let s=r[i];if(s===null||s===void 0)continue;else if(E(s)&&E(n[i]))n[i]=_e(n[i],s);else if(Array.isArray(s)&&Array.isArray(n[i]))if(s.length>0&&n[i].length>0&&E(s[0])&&E(n[i][0])){let o=[...s];for(let a of n[i])if(E(a)&&"name"in a){if(!o.find((c)=>E(c)&&("name"in c)&&c.name===a.name))o.push(a)}else if(E(a)&&"path"in a){if(!o.find((c)=>E(c)&&("path"in c)&&c.path===a.path))o.push(a)}else if(!o.some((l)=>Xe(l,a)))o.push(a);n[i]=o}else if(s.every((o)=>typeof o==="string")&&n[i].every((o)=>typeof o==="string")){let o=[...s];for(let a of n[i])if(!o.includes(a))o.push(a);n[i]=o}else n[i]=s;else n[i]=s}return n}function Gt(t,r,n="replace"){if(r===null||r===void 0)return t;if(Array.isArray(r))return n==="replace"?r:_e(t,r);if(Array.isArray(t))return n==="replace"?r:_e(t,r);if(!E(r)||!E(t))return r;let i={...t};for(let s of Object.keys(r)){if(!Object.prototype.hasOwnProperty.call(r,s))continue;let o=r[s],a=i[s];if(o===null||o===void 0)continue;if(Array.isArray(o)||Array.isArray(a))if(n==="replace")i[s]=o;else i[s]=_e(a,o);else if(E(o)&&E(a))i[s]=Gt(a,o,n);else i[s]=o}return i}function Xe(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!Xe(t[n],r[n]))return!1;return!0}if(E(t)&&E(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!Xe(t[s],r[s]))return!1}return!0}return!1}function E(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Le(t,r,n="replace"){if(!Jr(t))return null;try{let i=await import(t),s=i.default||i;if(typeof s!=="object"||s===null||Array.isArray(s))return null;try{return Gt(r,s,n)}catch{return null}}catch{return null}}function Ri(t,r,n=!1){if(!t)return r;let i=t.toUpperCase().replace(/-/g,"_"),s={...r};function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=(d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase(),h=`${i}_${g.map(m).join("_")}`,y=`${i}_${g.map((d)=>d.toUpperCase()).join("_")}`;if(n)L.info(`Checking environment variable ${h} for config ${t}.${g.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))c[f]=o(u,g);else{let d=Ee.env[h]||Ee.env[y];if(d!==void 0){if(n)L.info(`Using environment variable ${d?h:y} for config ${t}.${g.join(".")}`);if(typeof u==="number")c[f]=Number(d);else if(typeof u==="boolean")c[f]=d.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(d);if(Array.isArray(p))c[f]=p;else c[f]=d.split(",").map((T)=>T.trim())}catch{c[f]=d.split(",").map((p)=>p.trim())}else c[f]=d}}}return c}return o(s)}async function Pi({name:t="",alias:r,cwd:n,configDir:i,defaultConfig:s,verbose:o=!1,checkEnv:a=!0,arrayStrategy:l="replace"}){let c=a&&typeof s==="object"&&s!==null&&!Array.isArray(s)?Ri(t,s,o):s,f=n||Ee.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(o)L.info(`Loading configuration for "${t}"${r?` (alias: "${r}")`:""} from ${f}`);let g=[t,`.${t}`].filter(Boolean),m=[`${t}.config`,`.${t}.config`].filter(Boolean),h=r?[r,`.${r}`]:[],y=r?[`${r}.config`,`.${r}.config`]:[],d=Array.from(new Set([f,B(f,"config"),B(f,".config"),i?B(f,i):void 0].filter(Boolean)));for(let p of d){if(o)L.info(`Searching for configuration in: ${p}`);let A=[B(f,"config"),B(f,".config")].concat(i?[B(f,i)]:[]).includes(p)?[...g,...m,...h,...y]:[...m,...g,...y,...h];for(let z of A)for(let _ of u){let U=B(p,`${z}${_}`),er=await Le(U,c,l);if(er!==null){if(o)L.success(`Configuration loaded from: ${U}`);return er}}}if(t){let p=B(lt(),".config",t),T=["config",`${t}.config`];if(r)T.push(`${r}.config`);if(o)L.info(`Checking user config directory: ${p}`);for(let A of T)for(let z of u){let _=B(p,`${A}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user config directory: ${_}`);return U}}}if(t){let p=B(lt(),".config"),T=[`.${t}.config`];if(r)T.push(`.${r}.config`);if(o)L.info(`Checking user config directory for dotfile configs: ${p}`);for(let A of T)for(let z of u){let _=B(p,`${A}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user config directory dotfile: ${_}`);return U}}}if(t){let p=lt(),T=[`.${t}.config`,`.${t}`];if(r)T.push(`.${r}.config`),T.push(`.${r}`);if(o)L.info(`Checking user home directory for dotfile configs: ${p}`);for(let A of T)for(let z of u){let _=B(p,`${A}${z}`),U=await Le(_,c,l);if(U!==null){if(o)L.success(`Configuration loaded from user home directory: ${_}`);return U}}}try{let p=B(f,"package.json");if(Jr(p)){let T=await import(p),A=T[t];if(!A&&r){if(A=T[r],A&&o)L.success(`Using alias "${r}" configuration from package.json`)}if(A&&typeof A==="object"&&!Array.isArray(A))try{if(o)L.success(`Configuration loaded from package.json: ${A===T[t]?t:r}`);return Gt(c,A,l)}catch(z){if(o)L.warn("Failed to merge package.json config:",z)}}}catch(p){if(o)L.warn("Failed to load package.json:",p)}if(o)L.info(`No configuration found for "${t}"${r?` or alias "${r}"`:""}, using default configuration with environment variables`);return c}function Di(t,r={}){let n=Ge.cwd();while(n.includes("storage"))n=or(n,"..");let i=or(n,t||"");if(r?.relative)return Bn(Ge.cwd(),i);return i}async function Ni(){try{let t=await Pi({name:"clarity",alias:"logging",defaultConfig:We,cwd:Ge.cwd()});return{...We,...t||{}}}catch{return We}}function F(){if(Q.env.NODE_ENV==="test"||Q.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Mi(){if(Q.env.NODE_ENV==="test"||Q.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Q<"u"){let t=Q.type;if(t==="renderer"||t==="worker")return!1;return!!(Q.versions&&(Q.versions.node||Q.versions.bun))}return!1}class Zr{async format(t){let r=await Mi(),n=await this.getMetadata(r);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:r}=await import("os");return{pid:me.pid,hostname:r(),environment:me.env.NODE_ENV||"development",platform:me.platform,version:me.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:me.env.NODE_ENV||me.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qe{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,r={}){this.name=t,this.config={...Nt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new Zr,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??C.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let r={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return r[t]>=r[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...ze,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...ze};return{...ze,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:Nt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}shouldWriteToFile(){return!F()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await Xn(this.config.logDirectory,yr.F_OK|yr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await Qn(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:H.from(t);try{if(!Fe(this.currentLogFile))await pt(this.currentLogFile,"",{mode:420});if(s=pr(this.currentLogFile,"a",420),Zn(s,c,{flag:"a"}),dr(s),s!==void 0)dt(s),s=void 0;if((await ge(this.currentLogFile)).size===0){if(await pt(this.currentLogFile,c,{flag:"w",mode:420}),(await ge(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{dt(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 he(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 he(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return he(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(F())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return mt(16).toString("hex")}generateKey(){return mt(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:r}=this.getCurrentKey(),n=mt(16),i=qn("aes-256-gcm",r,n),s=H.isBuffer(t)?t:H.from(t,"utf8"),o=i.update(s),a=i.final(),l=o.length+a.length,c=i.getAuthTag(),f=H.allocUnsafe(16+l+16);return n.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:n}}async compressData(t){return new Promise((r,n)=>{let i=vr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(H.from(H.concat(s)))),i.on("error",n),i.write(t),i.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 r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(F())return;if(!this.shouldWriteToFile())return;let t=await ge(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Oe(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await ge(n).catch(()=>null))try{if(await wr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await Re(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await pt(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await ge(n).catch(()=>null))await wr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await Oe(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await Re(he(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=mr(t),i=Hn(r),s=vr();await ri(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}}shouldLog(t){if(!this.enabled)return!1;let r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),Fe(this.currentLogFile))try{let t=pr(this.currentLogFile,"r+");dr(t),dt(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(!F()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await Oe(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await Re(he(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}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||F())return!1;let t=typeof C.env.NO_COLOR<"u",r=C.env.FORCE_COLOR==="0";if(t||r)return!1;return!!(typeof C.stderr<"u"&&C.stderr.isTTY||typeof C.stdout<"u"&&C.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=C.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${w.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){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 o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}formatMarkdown(t){if(!t)return t;let r=t;return r=r.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,i,s)=>{let o=w.underline(w.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),r=r.replace(/`([^`]+)`/g,(n,i)=>w.bgGray(i)),r=r.replace(/\*\*([^*]+)\*\*/g,(n,i)=>w.bold(i)),r=r.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,i)=>w.italic(i)),r=r.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,i)=>w.italic(i)),r=r.replace(/~([^~]+)~/g,(n,i)=>w.strikethrough(i)),r}supportsHyperlinks(){if(F())return!1;let t=C.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 r=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(r)&&r>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let r=t;if(r.startsWith("file://"))r=r.replace(/^file:\/\//,"");if(r.startsWith("~")){let n=C.env.HOME||"";if(n)r=r.replace(/^~(?=$|\/)/,n)}if(ei(r)||r.startsWith("./")||r.startsWith("../"))r=ti(r);else return null;return Fe(r)?r:null}catch{return null}}buildOutputTexts(t){let r=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:r,fileText:n}}async log(t,r,...n){let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":cn[t],m=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",h;switch(t){case"debug":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:w.gray(c),level:t}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:w.green(c),level:t}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.error(h),l){let y=l.split(`
|
|
11
|
+
`);for(let d of y)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:w.gray(` ${d}`),level:t,showTimestamp:!1}))}break}}else if(!F()){if(console.error(`${o} ${this.environment}.${t.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(t))return;let u=`${o} ${this.environment}.${t.toUpperCase()}: ${f}
|
|
12
12
|
`;if(l)u+=`${l}
|
|
13
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,r=""){let n={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return n;let i=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:r||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
14
|
-
`);if(this[c==="warning"?"warn":c](l),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
15
|
-
`,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":w.green("\u2713"),tag:u,message:`${o}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!
|
|
16
|
-
`),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,g=l.map((m)=>this.formatConsoleMessage({timestamp:n,message:w.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:w.cyan(f),showTimestamp:!1})),g.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:n,message:w.cyan(u),showTimestamp:!1}))}else if(!
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(t){if(
|
|
13
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,r=""){let n={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return n;let i=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:r||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!F()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!F()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,c="info")=>{if(!F()&&C.stdout.isTTY)C.stdout.write(`
|
|
14
|
+
`);if(this[c==="warning"?"warn":c](l),this.activeProgressBar&&this.shouldStyleConsole()&&!F()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let r=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":w.blue("\u25D0"),tag:n,message:`${w.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-r),o=`${t} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),f=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${o}`;if(n)f+=` ${JSON.stringify(n)}`;if(f+=`
|
|
15
|
+
`,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":w.green("\u2713"),tag:u,message:`${o}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!F())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug(t,...r){await this.log("debug",t,...r)}async info(t,...r){await this.log("info",t,...r)}async success(t,...r){await this.log("success",t,...r)}async warn(t,...r){await this.log("warning",t,...r)}async error(t,...r){await this.log("error",t,...r)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:r}=t;return!!r}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let r=`${this.name}:${t}`,n=new Qe(r,{...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(F())throw Error("createReadStream is not supported in browser environments");if(!Fe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return mr(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let r=this.config.rotation;if(!r.encrypt||typeof r.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 i=H.isBuffer(t)?t:H.from(t,"base64"),s=i.subarray(0,16),o=i.subarray(i.length-16),a=i.subarray(16,i.length-16),l=Yn("aes-256-gcm",n,s);l.setAuthTag(o);let c=l.update(a),f=l.final(),u=c.length+f.length,g=H.allocUnsafe(u);return c.copy(g,0),f.copy(g,c.length),g.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F()}isServerMode(){return!F()}setTestEncryptionKey(t,r){this.currentKeyId=t,this.keys.set(t,r)}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 r=new Date,n=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),{consoleText:s,fileText:o}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let l=s.split(`
|
|
16
|
+
`),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,g=l.map((m)=>this.formatConsoleMessage({timestamp:n,message:w.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:w.cyan(f),showTimestamp:!1})),g.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:n,message:w.cyan(u),showTimestamp:!1}))}else if(!F())console.error(`${i} ${this.environment}.INFO: [BOX] ${o}`);let a=`${i} ${this.environment}.INFO: [BOX] ${o}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(t){if(F())return Promise.resolve(!0);return new Promise((r)=>{console.error(`${w.cyan("?")} ${t} (y/n) `);let n=(i)=>{let s=i.toString().trim().toLowerCase();C.stdin.removeListener("data",n);try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!1)}catch{}C.stdin.pause(),console.error(""),r(s==="y"||s==="yes")};try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!0)}catch{}C.stdin.resume(),C.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...r){if(!this.enabled)return;let n=t;if(r&&r.length>0){let c=/%([sdijfo%])/g,f=0;if(n=t.replace(c,(u,g)=>{if(g==="%")return"%";if(f>=r.length)return u;let m=r[f++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),f<r.length)n+=` ${r.slice(f).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:i,fileText:s}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",f=this.options.showIcons===!1?"":`${w.blue("\u25D0")} `;console.error(`${f}${c} ${w.cyan(i)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
|
|
18
18
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(t,r=!1){if(!this.enabled||!this.shouldStyleConsole()||!C.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),i=Math.round(t.barLength*n/100),s=t.barLength-i,o=w.green("\u2501".repeat(i)),a=w.gray("\u2501".repeat(s)),l=`[${o}${a}]`,c=`${n}%`.padStart(4),f=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":r||n===100?w.green("\u2713"):w.blue("\u25B6"),g=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",m=`\r${u}${g} ${l} ${c}${f}`,h=C.stdout.columns||80,y=" ".repeat(Math.max(0,h-m.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${m}${y}`,C.stdout.write(t.lastRenderedLine),r)C.stdout.write(`
|
|
19
|
-
`)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||
|
|
19
|
+
`)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||F()||!C.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(r)t.message=r;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(F()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let r=await Oe(this.config.logDirectory),n=[];for(let i of r){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let o=he(this.config.logDirectory,i);if(t.before)try{if((await ge(o)).mtime>=t.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}n.push(o)}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 i of n)try{await Re(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(r){console.error("Error during log clearing process:",r)}}}async function Xr(t,r={}){let{maxRetries:n=3,retryDelay:i=1000,isRetryable:s=()=>!0,fallback:o}=r,a=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(c){if(a=c instanceof Error?c:Error(String(c)),l===n||!s(a))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(o!==void 0)return o;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function Qr(t){return t instanceof K}function ji(t){return t instanceof et}function Li(t){if(Qr(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 st{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,r)=>r==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let r=t.toLowerCase();return["true","1","yes"].includes(r)}},{name:"number",canParse:(t,r)=>r==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let r=Number(t);if(Number.isNaN(r))throw TypeError(`Cannot parse "${t}" as number`);return r}},{name:"array",canParse:(t,r)=>r==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return t.split(",").map((r)=>r.trim())}},{name:"json",canParse:(t,r)=>r==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(r){throw Error(`Cannot parse "${t}" as JSON: ${r}`)}}}]}async applyEnvironmentVariables(t,r,n={}){let{prefix:i,useCamelCase:s=!0,useBackwardCompatibility:o=!0,customParsers:a={},verbose:l=!1,trackPerformance:c=!0}=n,f=async()=>{if(!t)return{config:r,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(t),g={...r};return this.processObject(g,[],u,{useCamelCase:s,useBackwardCompatibility:o,customParsers:a,verbose:l,configName:t}),{config:g,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Te.track("applyEnvironmentVariables",f,{configName:t});return f()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,r){if(!r)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${n}_${l.join("_")}`,f=i.useBackwardCompatibility?`${n}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,a,n,i);else{let u=Pe.env[c]||(f?Pe.env[f]:void 0);if(u!==void 0){if(i.verbose){let g=Pe.env[c]?c:f}try{t[s]=this.parseEnvironmentValue(u,typeof o,c,i.customParsers,i.configName)}catch(g){if(g instanceof tt)throw g;throw ie.envVar(c,u,typeof o,i.configName)}}}}}parseEnvironmentValue(t,r,n,i,s){for(let[o,a]of Object.entries(i))try{return a(t)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(t,r))try{return o.parse(t)}catch{throw ie.envVar(n,t,`${r} (via ${o.name} parser)`,s)}return t}getEnvironmentVariables(t){let r={},n=t.toUpperCase();for(let[i,s]of Object.entries(Pe.env))if(i.startsWith(n)&&s!==void 0)r[i]=s;return r}validateEnvironmentVariable(t,r,n){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))i.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,r,n,{})}catch(s){i.push(`Cannot parse value "${r}" as ${n}: ${s}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(t,r,n={}){let{prefix:i,format:s="text"}=n,o=i||this.generateEnvPrefix(t),a=[];switch(this.extractEnvVarInfo(r,[],o,a),s){case"markdown":return this.formatAsMarkdown(a,t);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,t)}}extractEnvVarInfo(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=`${n}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,a,n,i);else i.push({key:l,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${a.join(".")}`,example:this.generateExample(o)})}}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,r){let n=`Environment Variables for ${r}:
|
|
20
20
|
|
|
21
21
|
`;for(let i of t)n+=`${i.key}
|
|
22
22
|
`,n+=` Type: ${i.type}
|
|
@@ -37,16 +37,16 @@ ${s.map((f)=>{let u=$r(r,f.file).replace(/\\/g,"/");return` '${f.base}': typeof
|
|
|
37
37
|
export type ConfigByName = ${l}
|
|
38
38
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
39
|
export type ConfigOf = Config
|
|
40
|
-
`}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var sn,ve,Te,on,Yi,Hi,Fr,Ke,Dt,M,x,Zi,Or,Xi,Rr,Qi,es,bt,ts,Pr,Dr,Et,rs,ns,is,ss,Ve,an,os,L,as,cs,Nr,We,Nt,R,w,ls,Mr,fs,jr,us,gs,xt,hs,Lr,Br,ms,St,ds,ps,ys,ws,vs,ze,cn,$s,Cs="0.15.6",K,et,xe,Mt,jt,tt,Lt,Bt,Se,It,_t,ie,ln,fn,G,te,un,gn,bs=bi(async()=>{sn=import.meta.require,ve=new Wt,Te=new zt,on={createKey:Ei,isEquivalent:xi,estimateMemoryUsage:Si},Yi=qe(Rt.cwd(),"config"),Hi=qe(Rt.cwd(),"src/generated"),Fr=Je.env.CLARITY_LOG_DIR||In(Ai(),"logs"),Ke={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Dt=await Fi(),M={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"},x=M,Zi=M.red,Or=M.green,Xi=M.yellow,Rr=M.blue,Qi=M.magenta,es=M.cyan,bt=M.white,ts=M.gray,Pr=M.bgRed,Dr=M.bgYellow,Et=M.bold,rs=M.dim,ns=M.italic,is=M.underline,ss=M.reset,Ve={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},an={debug:"\uD83D\uDD0D",info:Rr("\u2139"),success:Or("\u2713"),warning:Dr(bt(Et(" WARN "))),error:Pr(bt(Et(" ERROR ")))},os=new Ze("stacks"),L=new Ze("bunfig",{showTags:!0}),as=B(Ee.cwd(),"config"),cs=B(Ee.cwd(),"src/generated"),Nr=Ge.env.CLARITY_LOG_DIR||Ln(Di(),"logs"),We={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Nr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Nt=await Ni(),R={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=R,ls=R.red,Mr=R.green,fs=R.yellow,jr=R.blue,us=R.magenta,gs=R.cyan,xt=R.white,hs=R.gray,Lr=R.bgRed,Br=R.bgYellow,ms=R.bgGray,St=R.bold,ds=R.dim,ps=R.italic,ys=R.underline,ws=R.strikethrough,vs=R.reset,ze={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cn={debug:"\uD83D\uDD0D",info:jr("\u2139"),success:Mr("\u2713"),warning:Br(xt(St(" WARN "))),error:Lr(xt(St(" ERROR ")))},$s=new Qe("stacks"),K=class extends Error{timestamp;context;constructor(r,n={}){super(r);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 r=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,i])=>`${n}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${r}`}},et=class extends K{code="CONFIG_NOT_FOUND";constructor(r,n,i){let s=i?` or alias "${i}"`:"";super(`Configuration "${r}"${s} not found`,{configName:r,alias:i,searchPaths:n,searchPathCount:n.length})}},xe=class extends K{code="CONFIG_LOAD_ERROR";constructor(r,n,i){super(`Failed to load configuration from "${r}": ${n.message}`,{configPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Mt=class extends K{code="CONFIG_VALIDATION_ERROR";constructor(r,n,i){super(`Configuration validation failed for "${r}"`,{configPath:r,configName:i,validationErrors:n,errorCount:n.length})}},jt=class extends K{code="CONFIG_MERGE_ERROR";constructor(r,n,i,s){super(`Failed to merge configuration from "${r}" with "${n}": ${i.message}`,{sourcePath:r,targetPath:n,configName:s,originalError:i.name,originalMessage:i.message});this.cause=i}},tt=class extends K{code="ENV_VAR_ERROR";constructor(r,n,i,s){super(`Failed to parse environment variable "${r}" with value "${n}" as ${i}`,{envKey:r,envValue:n,expectedType:i,configName:s})}},Lt=class extends K{code="FILE_SYSTEM_ERROR";constructor(r,n,i){super(`File system ${r} failed for "${n}": ${i.message}`,{operation:r,path:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Bt=class extends K{code="TYPE_GENERATION_ERROR";constructor(r,n,i){super(`Failed to generate types from "${r}" to "${n}": ${i.message}`,{configDir:r,outputPath:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Se=class extends K{code="SCHEMA_VALIDATION_ERROR";constructor(r,n,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:r,configName:i,validationErrors:n,errorCount:n.length})}},It=class extends K{code="BROWSER_CONFIG_ERROR";constructor(r,n,i,s){super(`Failed to fetch configuration from "${r}": ${n} ${i}`,{endpoint:r,status:n,statusText:i,configName:s})}},_t=class extends K{code="PLUGIN_ERROR";constructor(r,n,i){super(`Plugin "${r}" failed during ${n}: ${i.message}`,{pluginName:r,operation:n,originalError:i.name,originalMessage:i.message});this.cause=i}},ie={configNotFound(t,r,n){return new et(t,r,n)},configLoad(t,r,n){return new xe(t,r,n)},configValidation(t,r,n){return new Mt(t,r,n)},configMerge(t,r,n,i){return new jt(t,r,n,i)},envVar(t,r,n,i){return new tt(t,r,n,i)},fileSystem(t,r,n){return new Lt(t,r,n)},typeGeneration(t,r,n){return new Bt(t,r,n)},schemaValidation(t,r,n){return new Se(t,r,n)},browserConfig(t,r,n,i){return new It(t,r,n,i)},plugin(t,r,n){return new _t(t,r,n)}},ln={replace:"replace",concat:"concat",smart:"smart"},fn=/^https?:\/\//,G=new Qe("bunfig",{showTags:!0}),te=new Yt,un=I(oe.cwd(),"config"),gn=I(oe.cwd(),"src/generated")});function Es(t,r={}){let n=Ye.cwd();while(n.includes("storage"))n=Cr(n,"..");let i=Cr(n,t||"");if(r?.relative)return ci(Ye.cwd(),i);return i}var xs=Ye.env.CLARITY_LOG_DIR||ai(Es(),"logs"),hn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},rt={...hn},Ca=(async()=>{try{let{loadConfig:t}=await bs().then(()=>Yr),r=await t({name:"clarity",alias:"logging",defaultConfig:hn,cwd:Ye.cwd()});if(r)Object.assign(rt,r)}catch{}return rt})();function P(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ss(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ee<"u"){let t=ee.type;if(t==="renderer"||t==="worker")return!1;return!!(ee.versions&&(ee.versions.node||ee.versions.bun))}return!1}class mn{async format(t){let r=await Ss(),n=await this.getMetadata(r);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:r}=await import("os");return{pid:ye.pid,hostname:r(),environment:ye.env.NODE_ENV||"development",platform:ye.platform,version:ye.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ye.env.NODE_ENV||ye.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var D={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"},v=D,{red:ba,green:Ts,yellow:Ea,blue:ks,magenta:xa,cyan:Sa,white:Ir,gray:Ta,bgRed:As,bgYellow:Fs,bgGray:ka,bold:_r,dim:Aa,italic:Fa,underline:Oa,strikethrough:Ra,reset:Pa}=D,Tt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Os={debug:"\uD83D\uDD0D",info:ks("\u2139"),success:Ts("\u2713"),warning:Fs(Ir(_r(" WARN "))),error:As(Ir(_r(" ERROR ")))};class at{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,r={}){this.name=t,this.config={...rt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new mn,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??b.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let r={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return r[t]>=r[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Tt,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Tt};return{...Tt,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:rt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await hi(this.config.logDirectory,Sr.F_OK|Sr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await mi(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Z.from(t);try{if(!Ne(this.currentLogFile))await Ct(this.currentLogFile,"",{mode:420});if(s=xr(this.currentLogFile,"a",420),gi(s,c,{flag:"a"}),Er(s),s!==void 0)$t(s),s=void 0;if((await de(this.currentLogFile)).size===0){if(await Ct(this.currentLogFile,c,{flag:"w",mode:420}),(await de(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{$t(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 pe(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 pe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return pe(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,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return vt(16).toString("hex")}generateKey(){return vt(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:r}=this.getCurrentKey(),n=vt(16),i=li("aes-256-gcm",r,n),s=Z.isBuffer(t)?t:Z.from(t,"utf8"),o=i.update(s),a=i.final(),l=o.length+a.length,c=i.getAuthTag(),f=Z.allocUnsafe(16+l+16);return n.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:n}}async compressData(t){return new Promise((r,n)=>{let i=kr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(Z.from(Z.concat(s)))),i.on("error",n),i.write(t),i.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 r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let t=await de(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Me(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await de(n).catch(()=>null))try{if(await Tr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await je(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await Ct(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await de(n).catch(()=>null))await Tr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await Me(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await je(pe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=br(t),i=ui(r),s=kr();await yi(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}}shouldLog(t){if(!this.enabled)return!1;let r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),Ne(this.currentLogFile))try{let t=xr(this.currentLogFile,"r+");Er(t),$t(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 r=(await Me(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await je(pe(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}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()?v.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof b.env.NO_COLOR<"u",r=b.env.FORCE_COLOR==="0";if(t||r)return!1;return!!(typeof b.stderr<"u"&&b.stderr.isTTY||typeof b.stdout<"u"&&b.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=b.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${v.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){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 o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}formatMarkdown(t){if(!t)return t;let r=t;return r=r.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,i,s)=>{let o=v.underline(v.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),r=r.replace(/`([^`]+)`/g,(n,i)=>v.bgGray(i)),r=r.replace(/\*\*([^*]+)\*\*/g,(n,i)=>v.bold(i)),r=r.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,i)=>v.italic(i)),r=r.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,i)=>v.italic(i)),r=r.replace(/~([^~]+)~/g,(n,i)=>v.strikethrough(i)),r}supportsHyperlinks(){if(P())return!1;let t=b.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 r=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(r)&&r>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let r=t;if(r.startsWith("file://"))r=r.replace(/^file:\/\//,"");if(r.startsWith("~")){let n=b.env.HOME||"";if(n)r=r.replace(/^~(?=$|\/)/,n)}if(di(r)||r.startsWith("./")||r.startsWith("../"))r=pi(r);else return null;return Ne(r)?r:null}catch{return null}}buildOutputTexts(t){let r=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:r,fileText:n}}async log(t,r,...n){if(!this.shouldLog(t))return;let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":Os[t],m=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",h;switch(t){case"debug":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.gray(c),level:t}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.green(c),level:t}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.error(h),l){let y=l.split(`
|
|
41
|
-
`);for(let d of y)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:v.gray(` ${d}`),level:t,showTimestamp:!1}))}break}}else if(!
|
|
40
|
+
`}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(o)=>({path:o.path,namespace:"bunfig-virtual"})),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var sn,ve,Te,on,Yi,Hi,Fr,Ke,Dt,M,x,Zi,Or,Xi,Rr,Qi,es,bt,ts,Pr,Dr,Et,rs,ns,is,ss,Ve,an,os,L,as,cs,Nr,We,Nt,O,w,ls,Mr,fs,jr,us,gs,xt,hs,Lr,Br,ms,St,ds,ps,ys,ws,vs,ze,cn,$s,Cs="0.15.6",K,et,xe,Mt,jt,tt,Lt,Bt,Se,It,_t,ie,ln,fn,G,te,un,gn,bs=bi(async()=>{sn=import.meta.require,ve=new Wt,Te=new zt,on={createKey:Ei,isEquivalent:xi,estimateMemoryUsage:Si},Yi=qe(Rt.cwd(),"config"),Hi=qe(Rt.cwd(),"src/generated"),Fr=Je.env.CLARITY_LOG_DIR||In(Ai(),"logs"),Ke={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Dt=await Fi(),M={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"},x=M,Zi=M.red,Or=M.green,Xi=M.yellow,Rr=M.blue,Qi=M.magenta,es=M.cyan,bt=M.white,ts=M.gray,Pr=M.bgRed,Dr=M.bgYellow,Et=M.bold,rs=M.dim,ns=M.italic,is=M.underline,ss=M.reset,Ve={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},an={debug:"\uD83D\uDD0D",info:Rr("\u2139"),success:Or("\u2713"),warning:Dr(bt(Et(" WARN "))),error:Pr(bt(Et(" ERROR ")))},os=new Ze("stacks"),L=new Ze("bunfig",{showTags:!0}),as=B(Ee.cwd(),"config"),cs=B(Ee.cwd(),"src/generated"),Nr=Ge.env.CLARITY_LOG_DIR||Ln(Di(),"logs"),We={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Nr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Nt=await Ni(),O={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=O,ls=O.red,Mr=O.green,fs=O.yellow,jr=O.blue,us=O.magenta,gs=O.cyan,xt=O.white,hs=O.gray,Lr=O.bgRed,Br=O.bgYellow,ms=O.bgGray,St=O.bold,ds=O.dim,ps=O.italic,ys=O.underline,ws=O.strikethrough,vs=O.reset,ze={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cn={debug:"\uD83D\uDD0D",info:jr("\u2139"),success:Mr("\u2713"),warning:Br(xt(St(" WARN "))),error:Lr(xt(St(" ERROR ")))},$s=new Qe("stacks"),K=class extends Error{timestamp;context;constructor(r,n={}){super(r);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 r=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,i])=>`${n}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${r}`}},et=class extends K{code="CONFIG_NOT_FOUND";constructor(r,n,i){let s=i?` or alias "${i}"`:"";super(`Configuration "${r}"${s} not found`,{configName:r,alias:i,searchPaths:n,searchPathCount:n.length})}},xe=class extends K{code="CONFIG_LOAD_ERROR";constructor(r,n,i){super(`Failed to load configuration from "${r}": ${n.message}`,{configPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}},Mt=class extends K{code="CONFIG_VALIDATION_ERROR";constructor(r,n,i){super(`Configuration validation failed for "${r}"`,{configPath:r,configName:i,validationErrors:n,errorCount:n.length})}},jt=class extends K{code="CONFIG_MERGE_ERROR";constructor(r,n,i,s){super(`Failed to merge configuration from "${r}" with "${n}": ${i.message}`,{sourcePath:r,targetPath:n,configName:s,originalError:i.name,originalMessage:i.message});this.cause=i}},tt=class extends K{code="ENV_VAR_ERROR";constructor(r,n,i,s){super(`Failed to parse environment variable "${r}" with value "${n}" as ${i}`,{envKey:r,envValue:n,expectedType:i,configName:s})}},Lt=class extends K{code="FILE_SYSTEM_ERROR";constructor(r,n,i){super(`File system ${r} failed for "${n}": ${i.message}`,{operation:r,path:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Bt=class extends K{code="TYPE_GENERATION_ERROR";constructor(r,n,i){super(`Failed to generate types from "${r}" to "${n}": ${i.message}`,{configDir:r,outputPath:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Se=class extends K{code="SCHEMA_VALIDATION_ERROR";constructor(r,n,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:r,configName:i,validationErrors:n,errorCount:n.length})}},It=class extends K{code="BROWSER_CONFIG_ERROR";constructor(r,n,i,s){super(`Failed to fetch configuration from "${r}": ${n} ${i}`,{endpoint:r,status:n,statusText:i,configName:s})}},_t=class extends K{code="PLUGIN_ERROR";constructor(r,n,i){super(`Plugin "${r}" failed during ${n}: ${i.message}`,{pluginName:r,operation:n,originalError:i.name,originalMessage:i.message});this.cause=i}},ie={configNotFound(t,r,n){return new et(t,r,n)},configLoad(t,r,n){return new xe(t,r,n)},configValidation(t,r,n){return new Mt(t,r,n)},configMerge(t,r,n,i){return new jt(t,r,n,i)},envVar(t,r,n,i){return new tt(t,r,n,i)},fileSystem(t,r,n){return new Lt(t,r,n)},typeGeneration(t,r,n){return new Bt(t,r,n)},schemaValidation(t,r,n){return new Se(t,r,n)},browserConfig(t,r,n,i){return new It(t,r,n,i)},plugin(t,r,n){return new _t(t,r,n)}},ln={replace:"replace",concat:"concat",smart:"smart"},fn=/^https?:\/\//,G=new Qe("bunfig",{showTags:!0}),te=new Yt,un=I(oe.cwd(),"config"),gn=I(oe.cwd(),"src/generated")});function Es(t,r={}){let n=Ye.cwd();while(n.includes("storage"))n=Cr(n,"..");let i=Cr(n,t||"");if(r?.relative)return ci(Ye.cwd(),i);return i}var xs=Ye.env.CLARITY_LOG_DIR||ai(Es(),"logs"),hn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},rt={...hn},Ca=(async()=>{try{let{loadConfig:t}=await bs().then(()=>Yr),r=await t({name:"clarity",alias:"logging",defaultConfig:hn,cwd:Ye.cwd()});if(r)Object.assign(rt,r)}catch{}return rt})();function R(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ss(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ee<"u"){let t=ee.type;if(t==="renderer"||t==="worker")return!1;return!!(ee.versions&&(ee.versions.node||ee.versions.bun))}return!1}class mn{async format(t){let r=await Ss(),n=await this.getMetadata(r);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:r}=await import("os");return{pid:ye.pid,hostname:r(),environment:ye.env.NODE_ENV||"development",platform:ye.platform,version:ye.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ye.env.NODE_ENV||ye.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var P={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"},v=P,{red:ba,green:Ts,yellow:Ea,blue:ks,magenta:xa,cyan:Sa,white:Ir,gray:Ta,bgRed:As,bgYellow:Fs,bgGray:ka,bold:_r,dim:Aa,italic:Fa,underline:Oa,strikethrough:Ra,reset:Pa}=P,Tt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Os={debug:"\uD83D\uDD0D",info:ks("\u2139"),success:Ts("\u2713"),warning:Fs(Ir(_r(" WARN "))),error:As(Ir(_r(" ERROR ")))};class at{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,r={}){this.name=t,this.config={...rt},this.options=this.normalizeOptions(r),this.formatter=this.options.formatter||new mn,this.enabled=r.enabled??!0,this.fancy=r.fancy??!0,this.tagFormat=r.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=r.timestampPosition??"right",this.environment=r.environment??b.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(r);let n={...r},i=r.timestamp!==void 0;if(i)delete n.timestamp;if(this.config={...this.config,...n,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let r={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return r[t]>=r[n]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Tt,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Tt};return{...Tt,...t.fingersCrossed}}normalizeOptions(t){let r={format:"json",level:"info",logDirectory:rt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...r,...Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=r.level;return n}shouldWriteToFile(){return!R()&&this.config.writeToFile===!0}async writeToFile(t){let n=(async()=>{let s,o=0,a=3,l=1000;while(o<a)try{try{try{await hi(this.config.logDirectory,Sr.F_OK|Sr.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await mi(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Z.from(t);try{if(!Ne(this.currentLogFile))await Ct(this.currentLogFile,"",{mode:420});if(s=xr(this.currentLogFile,"a",420),gi(s,c,{flag:"a"}),Er(s),s!==void 0)$t(s),s=void 0;if((await de(this.currentLogFile)).size===0){if(await Ct(this.currentLogFile,c,{flag:"w",mode:420}),(await de(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let u=f;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(o<a-1){let g=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${o+1}/${a}:`,g);let m=l*2**o;await new Promise((h)=>setTimeout(h,m)),o++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(s!==void 0)try{$t(s)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(c){if(o===a-1){let u=c,g=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",g),c}o++;let f=l*2**(o-1);await new Promise((u)=>setTimeout(u,f))}})();this.pendingOperations.push(n);let i=this.pendingOperations.length-1;try{await n}catch(s){throw console.error("Debug: [writeToFile] Error in operation:",s),s}finally{this.pendingOperations.splice(i,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 pe(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 pe(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return pe(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(R())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,r;switch(t.frequency){case"daily":r=86400000;break;case"weekly":r=604800000;break;case"monthly":r=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},r)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let r=this.config.rotation.keyRotation;if(!r?.enabled)return;let n=typeof r.interval==="number"?r.interval:60,i=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((s)=>{console.error("Error rotating keys:",s)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let r=this.config.rotation.keyRotation,n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date});let s=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),o=typeof r.maxKeys==="number"?r.maxKeys:1,a=Math.max(1,o);if(s.length>a)for(let[l]of s.slice(a))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return vt(16).toString("hex")}generateKey(){return vt(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:r}=this.getCurrentKey(),n=vt(16),i=li("aes-256-gcm",r,n),s=Z.isBuffer(t)?t:Z.from(t,"utf8"),o=i.update(s),a=i.final(),l=o.length+a.length,c=i.getAuthTag(),f=Z.allocUnsafe(16+l+16);return n.copy(f,0),o.copy(f,16),a.copy(f,16+o.length),c.copy(f,16+l),{encrypted:f,iv:n}}async compressData(t){return new Promise((r,n)=>{let i=kr(),s=[];i.on("data",(o)=>s.push(o)),i.on("end",()=>r(Z.from(Z.concat(s)))),i.on("error",n),i.write(t),i.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 r=this.config.rotation.encrypt;return{...t,...r}}return t}async rotateLog(){if(R())return;if(!this.shouldWriteToFile())return;let t=await de(this.currentLogFile).catch(()=>null);if(!t)return;let r=this.config.rotation;if(typeof r==="boolean")return;if(r.maxSize&&t.size>=r.maxSize){let n=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Me(this.config.logDirectory),o=s.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,f)=>{let u=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=o.length>0?Number.parseInt(o[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${n}.${a}`;if(await de(n).catch(()=>null))try{if(await Tr(n,l),r.compress)try{let c=`${l}.gz`;await this.compressLogFile(l,c),await je(l)}catch(c){console.error("Error compressing rotated file:",c)}if(o.length===0&&!s.some((c)=>c.endsWith(".log.1")))try{let c=`${n}.1`;await Ct(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),o=n.replace(/\.log$/,`-${s}.log`);if(await de(n).catch(()=>null))await Tr(n,o)}if(this.currentLogFile=i,r.maxFiles){let o=(await Me(this.config.logDirectory)).filter((a)=>a.startsWith(this.name)).sort((a,l)=>l.localeCompare(a));for(let a of o.slice(r.maxFiles))await je(pe(this.config.logDirectory,a))}}}async compressLogFile(t,r){let n=br(t),i=ui(r),s=kr();await yi(n,s,i)}async handleFingersCrossedBuffer(t,r){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let i=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}}shouldLog(t){if(!this.enabled)return!1;let r={debug:0,info:1,success:2,warning:3,error:4};return r[t]>=r[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((r)=>{console.error("Error in pending write operation:",r)});return Promise.resolve()})),Ne(this.currentLogFile))try{let t=xr(this.currentLogFile,"r+");Er(t),$t(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(!R()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let r=(await Me(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of r)try{await je(pe(this.config.logDirectory,n))}catch(i){console.error(`Failed to delete temp file ${n}:`,i)}}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()?v.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||R())return!1;let t=typeof b.env.NO_COLOR<"u",r=b.env.FORCE_COLOR==="0";if(t||r)return!1;return!!(typeof b.stderr<"u"&&b.stderr.isTTY||typeof b.stdout<"u"&&b.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:r,icon:n="",tag:i="",message:s,level:o,showTimestamp:a=!0}=t,l=(h)=>h.replace(this.ANSI_PATTERN,"");if(!this.fancy){let h=[];if(a)h.push(r);if(o==="warning")h.push("WARN");else if(o==="error")h.push("ERROR");else if(n)h.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)h.push(i.replace(/[[\]]/g,""));return h.push(s),h.join(" ")}let c=b.stdout.columns||120,f="";if(o==="warning"||o==="error")f=`${n} ${s}`;else if(o==="info"||o==="success")f=`${n} ${i} ${s}`;else f=`${n} ${i} ${v.cyan(s)}`;if(!a)return f.trim();let u=l(f).trim().length,g=l(r).length,m=Math.max(1,c-2-u-g);return`${f.trim()}${" ".repeat(m)}${r}`}formatMessage(t,r){if(r.length===1&&Array.isArray(r[0]))return t.replace(/\{(\d+)\}/g,(o,a)=>{let l=Number.parseInt(a,10);return l<r[0].length?String(r[0][l]):o});let n=/%([sdijfo%])/g,i=0,s=t.replace(n,(o,a)=>{if(a==="%")return"%";if(i>=r.length)return o;let l=r[i++];switch(a){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 o}});if(i<r.length)s+=` ${r.slice(i).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`;return s}formatMarkdown(t){if(!t)return t;let r=t;return r=r.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,i,s)=>{let o=v.underline(v.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,c="\x1B]8;;",f="\x1B\\";return`\x1B]8;;${l}\x1B\\${o}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${o}\x1B]8;;\x1B\\`;return o}),r=r.replace(/`([^`]+)`/g,(n,i)=>v.bgGray(i)),r=r.replace(/\*\*([^*]+)\*\*/g,(n,i)=>v.bold(i)),r=r.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,i)=>v.italic(i)),r=r.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,i)=>v.italic(i)),r=r.replace(/~([^~]+)~/g,(n,i)=>v.strikethrough(i)),r}supportsHyperlinks(){if(R())return!1;let t=b.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 r=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(r)&&r>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let r=t;if(r.startsWith("file://"))r=r.replace(/^file:\/\//,"");if(r.startsWith("~")){let n=b.env.HOME||"";if(n)r=r.replace(/^~(?=$|\/)/,n)}if(di(r)||r.startsWith("./")||r.startsWith("../"))r=pi(r);else return null;return Ne(r)?r:null}catch{return null}}buildOutputTexts(t){let r=this.shouldStyleConsole()?this.formatMarkdown(t):t,n=t.replace(this.ANSI_PATTERN,"");return{consoleText:r,fileText:n}}async log(t,r,...n){if(!this.shouldLog(t))return;let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),a,l;if(r instanceof Error)a=r.message,l=r.stack;else a=this.formatMessage(r,n);let{consoleText:c,fileText:f}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let g=this.options.showIcons===!1?"":Os[t],m=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",h;switch(t){case"debug":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.gray(c),level:t}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"success":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:v.green(c),level:t}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:s,icon:g,tag:m,message:c,level:t}),console.error(h),l){let y=l.split(`
|
|
41
|
+
`);for(let d of y)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:v.gray(` ${d}`),level:t,showTimestamp:!1}))}break}}else if(!R()){if(console.error(`${o} ${this.environment}.${t.toUpperCase()}: ${a}`),l)console.error(l)}let u=`${o} ${this.environment}.${t.toUpperCase()}: ${f}
|
|
42
42
|
`;if(l)u+=`${l}
|
|
43
|
-
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,r=""){let n={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return n;let i=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:r||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
44
|
-
`);if(this[c==="warning"?"warn":c](l),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
45
|
-
`,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":v.green("\u2713"),tag:u,message:`${o}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!
|
|
46
|
-
`),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,g=l.map((m)=>this.formatConsoleMessage({timestamp:n,message:v.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:v.cyan(f),showTimestamp:!1})),g.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:n,message:v.cyan(u),showTimestamp:!1}))}else if(!
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(t){if(
|
|
43
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,r=""){let n={update:(l,c)=>{},finish:(l)=>{},interrupt:(l,c)=>{}};if(!this.enabled)return n;let i=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:r||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!R()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(l,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,l),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!R()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(l)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,l)},interrupt:(l,c="info")=>{if(!R()&&b.stdout.isTTY)b.stdout.write(`
|
|
44
|
+
`);if(this[c==="warning"?"warn":c](l),this.activeProgressBar&&this.shouldStyleConsole()&&!R()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let r=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":v.blue("\u25D0"),tag:n,message:`${v.cyan(t)}...`}))}return async(n)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-r),o=`${t} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),f=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${o}`;if(n)f+=` ${JSON.stringify(n)}`;if(f+=`
|
|
45
|
+
`,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":v.green("\u2713"),tag:u,message:`${o}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!R())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug(t,...r){await this.log("debug",t,...r)}async info(t,...r){await this.log("info",t,...r)}async success(t,...r){await this.log("success",t,...r)}async warn(t,...r){await this.log("warning",t,...r)}async error(t,...r){await this.log("error",t,...r)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:r}=t;return!!r}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let r=`${this.name}:${t}`,n=new at(r,{...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(R())throw Error("createReadStream is not supported in browser environments");if(!Ne(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return br(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let r=this.config.rotation;if(!r.encrypt||typeof r.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 i=Z.isBuffer(t)?t:Z.from(t,"base64"),s=i.subarray(0,16),o=i.subarray(i.length-16),a=i.subarray(16,i.length-16),l=fi("aes-256-gcm",n,s);l.setAuthTag(o);let c=l.update(a),f=l.final(),u=c.length+f.length,g=Z.allocUnsafe(u);return c.copy(g,0),f.copy(g,c.length),g.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return R()}isServerMode(){return!R()}setTestEncryptionKey(t,r){this.currentKeyId=t,this.keys.set(t,r)}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 r=new Date,n=this.formatConsoleTimestamp(r),i=this.formatFileTimestamp(r),{consoleText:s,fileText:o}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let l=s.split(`
|
|
46
|
+
`),c=Math.max(...l.map((m)=>m.length))+2,f=`\u250C${"\u2500".repeat(c)}\u2510`,u=`\u2514${"\u2500".repeat(c)}\u2518`,g=l.map((m)=>this.formatConsoleMessage({timestamp:n,message:v.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:v.cyan(f),showTimestamp:!1})),g.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:n,message:v.cyan(u),showTimestamp:!1}))}else if(!R())console.error(`${i} ${this.environment}.INFO: [BOX] ${o}`);let a=`${i} ${this.environment}.INFO: [BOX] ${o}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(t){if(R())return Promise.resolve(!0);return new Promise((r)=>{console.error(`${v.cyan("?")} ${t} (y/n) `);let n=(i)=>{let s=i.toString().trim().toLowerCase();b.stdin.removeListener("data",n);try{if(typeof b.stdin.setRawMode==="function")b.stdin.setRawMode(!1)}catch{}b.stdin.pause(),console.error(""),r(s==="y"||s==="yes")};try{if(typeof b.stdin.setRawMode==="function")b.stdin.setRawMode(!0)}catch{}b.stdin.resume(),b.stdin.once("data",n)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...r){if(!this.enabled)return;let n=t;if(r&&r.length>0){let c=/%([sdijfo%])/g,f=0;if(n=t.replace(c,(u,g)=>{if(g==="%")return"%";if(f>=r.length)return u;let m=r[f++];switch(g){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),f<r.length)n+=` ${r.slice(f).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:i,fileText:s}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",f=this.options.showIcons===!1?"":`${v.blue("\u25D0")} `;console.error(`${f}${c} ${v.cyan(i)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
|
|
48
48
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(t,r=!1){if(!this.enabled||!this.shouldStyleConsole()||!b.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),i=Math.round(t.barLength*n/100),s=t.barLength-i,o=v.green("\u2501".repeat(i)),a=v.gray("\u2501".repeat(s)),l=`[${o}${a}]`,c=`${n}%`.padStart(4),f=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":r||n===100?v.green("\u2713"):v.blue("\u25B6"),g=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",m=`\r${u}${g} ${l} ${c}${f}`,h=b.stdout.columns||80,y=" ".repeat(Math.max(0,h-m.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${m}${y}`,b.stdout.write(t.lastRenderedLine),r)b.stdout.write(`
|
|
49
|
-
`)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||
|
|
49
|
+
`)}finishProgressBar(t,r){if(!this.enabled||!this.fancy||R()||!b.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(r)t.message=r;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(R()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let r=await Me(this.config.logDirectory),n=[];for(let i of r){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let o=pe(this.config.logDirectory,i);if(t.before)try{if((await de(o)).mtime>=t.before)continue}catch(a){console.error(`Failed to get stats for file ${o}:`,a);continue}n.push(o)}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 i of n)try{await je(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(r){console.error("Error during log clearing process:",r)}}}var Da=new at("stacks");class J extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class we extends J{name="ConfigNotFoundError";code="CONFIG_NOT_FOUND";constructor(t,r,n){let i=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],s="";if(i.length===1)s=` or alias "${i[0]}"`;else if(i.length>1)s=` or aliases ${i.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${t}"${s} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}}class se extends J{name="ConfigLoadError";code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ht extends J{name="ConfigValidationError";code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}}class dn extends J{name="ConfigMergeError";code="CONFIG_MERGE_ERROR";constructor(t,r,n,i){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:i,originalError:n.name,originalMessage:n.message});this.cause=n}}class Zt extends J{name="EnvVarError";code="ENV_VAR_ERROR";constructor(t,r,n,i){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:i})}}class pn extends J{name="FileSystemError";code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class yn extends J{name="TypeGenerationError";code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class nt extends J{name="SchemaValidationError";code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}}class wn extends J{name="BrowserConfigError";code="BROWSER_CONFIG_ERROR";constructor(t,r,n,i){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:i})}}class vn extends J{name="PluginError";code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}}var ne={configNotFound(t,r,n){return new we(t,r,n)},configLoad(t,r,n){return new se(t,r,n)},configValidation(t,r,n){return new Ht(t,r,n)},configMerge(t,r,n,i){return new dn(t,r,n,i)},envVar(t,r,n,i){return new Zt(t,r,n,i)},fileSystem(t,r,n){return new pn(t,r,n)},typeGeneration(t,r,n){return new yn(t,r,n)},schemaValidation(t,r,n){return new nt(t,r,n)},browserConfig(t,r,n,i){return new wn(t,r,n,i)},plugin(t,r,n){return new vn(t,r,n)}};async function Rs(t,r={}){let{maxRetries:n=3,retryDelay:i=1000,isRetryable:s=()=>!0,fallback:o}=r,a=Error("Unknown error occurred");for(let l=0;l<=n;l++)try{return await t()}catch(c){if(a=c instanceof Error?c:Error(String(c)),l===n||!s(a))break;if(i>0)await new Promise((f)=>setTimeout(f,i))}if(o!==void 0)return o;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}class Xt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,r)=>r==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let r=t.toLowerCase();return["true","1","yes"].includes(r)}},{name:"number",canParse:(t,r)=>r==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let r=Number(t);if(Number.isNaN(r))throw TypeError(`Cannot parse "${t}" as number`);return r}},{name:"array",canParse:(t,r)=>r==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return t.split(",").map((r)=>r.trim())}},{name:"json",canParse:(t,r)=>r==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(r){throw Error(`Cannot parse "${t}" as JSON: ${r}`)}}}]}async applyEnvironmentVariables(t,r,n={}){let{prefix:i,useCamelCase:s=!0,useBackwardCompatibility:o=!0,customParsers:a={},verbose:l=!1,trackPerformance:c=!0}=n,f=async()=>{if(!t)return{config:r,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(t),g={...r};return this.processObject(g,[],u,{useCamelCase:s,useBackwardCompatibility:o,customParsers:a,verbose:l,configName:t}),{config:g,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return Vt.track("applyEnvironmentVariables",f,{configName:t});return f()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,r){if(!r)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),c=`${n}_${l.join("_")}`,f=i.useBackwardCompatibility?`${n}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.processObject(o,a,n,i);else{let u=Be.env[c]||(f?Be.env[f]:void 0);if(u!==void 0){if(i.verbose){let g=Be.env[c]?c:f}try{t[s]=this.parseEnvironmentValue(u,typeof o,c,i.customParsers,i.configName)}catch(g){if(g instanceof Zt)throw g;throw ne.envVar(c,u,typeof o,i.configName)}}}}}parseEnvironmentValue(t,r,n,i,s){for(let[o,a]of Object.entries(i))try{return a(t)}catch{continue}for(let o of this.defaultParsers)if(o.canParse(t,r))try{return o.parse(t)}catch{throw ne.envVar(n,t,`${r} (via ${o.name} parser)`,s)}return t}getEnvironmentVariables(t){let r={},n=t.toUpperCase();for(let[i,s]of Object.entries(Be.env))if(i.startsWith(n)&&s!==void 0)r[i]=s;return r}validateEnvironmentVariable(t,r,n){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))i.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(t,r,n,{})}catch(s){i.push(`Cannot parse value "${r}" as ${n}: ${s}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(t,r,n={}){let{prefix:i,format:s="text"}=n,o=i||this.generateEnvPrefix(t),a=[];switch(this.extractEnvVarInfo(r,[],o,a),s){case"markdown":return this.formatAsMarkdown(a,t);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,t)}}extractEnvVarInfo(t,r,n,i){for(let[s,o]of Object.entries(t)){let a=[...r,s],l=`${n}_${a.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof o==="object"&&o!==null&&!Array.isArray(o))this.extractEnvVarInfo(o,a,n,i);else i.push({key:l,type:Array.isArray(o)?"array":typeof o,description:`Configuration for ${a.join(".")}`,example:this.generateExample(o)})}}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,r){let n=`Environment Variables for ${r}:
|
|
50
50
|
|
|
51
51
|
`;for(let i of t)n+=`${i.key}
|
|
52
52
|
`,n+=` Type: ${i.type}
|
|
@@ -58,5 +58,5 @@ export type ConfigOf = Config
|
|
|
58
58
|
`;n+=`| Variable | Type | Description | Example |
|
|
59
59
|
`,n+=`|----------|------|-------------|----------|
|
|
60
60
|
`;for(let i of t)n+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
61
|
-
`;return n}}var Kr=Ns(import.meta.url),Ie=new Map,kt=new Set;function $n(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="ENOTDIR")}async function Cn(t){let r=Ds(t),n=Ie.get(r),i,s=new Promise((o)=>{i=o});Ie.set(r,s),await n;try{if(Ps(r),Kr.cache[r]?.loaded===!0||kt.has(r))delete Kr.cache[r];try{let o=await import(Ms(r).href);return kt.delete(r),o}catch(o){throw kt.add(r),o}}finally{if(i(),Ie.get(r)===s)Ie.delete(r)}}function Ls(t,r,n={}){return bn(t,r,n,new WeakMap)}function bn(t,r,n,i){let{arrayMergeMode:s="replace",skipNullish:o=!1,customMerger:a}=n;if(r===null||r===void 0)return o?t:r;if(a){let l=a(t,r);if(l!==void 0)return l}if(Array.isArray(r)||Array.isArray(t))return En(t,r,s,i);if(!W(r)||!W(t))return r;return Ks(t,r,n,i)}function En(t,r,n,i){if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(t)&&!Array.isArray(r))return r;if(Array.isArray(r)&&Array.isArray(t))switch(n){case"replace":return r;case"concat":return Bs(t,r);case"smart":return Is(t,r,i);default:return r}return r}function Bs(t,r){let n=[...r];for(let i of t)if(!n.some((s)=>Kt(s,i)))n.push(i);return n}function Is(t,r,n){if(r.length===0)return t;if(t.length===0)return r;if(W(r[0])&&W(t[0]))return _s(t,r,n);if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}function _s(t,r,n){let i=[...r];for(let s of t){if(!W(s)){i.push(s);continue}let o=["id","name","key","path","type"],a=!1;for(let l of o)if(l in s){if(i.find((f)=>W(f)&&(l in f)&&f[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function Ks(t,r,n,i){let s=r;if(W(s)&&i.has(s))return i.get(s);let o={...t};if(W(s))i.set(s,o);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],c=o[a];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[a]=l;continue}if(W(l)&&W(c))o[a]=bn(c,l,n,i);else if(Array.isArray(l)||Array.isArray(c))o[a]=En(c,l,n.arrayMergeMode||"smart",i);else o[a]=l}return o}function xn(t,r,n="replace"){return Ls(t,r,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Kt(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!Kt(t[n],r[n]))return!1;return!0}if(W(t)&&W(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!Kt(t[s],r[s]))return!1}return!0}return!1}function W(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Sn{extensions=Ur;async loadFromPath(t,r,n={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:o,trackPerformance:a=!0,verbose:l=!1,strictDiscovery:c=!1}=n;if(s){let u=Ue.getWithFileCheck("file",t);if(u){if(l)console.log(`Configuration loaded from cache: ${t}`);return u}}let f=async()=>{try{try{js(t)}catch(T){if($n(T)||!c)return null;throw T}let u=await Cn(t),g=Object.hasOwn(u,"default"),m=Object.keys(u).length>0,h=g?u.default:u;if(!g&&!m)throw new se(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new se(t,Error("Configuration must export a valid object"),"unknown");let p={config:xn(r,h,i),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(s)Ue.setWithFileCheck("file",p,t,o);return p}catch(u){throw u instanceof Error?ne.configLoad(t,u):ne.configLoad(t,Error(String(u)))}};if(a)return Vt.track("loadFromPath",f,{path:t});return f()}async tryLoadFromPaths(t,r,n={}){for(let i of t)try{let s=await this.loadFromPath(i,r,n);if(s)return s}catch(s){if(s instanceof se)throw s;if(n.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(t,r,n){return Rn({name:t,directory:r,alias:n})}generateNamePatterns(t,r){return Gr({name:t,alias:r})}checkFileAccess(t){return Rs(async()=>At(t),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,r,n){let i=[];if(!At(t))return i;if(r||n){let s=this.generateNamePatterns(r||"",n);for(let o of s)for(let a of this.extensions){let l=Vr(t,`${o}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),o=s(t);for(let a of o)if(this.looksLikeConfigFile(a)){let l=Vr(t,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}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 r=[];try{if(!At(t))return r.push("Configuration file does not exist"),r;let n=await import(t),i=n.default||n;if(i===void 0)r.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)r.push("Configuration must be an object");else if(Array.isArray(i))r.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),o=s(t,"utf8");JSON.parse(o)}catch(s){r.push(`Invalid JSON syntax: ${s}`)}}catch(n){r.push(`Failed to load configuration file: ${n}`)}return r}async getFileModificationTime(t){try{let{statSync:r}=await import("fs");return r(t).mtime}catch{return null}}async preloadConfigurations(t,r={}){let n=new Map;return await Promise.allSettled(t.map(async(i)=>{try{let s=await this.loadFromPath(i,{},r);if(s)n.set(i,s.config)}catch(s){if(r.verbose)console.warn(`Failed to preload ${i}:`,s)}})),n}}var Ws=/^https?:\/\//;class Tn{async validateConfiguration(t,r,n={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:o=!0,customRules:a=[],trackPerformance:l=!0,verbose:c=!1}=n,f=async()=>{let u=[],g=[],m={stopOnFirstError:i,validateRequired:s,validateTypes:o,customRules:a,trackPerformance:l,verbose:c};try{if(typeof r==="string")return await this.validateWithSchemaFile(t,r,m);else if(Array.isArray(r))return this.validateWithRules(t,[...r,...a],m);else return this.validateWithJSONSchema(t,r,m)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:g}}};if(l)return await Vt.track("validateConfiguration",f);return f()}async validateWithSchemaFile(t,r,n){try{if(!Vs(r))throw new nt(r,[{path:"",message:"Schema file does not exist"}]);let i=await Cn(r),s=Object.hasOwn(i,"default")?i.default:i;if(Array.isArray(s))return this.validateWithRules(t,s,n);else{if(typeof s!=="object"||s===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(t,s,n)}}catch(i){throw new nt(r,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(t,r,n){let i=[],s=[];return this.validateObjectAgainstSchema(t,r,"",i,s,n),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(t,r,n,i,s,o){if(o.validateTypes&&r.type){let a=Array.isArray(t)?"array":typeof t,l=Array.isArray(r.type)?r.type:[r.type];if(!l.includes(a)){if(i.push({path:n,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),o.stopOnFirstError)return}}if(r.enum&&!r.enum.includes(t)){if(i.push({path:n,message:`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"}),o.stopOnFirstError)return}if(typeof t==="string"){if(r.minLength!==void 0&&t.length<r.minLength)i.push({path:n,message:`String length must be at least ${r.minLength}`,expected:`>= ${r.minLength}`,actual:t.length,rule:"minLength"});if(r.maxLength!==void 0&&t.length>r.maxLength)i.push({path:n,message:`String length must not exceed ${r.maxLength}`,expected:`<= ${r.maxLength}`,actual:t.length,rule:"maxLength"});if(r.pattern){if(!new RegExp(r.pattern).test(t))i.push({path:n,message:`String does not match pattern ${r.pattern}`,expected:r.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(r.minimum!==void 0&&t<r.minimum)i.push({path:n,message:`Value must be at least ${r.minimum}`,expected:`>= ${r.minimum}`,actual:t,rule:"minimum"});if(r.maximum!==void 0&&t>r.maximum)i.push({path:n,message:`Value must not exceed ${r.maximum}`,expected:`<= ${r.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&r.items)for(let a=0;a<t.length;a++){let l=n?`${n}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(t[a],r.items,l,i,s,o),o.stopOnFirstError&&i.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let a=t;if(o.validateRequired&&r.required){for(let l of r.required)if(!(l in a)){if(i.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(r.properties){for(let[l,c]of Object.entries(r.properties))if(l in a){let f=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],c,f,i,s,o),o.stopOnFirstError&&i.length>0)return}}if(r.additionalProperties===!1){let l=new Set(Object.keys(r.properties||{}));for(let c of Object.keys(a))if(!l.has(c))s.push({path:n?`${n}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,r,n){let i=[],s=[];for(let o of r)try{let a=this.getValueByPath(t,o.path),l=this.validateWithRule(a,o,o.path);if(i.push(...l),n.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:o.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(t,r,n){let i=[];if(r.required&&(t===void 0||t===null))return i.push({path:n,message:r.message||`Property '${n}' is required`,expected:"required",rule:"required"}),i;if(t===void 0||t===null)return i;if(r.type){let s=Array.isArray(t)?"array":typeof t;if(s!==r.type)i.push({path:n,message:r.message||`Expected type ${r.type}, got ${s}`,expected:r.type,actual:s,rule:"type"})}if(r.min!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s<r.min)i.push({path:n,message:r.message||`Value must be at least ${r.min}`,expected:`>= ${r.min}`,actual:s,rule:"min"})}if(r.max!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s>r.max)i.push({path:n,message:r.message||`Value must not exceed ${r.max}`,expected:`<= ${r.max}`,actual:s,rule:"max"})}if(r.pattern&&typeof t==="string"){if(!r.pattern.test(t))i.push({path:n,message:r.message||`Value does not match pattern ${r.pattern}`,expected:r.pattern.toString(),actual:t,rule:"pattern"})}if(r.enum&&!r.enum.includes(t))i.push({path:n,message:r.message||`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"});if(r.validator){let s=r.validator(t);if(s)i.push({path:n,message:r.message||s,rule:"custom"})}return i}getValueByPath(t,r){if(!r)return t;let n=r.split("."),i=t;for(let s of n)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(t){let r=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of n){let[,s,o,a]=i;r.push({path:s,required:!o,type:this.mapTypeScriptType(a)})}return r}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:Ws},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var q=new at("bunfig",{showTags:!0});function zs(t){if(!t)return"";let r=Array.isArray(t)?t.filter(Boolean):[t];if(r.length===0)return"";if(r.length===1)return` or alias "${r[0]}"`;return` or aliases ${r.map((n)=>`"${n}"`).join(", ")}`}class kn{fileLoader=new Sn;envProcessor=new Xt;validator=new Tn;async loadConfig(t){let r=Date.now(),{cache:n,performance:i,schema:s,validate:o,...a}=t,l=a.errorPolicy==="throw"?{...n,enabled:!1}:n;try{if(l?.enabled){let f=this.checkCache(a.name||"",a);if(f)return f}let c;try{c=await this.loadConfigurationStrategies(a,!0,l)}catch(f){if(a.configFile||a.errorPolicy==="throw"&&!(f instanceof we))throw f;let u=a.__strictErrorHandling;if(f instanceof we){if(u&&a.errorPolicy!=="throw")throw f;c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(f instanceof se){let g=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),m=!g&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),h=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(u&&(h||g))throw f;if(m&&(!u||!h))c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(s||o)await this.validateConfiguration(c.config,s,o,a.name);if(l?.enabled&&c)this.cacheResult(a.name||"",c,l,a);if(i?.enabled){let f={operation:"loadConfig",duration:Date.now()-r,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(f);if(i.slowThreshold&&f.duration>i.slowThreshold)q.warn(`Slow configuration loading detected: ${f.duration}ms for ${a.name}`);c.metrics=f}return c}catch(c){if(c instanceof we)throw c;let f=Date.now()-r;throw q.error(`Configuration loading failed after ${f}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,r=!1,n){let{name:i="",alias:s,configFile:o,cwd:a,configDir:l,defaultConfig:c,checkEnv:f=!0,arrayStrategy:u="replace",verbose:g=!1}=t,m=a||it.cwd(),h=[];if(o){let F=Y(m,o);h.push(F);let z=f?$e(i,c,g):c,_=await this.fileLoader.tryLoadFromPaths([F],z,{arrayStrategy:u,verbose:g,cacheTtl:n?.ttl,useCache:n?.enabled!==!1&&(!n?.ttl||n.ttl>100),strictDiscovery:!0});if(!_)throw ne.configNotFound(i||o,h,s);if(g)q.success(`Configuration loaded from explicit path: ${F}`);return this.finalizeResult(_,h,f,i,g)}let y=await this.loadLocalConfiguration(i,s,m,l,c,u,g,f,n,t.errorPolicy==="throw");if(y)return h.push(...this.getLocalSearchPaths(i,s,m,l)),this.finalizeResult(y,h,f,i,g);let d=await this.loadHomeConfiguration(i,s,c,u,g,f,n,t.errorPolicy==="throw");if(d)return h.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,h,f,i,g);let p=await this.loadPackageJsonConfiguration(i,s,m,c,u,g,f,t.errorPolicy);if(p)return h.push(Y(m,"package.json")),this.finalizeResult(p,h,f,i,g);if(h.push(...this.getAllSearchPaths(i,s,m,l)),r)throw ne.configNotFound(i,h,s);return{...await this.applyEnvironmentVariables(i,c,f,g),warnings:[`No configuration file found for "${i}"${zs(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,r,n,i,s,o,a,l,c,f=!1){let u=l?$e(t,s,a):s,g=this.getLocalDirectories(n,i);for(let m of g){if(a)q.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(t,m,r),y=await this.fileLoader.tryLoadFromPaths(h,u,{arrayStrategy:o,verbose:a,cacheTtl:c?.ttl,useCache:c?.enabled!==!1&&(!c?.ttl||c.ttl>100),strictDiscovery:f});if(y){if(a)q.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,r,n,i,s,o,a,l=!1){if(!t)return null;let c=o?$e(t,n,s):n,f=[Y(ae(),".config",t),Y(ae(),".config"),ae()];for(let u of f){if(s)q.info(`Checking home directory: ${u}`);let g=this.fileLoader.generateConfigPaths(t,u,r),m=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:i,verbose:s,cacheTtl:a?.ttl,useCache:a?.enabled!==!1&&(!a?.ttl||a.ttl>100),strictDiscovery:l});if(m){if(s)q.success(`Configuration loaded from home directory: ${m.source.path}`);return m}}return null}async loadPackageJsonConfiguration(t,r,n,i,s,o,a,l){let c=a?$e(t,i,o):i,f=Y(n,"package.json"),u=l==="throw";try{let g=JSON.parse(Dn(f,"utf8"));if(typeof g!=="object"||g===null||Array.isArray(g))throw Error("package.json must contain an object");let m=g,h=r===void 0?[]:Array.isArray(r)?r:[r],d=[t,...h.filter(Boolean)].find((T)=>Object.hasOwn(m,T)&&(u||Boolean(m[T])));if(d===void 0)return null;let p=m[d];if(typeof p!=="object"||p===null||Array.isArray(p))throw Error(`Configuration field "${d}" must contain an object`);if(o)q.success(`Configuration loaded from package.json: ${d}`);return{config:xn(c,p,s),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(g){if($n(g))return null;if(u)throw ne.configLoad(f,g instanceof Error?g:Error(String(g)));if(o)q.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))]);return null}}async applyEnvironmentVariables(t,r,n,i){if(!n||!t||typeof r!=="object"||r===null||Array.isArray(r))return{config:r,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(t,r,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,r,n,i,s){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,r,n,i){let s=[];if(n){let o=n(t);if(o)s.push(...o)}if(r){let o=await this.validator.validateConfiguration(t,r);if(!o.isValid)s.push(...o.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw ne.configValidation(i||"unknown",s,i)}checkCache(t,r){let n=this.generateCacheKey(t,r);return Ue.get(n)||null}cacheResult(t,r,n,i){let s=this.generateCacheKey(t,i);Ue.set(s,r,void 0,n.ttl)}generateCacheKey(t,r){let n=[t];if(r.alias){let i=Array.isArray(r.alias)?r.alias.join(","):r.alias;n.push(`alias:${i}`)}if(r.cwd)n.push(`cwd:${r.cwd}`);if(r.configFile)n.push(`configFile:${r.configFile}`);if(r.configDir)n.push(`configDir:${r.configDir}`);if("checkEnv"in r)n.push(`checkEnv:${r.checkEnv}`);return n.join("|")}getLocalDirectories(t,r){return Pn({cwd:t,configDir:r})}getAllSearchPaths(t,r,n,i){let s=[];return s.push(...this.getLocalSearchPaths(t,r,n,i)),s.push(...this.getHomeSearchPaths(t,r)),s.push(Y(n,"package.json")),s}getLocalSearchPaths(t,r,n,i){let s=this.getLocalDirectories(n,i),o=[];for(let a of s)o.push(...this.fileLoader.generateConfigPaths(t,a,r));return o}getHomeSearchPaths(t,r){if(!t)return[];let n=[Y(ae(),".config",t),Y(ae(),".config"),ae()],i=[];for(let s of n)i.push(...this.fileLoader.generateConfigPaths(t,s,r));return i}async loadConfigWithResult(t){return this.loadConfig(t)}}var Ft=new kn;async function An(t){let r="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let i;if(n)i=await Ft.loadConfig(t);else i=await Ft.loadConfig({...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??r}catch(i){if(t.configFile||t.errorPolicy==="throw")throw i;let s=i instanceof Error?i.message:String(i);if(!(i instanceof we||i instanceof se||i instanceof Ht||s.includes("config"))&&t.verbose)q.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=n?{...t,defaultConfig:r}:{...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Ft.applyEnvironmentVariables(a.name||"",r,!0,a.verbose||!1))?.config??r;return r}}function $e(t,r,n=!1){let i=new Xt,s=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=[`${s}_${g.join("_").toUpperCase()}`,`${s}_${g.map((d)=>d.toUpperCase()).join("")}`,`${s}_${g.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,y;for(let d of m)if(h=it.env[d],h!==void 0){y=d;break}if(h!==void 0&&y)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let d=Number(h);if(!Number.isNaN(d))c[f]=d}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((d)=>d.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,g)}return c}return o(r)}var Ka=Y(it.cwd(),"config"),Va=Y(it.cwd(),"src/generated");var j={cwd:Qt.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},Js=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function qs(t=Qt.cwd()){for(let r of Js){let n=Fn(t,r);if(Us(n))try{let s=await import(Gs(n).href),o=s.default||s.config||s,a=typeof o==="function"?await o():o;return{...j,...a,cwd:t}}catch(i){let s=i instanceof Error?i.message:String(i);e.warn(`Failed to load config from ${r}: ${s}`)}}return null}var ct=new Map;async function oa(t){let r=Fn(t??Qt.cwd()),n=ct.get(r);if(!n)n=(async()=>{let i=await qs(r);if(i)return i;return{...await An({name:"dts",cwd:r,defaultConfig:{...j,cwd:r}}),cwd:r}})(),ct.set(r,n);try{return await n}catch(i){throw ct.delete(r),i}}function aa(){ct.clear()}function ca(t){return{...j,...t}}function la(t){return async()=>{let r=await t();return{...j,...r}}}var A=j;
|
|
62
|
-
export{j,oa,aa,ca,la,
|
|
61
|
+
`;return n}}var Kr=Ns(import.meta.url),Ie=new Map,kt=new Set;function $n(t){return t instanceof Error&&"code"in t&&(t.code==="ENOENT"||t.code==="ENOTDIR")}async function Cn(t){let r=Ds(t),n=Ie.get(r),i,s=new Promise((o)=>{i=o});Ie.set(r,s),await n;try{if(Ps(r),Kr.cache[r]?.loaded===!0||kt.has(r))delete Kr.cache[r];try{let o=await import(Ms(r).href);return kt.delete(r),o}catch(o){throw kt.add(r),o}}finally{if(i(),Ie.get(r)===s)Ie.delete(r)}}function Ls(t,r,n={}){return bn(t,r,n,new WeakMap)}function bn(t,r,n,i){let{arrayMergeMode:s="replace",skipNullish:o=!1,customMerger:a}=n;if(r===null||r===void 0)return o?t:r;if(a){let l=a(t,r);if(l!==void 0)return l}if(Array.isArray(r)||Array.isArray(t))return En(t,r,s,i);if(!W(r)||!W(t))return r;return Ks(t,r,n,i)}function En(t,r,n,i){if(Array.isArray(r)&&!Array.isArray(t))return r;if(Array.isArray(t)&&!Array.isArray(r))return r;if(Array.isArray(r)&&Array.isArray(t))switch(n){case"replace":return r;case"concat":return Bs(t,r);case"smart":return Is(t,r,i);default:return r}return r}function Bs(t,r){let n=[...r];for(let i of t)if(!n.some((s)=>Kt(s,i)))n.push(i);return n}function Is(t,r,n){if(r.length===0)return t;if(t.length===0)return r;if(W(r[0])&&W(t[0]))return _s(t,r,n);if(r.every((i)=>typeof i==="string")&&t.every((i)=>typeof i==="string")){let i=[...r];for(let s of t)if(!i.includes(s))i.push(s);return i}return r}function _s(t,r,n){let i=[...r];for(let s of t){if(!W(s)){i.push(s);continue}let o=["id","name","key","path","type"],a=!1;for(let l of o)if(l in s){if(i.find((f)=>W(f)&&(l in f)&&f[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function Ks(t,r,n,i){let s=r;if(W(s)&&i.has(s))return i.get(s);let o={...t};if(W(s))i.set(s,o);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],c=o[a];if(n.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){o[a]=l;continue}if(W(l)&&W(c))o[a]=bn(c,l,n,i);else if(Array.isArray(l)||Array.isArray(c))o[a]=En(c,l,n.arrayMergeMode||"smart",i);else o[a]=l}return o}function xn(t,r,n="replace"){return Ls(t,r,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Kt(t,r){if(t===r)return!0;if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!Kt(t[n],r[n]))return!1;return!0}if(W(t)&&W(r)){let n=Object.keys(t),i=Object.keys(r);if(n.length!==i.length)return!1;for(let s of n){if(!Object.prototype.hasOwnProperty.call(r,s))return!1;if(!Kt(t[s],r[s]))return!1}return!0}return!1}function W(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Sn{extensions=Ur;async loadFromPath(t,r,n={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:o,trackPerformance:a=!0,verbose:l=!1,strictDiscovery:c=!1}=n;if(s){let u=Ue.getWithFileCheck("file",t);if(u){if(l)console.log(`Configuration loaded from cache: ${t}`);return u}}let f=async()=>{try{try{js(t)}catch(T){if($n(T)||!c)return null;throw T}let u=await Cn(t),g=Object.hasOwn(u,"default"),m=Object.keys(u).length>0,h=g?u.default:u;if(!g&&!m)throw new se(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new se(t,Error("Configuration must export a valid object"),"unknown");let p={config:xn(r,h,i),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(s)Ue.setWithFileCheck("file",p,t,o);return p}catch(u){throw u instanceof Error?ne.configLoad(t,u):ne.configLoad(t,Error(String(u)))}};if(a)return Vt.track("loadFromPath",f,{path:t});return f()}async tryLoadFromPaths(t,r,n={}){for(let i of t)try{let s=await this.loadFromPath(i,r,n);if(s)return s}catch(s){if(s instanceof se)throw s;if(n.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(t,r,n){return Rn({name:t,directory:r,alias:n})}generateNamePatterns(t,r){return Gr({name:t,alias:r})}checkFileAccess(t){return Rs(async()=>At(t),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,r,n){let i=[];if(!At(t))return i;if(r||n){let s=this.generateNamePatterns(r||"",n);for(let o of s)for(let a of this.extensions){let l=Vr(t,`${o}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),o=s(t);for(let a of o)if(this.looksLikeConfigFile(a)){let l=Vr(t,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}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 r=[];try{if(!At(t))return r.push("Configuration file does not exist"),r;let n=await import(t),i=n.default||n;if(i===void 0)r.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)r.push("Configuration must be an object");else if(Array.isArray(i))r.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),o=s(t,"utf8");JSON.parse(o)}catch(s){r.push(`Invalid JSON syntax: ${s}`)}}catch(n){r.push(`Failed to load configuration file: ${n}`)}return r}async getFileModificationTime(t){try{let{statSync:r}=await import("fs");return r(t).mtime}catch{return null}}async preloadConfigurations(t,r={}){let n=new Map;return await Promise.allSettled(t.map(async(i)=>{try{let s=await this.loadFromPath(i,{},r);if(s)n.set(i,s.config)}catch(s){if(r.verbose)console.warn(`Failed to preload ${i}:`,s)}})),n}}var Ws=/^https?:\/\//;class Tn{async validateConfiguration(t,r,n={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:o=!0,customRules:a=[],trackPerformance:l=!0,verbose:c=!1}=n,f=async()=>{let u=[],g=[],m={stopOnFirstError:i,validateRequired:s,validateTypes:o,customRules:a,trackPerformance:l,verbose:c};try{if(typeof r==="string")return await this.validateWithSchemaFile(t,r,m);else if(Array.isArray(r))return this.validateWithRules(t,[...r,...a],m);else return this.validateWithJSONSchema(t,r,m)}catch(h){return u.push({path:"",message:`Validation failed: ${h}`,rule:"system"}),{isValid:!1,errors:u,warnings:g}}};if(l)return await Vt.track("validateConfiguration",f);return f()}async validateWithSchemaFile(t,r,n){try{if(!Vs(r))throw new nt(r,[{path:"",message:"Schema file does not exist"}]);let i=await Cn(r),s=Object.hasOwn(i,"default")?i.default:i;if(Array.isArray(s))return this.validateWithRules(t,s,n);else{if(typeof s!=="object"||s===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(t,s,n)}}catch(i){throw new nt(r,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(t,r,n){let i=[],s=[];return this.validateObjectAgainstSchema(t,r,"",i,s,n),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(t,r,n,i,s,o){if(o.validateTypes&&r.type){let a=Array.isArray(t)?"array":typeof t,l=Array.isArray(r.type)?r.type:[r.type];if(!l.includes(a)){if(i.push({path:n,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),o.stopOnFirstError)return}}if(r.enum&&!r.enum.includes(t)){if(i.push({path:n,message:`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"}),o.stopOnFirstError)return}if(typeof t==="string"){if(r.minLength!==void 0&&t.length<r.minLength)i.push({path:n,message:`String length must be at least ${r.minLength}`,expected:`>= ${r.minLength}`,actual:t.length,rule:"minLength"});if(r.maxLength!==void 0&&t.length>r.maxLength)i.push({path:n,message:`String length must not exceed ${r.maxLength}`,expected:`<= ${r.maxLength}`,actual:t.length,rule:"maxLength"});if(r.pattern){if(!new RegExp(r.pattern).test(t))i.push({path:n,message:`String does not match pattern ${r.pattern}`,expected:r.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(r.minimum!==void 0&&t<r.minimum)i.push({path:n,message:`Value must be at least ${r.minimum}`,expected:`>= ${r.minimum}`,actual:t,rule:"minimum"});if(r.maximum!==void 0&&t>r.maximum)i.push({path:n,message:`Value must not exceed ${r.maximum}`,expected:`<= ${r.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&r.items)for(let a=0;a<t.length;a++){let l=n?`${n}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(t[a],r.items,l,i,s,o),o.stopOnFirstError&&i.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let a=t;if(o.validateRequired&&r.required){for(let l of r.required)if(!(l in a)){if(i.push({path:n?`${n}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),o.stopOnFirstError)return}}if(r.properties){for(let[l,c]of Object.entries(r.properties))if(l in a){let f=n?`${n}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],c,f,i,s,o),o.stopOnFirstError&&i.length>0)return}}if(r.additionalProperties===!1){let l=new Set(Object.keys(r.properties||{}));for(let c of Object.keys(a))if(!l.has(c))s.push({path:n?`${n}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,r,n){let i=[],s=[];for(let o of r)try{let a=this.getValueByPath(t,o.path),l=this.validateWithRule(a,o,o.path);if(i.push(...l),n.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:o.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(t,r,n){let i=[];if(r.required&&(t===void 0||t===null))return i.push({path:n,message:r.message||`Property '${n}' is required`,expected:"required",rule:"required"}),i;if(t===void 0||t===null)return i;if(r.type){let s=Array.isArray(t)?"array":typeof t;if(s!==r.type)i.push({path:n,message:r.message||`Expected type ${r.type}, got ${s}`,expected:r.type,actual:s,rule:"type"})}if(r.min!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s<r.min)i.push({path:n,message:r.message||`Value must be at least ${r.min}`,expected:`>= ${r.min}`,actual:s,rule:"min"})}if(r.max!==void 0){let s=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(s>r.max)i.push({path:n,message:r.message||`Value must not exceed ${r.max}`,expected:`<= ${r.max}`,actual:s,rule:"max"})}if(r.pattern&&typeof t==="string"){if(!r.pattern.test(t))i.push({path:n,message:r.message||`Value does not match pattern ${r.pattern}`,expected:r.pattern.toString(),actual:t,rule:"pattern"})}if(r.enum&&!r.enum.includes(t))i.push({path:n,message:r.message||`Value must be one of: ${r.enum.join(", ")}`,expected:r.enum.join(", "),actual:t,rule:"enum"});if(r.validator){let s=r.validator(t);if(s)i.push({path:n,message:r.message||s,rule:"custom"})}return i}getValueByPath(t,r){if(!r)return t;let n=r.split("."),i=t;for(let s of n)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(t){let r=[],n=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of n){let[,s,o,a]=i;r.push({path:s,required:!o,type:this.mapTypeScriptType(a)})}return r}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:Ws},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var q=new at("bunfig",{showTags:!0});function zs(t){if(!t)return"";let r=Array.isArray(t)?t.filter(Boolean):[t];if(r.length===0)return"";if(r.length===1)return` or alias "${r[0]}"`;return` or aliases ${r.map((n)=>`"${n}"`).join(", ")}`}class kn{fileLoader=new Sn;envProcessor=new Xt;validator=new Tn;async loadConfig(t){let r=Date.now(),{cache:n,performance:i,schema:s,validate:o,...a}=t,l=a.errorPolicy==="throw"?{...n,enabled:!1}:n;try{if(l?.enabled){let f=this.checkCache(a.name||"",a);if(f)return f}let c;try{c=await this.loadConfigurationStrategies(a,!0,l)}catch(f){if(a.configFile||a.errorPolicy==="throw"&&!(f instanceof we))throw f;let u=a.__strictErrorHandling;if(f instanceof we){if(u&&a.errorPolicy!=="throw")throw f;c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(f instanceof se){let g=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),m=!g&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),h=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(u&&(h||g))throw f;if(m&&(!u||!h))c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else c={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(s||o)await this.validateConfiguration(c.config,s,o,a.name);if(l?.enabled&&c)this.cacheResult(a.name||"",c,l,a);if(i?.enabled){let f={operation:"loadConfig",duration:Date.now()-r,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(f);if(i.slowThreshold&&f.duration>i.slowThreshold)q.warn(`Slow configuration loading detected: ${f.duration}ms for ${a.name}`);c.metrics=f}return c}catch(c){if(c instanceof we)throw c;let f=Date.now()-r;throw q.error(`Configuration loading failed after ${f}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,r=!1,n){let{name:i="",alias:s,configFile:o,cwd:a,configDir:l,defaultConfig:c,checkEnv:f=!0,arrayStrategy:u="replace",verbose:g=!1}=t,m=a||it.cwd(),h=[];if(o){let A=Y(m,o);h.push(A);let z=f?$e(i,c,g):c,_=await this.fileLoader.tryLoadFromPaths([A],z,{arrayStrategy:u,verbose:g,cacheTtl:n?.ttl,useCache:n?.enabled!==!1&&(!n?.ttl||n.ttl>100),strictDiscovery:!0});if(!_)throw ne.configNotFound(i||o,h,s);if(g)q.success(`Configuration loaded from explicit path: ${A}`);return this.finalizeResult(_,h,f,i,g)}let y=await this.loadLocalConfiguration(i,s,m,l,c,u,g,f,n,t.errorPolicy==="throw");if(y)return h.push(...this.getLocalSearchPaths(i,s,m,l)),this.finalizeResult(y,h,f,i,g);let d=await this.loadHomeConfiguration(i,s,c,u,g,f,n,t.errorPolicy==="throw");if(d)return h.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,h,f,i,g);let p=await this.loadPackageJsonConfiguration(i,s,m,c,u,g,f,t.errorPolicy);if(p)return h.push(Y(m,"package.json")),this.finalizeResult(p,h,f,i,g);if(h.push(...this.getAllSearchPaths(i,s,m,l)),r)throw ne.configNotFound(i,h,s);return{...await this.applyEnvironmentVariables(i,c,f,g),warnings:[`No configuration file found for "${i}"${zs(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,r,n,i,s,o,a,l,c,f=!1){let u=l?$e(t,s,a):s,g=this.getLocalDirectories(n,i);for(let m of g){if(a)q.info(`Searching for configuration in: ${m}`);let h=this.fileLoader.generateConfigPaths(t,m,r),y=await this.fileLoader.tryLoadFromPaths(h,u,{arrayStrategy:o,verbose:a,cacheTtl:c?.ttl,useCache:c?.enabled!==!1&&(!c?.ttl||c.ttl>100),strictDiscovery:f});if(y){if(a)q.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,r,n,i,s,o,a,l=!1){if(!t)return null;let c=o?$e(t,n,s):n,f=[Y(ae(),".config",t),Y(ae(),".config"),ae()];for(let u of f){if(s)q.info(`Checking home directory: ${u}`);let g=this.fileLoader.generateConfigPaths(t,u,r),m=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:i,verbose:s,cacheTtl:a?.ttl,useCache:a?.enabled!==!1&&(!a?.ttl||a.ttl>100),strictDiscovery:l});if(m){if(s)q.success(`Configuration loaded from home directory: ${m.source.path}`);return m}}return null}async loadPackageJsonConfiguration(t,r,n,i,s,o,a,l){let c=a?$e(t,i,o):i,f=Y(n,"package.json"),u=l==="throw";try{let g=JSON.parse(Dn(f,"utf8"));if(typeof g!=="object"||g===null||Array.isArray(g))throw Error("package.json must contain an object");let m=g,h=r===void 0?[]:Array.isArray(r)?r:[r],d=[t,...h.filter(Boolean)].find((T)=>Object.hasOwn(m,T)&&(u||Boolean(m[T])));if(d===void 0)return null;let p=m[d];if(typeof p!=="object"||p===null||Array.isArray(p))throw Error(`Configuration field "${d}" must contain an object`);if(o)q.success(`Configuration loaded from package.json: ${d}`);return{config:xn(c,p,s),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}catch(g){if($n(g))return null;if(u)throw ne.configLoad(f,g instanceof Error?g:Error(String(g)));if(o)q.warn("Failed to load package.json:",[g instanceof Error?g:Error(String(g))]);return null}}async applyEnvironmentVariables(t,r,n,i){if(!n||!t||typeof r!=="object"||r===null||Array.isArray(r))return{config:r,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(t,r,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,r,n,i,s){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,r,n,i){let s=[];if(n){let o=n(t);if(o)s.push(...o)}if(r){let o=await this.validator.validateConfiguration(t,r);if(!o.isValid)s.push(...o.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw ne.configValidation(i||"unknown",s,i)}checkCache(t,r){let n=this.generateCacheKey(t,r);return Ue.get(n)||null}cacheResult(t,r,n,i){let s=this.generateCacheKey(t,i);Ue.set(s,r,void 0,n.ttl)}generateCacheKey(t,r){let n=[t];if(r.alias){let i=Array.isArray(r.alias)?r.alias.join(","):r.alias;n.push(`alias:${i}`)}if(r.cwd)n.push(`cwd:${r.cwd}`);if(r.configFile)n.push(`configFile:${r.configFile}`);if(r.configDir)n.push(`configDir:${r.configDir}`);if("checkEnv"in r)n.push(`checkEnv:${r.checkEnv}`);return n.join("|")}getLocalDirectories(t,r){return Pn({cwd:t,configDir:r})}getAllSearchPaths(t,r,n,i){let s=[];return s.push(...this.getLocalSearchPaths(t,r,n,i)),s.push(...this.getHomeSearchPaths(t,r)),s.push(Y(n,"package.json")),s}getLocalSearchPaths(t,r,n,i){let s=this.getLocalDirectories(n,i),o=[];for(let a of s)o.push(...this.fileLoader.generateConfigPaths(t,a,r));return o}getHomeSearchPaths(t,r){if(!t)return[];let n=[Y(ae(),".config",t),Y(ae(),".config"),ae()],i=[];for(let s of n)i.push(...this.fileLoader.generateConfigPaths(t,s,r));return i}async loadConfigWithResult(t){return this.loadConfig(t)}}var Ft=new kn;async function An(t){let r="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},n="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let i;if(n)i=await Ft.loadConfig(t);else i=await Ft.loadConfig({...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??r}catch(i){if(t.configFile||t.errorPolicy==="throw")throw i;let s=i instanceof Error?i.message:String(i);if(!(i instanceof we||i instanceof se||i instanceof Ht||s.includes("config"))&&t.verbose)q.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=n?{...t,defaultConfig:r}:{...t,defaultConfig:r,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Ft.applyEnvironmentVariables(a.name||"",r,!0,a.verbose||!1))?.config??r;return r}}function $e(t,r,n=!1){let i=new Xt,s=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function o(a,l=[]){let c={...a};for(let[f,u]of Object.entries(a)){let g=[...l,f],m=[`${s}_${g.join("_").toUpperCase()}`,`${s}_${g.map((d)=>d.toUpperCase()).join("")}`,`${s}_${g.map((d)=>d.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],h,y;for(let d of m)if(h=it.env[d],h!==void 0){y=d;break}if(h!==void 0&&y)if(typeof u==="boolean")c[f]=["true","1","yes"].includes(h.toLowerCase());else if(typeof u==="number"){let d=Number(h);if(!Number.isNaN(d))c[f]=d}else if(Array.isArray(u))try{c[f]=JSON.parse(h)}catch{c[f]=h.split(",").map((d)=>d.trim())}else c[f]=h;else if(u&&typeof u==="object"&&!Array.isArray(u))c[f]=o(u,g)}return c}return o(r)}var Ka=Y(it.cwd(),"config"),Va=Y(it.cwd(),"src/generated");var j={cwd:Qt.cwd(),root:"./src",entrypoints:["**/*.{ts,tsx,mts,cts,vue,stx}"],outdir:"./dist",keepComments:!0,clean:!0,tsconfigPath:"./tsconfig.json",outputStructure:"mirror",moduleSpecifierMode:"preserve",verbose:!1,importOrder:["bun"],declarationMap:!1},Js=["dtsx.config.ts","dtsx.config.js","dtsx.config.mjs","dtsx.config.mts","dts.config.ts","dts.config.js"];async function qs(t=Qt.cwd()){for(let r of Js){let n=Fn(t,r);if(Us(n))try{let s=await import(Gs(n).href),o=s.default||s.config||s,a=typeof o==="function"?await o():o;return{...j,...a,cwd:t}}catch(i){let s=i instanceof Error?i.message:String(i);e.warn(`Failed to load config from ${r}: ${s}`)}}return null}var ct=new Map;async function oa(t){let r=Fn(t??Qt.cwd()),n=ct.get(r);if(!n)n=(async()=>{let i=await qs(r);if(i)return i;return{...await An({name:"dts",cwd:r,defaultConfig:{...j,cwd:r}}),cwd:r}})(),ct.set(r,n);try{return await n}catch(i){throw ct.delete(r),i}}function aa(){ct.clear()}function ca(t){return{...j,...t}}function la(t){return async()=>{let r=await t();return{...j,...r}}}var D=j;
|
|
62
|
+
export{j,oa,aa,ca,la,D};
|