better-dx 0.2.37 → 0.2.39
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/CHANGELOG.md +34 -0
- package/README.md +23 -0
- package/dist/chunk-1ts3tqy6.js +62 -0
- package/dist/config.d.ts +1 -1
- package/dist/config.js +2 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -60
- package/dist/types.js +1 -0
- package/package.json +26 -16
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
+
[Compare changes](https://github.com/stacksjs/better-dx/compare/v0.2.38...v0.2.39)
|
|
2
|
+
|
|
3
|
+
## 🐛 Bug Fixes
|
|
4
|
+
|
|
5
|
+
- raise the shared declaration producer floor to 0.11.55 ([ebe5fc4](https://github.com/stacksjs/better-dx/commit/ebe5fc4)) _(by Chris Breuer)_ ([#970](https://github.com/stacksjs/better-dx/issues/970), [#971](https://github.com/stacksjs/better-dx/issues/971))
|
|
6
|
+
- ship typed SDK subpaths and verify bundled tools ([d490f87](https://github.com/stacksjs/better-dx/commit/d490f87)) _(by Chris Breuer)_ ([#970](https://github.com/stacksjs/better-dx/issues/970), [#971](https://github.com/stacksjs/better-dx/issues/971), [stacksjs/dtsx#3139](https://github.com/stacksjs/dtsx/issues/3139))
|
|
7
|
+
|
|
8
|
+
## ✅ Tests
|
|
9
|
+
|
|
10
|
+
- verify public SDKs against original CI archives ([23b9d0b](https://github.com/stacksjs/better-dx/commit/23b9d0b)) _(by Chris Breuer)_ ([#970](https://github.com/stacksjs/better-dx/issues/970), [#971](https://github.com/stacksjs/better-dx/issues/971))
|
|
11
|
+
|
|
12
|
+
## 🔧 Chores
|
|
13
|
+
|
|
14
|
+
- **deps**: update shared development tools and managed CI ([9499d5b](https://github.com/stacksjs/better-dx/commit/9499d5b)) _(by Chris Breuer)_ ([#960](https://github.com/stacksjs/better-dx/issues/960), [#970](https://github.com/stacksjs/better-dx/issues/970), [#971](https://github.com/stacksjs/better-dx/issues/971))
|
|
15
|
+
|
|
16
|
+
## Contributors
|
|
17
|
+
|
|
18
|
+
- _Chris Breuer_
|
|
19
|
+
|
|
20
|
+
[Compare changes](https://github.com/stacksjs/better-dx/compare/v0.2.37...v0.2.38)
|
|
21
|
+
|
|
22
|
+
## 🐛 Bug Fixes
|
|
23
|
+
|
|
24
|
+
- **deps**: use the compiler with patched Go runtime ([5565706](https://github.com/stacksjs/better-dx/commit/5565706)) _(by Chris <chris@stacksjs.com>)_
|
|
25
|
+
|
|
26
|
+
## 🔧 Chores
|
|
27
|
+
|
|
28
|
+
- release v0.2.38 ([4e9068d](https://github.com/stacksjs/better-dx/commit/4e9068d)) _(by Chris <chris@stacksjs.com>)_
|
|
29
|
+
- rebuild the shared tooling CLI ([6a313e3](https://github.com/stacksjs/better-dx/commit/6a313e3)) _(by Chris <chris@stacksjs.com>)_
|
|
30
|
+
|
|
31
|
+
## Contributors
|
|
32
|
+
|
|
33
|
+
- _Chris <chris@stacksjs.com>_
|
|
34
|
+
|
|
1
35
|
[Compare changes](https://github.com/stacksjs/better-dx/compare/v0.2.36...v0.2.37)
|
|
2
36
|
|
|
3
37
|
## 🐛 Bug Fixes
|
package/README.md
CHANGED
|
@@ -8,6 +8,11 @@
|
|
|
8
8
|
|
|
9
9
|
# better-dx
|
|
10
10
|
|
|
11
|
+
TypeScript is pinned to `7.1.0-dev.20261011.1`: its native compiler uses Go
|
|
12
|
+
1.27.2. The stable 7.0.2 compiler bundles Go 1.26.4, which is affected by
|
|
13
|
+
GO-2026-6604 and GO-2026-6612. Keep the compiler pin until a stable TypeScript
|
|
14
|
+
release includes the patched Go runtime.
|
|
15
|
+
|
|
11
16
|
All the development dependencies you need.
|
|
12
17
|
|
|
13
18
|
## Features
|
|
@@ -30,12 +35,30 @@ npm install -D better-dx
|
|
|
30
35
|
|
|
31
36
|
And this sets up your project!
|
|
32
37
|
|
|
38
|
+
## Configuration
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { getConfig } from 'better-dx/config'
|
|
42
|
+
import type { DXConfig } from 'better-dx/types'
|
|
43
|
+
|
|
44
|
+
const config: DXConfig = await getConfig()
|
|
45
|
+
console.log(config.verbose)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The root `better-dx` entry exports the same configuration API and shares its cached configuration with `better-dx/config`.
|
|
49
|
+
|
|
33
50
|
## Testing
|
|
34
51
|
|
|
35
52
|
```bash
|
|
36
53
|
bun test
|
|
54
|
+
bun run build
|
|
55
|
+
bun run test:sdk
|
|
37
56
|
```
|
|
38
57
|
|
|
58
|
+
The SDK check packs the built package, checks normal and fresh frozen installs, and verifies runtime subpaths, strict typed consumers and the bundled release/declaration tools.
|
|
59
|
+
|
|
60
|
+
To verify a published package, set `BETTER_DX_SDK_PUBLIC_PACKAGE` to its HTTPS package URL and `BETTER_DX_SDK_EXPECTED_ARCHIVE` to the original final CI archive. The check compares every original member's name, bytes and mode, then installs from the public URL without repacking it.
|
|
61
|
+
|
|
39
62
|
## Changelog
|
|
40
63
|
|
|
41
64
|
Please see our [releases](https://github.com/stackjs/better-dx/releases) page for more information on what has changed recently.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{existsSync as er,statSync as tr}from"fs";import{resolve as Ce}from"path";import An from"process";import{existsSync as Gs,mkdirSync as qs,readdirSync as Ys,readFileSync as On,writeFileSync as Hs}from"fs";import{homedir as ae}from"os";import{dirname as Qs,resolve as Y}from"path";import it from"process";import{existsSync as rr,statSync as nr}from"fs";import{existsSync as Ft,mkdirSync as Pn,readdirSync as Nn,writeFileSync as Dn}from"fs";import{homedir as ce}from"os";import{dirname as ir,resolve as I}from"path";import oe from"process";import{join as Mn,relative as jn,resolve as sr}from"path";import Je from"process";import{existsSync as Jr,mkdirSync as lo,readdirSync as fo,writeFileSync as uo}from"fs";import{homedir as ct}from"os";import{dirname as mo,resolve as B}from"path";import Ee from"process";import{join as Ln,relative as Bn,resolve as or}from"path";import Ge from"process";import{existsSync as Gr,mkdirSync as $o,readdirSync as Co,writeFileSync as bo}from"fs";import{dirname as xo,resolve as qe}from"path";import Rt from"process";import{Buffer as re}from"buffer";import{createCipheriv as In,createDecipheriv as _n,randomBytes as lt}from"crypto";import{closeSync as ft,createReadStream as ar,createWriteStream as Kn,existsSync as ut,fsyncSync as cr,openSync as lr,writeFileSync as Vn}from"fs";import{access as Wn,constants as fr,mkdir as zn,readdir as ke,rename as ur,stat as le,unlink as Ae,writeFile as gt}from"fs/promises";import{join as fe}from"path";import M from"process";import{pipeline as Un}from"stream/promises";import{createGzip as gr}from"zlib";import ue from"process";import X from"process";import{Buffer as H}from"buffer";import{createCipheriv as Jn,createDecipheriv as Gn,randomBytes as ht}from"crypto";import{closeSync as mt,createReadStream as hr,createWriteStream as qn,existsSync as Fe,fsyncSync as mr,openSync as dr,writeFileSync as Yn}from"fs";import{access as Hn,constants as pr,mkdir as Zn,readdir as Re,rename as yr,stat as ge,unlink as Oe,writeFile as dt}from"fs/promises";import{isAbsolute as Xn,join as he,resolve as Qn}from"path";import E from"process";import{pipeline as ei}from"stream/promises";import{createGzip as wr}from"zlib";import me from"process";import Q from"process";import Pe from"process";import{existsSync as Ne}from"fs";import{resolve as pt}from"path";import{existsSync as ti}from"fs";import{existsSync as ri,readdirSync as ni}from"fs";import{extname as yt,resolve as vr}from"path";import ii from"process";import{join as si,relative as oi,resolve as $r}from"path";import Ye from"process";import{Buffer as Z}from"buffer";import{createCipheriv as ai,createDecipheriv as ci,randomBytes as wt}from"crypto";import{closeSync as vt,createReadStream as Cr,createWriteStream as li,existsSync as De,fsyncSync as br,openSync as Er,writeFileSync as fi}from"fs";import{access as ui,constants as xr,mkdir as gi,readdir as Me,rename as Sr,stat as de,unlink as je,writeFile as $t}from"fs/promises";import{isAbsolute as hi,join as pe,resolve as mi}from"path";import x from"process";import{pipeline as di}from"stream/promises";import{createGzip as Tr}from"zlib";import ye from"process";import ee from"process";import Be from"process";import{readFileSync as Rs,realpathSync as Os}from"fs";import{createRequire as Ps}from"module";import{pathToFileURL as Ns}from"url";import{existsSync as kt,statSync as Ds}from"fs";import{resolve as Kr}from"path";import{existsSync as _s}from"fs";class Vr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(n={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...n}}generateKey(n,i){let s=i?`:${i}`:"";return`${this.options.keyPrefix}${n}${s}`}isExpired(n){return Date.now()-n.timestamp.getTime()>n.ttl}estimateSize(n){try{return JSON.stringify(n).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let n=Array.from(this.cache.entries()).sort(([,s],[,o])=>s.timestamp.getTime()-o.timestamp.getTime()),i=n.length-this.options.maxSize+1;for(let s=0;s<i;s++)this.cache.delete(n[s][0])}set(n,i,s,o){if(!this.options.enabled)return;let a=this.generateKey(n,s),c=o??this.options.ttl,l=this.estimateSize(i);this.cache.set(a,{value:i,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(n,i){if(!this.options.enabled){this.totalMisses++;return}let s=this.generateKey(n,i),o=this.cache.get(s);if(!o){this.totalMisses++;return}if(this.isExpired(o)){this.cache.delete(s),this.totalMisses++;return}return o.hits++,this.totalHits++,o.value}isFileModified(n,i){try{if(!er(n))return!0;return tr(n).mtime>i}catch{return!0}}getWithFileCheck(n,i){let s=this.get(n,i);if(!s)return;if(this.isFileModified(i,s.fileTimestamp)){this.delete(n,i);return}return s.value}setWithFileCheck(n,i,s,o){try{let a=er(s)?tr(s):null,c=a?a.mtime:new Date;this.set(n,{value:i,fileTimestamp:c},s,o)}catch{this.set(n,i,s,o)}}delete(n,i){let s=this.generateKey(n,i);return this.cache.delete(s)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let n=0;for(let[i,s]of this.cache.entries())if(this.isExpired(s))this.cache.delete(i),n++;return n}getStats(){let n=Array.from(this.cache.values()),i=n.reduce((o,a)=>o+a.size,0),s=n.map((o)=>o.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:s[0],newestEntry:s[s.length-1]}}export(){let n={};for(let[i,s]of this.cache.entries())n[i]={value:s.value,timestamp:s.timestamp.toISOString(),ttl:s.ttl,hits:s.hits,size:s.size};return n}import(n){this.cache.clear();for(let[i,s]of Object.entries(n))if(typeof s==="object"&&s!==null){let o=s;this.cache.set(i,{value:o.value,timestamp:new Date(o.timestamp),ttl:o.ttl,hits:o.hits,size:o.size})}}}class Wr{metrics=[];maxMetrics=1000;async track(n,i,s={}){let o=performance.now(),a=new Date;try{let c=await i(),l=performance.now()-o;return this.recordMetric({operation:n,duration:l,timestamp:a,...s}),c}catch(c){let l=performance.now()-o;throw this.recordMetric({operation:`${n}:error`,duration:l,timestamp:a,...s}),c}}recordMetric(n){if(this.metrics.push(n),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(n){let i=n?this.metrics.filter((a)=>a.operation===n):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let s=i.map((a)=>a.duration),o=s.reduce((a,c)=>a+c,0);return{count:i.length,averageDuration:o/i.length,minDuration:Math.min(...s),maxDuration:Math.max(...s),totalDuration:o,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(n){return this.metrics.filter((i)=>i.duration>n)}}var Ue=new Vr,Kt=new Wr;var zr=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Ur(n={}){let{name:i="",alias:s}=n,o=["config",".config"];if(i)o.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let a=s===void 0?[]:Array.isArray(s)?s:[s];for(let c of a){if(!c)continue;if(o.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)o.push(`${i}.${c}.config`,`.${i}.${c}.config`)}return Array.from(new Set(o.filter(Boolean)))}function Fn(n){return Ur(n).flatMap((s)=>zr.map((o)=>Ce(n.directory,`${s}${o}`)))}function Rn(n={}){let i=Ce(n.cwd||An.cwd());return Array.from(new Set([i,Ce(i,"config"),Ce(i,".config"),n.configDir?Ce(i,n.configDir):void 0].filter((s)=>Boolean(s))))}var pi=Object.defineProperty,yi=(n)=>n;function wi(n,i){this[n]=yi.bind(null,i)}var vi=(n,i)=>{for(var s in i)pi(n,s,{get:i[s],enumerable:!0,configurable:!0,set:wi.bind(i,s)})},$i=(n,i)=>()=>(n&&(i=n(n=0)),i),qr={};vi(qr,{withErrorRecovery:()=>Zr,tryLoadConfig:()=>Wi,loadConfigWithResult:()=>Ki,loadConfig:()=>rn,isRetryableError:()=>Mi,isConfigNotFoundError:()=>Di,isBunfigError:()=>Xr,globalPerformanceMonitor:()=>Te,globalCache:()=>ve,getEnvOrDefault:()=>ji,generateConfigTypes:()=>zi,defaultGeneratedDir:()=>un,defaultConfigDir:()=>fn,deepMergeWithArrayStrategy:()=>Jt,deepMerge:()=>Qr,createLibraryConfig:()=>Ui,config:()=>Vi,bunfigPlugin:()=>Ji,applyEnvVarsToConfig:()=>be,TypeGenerationError:()=>Lt,SchemaValidationError:()=>Se,PluginError:()=>It,PerformanceMonitor:()=>Wt,FileSystemError:()=>jt,ErrorFactory:()=>ie,EnvVarError:()=>tt,EnvProcessor:()=>st,ConfigValidator:()=>Gt,ConfigValidationError:()=>Dt,ConfigNotFoundError:()=>et,ConfigMergeError:()=>Mt,ConfigLoader:()=>qt,ConfigLoadError:()=>xe,ConfigFileLoader:()=>ot,ConfigCache:()=>Vt,CacheUtils:()=>sn,BunfigError:()=>K,BrowserConfigError:()=>Bt,ArrayMergeStrategies:()=>cn});class Vt{cache=new Map;totalHits=0;totalMisses=0;options;constructor(n={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...n}}generateKey(n,i){let s=i?`:${i}`:"";return`${this.options.keyPrefix}${n}${s}`}isExpired(n){return Date.now()-n.timestamp.getTime()>n.ttl}estimateSize(n){try{return JSON.stringify(n).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let n=Array.from(this.cache.entries()).sort(([,s],[,o])=>s.timestamp.getTime()-o.timestamp.getTime()),i=n.length-this.options.maxSize+1;for(let s=0;s<i;s++)this.cache.delete(n[s][0])}set(n,i,s,o){if(!this.options.enabled)return;let a=this.generateKey(n,s),c=o??this.options.ttl,l=this.estimateSize(i);this.cache.set(a,{value:i,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(n,i){if(!this.options.enabled){this.totalMisses++;return}let s=this.generateKey(n,i),o=this.cache.get(s);if(!o){this.totalMisses++;return}if(this.isExpired(o)){this.cache.delete(s),this.totalMisses++;return}return o.hits++,this.totalHits++,o.value}isFileModified(n,i){try{if(!rr(n))return!0;return nr(n).mtime>i}catch{return!0}}getWithFileCheck(n,i){let s=this.get(n,i);if(!s)return;if(this.isFileModified(i,s.fileTimestamp)){this.delete(n,i);return}return s.value}setWithFileCheck(n,i,s,o){try{let a=rr(s)?nr(s):null,c=a?a.mtime:new Date;this.set(n,{value:i,fileTimestamp:c},s,o)}catch{this.set(n,i,s,o)}}delete(n,i){let s=this.generateKey(n,i);return this.cache.delete(s)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let n=0;for(let[i,s]of this.cache.entries())if(this.isExpired(s))this.cache.delete(i),n++;return n}getStats(){let n=Array.from(this.cache.values()),i=n.reduce((o,a)=>o+a.size,0),s=n.map((o)=>o.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:s[0],newestEntry:s[s.length-1]}}export(){let n={};for(let[i,s]of this.cache.entries())n[i]={value:s.value,timestamp:s.timestamp.toISOString(),ttl:s.ttl,hits:s.hits,size:s.size};return n}import(n){this.cache.clear();for(let[i,s]of Object.entries(n))if(typeof s==="object"&&s!==null){let o=s;this.cache.set(i,{value:o.value,timestamp:new Date(o.timestamp),ttl:o.ttl,hits:o.hits,size:o.size})}}}class Wt{metrics=[];maxMetrics=1000;async track(n,i,s={}){let o=performance.now(),a=new Date;try{let c=await i(),l=performance.now()-o;return this.recordMetric({operation:n,duration:l,timestamp:a,...s}),c}catch(c){let l=performance.now()-o;throw this.recordMetric({operation:`${n}:error`,duration:l,timestamp:a,...s}),c}}recordMetric(n){if(this.metrics.push(n),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(n){let i=n?this.metrics.filter((a)=>a.operation===n):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let s=i.map((a)=>a.duration),o=s.reduce((a,c)=>a+c,0);return{count:i.length,averageDuration:o/i.length,minDuration:Math.min(...s),maxDuration:Math.max(...s),totalDuration:o,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(n){return this.metrics.filter((i)=>i.duration>n)}}function Ci(n,i={}){let o=Object.keys(i).sort().map((a)=>`${a}:${i[a]}`).join("|");return o?`${n}:${o}`:n}function bi(n,i){try{return JSON.stringify(n)===JSON.stringify(i)}catch{return n===i}}function Ei(n){return n.getStats().size*2}function zt(n,i){if(Array.isArray(i)&&Array.isArray(n)&&i.length===2&&n.length===2&&k(i[0])&&"id"in i[0]&&i[0].id===3&&k(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(k(i)&&k(n)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return n;if(Array.isArray(i)&&!Array.isArray(n))return i;if(Array.isArray(i)&&Array.isArray(n)){if(k(n)&&"arr"in n&&Array.isArray(n.arr)&&k(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&n.length>0&&k(i[0])&&k(n[0])){let o=[...i];for(let a of n)if(k(a)&&"name"in a){if(!o.find((l)=>k(l)&&("name"in l)&&l.name===a.name))o.push(a)}else if(k(a)&&"path"in a){if(!o.find((l)=>k(l)&&("path"in l)&&l.path===a.path))o.push(a)}else if(!o.some((c)=>He(c,a)))o.push(a);return o}if(i.every((o)=>typeof o==="string")&&n.every((o)=>typeof o==="string")){let o=[...i];for(let a of n)if(!o.includes(a))o.push(a);return o}return i}if(!k(i)||!k(n))return i;let s={...n};for(let o in i)if(Object.prototype.hasOwnProperty.call(i,o)){let a=i[o];if(a===null||a===void 0)continue;else if(k(a)&&k(s[o]))s[o]=zt(s[o],a);else if(Array.isArray(a)&&Array.isArray(s[o]))if(a.length>0&&s[o].length>0&&k(a[0])&&k(s[o][0])){let c=[...a];for(let l of s[o])if(k(l)&&"name"in l){if(!c.find((f)=>k(f)&&("name"in f)&&f.name===l.name))c.push(l)}else if(k(l)&&"path"in l){if(!c.find((f)=>k(f)&&("path"in f)&&f.path===l.path))c.push(l)}else if(!c.some((u)=>He(u,l)))c.push(l);s[o]=c}else if(a.every((c)=>typeof c==="string")&&s[o].every((c)=>typeof c==="string")){let c=[...a];for(let l of s[o])if(!c.includes(l))c.push(l);s[o]=c}else s[o]=a;else s[o]=a}return s}function He(n,i){if(n===i)return!0;if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(!He(n[s],i[s]))return!1;return!0}if(k(n)&&k(i)){let s=Object.keys(n),o=Object.keys(i);if(s.length!==o.length)return!1;for(let a of s){if(!Object.prototype.hasOwnProperty.call(i,a))return!1;if(!He(n[a],i[a]))return!1}return!0}return!1}function k(n){return Boolean(n&&typeof n==="object"&&!Array.isArray(n))}async function xi(n,i){if(!Gr(n))return null;try{let s=await import(n),o=s.default||s;if(typeof o!=="object"||o===null||Array.isArray(o))return null;try{return zt(i,o)}catch{return null}}catch{return null}}async function Si({name:n="",cwd:i,defaultConfig:s}){let o=i||Rt.cwd(),a=[".ts",".js",".mjs",".cjs",".json"],c=[`${n}.config`,`.${n}.config`,n,`.${n}`];for(let l of c)for(let u of a){let f=qe(o,`${l}${u}`),g=await xi(f,s);if(g!==null)return g}try{let l=qe(o,"package.json");if(Gr(l)){let f=(await import(l))[n];if(f&&typeof f==="object"&&!Array.isArray(f))try{return zt(s,f)}catch{}}}catch{}return s}function Ti(n,i={}){let s=Ge.cwd();while(s.includes("storage"))s=or(s,"..");let o=or(s,n||"");if(i?.relative)return Bn(Ge.cwd(),o);return o}async function ki(){try{let n=await Si({name:"clarity",defaultConfig:Ke,cwd:Ge.cwd(),endpoint:"",headers:{}});return{...Ke,...n}}catch{return Ke}}function F(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ai(){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 n=X.type;if(n==="renderer"||n==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class Yr{async format(n){let i=await Ai(),s=await this.getMetadata(i);return JSON.stringify({timestamp:n.timestamp.toISOString(),level:n.level,name:n.name,message:n.message,metadata:s})}async getMetadata(n){if(n){let{hostname:i}=await import("os");return{pid:ue.pid,hostname:i(),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(n,i={}){this.name=n,this.config={...Pt},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Yr,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let s={...i},o=i.timestamp!==void 0;if(o)delete s.timestamp;if(this.config={...this.config,...s,timestamp:o||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let a=this.generateKeyId(),c=this.generateKey();this.currentKeyId=a,this.keys.set(a,c),this.encryptionKeys.set(a,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(n){if(!n.fingersCrossedEnabled&&n.fingersCrossed)return{...Ve,...n.fingersCrossed};if(!n.fingersCrossedEnabled)return null;if(!n.fingersCrossed)return{...Ve};return{...Ve,...n.fingersCrossed}}normalizeOptions(n){let i={format:"json",level:"info",logDirectory:Pt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},s={...i,...Object.fromEntries(Object.entries(n).filter(([,o])=>o!==void 0))};if(!s.level||!["debug","info","success","warning","error"].includes(s.level))s.level=i.level;return s}async writeToFile(n){let s=(async()=>{let a,c=0,l=3,u=1000;while(c<l)try{try{try{await Wn(this.config.logDirectory,fr.F_OK|fr.W_OK)}catch(g){if(g instanceof Error&&"code"in g)if(g.code==="ENOENT")await zn(this.config.logDirectory,{recursive:!0,mode:493});else if(g.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw g;else throw g}}catch(g){throw console.error("Debug: [writeToFile] Failed to create log directory:",g),g}let f=this.validateEncryptionConfig()?(await this.encrypt(n)).encrypted:re.from(n);try{if(!ut(this.currentLogFile))await gt(this.currentLogFile,"",{mode:420});if(a=lr(this.currentLogFile,"a",420),Vn(a,f,{flag:"a"}),cr(a),a!==void 0)ft(a),a=void 0;if((await le(this.currentLogFile)).size===0){if(await gt(this.currentLogFile,f,{flag:"w",mode:420}),(await le(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(g){let h=g;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let m=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,m);let p=u*2**c;await new Promise((d)=>setTimeout(d,p)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(a!==void 0)try{ft(a)}catch(g){console.error("Debug: [writeToFile] Error closing file descriptor:",g)}}}catch(f){if(c===l-1){let h=f,m=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),f}c++;let g=u*2**(c-1);await new Promise((h)=>setTimeout(h,g))}})();this.pendingOperations.push(s);let o=this.pendingOperations.length-1;try{await s}catch(a){throw console.error("Debug: [writeToFile] Error in operation:",a),a}finally{this.pendingOperations.splice(o,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 n=new Date().toISOString().split("T")[0];return fe(this.config.logDirectory,`${this.name}-${n}.log`)}setupRotation(){if(F())return;if(typeof this.config.rotation==="boolean")return;let n=this.config.rotation,i;switch(n.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let s=typeof i.interval==="number"?i.interval:60,o=Math.max(s,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((a)=>{console.error("Error rotating keys:",a)})},o)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date});let a=Array.from(this.encryptionKeys.entries()).sort(([,u],[,f])=>f.createdAt.getTime()-u.createdAt.getTime()),c=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,c);if(a.length>l)for(let[u]of a.slice(l))this.encryptionKeys.delete(u),this.keys.delete(u)}generateKeyId(){return lt(16).toString("hex")}generateKey(){return lt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let n=this.keys.get(this.currentKeyId);if(!n)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:n,id:this.currentKeyId}}encrypt(n){let{key:i}=this.getCurrentKey(),s=lt(16),o=In("aes-256-gcm",i,s),a=re.concat([o.update(n,"utf8"),o.final()]),c=o.getAuthTag();return{encrypted:re.concat([s,a,c]),iv:s}}async compressData(n){return new Promise((i,s)=>{let o=gr(),a=[];o.on("data",(c)=>a.push(c)),o.on("end",()=>i(re.from(re.concat(a)))),o.on("error",s),o.write(n),o.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let n={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...n,...i}}return n}async rotateLog(){if(F())return;let n=await le(this.currentLogFile).catch(()=>null);if(!n)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&n.size>=i.maxSize){let s=this.currentLogFile,o=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let a=await ke(this.config.logDirectory),c=a.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,g)=>{let h=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(g.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,u=`${s}.${l}`;if(await le(s).catch(()=>null))try{if(await ur(s,u),i.compress)try{let f=`${u}.gz`;await this.compressLogFile(u,f),await Ae(u)}catch(f){console.error("Error compressing rotated file:",f)}if(c.length===0&&!a.some((f)=>f.endsWith(".log.1")))try{let f=`${s}.1`;await gt(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let a=new Date().toISOString().replace(/[:.]/g,"-"),c=s.replace(/\.log$/,`-${a}.log`);if(await le(s).catch(()=>null))await ur(s,c)}if(this.currentLogFile=o,i.maxFiles){let c=(await ke(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,u)=>u.localeCompare(l));for(let l of c.slice(i.maxFiles))await Ae(fe(this.config.logDirectory,l))}}}async compressLogFile(n,i){let s=ar(n),o=Kn(i),a=gr();await Un(s,a,o)}async handleFingersCrossedBuffer(n,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(n)&&!this.isActivated){this.isActivated=!0;for(let s of this.logBuffer){let o=await this.formatter.format(s);await this.writeToFile(o),console.log(o)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let s={timestamp:new Date,level:n,message:i,name:this.name};this.logBuffer.push(s)}}shouldActivateFingersCrossed(n){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(n)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(n){return{debug:0,info:1,success:2,warning:3,error:4}[n]}shouldLog(n){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[n]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((n)=>{if(n instanceof Promise)return n.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),ut(this.currentLogFile))try{let n=lr(this.currentLogFile,"r+");cr(n),ft(n)}catch(n){console.error(`Error flushing file: ${n}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let n of this.pendingOperations)if(typeof n.cancel==="function")n.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(n){console.error("Error waiting for pending operations:",n)}if(!F()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await ke(this.config.logDirectory)).filter((s)=>(s.includes("temp")||s.includes(".tmp"))&&s.includes(this.name));for(let s of i)try{await Ae(fe(this.config.logDirectory,s))}catch(o){console.error(`Failed to delete temp file ${s}:`,o)}}catch(n){console.error("Error cleaning up temporary files:",n)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(n){if(!n)return"";return`${this.tagFormat.prefix}${n}${this.tagFormat.suffix}`}formatFileTimestamp(n){return`[${n.toISOString()}]`}formatConsoleTimestamp(n){return this.fancy?T.gray(n.toLocaleTimeString()):n.toLocaleTimeString()}formatConsoleMessage(n){let{timestamp:i,icon:s="",tag:o="",message:a,level:c,showTimestamp:l=!0}=n,u=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(l)d.push(i);if(c==="warning")d.push("WARN");else if(c==="error")d.push("ERROR");else if(s)d.push(s.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(o)d.push(o.replace(/[[\]]/g,""));return d.push(a),d.join(" ")}let f=M.stdout.columns||120,g="";if(c==="warning"||c==="error")g=`${s} ${a}`;else if(c==="info"||c==="success")g=`${s} ${o} ${a}`;else g=`${s} ${o} ${T.cyan(a)}`;if(!l)return g.trim();let h=u(g).trim().length,m=u(i).length,p=Math.max(1,f-2-h-m);return`${g.trim()}${" ".repeat(p)}${i}`}formatMessage(n,i){if(i.length===1&&Array.isArray(i[0]))return n.replace(/\{(\d+)\}/g,(c,l)=>{let u=Number.parseInt(l,10);return u<i[0].length?String(i[0][u]):c});let s=/%([sdijfo%])/g,o=0,a=n.replace(s,(c,l)=>{if(l==="%")return"%";if(o>=i.length)return c;let u=i[o++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}});if(o<i.length)a+=` ${i.slice(o).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return a}async log(n,i,...s){let o=new Date,a=this.formatConsoleTimestamp(o),c=this.formatFileTimestamp(o),l,u;if(i instanceof Error)l=i.message,u=i.stack;else l=this.formatMessage(i,s);if(this.fancy&&!F()){let g=on[n],h=this.options.showTags!==!1&&this.name?T.gray(this.formatTag(this.name)):"",m;switch(n){case"debug":m=this.formatConsoleMessage({timestamp:a,icon:g,tag:h,message:T.gray(l),level:n}),console.error(m);break;case"info":m=this.formatConsoleMessage({timestamp:a,icon:g,tag:h,message:l,level:n}),console.error(m);break;case"success":m=this.formatConsoleMessage({timestamp:a,icon:g,tag:h,message:T.green(l),level:n}),console.error(m);break;case"warning":m=this.formatConsoleMessage({timestamp:a,icon:g,tag:h,message:l,level:n}),console.warn(m);break;case"error":if(m=this.formatConsoleMessage({timestamp:a,icon:g,tag:h,message:l,level:n}),console.error(m),u){let p=u.split(`
|
|
3
|
+
`);for(let d of p)if(d.trim()&&!d.includes(l))console.error(this.formatConsoleMessage({timestamp:a,message:T.gray(` ${d}`),level:n,showTimestamp:!1}))}break}}else if(!F()){if(console.error(`${c} ${this.environment}.${n.toUpperCase()}: ${l}`),u)console.error(u)}if(!this.shouldLog(n))return;let f=`${c} ${this.environment}.${n.toUpperCase()}: ${l}
|
|
4
|
+
`;if(u)f+=`${u}
|
|
5
|
+
`;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time(n){let i=performance.now();if(this.fancy&&!F()){let s=this.options.showTags!==!1&&this.name?T.gray(this.formatTag(this.name)):"",o=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:o,icon:T.blue("\u25D0"),tag:s,message:`${T.cyan(n)}...`}))}return async(s)=>{if(!this.enabled)return;let o=performance.now(),a=Math.round(o-i),c=`${n} completed in ${a}ms`,l=new Date,u=this.formatConsoleTimestamp(l),g=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(s)g+=` ${JSON.stringify(s)}`;if(g+=`
|
|
6
|
+
`,g=g.replace(this.ANSI_PATTERN,""),this.fancy&&!F()){let h=this.options.showTags!==!1&&this.name?T.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:u,icon:T.green("\u2713"),tag:h,message:`${c}${s?` ${JSON.stringify(s)}`:""}`}))}else if(!F())console.error(g.trim());await this.writeToFile(g)}}async debug(n,...i){await this.log("debug",n,...i)}async info(n,...i){await this.log("info",n,...i)}async success(n,...i){await this.log("success",n,...i)}async warn(n,...i){await this.log("warning",n,...i)}async error(n,...i){await this.log("error",n,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let n=this.config.rotation,{encrypt:i}=n;return!!i}async only(n){if(!this.enabled)return;return await n()}isEnabled(){return this.enabled}setEnabled(n){this.enabled=n}extend(n){let i=`${this.name}:${n}`,s=new Ze(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(s),s}createReadStream(){if(F())throw Error("createReadStream is not supported in browser environments");if(!ut(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ar(this.currentLogFile,{encoding:"utf8"})}async decrypt(n){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let s=this.keys.get(this.currentKeyId);try{let o=re.isBuffer(n)?n:re.from(n,"base64"),a=o.slice(0,16),c=o.slice(-16),l=o.slice(16,-16),u=_n("aes-256-gcm",s,a);return u.setAuthTag(c),re.concat([u.update(l),u.final()]).toString("utf8")}catch(o){throw Error(`Decryption failed: ${o instanceof Error?o.message:String(o)}`)}}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(n,i){this.currentKeyId=n,this.keys.set(n,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(n){if(!this.enabled)return;let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i);if(this.fancy&&!F()){let c=n.split(`
|
|
7
|
+
`),l=Math.max(...c.map((h)=>h.length))+2,u=`\u250C${"\u2500".repeat(l)}\u2510`,f=`\u2514${"\u2500".repeat(l)}\u2518`,g=c.map((h)=>{let m=" ".repeat(l-h.length-2);return`\u2502 ${h}${m} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:s,message:T.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:s,message:T.cyan(u)})),g.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:s,message:T.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:s,message:T.cyan(f),showTimestamp:!1}))}else if(!F())console.error(`${o} ${this.environment}.INFO: [BOX] ${n}`);let a=`${o} ${this.environment}.INFO: [BOX] ${n}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(a)}async prompt(n){if(F())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${T.cyan("?")} ${n} (y/n) `);let s=(o)=>{let a=o.toString().trim().toLowerCase();M.stdin.removeListener("data",s);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),i(a==="y"||a==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",s)})}setFancy(n){this.fancy=n}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(n,...i){if(!this.enabled)return;let s=n;if(i&&i.length>0){let l=/%([sdijfo%])/g,u=0;if(s=n.replace(l,(f,g)=>{if(g==="%")return"%";if(u>=i.length)return f;let h=i[u++];switch(g){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),u<i.length)s+=` ${i.slice(u).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!F()){let l=this.options.showTags!==!1&&this.name?T.gray(this.formatTag(this.name)):"",u=T.blue("\u25D0");console.error(`${u} ${l} ${T.cyan(s)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
|
|
9
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(c)}progress(n,i=""){if(!this.enabled||!this.fancy||F()||n<=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 s=20;return this.activeProgressBar={total:n,current:0,message:i,barLength:s,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(l,u)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||F())return;if(this.activeProgressBar.current=Math.max(0,Math.min(n,l)),u!==void 0)this.activeProgressBar.message=u;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||F())return;if(this.activeProgressBar.current=this.activeProgressBar.total,l!==void 0)this.activeProgressBar.message=l;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(l,u="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||F())return;M.stdout.write(`${"\r".padEnd(M.stdout.columns||80)}\r`),this.log(u,l),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(n,i=!1){if(!this.enabled||!this.fancy||F()||!M.stdout.isTTY)return;let s=Math.min(100,Math.max(0,Math.round(n.current/n.total*100))),o=Math.round(n.barLength*s/100),a=n.barLength-o,c=T.green("\u2501".repeat(o)),l=T.gray("\u2501".repeat(a)),u=`[${c}${l}]`,f=`${s}%`.padStart(4),g=n.message?` ${n.message}`:"",h=i||s===100?T.green("\u2713"):T.blue("\u25B6"),m=this.options.showTags!==!1&&this.name?` ${T.gray(this.formatTag(this.name))}`:"",p=`\r${h}${m} ${u} ${f}${g}`,d=M.stdout.columns||80,v=" ".repeat(Math.max(0,d-p.replace(this.ANSI_PATTERN,"").length));if(n.lastRenderedLine=`${p}${v}`,M.stdout.write(n.lastRenderedLine),i)M.stdout.write(`
|
|
10
|
+
`)}finishProgressBar(n,i){if(!this.enabled||!this.fancy||F()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(n.current<n.total)n.current=n.total;if(i)n.message=i;this.renderProgressBar(n,!0),this.activeProgressBar=null}async clear(n={}){if(F()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await ke(this.config.logDirectory),s=[];for(let o of i){if(!(n.name?new RegExp(n.name.replace("*",".*")).test(o):o.startsWith(this.name))||!o.endsWith(".log"))continue;let c=fe(this.config.logDirectory,o);if(n.before)try{if((await le(c)).mtime>=n.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}s.push(c)}if(s.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${s.length} log file(s)...`);for(let o of s)try{await Ae(o),console.warn(`Deleted log file: ${o}`)}catch(a){console.error(`Failed to delete log file ${o}:`,a)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function _e(n,i){if(Array.isArray(i)&&Array.isArray(n)&&i.length===2&&n.length===2&&S(i[0])&&"id"in i[0]&&i[0].id===3&&S(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(S(i)&&S(n)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return n;if(Array.isArray(i)&&!Array.isArray(n))return i;if(Array.isArray(i)&&Array.isArray(n)){if(S(n)&&"arr"in n&&Array.isArray(n.arr)&&S(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&n.length>0&&S(i[0])&&S(n[0])){let o=[...i];for(let a of n)if(S(a)&&"name"in a){if(!o.find((l)=>S(l)&&("name"in l)&&l.name===a.name))o.push(a)}else if(S(a)&&"path"in a){if(!o.find((l)=>S(l)&&("path"in l)&&l.path===a.path))o.push(a)}else if(!o.some((c)=>Xe(c,a)))o.push(a);return o}if(i.every((o)=>typeof o==="string")&&n.every((o)=>typeof o==="string")){let o=[...i];for(let a of n)if(!o.includes(a))o.push(a);return o}return i}if(!S(i)||!S(n))return i;let s={...n};for(let o in i)if(Object.prototype.hasOwnProperty.call(i,o)){let a=i[o];if(a===null||a===void 0)continue;else if(S(a)&&S(s[o]))s[o]=_e(s[o],a);else if(Array.isArray(a)&&Array.isArray(s[o]))if(a.length>0&&s[o].length>0&&S(a[0])&&S(s[o][0])){let c=[...a];for(let l of s[o])if(S(l)&&"name"in l){if(!c.find((f)=>S(f)&&("name"in f)&&f.name===l.name))c.push(l)}else if(S(l)&&"path"in l){if(!c.find((f)=>S(f)&&("path"in f)&&f.path===l.path))c.push(l)}else if(!c.some((u)=>Xe(u,l)))c.push(l);s[o]=c}else if(a.every((c)=>typeof c==="string")&&s[o].every((c)=>typeof c==="string")){let c=[...a];for(let l of s[o])if(!c.includes(l))c.push(l);s[o]=c}else s[o]=a;else s[o]=a}return s}function Ut(n,i,s="replace"){if(i===null||i===void 0)return n;if(Array.isArray(i))return s==="replace"?i:_e(n,i);if(Array.isArray(n))return s==="replace"?i:_e(n,i);if(!S(i)||!S(n))return i;let o={...n};for(let a of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,a))continue;let c=i[a],l=o[a];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(s==="replace")o[a]=c;else o[a]=_e(l,c);else if(S(c)&&S(l))o[a]=Ut(l,c,s);else o[a]=c}return o}function Xe(n,i){if(n===i)return!0;if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(!Xe(n[s],i[s]))return!1;return!0}if(S(n)&&S(i)){let s=Object.keys(n),o=Object.keys(i);if(s.length!==o.length)return!1;for(let a of s){if(!Object.prototype.hasOwnProperty.call(i,a))return!1;if(!Xe(n[a],i[a]))return!1}return!0}return!1}function S(n){return Boolean(n&&typeof n==="object"&&!Array.isArray(n))}async function Le(n,i,s="replace"){if(!Jr(n))return null;try{let o=await import(n),a=o.default||o;if(typeof a!=="object"||a===null||Array.isArray(a))return null;try{return Ut(i,a,s)}catch{return null}}catch{return null}}function Fi(n,i,s=!1){if(!n)return i;let o=n.toUpperCase().replace(/-/g,"_"),a={...i};function c(l,u=[]){let f={...l};for(let[g,h]of Object.entries(l)){let m=[...u,g],p=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${o}_${m.map(p).join("_")}`,v=`${o}_${m.map((y)=>y.toUpperCase()).join("_")}`;if(s)L.info(`Checking environment variable ${d} for config ${n}.${m.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))f[g]=c(h,m);else{let y=Ee.env[d]||Ee.env[v];if(y!==void 0){if(s)L.info(`Using environment variable ${y?d:v} for config ${n}.${m.join(".")}`);if(typeof h==="number")f[g]=Number(y);else if(typeof h==="boolean")f[g]=y.toLowerCase()==="true";else if(Array.isArray(h))try{let w=JSON.parse(y);if(Array.isArray(w))f[g]=w;else f[g]=y.split(",").map((A)=>A.trim())}catch{f[g]=y.split(",").map((w)=>w.trim())}else f[g]=y}}}return f}return c(a)}async function Ri({name:n="",alias:i,cwd:s,configDir:o,defaultConfig:a,verbose:c=!1,checkEnv:l=!0,arrayStrategy:u="replace"}){let f=l&&typeof a==="object"&&a!==null&&!Array.isArray(a)?Fi(n,a,c):a,g=s||Ee.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)L.info(`Loading configuration for "${n}"${i?` (alias: "${i}")`:""} from ${g}`);let m=[n,`.${n}`].filter(Boolean),p=[`${n}.config`,`.${n}.config`].filter(Boolean),d=i?[i,`.${i}`]:[],v=i?[`${i}.config`,`.${i}.config`]:[],y=Array.from(new Set([g,B(g,"config"),B(g,".config"),o?B(g,o):void 0].filter(Boolean)));for(let w of y){if(c)L.info(`Searching for configuration in: ${w}`);let R=[B(g,"config"),B(g,".config")].concat(o?[B(g,o)]:[]).includes(w)?[...m,...p,...d,...v]:[...p,...m,...v,...d];for(let z of R)for(let _ of h){let U=B(w,`${z}${_}`),Qt=await Le(U,f,u);if(Qt!==null){if(c)L.success(`Configuration loaded from: ${U}`);return Qt}}}if(n){let w=B(ct(),".config",n),A=["config",`${n}.config`];if(i)A.push(`${i}.config`);if(c)L.info(`Checking user config directory: ${w}`);for(let R of A)for(let z of h){let _=B(w,`${R}${z}`),U=await Le(_,f,u);if(U!==null){if(c)L.success(`Configuration loaded from user config directory: ${_}`);return U}}}if(n){let w=B(ct(),".config"),A=[`.${n}.config`];if(i)A.push(`.${i}.config`);if(c)L.info(`Checking user config directory for dotfile configs: ${w}`);for(let R of A)for(let z of h){let _=B(w,`${R}${z}`),U=await Le(_,f,u);if(U!==null){if(c)L.success(`Configuration loaded from user config directory dotfile: ${_}`);return U}}}if(n){let w=ct(),A=[`.${n}.config`,`.${n}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(c)L.info(`Checking user home directory for dotfile configs: ${w}`);for(let R of A)for(let z of h){let _=B(w,`${R}${z}`),U=await Le(_,f,u);if(U!==null){if(c)L.success(`Configuration loaded from user home directory: ${_}`);return U}}}try{let w=B(g,"package.json");if(Jr(w)){let A=await import(w),R=A[n];if(!R&&i){if(R=A[i],R&&c)L.success(`Using alias "${i}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(c)L.success(`Configuration loaded from package.json: ${R===A[n]?n:i}`);return Ut(f,R,u)}catch(z){if(c)L.warn("Failed to merge package.json config:",z)}}}catch(w){if(c)L.warn("Failed to load package.json:",w)}if(c)L.info(`No configuration found for "${n}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return f}function Oi(n,i={}){let s=Je.cwd();while(s.includes("storage"))s=sr(s,"..");let o=sr(s,n||"");if(i?.relative)return jn(Je.cwd(),o);return o}async function Pi(){try{let n=await Ri({name:"clarity",alias:"logging",defaultConfig:We,cwd:Je.cwd()});return{...We,...n||{}}}catch{return We}}function O(){if(Q.env.NODE_ENV==="test"||Q.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ni(){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 n=Q.type;if(n==="renderer"||n==="worker")return!1;return!!(Q.versions&&(Q.versions.node||Q.versions.bun))}return!1}class Hr{async format(n){let i=await Ni(),s=await this.getMetadata(i);return JSON.stringify({timestamp:n.timestamp.toISOString(),level:n.level,name:n.name,message:n.message,metadata:s})}async getMetadata(n){if(n){let{hostname:i}=await import("os");return{pid:me.pid,hostname:i(),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(n,i={}){this.name=n,this.config={...Nt},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Hr,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??E.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let s={...i},o=i.timestamp!==void 0;if(o)delete s.timestamp;if(this.config={...this.config,...s,timestamp:o||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let a=this.generateKeyId(),c=this.generateKey();this.currentKeyId=a,this.keys.set(a,c),this.encryptionKeys.set(a,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(n){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},s=this.fingersCrossedConfig.activationLevel??"error";return i[n]>=i[s]}initializeFingersCrossedConfig(n){if(!n.fingersCrossedEnabled&&n.fingersCrossed)return{...ze,...n.fingersCrossed};if(!n.fingersCrossedEnabled)return null;if(!n.fingersCrossed)return{...ze};return{...ze,...n.fingersCrossed}}normalizeOptions(n){let i={format:"json",level:"info",logDirectory:Nt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},s={...i,...Object.fromEntries(Object.entries(n).filter(([,o])=>o!==void 0))};if(!s.level||!["debug","info","success","warning","error"].includes(s.level))s.level=i.level;return s}shouldWriteToFile(){return!O()&&this.config.writeToFile===!0}async writeToFile(n){let s=(async()=>{let a,c=0,l=3,u=1000;while(c<l)try{try{try{await Hn(this.config.logDirectory,pr.F_OK|pr.W_OK)}catch(g){if(g instanceof Error&&"code"in g)if(g.code==="ENOENT")await Zn(this.config.logDirectory,{recursive:!0,mode:493});else if(g.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw g;else throw g}}catch(g){throw console.error("Debug: [writeToFile] Failed to create log directory:",g),g}let f=this.validateEncryptionConfig()?(await this.encrypt(n)).encrypted:H.from(n);try{if(!Fe(this.currentLogFile))await dt(this.currentLogFile,"",{mode:420});if(a=dr(this.currentLogFile,"a",420),Yn(a,f,{flag:"a"}),mr(a),a!==void 0)mt(a),a=void 0;if((await ge(this.currentLogFile)).size===0){if(await dt(this.currentLogFile,f,{flag:"w",mode:420}),(await ge(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(g){let h=g;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let m=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,m);let p=u*2**c;await new Promise((d)=>setTimeout(d,p)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(a!==void 0)try{mt(a)}catch(g){console.error("Debug: [writeToFile] Error closing file descriptor:",g)}}}catch(f){if(c===l-1){let h=f,m=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),f}c++;let g=u*2**(c-1);await new Promise((h)=>setTimeout(h,g))}})();this.pendingOperations.push(s);let o=this.pendingOperations.length-1;try{await s}catch(a){throw console.error("Debug: [writeToFile] Error in operation:",a),a}finally{this.pendingOperations.splice(o,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 n=new Date().toISOString().split("T")[0];return he(this.config.logDirectory,`${this.name}-${n}.log`)}setupRotation(){if(O())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let n=this.config.rotation,i;switch(n.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let s=typeof i.interval==="number"?i.interval:60,o=Math.max(s,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((a)=>{console.error("Error rotating keys:",a)})},o)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date});let a=Array.from(this.encryptionKeys.entries()).sort(([,u],[,f])=>f.createdAt.getTime()-u.createdAt.getTime()),c=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,c);if(a.length>l)for(let[u]of a.slice(l))this.encryptionKeys.delete(u),this.keys.delete(u)}generateKeyId(){return ht(16).toString("hex")}generateKey(){return ht(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let n=this.keys.get(this.currentKeyId);if(!n)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:n,id:this.currentKeyId}}encrypt(n){let{key:i}=this.getCurrentKey(),s=ht(16),o=Jn("aes-256-gcm",i,s),a=H.isBuffer(n)?n:H.from(n,"utf8"),c=o.update(a),l=o.final(),u=c.length+l.length,f=o.getAuthTag(),g=H.allocUnsafe(16+u+16);return s.copy(g,0),c.copy(g,16),l.copy(g,16+c.length),f.copy(g,16+u),{encrypted:g,iv:s}}async compressData(n){return new Promise((i,s)=>{let o=wr(),a=[];o.on("data",(c)=>a.push(c)),o.on("end",()=>i(H.from(H.concat(a)))),o.on("error",s),o.write(n),o.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let n={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...n,...i}}return n}async rotateLog(){if(O())return;if(!this.shouldWriteToFile())return;let n=await ge(this.currentLogFile).catch(()=>null);if(!n)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&n.size>=i.maxSize){let s=this.currentLogFile,o=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let a=await Re(this.config.logDirectory),c=a.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,g)=>{let h=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(g.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,u=`${s}.${l}`;if(await ge(s).catch(()=>null))try{if(await yr(s,u),i.compress)try{let f=`${u}.gz`;await this.compressLogFile(u,f),await Oe(u)}catch(f){console.error("Error compressing rotated file:",f)}if(c.length===0&&!a.some((f)=>f.endsWith(".log.1")))try{let f=`${s}.1`;await dt(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let a=new Date().toISOString().replace(/[:.]/g,"-"),c=s.replace(/\.log$/,`-${a}.log`);if(await ge(s).catch(()=>null))await yr(s,c)}if(this.currentLogFile=o,i.maxFiles){let c=(await Re(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,u)=>u.localeCompare(l));for(let l of c.slice(i.maxFiles))await Oe(he(this.config.logDirectory,l))}}}async compressLogFile(n,i){let s=hr(n),o=qn(i),a=wr();await ei(s,a,o)}async handleFingersCrossedBuffer(n,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(n)&&!this.isActivated){this.isActivated=!0;for(let s of this.logBuffer){let o=await this.formatter.format(s);if(this.shouldWriteToFile())await this.writeToFile(o);console.log(o)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(n){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[n]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((n)=>{if(n instanceof Promise)return n.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Fe(this.currentLogFile))try{let n=dr(this.currentLogFile,"r+");mr(n),mt(n)}catch(n){console.error(`Error flushing file: ${n}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let n of this.pendingOperations)if(typeof n.cancel==="function")n.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(n){console.error("Error waiting for pending operations:",n)}if(!O()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Re(this.config.logDirectory)).filter((s)=>(s.includes("temp")||s.includes(".tmp"))&&s.includes(this.name));for(let s of i)try{await Oe(he(this.config.logDirectory,s))}catch(o){console.error(`Failed to delete temp file ${s}:`,o)}}catch(n){console.error("Error cleaning up temporary files:",n)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(n){if(!n)return"";return`${this.tagFormat.prefix}${n}${this.tagFormat.suffix}`}formatFileTimestamp(n){return`[${n.toISOString()}]`}formatConsoleTimestamp(n){return this.shouldStyleConsole()?C.gray(n.toLocaleTimeString()):n.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||O())return!1;let n=typeof E.env.NO_COLOR<"u",i=E.env.FORCE_COLOR==="0";if(n||i)return!1;return!!(typeof E.stderr<"u"&&E.stderr.isTTY||typeof E.stdout<"u"&&E.stdout.isTTY)}formatConsoleMessage(n){let{timestamp:i,icon:s="",tag:o="",message:a,level:c,showTimestamp:l=!0}=n,u=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(l)d.push(i);if(c==="warning")d.push("WARN");else if(c==="error")d.push("ERROR");else if(s)d.push(s.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(o)d.push(o.replace(/[[\]]/g,""));return d.push(a),d.join(" ")}let f=E.stdout.columns||120,g="";if(c==="warning"||c==="error")g=`${s} ${a}`;else if(c==="info"||c==="success")g=`${s} ${o} ${a}`;else g=`${s} ${o} ${C.cyan(a)}`;if(!l)return g.trim();let h=u(g).trim().length,m=u(i).length,p=Math.max(1,f-2-h-m);return`${g.trim()}${" ".repeat(p)}${i}`}formatMessage(n,i){if(i.length===1&&Array.isArray(i[0]))return n.replace(/\{(\d+)\}/g,(c,l)=>{let u=Number.parseInt(l,10);return u<i[0].length?String(i[0][u]):c});let s=/%([sdijfo%])/g,o=0,a=n.replace(s,(c,l)=>{if(l==="%")return"%";if(o>=i.length)return c;let u=i[o++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}});if(o<i.length)a+=` ${i.slice(o).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return a}formatMarkdown(n){if(!n)return n;let i=n;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(s,o,a)=>{let c=C.underline(C.blue(o)),l=this.toAbsoluteFilePath(a);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let u=`file://${encodeURI(l)}`,f="\x1B]8;;",g="\x1B\\";return`\x1B]8;;${u}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${a}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),i=i.replace(/`([^`]+)`/g,(s,o)=>C.bgGray(o)),i=i.replace(/\*\*([^*]+)\*\*/g,(s,o)=>C.bold(o)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(s,o)=>C.italic(o)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(s,o)=>C.italic(o)),i=i.replace(/~([^~]+)~/g,(s,o)=>C.strikethrough(o)),i}supportsHyperlinks(){if(O())return!1;let n=E.env;if(!n)return!1;if(n.TERM_PROGRAM==="iTerm.app"||n.TERM_PROGRAM==="vscode"||n.TERM_PROGRAM==="WezTerm")return!0;if(n.WT_SESSION)return!0;if(n.TERM==="xterm-kitty")return!0;let i=n.VTE_VERSION?Number.parseInt(n.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(n){try{let i=n;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let s=E.env.HOME||"";if(s)i=i.replace(/^~(?=$|\/)/,s)}if(Xn(i)||i.startsWith("./")||i.startsWith("../"))i=Qn(i);else return null;return Fe(i)?i:null}catch{return null}}buildOutputTexts(n){let i=this.shouldStyleConsole()?this.formatMarkdown(n):n,s=n.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:s}}async log(n,i,...s){let o=new Date,a=this.formatConsoleTimestamp(o),c=this.formatFileTimestamp(o),l,u;if(i instanceof Error)l=i.message,u=i.stack;else l=this.formatMessage(i,s);let{consoleText:f,fileText:g}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":an[n],p=this.options.showTags!==!1&&this.name?C.gray(this.formatTag(this.name)):"",d;switch(n){case"debug":d=this.formatConsoleMessage({timestamp:a,icon:m,tag:p,message:C.gray(f),level:n}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:a,icon:m,tag:p,message:f,level:n}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:a,icon:m,tag:p,message:C.green(f),level:n}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:a,icon:m,tag:p,message:f,level:n}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:a,icon:m,tag:p,message:f,level:n}),console.error(d),u){let v=u.split(`
|
|
11
|
+
`);for(let y of v)if(y.trim()&&!y.includes(l))console.error(this.formatConsoleMessage({timestamp:a,message:C.gray(` ${y}`),level:n,showTimestamp:!1}))}break}}else if(!O()){if(console.error(`${c} ${this.environment}.${n.toUpperCase()}: ${l}`),u)console.error(u)}if(!this.shouldLog(n))return;let h=`${c} ${this.environment}.${n.toUpperCase()}: ${g}
|
|
12
|
+
`;if(u)h+=`${u}
|
|
13
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(n,i=""){let s={update:(u,f)=>{},finish:(u)=>{},interrupt:(u,f)=>{}};if(!this.enabled)return s;let o=30;if(this.activeProgressBar={total:Math.max(1,n||1),current:0,message:i||"",barLength:o,lastRenderedLine:""},this.shouldStyleConsole()&&!O()&&E.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(u,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,u),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!O()&&E.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(u)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,u)},interrupt:(u,f="info")=>{if(!O()&&E.stdout.isTTY)E.stdout.write(`
|
|
14
|
+
`);if(this[f==="warning"?"warn":f](u),this.activeProgressBar&&this.shouldStyleConsole()&&!O()&&E.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(n){let i=performance.now();if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?C.gray(this.formatTag(this.name)):"",o=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":C.blue("\u25D0"),tag:s,message:`${C.cyan(n)}...`}))}return async(s)=>{if(!this.enabled)return;let o=performance.now(),a=Math.round(o-i),c=`${n} completed in ${a}ms`,l=new Date,u=this.formatConsoleTimestamp(l),g=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(s)g+=` ${JSON.stringify(s)}`;if(g+=`
|
|
15
|
+
`,g=g.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?C.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:u,icon:this.options.showIcons===!1?"":C.green("\u2713"),tag:h,message:`${c}${s?` ${JSON.stringify(s)}`:""}`}))}else if(!O())console.error(g.trim());if(this.shouldWriteToFile())await this.writeToFile(g)}}async debug(n,...i){await this.log("debug",n,...i)}async info(n,...i){await this.log("info",n,...i)}async success(n,...i){await this.log("success",n,...i)}async warn(n,...i){await this.log("warning",n,...i)}async error(n,...i){await this.log("error",n,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let n=this.config.rotation,{encrypt:i}=n;return!!i}async only(n){if(!this.enabled)return;return await n()}isEnabled(){return this.enabled}setEnabled(n){this.enabled=n}extend(n){let i=`${this.name}:${n}`,s=new Qe(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(s),s}createReadStream(){if(O())throw Error("createReadStream is not supported in browser environments");if(!Fe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return hr(this.currentLogFile,{encoding:"utf8"})}async decrypt(n){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let s=this.keys.get(this.currentKeyId);try{let o=H.isBuffer(n)?n:H.from(n,"base64"),a=o.subarray(0,16),c=o.subarray(o.length-16),l=o.subarray(16,o.length-16),u=Gn("aes-256-gcm",s,a);u.setAuthTag(c);let f=u.update(l),g=u.final(),h=f.length+g.length,m=H.allocUnsafe(h);return f.copy(m,0),g.copy(m,f.length),m.toString("utf8")}catch(o){throw Error(`Decryption failed: ${o instanceof Error?o.message:String(o)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return O()}isServerMode(){return!O()}setTestEncryptionKey(n,i){this.currentKeyId=n,this.keys.set(n,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(n){if(!this.enabled)return;let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),{consoleText:a,fileText:c}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let u=a.split(`
|
|
16
|
+
`),f=Math.max(...u.map((p)=>p.length))+2,g=`\u250C${"\u2500".repeat(f)}\u2510`,h=`\u2514${"\u2500".repeat(f)}\u2518`,m=u.map((p)=>this.formatConsoleMessage({timestamp:s,message:C.cyan(p),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:s,message:C.cyan(g),showTimestamp:!1})),m.forEach((p)=>console.error(p)),console.error(this.formatConsoleMessage({timestamp:s,message:C.cyan(h),showTimestamp:!1}))}else if(!O())console.error(`${o} ${this.environment}.INFO: [BOX] ${c}`);let l=`${o} ${this.environment}.INFO: [BOX] ${c}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(n){if(O())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${C.cyan("?")} ${n} (y/n) `);let s=(o)=>{let a=o.toString().trim().toLowerCase();E.stdin.removeListener("data",s);try{if(typeof E.stdin.setRawMode==="function")E.stdin.setRawMode(!1)}catch{}E.stdin.pause(),console.error(""),i(a==="y"||a==="yes")};try{if(typeof E.stdin.setRawMode==="function")E.stdin.setRawMode(!0)}catch{}E.stdin.resume(),E.stdin.once("data",s)})}setFancy(n){this.fancy=n}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(n,...i){if(!this.enabled)return;let s=n;if(i&&i.length>0){let f=/%([sdijfo%])/g,g=0;if(s=n.replace(f,(h,m)=>{if(m==="%")return"%";if(g>=i.length)return h;let p=i[g++];switch(m){case"s":return String(p);case"d":case"i":return Number(p).toString();case"j":case"o":return JSON.stringify(p,null,2);default:return h}}),g<i.length)s+=` ${i.slice(g).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:o,fileText:a}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?C.gray(this.formatTag(this.name)):"",g=this.options.showIcons===!1?"":`${C.blue("\u25D0")} `;console.error(`${g}${f} ${C.cyan(o)}`)}let u=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${a}
|
|
18
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(u)}renderProgressBar(n,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!E.stdout.isTTY)return;let s=Math.min(100,Math.max(0,Math.round(n.current/n.total*100))),o=Math.round(n.barLength*s/100),a=n.barLength-o,c=C.green("\u2501".repeat(o)),l=C.gray("\u2501".repeat(a)),u=`[${c}${l}]`,f=`${s}%`.padStart(4),g=n.message?` ${n.message}`:"",h=this.options.showIcons===!1?"":i||s===100?C.green("\u2713"):C.blue("\u25B6"),m=this.options.showTags!==!1&&this.name?` ${C.gray(this.formatTag(this.name))}`:"",p=`\r${h}${m} ${u} ${f}${g}`,d=E.stdout.columns||80,v=" ".repeat(Math.max(0,d-p.replace(this.ANSI_PATTERN,"").length));if(n.lastRenderedLine=`${p}${v}`,E.stdout.write(n.lastRenderedLine),i)E.stdout.write(`
|
|
19
|
+
`)}finishProgressBar(n,i){if(!this.enabled||!this.fancy||O()||!E.stdout.isTTY){this.activeProgressBar=null;return}if(n.current<n.total)n.current=n.total;if(i)n.message=i;this.renderProgressBar(n,!0),this.activeProgressBar=null}async clear(n={}){if(O()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Re(this.config.logDirectory),s=[];for(let o of i){if(!(n.name?new RegExp(n.name.replace("*",".*")).test(o):o.startsWith(this.name))||!o.endsWith(".log"))continue;let c=he(this.config.logDirectory,o);if(n.before)try{if((await ge(c)).mtime>=n.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}s.push(c)}if(s.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${s.length} log file(s)...`);for(let o of s)try{await Oe(o),console.warn(`Deleted log file: ${o}`)}catch(a){console.error(`Failed to delete log file ${o}:`,a)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function Zr(n,i={}){let{maxRetries:s=3,retryDelay:o=1000,isRetryable:a=()=>!0,fallback:c}=i,l=Error("Unknown error occurred");for(let u=0;u<=s;u++)try{return await n()}catch(f){if(l=f instanceof Error?f:Error(String(f)),u===s||!a(l))break;if(o>0)await new Promise((g)=>setTimeout(g,o))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function Xr(n){return n instanceof K}function Di(n){return n instanceof et}function Mi(n){if(Xr(n))return n.code==="FILE_SYSTEM_ERROR"||n.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((s)=>n.message.toLowerCase().includes(s.toLowerCase()))}class st{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(n,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(n.toLowerCase()),parse:(n)=>{let i=n.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(n,i)=>i==="number"||!Number.isNaN(Number(n))&&!Number.isNaN(Number.parseFloat(n)),parse:(n)=>{let i=Number(n);if(Number.isNaN(i))throw TypeError(`Cannot parse "${n}" as number`);return i}},{name:"array",canParse:(n,i)=>i==="array"||n.startsWith("[")||n.includes(","),parse:(n)=>{try{let i=JSON.parse(n);if(Array.isArray(i))return i}catch{}return n.split(",").map((i)=>i.trim())}},{name:"json",canParse:(n,i)=>i==="object"||(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]")),parse:(n)=>{try{return JSON.parse(n)}catch(i){throw Error(`Cannot parse "${n}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(n,i,s={}){let{prefix:o,useCamelCase:a=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:u=!1,trackPerformance:f=!0}=s,g=async()=>{if(!n)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let h=o||this.generateEnvPrefix(n),m={...i};return this.processObject(m,[],h,{useCamelCase:a,useBackwardCompatibility:c,customParsers:l,verbose:u,configName:n}),{config:m,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return Te.track("applyEnvironmentVariables",g,{configName:n});return g()}generateEnvPrefix(n){return n.toUpperCase().replace(/-/g,"_")}formatEnvKey(n,i){if(!i)return n.toUpperCase();return n.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(n,i,s,o){for(let[a,c]of Object.entries(n)){let l=[...i,a],u=l.map((h)=>this.formatEnvKey(h,o.useCamelCase)),f=`${s}_${u.join("_")}`,g=o.useBackwardCompatibility?`${s}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(o.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,s,o);else{let h=Pe.env[f]||(g?Pe.env[g]:void 0);if(h!==void 0){if(o.verbose){let m=Pe.env[f]?f:g}try{n[a]=this.parseEnvironmentValue(h,typeof c,f,o.customParsers,o.configName)}catch(m){if(m instanceof tt)throw m;throw ie.envVar(f,h,typeof c,o.configName)}}}}}parseEnvironmentValue(n,i,s,o,a){for(let[c,l]of Object.entries(o))try{return l(n)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(n,i))try{return c.parse(n)}catch{throw ie.envVar(s,n,`${i} (via ${c.name} parser)`,a)}return n}getEnvironmentVariables(n){let i={},s=n.toUpperCase();for(let[o,a]of Object.entries(Pe.env))if(o.startsWith(s)&&a!==void 0)i[o]=a;return i}validateEnvironmentVariable(n,i,s){let o=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(n))o.push(`Environment variable key "${n}" should only contain uppercase letters, numbers, and underscores`);if(s)try{this.parseEnvironmentValue(n,i,s,{})}catch(a){o.push(`Cannot parse value "${i}" as ${s}: ${a}`)}return{isValid:o.length===0,errors:o}}generateEnvVarDocs(n,i,s={}){let{prefix:o,format:a="text"}=s,c=o||this.generateEnvPrefix(n),l=[];switch(this.extractEnvVarInfo(i,[],c,l),a){case"markdown":return this.formatAsMarkdown(l,n);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,n)}}extractEnvVarInfo(n,i,s,o){for(let[a,c]of Object.entries(n)){let l=[...i,a],u=`${s}_${l.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,s,o);else o.push({key:u,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}generateExample(n){if(Array.isArray(n))return JSON.stringify(n);if(typeof n==="object"&&n!==null)return JSON.stringify(n);return String(n)}formatAsText(n,i){let s=`Environment Variables for ${i}:
|
|
20
|
+
|
|
21
|
+
`;for(let o of n)s+=`${o.key}
|
|
22
|
+
`,s+=` Type: ${o.type}
|
|
23
|
+
`,s+=` Description: ${o.description}
|
|
24
|
+
`,s+=` Example: ${o.example}
|
|
25
|
+
|
|
26
|
+
`;return s}formatAsMarkdown(n,i){let s=`# Environment Variables for ${i}
|
|
27
|
+
|
|
28
|
+
`;s+=`| Variable | Type | Description | Example |
|
|
29
|
+
`,s+=`|----------|------|-------------|----------|
|
|
30
|
+
`;for(let o of n)s+=`| \`${o.key}\` | ${o.type} | ${o.description} | \`${o.example}\` |
|
|
31
|
+
`;return s}}function ji(n,i){let s=nn("process");if(typeof s>"u"||!s.env)return i;let o=s.env[n];return o!==void 0?o:i}function Qr(n,i,s={}){return en(n,i,s,new WeakMap)}function en(n,i,s,o){let{arrayMergeMode:a="replace",skipNullish:c=!1,customMerger:l}=s;if(i===null||i===void 0)return c?n:i;if(l){let u=l(n,i);if(u!==void 0)return u}if(Array.isArray(i)||Array.isArray(n))return tn(n,i,a,o);if(!V(i)||!V(n))return i;return _i(n,i,s,o)}function tn(n,i,s,o){if(Array.isArray(i)&&!Array.isArray(n))return i;if(Array.isArray(n)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(n))switch(s){case"replace":return i;case"concat":return Li(n,i);case"smart":return Bi(n,i,o);default:return i}return i}function Li(n,i){let s=[...i];for(let o of n)if(!s.some((a)=>Ot(a,o)))s.push(o);return s}function Bi(n,i,s){if(i.length===0)return n;if(n.length===0)return i;if(V(i[0])&&V(n[0]))return Ii(n,i,s);if(i.every((o)=>typeof o==="string")&&n.every((o)=>typeof o==="string")){let o=[...i];for(let a of n)if(!o.includes(a))o.push(a);return o}return i}function Ii(n,i,s){let o=[...i];for(let a of n){if(!V(a)){o.push(a);continue}let c=["id","name","key","path","type"],l=!1;for(let u of c)if(u in a){if(o.find((g)=>V(g)&&(u in g)&&g[u]===a[u])){l=!0;break}}if(!l)o.push(a)}return o}function _i(n,i,s,o){let a=i;if(V(a)&&o.has(a))return o.get(a);let c={...n};if(V(a))o.set(a,c);for(let l in a){if(!Object.prototype.hasOwnProperty.call(a,l))continue;let u=a[l],f=c[l];if(s.skipNullish&&(u===null||u===void 0))continue;if(u===null||u===void 0){c[l]=u;continue}if(V(u)&&V(f))c[l]=en(f,u,s,o);else if(Array.isArray(u)||Array.isArray(f))c[l]=tn(f,u,s.arrayMergeMode||"smart",o);else c[l]=u}return c}function Jt(n,i,s="replace"){return Qr(n,i,{arrayMergeMode:s==="replace"?"replace":"smart",skipNullish:!0})}function Ot(n,i){if(n===i)return!0;if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(!Ot(n[s],i[s]))return!1;return!0}if(V(n)&&V(i)){let s=Object.keys(n),o=Object.keys(i);if(s.length!==o.length)return!1;for(let a of s){if(!Object.prototype.hasOwnProperty.call(i,a))return!1;if(!Ot(n[a],i[a]))return!1}return!0}return!1}function V(n){return Boolean(n&&typeof n==="object"&&!Array.isArray(n))}class ot{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(n,i,s={}){let{arrayStrategy:o="replace",useCache:a=!0,cacheTtl:c,trackPerformance:l=!0,verbose:u=!1}=s;if(a){let g=ve.getWithFileCheck("file",n);if(g){if(u)console.log(`Configuration loaded from cache: ${n}`);return g}}let f=async()=>{if(!Ne(n))return null;try{let g=`?t=${Date.now()}`,h=await import(n+g),m=h.default||h,p="default"in h,d=Object.keys(h).length>0;if(!p&&!d)throw new xe(n,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof m!=="object"||m===null||Array.isArray(m))throw new xe(n,Error("Configuration must export a valid object"),"unknown");let w={config:Jt(i,m,o),source:{type:"file",path:n,priority:100,timestamp:new Date}};if(a)ve.setWithFileCheck("file",w,n,c);return w}catch(g){throw g instanceof Error?ie.configLoad(n,g):ie.configLoad(n,Error(String(g)))}};if(l)return Te.track("loadFromPath",f,{path:n});return f()}async tryLoadFromPaths(n,i,s={}){for(let o of n)try{let a=await this.loadFromPath(o,i,s);if(a)return a}catch(a){if(a instanceof Error&&a.name==="ConfigLoadError")throw a;if(s.verbose)console.warn(`Failed to load config from ${o}:`,a)}return null}generateConfigPaths(n,i,s){let o=this.generateNamePatterns(n,s),a=[];for(let c of o)for(let l of this.extensions)a.push(pt(i,`${c}${l}`));return a}generateNamePatterns(n,i){let s=[];if(s.push("config",".config"),n)s.push(n,`.${n}.config`,`${n}.config`,`.${n}`);if(i){if(s.push(i,`.${i}.config`,`${i}.config`,`.${i}`),n)s.push(`${n}.${i}.config`,`.${n}.${i}.config`)}return s.filter(Boolean)}checkFileAccess(n){return Zr(async()=>Ne(n),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(n,i,s){let o=[];if(!Ne(n))return o;if(i||s){let a=this.generateNamePatterns(i||"",s);for(let c of a)for(let l of this.extensions){let u=pt(n,`${c}${l}`);if(await this.checkFileAccess(u))o.push(u)}}else try{let{readdirSync:a}=await import("fs"),c=a(n);for(let l of c)if(this.looksLikeConfigFile(l)){let u=pt(n,l);if(await this.checkFileAccess(u))o.push(u)}}catch{return[]}return o}looksLikeConfigFile(n){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((s)=>s.test(n))}async validateConfigFile(n){let i=[];try{if(!Ne(n))return i.push("Configuration file does not exist"),i;let s=await import(n),o=s.default||s;if(o===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof o!=="object"||o===null)i.push("Configuration must be an object");else if(Array.isArray(o))i.push("Configuration cannot be an array at the root level");if(n.endsWith(".json"))try{let{readFileSync:a}=await import("fs"),c=a(n,"utf8");JSON.parse(c)}catch(a){i.push(`Invalid JSON syntax: ${a}`)}}catch(s){i.push(`Failed to load configuration file: ${s}`)}return i}async getFileModificationTime(n){try{let{statSync:i}=await import("fs");return i(n).mtime}catch{return null}}async preloadConfigurations(n,i={}){let s=new Map;return await Promise.allSettled(n.map(async(o)=>{try{let a=await this.loadFromPath(o,{},i);if(a)s.set(o,a.config)}catch(a){if(i.verbose)console.warn(`Failed to preload ${o}:`,a)}})),s}}class Gt{async validateConfiguration(n,i,s={}){let{stopOnFirstError:o=!1,validateRequired:a=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:u=!0,verbose:f=!1}=s,g=async()=>{let h=[],m=[],p={stopOnFirstError:o,validateRequired:a,validateTypes:c,customRules:l,trackPerformance:u,verbose:f};try{if(typeof i==="string")return await this.validateWithSchemaFile(n,i,p);else if(Array.isArray(i))return this.validateWithRules(n,[...i,...l],p);else return this.validateWithJSONSchema(n,i,p)}catch(d){return h.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:h,warnings:m}}};if(u)return await Te.track("validateConfiguration",g);return g()}async validateWithSchemaFile(n,i,s){try{if(!ti(i))throw new Se(i,[{path:"",message:"Schema file does not exist"}]);let o=await import(i),a=o.default||o;if(Array.isArray(a))return this.validateWithRules(n,a,s);else return this.validateWithJSONSchema(n,a,s)}catch(o){throw new Se(i,[{path:"",message:`Failed to load schema: ${o}`}])}}validateWithJSONSchema(n,i,s){let o=[],a=[];return this.validateObjectAgainstSchema(n,i,"",o,a,s),{isValid:o.length===0,errors:o,warnings:a}}validateObjectAgainstSchema(n,i,s,o,a,c){if(c.validateTypes&&i.type){let l=Array.isArray(n)?"array":typeof n,u=Array.isArray(i.type)?i.type:[i.type];if(!u.includes(l)){if(o.push({path:s,message:`Expected type ${u.join(" or ")}, got ${l}`,expected:u.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(n)){if(o.push({path:s,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:n,rule:"enum"}),c.stopOnFirstError)return}if(typeof n==="string"){if(i.minLength!==void 0&&n.length<i.minLength)o.push({path:s,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:n.length,rule:"minLength"});if(i.maxLength!==void 0&&n.length>i.maxLength)o.push({path:s,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:n.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(n))o.push({path:s,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:n,rule:"pattern"})}}if(typeof n==="number"){if(i.minimum!==void 0&&n<i.minimum)o.push({path:s,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:n,rule:"minimum"});if(i.maximum!==void 0&&n>i.maximum)o.push({path:s,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:n,rule:"maximum"})}if(Array.isArray(n)&&i.items)for(let l=0;l<n.length;l++){let u=s?`${s}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(n[l],i.items,u,o,a,c),c.stopOnFirstError&&o.length>0)return}if(n&&typeof n==="object"&&!Array.isArray(n)){let l=n;if(c.validateRequired&&i.required){for(let u of i.required)if(!(u in l)){if(o.push({path:s?`${s}.${u}`:u,message:`Missing required property '${u}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(i.properties){for(let[u,f]of Object.entries(i.properties))if(u in l){let g=s?`${s}.${u}`:u;if(this.validateObjectAgainstSchema(l[u],f,g,o,a,c),c.stopOnFirstError&&o.length>0)return}}if(i.additionalProperties===!1){let u=new Set(Object.keys(i.properties||{}));for(let f of Object.keys(l))if(!u.has(f))a.push({path:s?`${s}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(n,i,s){let o=[],a=[];for(let c of i)try{let l=this.getValueByPath(n,c.path),u=this.validateWithRule(l,c,c.path);if(o.push(...u),s.stopOnFirstError&&o.length>0)break}catch(l){o.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:o.length===0,errors:o,warnings:a}}validateWithRule(n,i,s){let o=[];if(i.required&&(n===void 0||n===null))return o.push({path:s,message:i.message||`Property '${s}' is required`,expected:"required",rule:"required"}),o;if(n===void 0||n===null)return o;if(i.type){let a=Array.isArray(n)?"array":typeof n;if(a!==i.type)o.push({path:s,message:i.message||`Expected type ${i.type}, got ${a}`,expected:i.type,actual:a,rule:"type"})}if(i.min!==void 0){let a=Array.isArray(n)?n.length:typeof n==="string"?n.length:typeof n==="number"?n:0;if(a<i.min)o.push({path:s,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:a,rule:"min"})}if(i.max!==void 0){let a=Array.isArray(n)?n.length:typeof n==="string"?n.length:typeof n==="number"?n:0;if(a>i.max)o.push({path:s,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:a,rule:"max"})}if(i.pattern&&typeof n==="string"){if(!i.pattern.test(n))o.push({path:s,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:n,rule:"pattern"})}if(i.enum&&!i.enum.includes(n))o.push({path:s,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:n,rule:"enum"});if(i.validator){let a=i.validator(n);if(a)o.push({path:s,message:i.message||a,rule:"custom"})}return o}getValueByPath(n,i){if(!i)return n;let s=i.split("."),o=n;for(let a of s)if(o&&typeof o==="object"&&a in o)o=o[a];else return;return o}generateRulesFromInterface(n){let i=[],s=n.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let o of s){let[,a,c,l]=o;i.push({path:a,required:!c,type:this.mapTypeScriptType(l)})}return i}mapTypeScriptType(n){switch(n.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:ln},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class qt{fileLoader=new ot;envProcessor=new st;validator=new Gt;async loadConfig(n){let i=Date.now(),{cache:s,performance:o,schema:a,validate:c,...l}=n;try{if(s?.enabled){let f=this.checkCache(l.name||"",l);if(f)return f}let u;try{u=await this.loadConfigurationStrategies(l,!0,s)}catch(f){let g=l.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(g)throw f;u={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let h=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),m=!h&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),p=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(g&&(p||h))throw f;if(m&&(!g||!p))u={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!g)u={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else u={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(a||c)await this.validateConfiguration(u.config,a,c,l.name);if(s?.enabled&&u)this.cacheResult(l.name||"",u,s,l);if(o?.enabled){let f={operation:"loadConfig",duration:Date.now()-i,configName:l.name,timestamp:new Date};if(o.onMetrics)o.onMetrics(f);if(o.slowThreshold&&f.duration>o.slowThreshold)J.warn(`Slow configuration loading detected: ${f.duration}ms for ${l.name}`);u.metrics=f}return u}catch(u){let f=Date.now()-i;throw J.error(`Configuration loading failed after ${f}ms:`,[u instanceof Error?u:Error(String(u))]),u}}async loadConfigurationStrategies(n,i=!1,s){let{name:o="",alias:a,cwd:c,configDir:l,defaultConfig:u,checkEnv:f=!0,arrayStrategy:g="replace",verbose:h=!1}=n,m=c||oe.cwd(),p=[],d=await this.loadLocalConfiguration(o,a,m,l,u,g,h,f,s);if(d)return p.push(...this.getLocalSearchPaths(o,a,m,l)),this.finalizeResult(d,p,f,o,h);let v=await this.loadHomeConfiguration(o,a,u,g,h,f);if(v)return p.push(...this.getHomeSearchPaths(o,a)),this.finalizeResult(v,p,f,o,h);let y=await this.loadPackageJsonConfiguration(o,a,m,u,g,h,f);if(y)return p.push(I(m,"package.json")),this.finalizeResult(y,p,f,o,h);if(p.push(...this.getAllSearchPaths(o,a,m,l)),i)throw ie.configNotFound(o,p,a);return{...await this.applyEnvironmentVariables(o,u,f,h),warnings:[`No configuration file found for "${o}"${a?` or alias "${a}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(n,i,s,o,a,c,l,u,f){let g=u?be(n,a,l):a,h=this.getLocalDirectories(s,o);for(let m of h){if(l)J.info(`Searching for configuration in: ${m}`);let p=this.fileLoader.generateConfigPaths(n,m,i),d=await this.fileLoader.tryLoadFromPaths(p,g,{arrayStrategy:c,verbose:l,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(d){if(l)J.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(n,i,s,o,a,c){if(!n)return null;let l=c?be(n,s,a):s,u=[I(ce(),".config",n),I(ce(),".config"),ce()];for(let f of u){if(a)J.info(`Checking home directory: ${f}`);let g=this.fileLoader.generateConfigPaths(n,f,i),h=await this.fileLoader.tryLoadFromPaths(g,l,{arrayStrategy:o,verbose:a});if(h){if(a)J.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(n,i,s,o,a,c,l){let u=l?be(n,o,c):o;try{let f=I(s,"package.json");if(!Ft(f))return null;let g=await import(f),h=g[n],m=n;if(!h&&i)h=g[i],m=i;if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)J.success(`Configuration loaded from package.json: ${m}`);return{config:Jt(u,h,a),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(c)J.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables(n,i,s,o){if(!s||!n||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:be(n,i,o),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(n,i,s,o,a){return{config:n.config,source:n.source,path:n.source.path}}async validateConfiguration(n,i,s,o){let a=[];if(s){let c=s(n);if(c)a.push(...c)}if(i){let c=await this.validator.validateConfiguration(n,i);if(!c.isValid)a.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(a.length>0)throw ie.configValidation(o||"unknown",a,o)}checkCache(n,i){let s=this.generateCacheKey(n,i);return ve.get(s)||null}cacheResult(n,i,s,o){let a=this.generateCacheKey(n,o);ve.set(a,i,void 0,s.ttl)}generateCacheKey(n,i){let s=[n];if(i.alias)s.push(`alias:${i.alias}`);if(i.cwd)s.push(`cwd:${i.cwd}`);if(i.configDir)s.push(`configDir:${i.configDir}`);if("checkEnv"in i)s.push(`checkEnv:${i.checkEnv}`);return s.join("|")}getLocalDirectories(n,i){return Array.from(new Set([n,I(n,"config"),I(n,".config"),i?I(n,i):void 0].filter(Boolean)))}getAllSearchPaths(n,i,s,o){let a=[];return a.push(...this.getLocalSearchPaths(n,i,s,o)),a.push(...this.getHomeSearchPaths(n,i)),a.push(I(s,"package.json")),a}getLocalSearchPaths(n,i,s,o){let a=this.getLocalDirectories(s,o),c=[];for(let l of a)c.push(...this.fileLoader.generateConfigPaths(n,l,i));return c}getHomeSearchPaths(n,i){if(!n)return[];let s=[I(ce(),".config",n),I(ce(),".config"),ce()],o=[];for(let a of s)o.push(...this.fileLoader.generateConfigPaths(n,a,i));return o}async loadConfigWithResult(n){return this.loadConfig(n)}}function kr(n){let s=!(n.message.includes("EACCES")||n.message.includes("EPERM")||n.message.includes("permission denied"))&&(n.message.includes("syntax")||n.message.includes("Expected")||n.message.includes("Unexpected")||n.message.includes("BuildMessage")),o=n.message.includes("Configuration must export a valid object")||n.message.includes("Configuration file is empty and exports nothing");return s||o}async function Ki(n){return te.loadConfig({...n,__strictErrorHandling:!0})}async function rn(n){let i="defaultConfig"in n&&n.defaultConfig!==void 0?n.defaultConfig:{},s="cache"in n||"performance"in n||"schema"in n||"validate"in n;try{let o;if(s)o=await te.loadConfig(n);else o=await te.loadConfig({...n,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return o?.config??i}catch(o){let a=o instanceof Error?o.name:"UnknownError",c=o instanceof Error?o.message:String(o);if(!(a==="ConfigNotFoundError"||a==="ConfigLoadError"||a==="ConfigValidationError"||c.includes("config"))&&n.verbose)J.warn("Unexpected error loading config, using defaults:",[o instanceof Error?o:Error(String(o))]);let u=s?{...n,defaultConfig:i}:{...n,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in n?n.checkEnv!==!1:!0)return(await te.applyEnvironmentVariables(u.name||"",i,!0,u.verbose||!1))?.config??i;return i}}async function Vi(n={defaultConfig:{}}){if(typeof n==="string"){let{cwd:i}=await import("process");try{return(await te.loadConfig({name:n,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(s){if(s instanceof Error&&(s.name==="ConfigNotFoundError"||s.name==="ConfigLoadError"&&kr(s)))return(await te.applyEnvironmentVariables(n,{},!0,!1)).config;throw s}}try{return(await te.loadConfig({...n,cwd:n.cwd||oe.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&kr(i)))return(await te.applyEnvironmentVariables(n.name||"",n.defaultConfig||{},n.checkEnv!==!1,n.verbose||!1)).config;throw i}}async function Wi(n,i,s="replace"){let o=new ot;try{let a=await o.loadFromPath(n,i,{arrayStrategy:s,useCache:!1,trackPerformance:!1});return a?a.config:null}catch{return null}}function be(n,i,s=!1){let o=new st,a=n.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,u=[]){let f={...l};for(let[g,h]of Object.entries(l)){let m=[...u,g],p=[`${a}_${m.join("_").toUpperCase()}`,`${a}_${m.map((y)=>y.toUpperCase()).join("")}`,`${a}_${m.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,v;for(let y of p)if(d=oe.env[y],d!==void 0){v=y;break}if(d!==void 0&&v)if(typeof h==="boolean")f[g]=["true","1","yes"].includes(d.toLowerCase());else if(typeof h==="number"){let y=Number(d);if(!Number.isNaN(y))f[g]=y}else if(Array.isArray(h))try{f[g]=JSON.parse(d)}catch{f[g]=d.split(",").map((y)=>y.trim())}else f[g]=d;else if(h&&typeof h==="object"&&!Array.isArray(h))f[g]=c(h,m)}return f}return c(i)}function zi(n){let i=I(oe.cwd(),n.configDir),s=I(oe.cwd(),n.generatedDir),o=I(s,"config-types.ts");if(!Ft(ir(o)))Pn(ir(o),{recursive:!0,mode:511});let a=Ft(i)?Nn(i).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${vs}
|
|
32
|
+
export type ConfigNames = ${a.length?`'${a.join("' | '")}'`:"string"}
|
|
33
|
+
`;Dn(o,c,{mode:438})}function Ui(n){let i=null,s=null,o=()=>{if(!s)s=rn(n).then((c)=>(i=c,c),(c)=>{let l="defaultConfig"in n?n.defaultConfig:{};if(i=l,"verbose"in n&&n.verbose)J.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return s},a="defaultConfig"in n?n.defaultConfig:{};return i=a,o(),new Proxy({},{get(c,l){if(i)return i[l];let u=a[l];return o(),u},has(c,l){return l in(i||a)},ownKeys(){return Object.keys(i||a)},getOwnPropertyDescriptor(c,l){return Object.getOwnPropertyDescriptor(i||a,l)},set(c,l,u){if(!i)i={...a};return i[l]=u,!0}})}function Ji(n){let i=vr(ii.cwd(),n?.configDir||"./config");function s(){if(!ri(i))return[];let a=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=ni(i).filter((f)=>a.has(yt(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),u=new Map;for(let{base:f,file:g}of l){let h=yt(g).toLowerCase(),m=u.get(f);if(!m){u.set(f,g);continue}let p=yt(m).toLowerCase();if(c.indexOf(h)<c.indexOf(p))u.set(f,g)}return Array.from(u.entries()).map(([f,g])=>({base:f,file:g})).sort((f,g)=>f.base.localeCompare(g.base))}function o(){let a=s(),c=a.map((g)=>g.base),l=c.length?c.map((g)=>`'${g}'`).join(" | "):"string",u=a.length?`{
|
|
34
|
+
${a.map((g)=>{let h=vr(i,g.file).replace(/\\/g,"/");return` '${g.base}': typeof import('${h}').default`}).join(`,
|
|
35
|
+
`)}
|
|
36
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${l}
|
|
37
|
+
export type ConfigByName = ${u}
|
|
38
|
+
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
|
+
export type ConfigOf = Config
|
|
40
|
+
`}return{name:"bunfig-plugin",setup(a){a.onResolve({filter:/^virtual:bunfig-types$/},(c)=>({path:c.path,namespace:"bunfig-virtual"})),a.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:o(),loader:"ts"}))}}}var nn,ve,Te,sn,Gi,qi,Ar,Ke,Pt,j,T,Yi,Fr,Hi,Rr,Zi,Xi,Ct,Qi,Or,Pr,bt,es,ts,rs,ns,Ve,on,is,L,ss,os,Nr,We,Nt,P,C,as,Dr,cs,Mr,ls,fs,Et,us,jr,Lr,gs,xt,hs,ms,ds,ps,ys,ze,an,ws,vs="0.15.6",K,et,xe,Dt,Mt,tt,jt,Lt,Se,Bt,It,ie,cn,ln,J,te,fn,un,$s=$i(async()=>{nn=import.meta.require,ve=new Vt,Te=new Wt,sn={createKey:Ci,isEquivalent:bi,estimateMemoryUsage:Ei},Gi=qe(Rt.cwd(),"config"),qi=qe(Rt.cwd(),"src/generated"),Ar=Ge.env.CLARITY_LOG_DIR||Ln(Ti(),"logs"),Ke={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ar,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Pt=await ki(),j={red:(n)=>`\x1B[31m${n}\x1B[0m`,green:(n)=>`\x1B[32m${n}\x1B[0m`,yellow:(n)=>`\x1B[33m${n}\x1B[0m`,blue:(n)=>`\x1B[34m${n}\x1B[0m`,magenta:(n)=>`\x1B[35m${n}\x1B[0m`,cyan:(n)=>`\x1B[36m${n}\x1B[0m`,white:(n)=>`\x1B[37m${n}\x1B[0m`,gray:(n)=>`\x1B[90m${n}\x1B[0m`,bgRed:(n)=>`\x1B[41m${n}\x1B[0m`,bgYellow:(n)=>`\x1B[43m${n}\x1B[0m`,bold:(n)=>`\x1B[1m${n}\x1B[0m`,dim:(n)=>`\x1B[2m${n}\x1B[0m`,italic:(n)=>`\x1B[3m${n}\x1B[0m`,underline:(n)=>`\x1B[4m${n}\x1B[0m`,reset:"\x1B[0m"},T=j,Yi=j.red,Fr=j.green,Hi=j.yellow,Rr=j.blue,Zi=j.magenta,Xi=j.cyan,Ct=j.white,Qi=j.gray,Or=j.bgRed,Pr=j.bgYellow,bt=j.bold,es=j.dim,ts=j.italic,rs=j.underline,ns=j.reset,Ve={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},on={debug:"\uD83D\uDD0D",info:Rr("\u2139"),success:Fr("\u2713"),warning:Pr(Ct(bt(" WARN "))),error:Or(Ct(bt(" ERROR ")))},is=new Ze("stacks"),L=new Ze("bunfig",{showTags:!0}),ss=B(Ee.cwd(),"config"),os=B(Ee.cwd(),"src/generated"),Nr=Je.env.CLARITY_LOG_DIR||Mn(Oi(),"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 Pi(),P={red:(n)=>`\x1B[31m${n}\x1B[0m`,green:(n)=>`\x1B[32m${n}\x1B[0m`,yellow:(n)=>`\x1B[33m${n}\x1B[0m`,blue:(n)=>`\x1B[34m${n}\x1B[0m`,magenta:(n)=>`\x1B[35m${n}\x1B[0m`,cyan:(n)=>`\x1B[36m${n}\x1B[0m`,white:(n)=>`\x1B[37m${n}\x1B[0m`,gray:(n)=>`\x1B[90m${n}\x1B[0m`,bgRed:(n)=>`\x1B[41m${n}\x1B[0m`,bgYellow:(n)=>`\x1B[43m${n}\x1B[0m`,bgGray:(n)=>`\x1B[100m${n}\x1B[0m`,bold:(n)=>`\x1B[1m${n}\x1B[0m`,dim:(n)=>`\x1B[2m${n}\x1B[0m`,italic:(n)=>`\x1B[3m${n}\x1B[0m`,underline:(n)=>`\x1B[4m${n}\x1B[0m`,strikethrough:(n)=>`\x1B[9m${n}\x1B[0m`,reset:"\x1B[0m"},C=P,as=P.red,Dr=P.green,cs=P.yellow,Mr=P.blue,ls=P.magenta,fs=P.cyan,Et=P.white,us=P.gray,jr=P.bgRed,Lr=P.bgYellow,gs=P.bgGray,xt=P.bold,hs=P.dim,ms=P.italic,ds=P.underline,ps=P.strikethrough,ys=P.reset,ze={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},an={debug:"\uD83D\uDD0D",info:Mr("\u2139"),success:Dr("\u2713"),warning:Lr(Et(xt(" WARN "))),error:jr(Et(xt(" ERROR ")))},ws=new Qe("stacks"),K=class extends Error{timestamp;context;constructor(i,s={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=s,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([s,o])=>`${s}: ${o}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},et=class extends K{code="CONFIG_NOT_FOUND";constructor(i,s,o){let a=o?` or alias "${o}"`:"";super(`Configuration "${i}"${a} not found`,{configName:i,alias:o,searchPaths:s,searchPathCount:s.length})}},xe=class extends K{code="CONFIG_LOAD_ERROR";constructor(i,s,o){super(`Failed to load configuration from "${i}": ${s.message}`,{configPath:i,configName:o,originalError:s.name,originalMessage:s.message});this.cause=s}},Dt=class extends K{code="CONFIG_VALIDATION_ERROR";constructor(i,s,o){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:o,validationErrors:s,errorCount:s.length})}},Mt=class extends K{code="CONFIG_MERGE_ERROR";constructor(i,s,o,a){super(`Failed to merge configuration from "${i}" with "${s}": ${o.message}`,{sourcePath:i,targetPath:s,configName:a,originalError:o.name,originalMessage:o.message});this.cause=o}},tt=class extends K{code="ENV_VAR_ERROR";constructor(i,s,o,a){super(`Failed to parse environment variable "${i}" with value "${s}" as ${o}`,{envKey:i,envValue:s,expectedType:o,configName:a})}},jt=class extends K{code="FILE_SYSTEM_ERROR";constructor(i,s,o){super(`File system ${i} failed for "${s}": ${o.message}`,{operation:i,path:s,originalError:o.name,originalMessage:o.message});this.cause=o}},Lt=class extends K{code="TYPE_GENERATION_ERROR";constructor(i,s,o){super(`Failed to generate types from "${i}" to "${s}": ${o.message}`,{configDir:i,outputPath:s,originalError:o.name,originalMessage:o.message});this.cause=o}},Se=class extends K{code="SCHEMA_VALIDATION_ERROR";constructor(i,s,o){super(`Schema validation failed${o?` for config "${o}"`:""}`,{schemaPath:i,configName:o,validationErrors:s,errorCount:s.length})}},Bt=class extends K{code="BROWSER_CONFIG_ERROR";constructor(i,s,o,a){super(`Failed to fetch configuration from "${i}": ${s} ${o}`,{endpoint:i,status:s,statusText:o,configName:a})}},It=class extends K{code="PLUGIN_ERROR";constructor(i,s,o){super(`Plugin "${i}" failed during ${s}: ${o.message}`,{pluginName:i,operation:s,originalError:o.name,originalMessage:o.message});this.cause=o}},ie={configNotFound(n,i,s){return new et(n,i,s)},configLoad(n,i,s){return new xe(n,i,s)},configValidation(n,i,s){return new Dt(n,i,s)},configMerge(n,i,s,o){return new Mt(n,i,s,o)},envVar(n,i,s,o){return new tt(n,i,s,o)},fileSystem(n,i,s){return new jt(n,i,s)},typeGeneration(n,i,s){return new Lt(n,i,s)},schemaValidation(n,i,s){return new Se(n,i,s)},browserConfig(n,i,s,o){return new Bt(n,i,s,o)},plugin(n,i,s){return new It(n,i,s)}},cn={replace:"replace",concat:"concat",smart:"smart"},ln=/^https?:\/\//,J=new Qe("bunfig",{showTags:!0}),te=new qt,fn=I(oe.cwd(),"config"),un=I(oe.cwd(),"src/generated")});function Cs(n,i={}){let s=Ye.cwd();while(s.includes("storage"))s=$r(s,"..");let o=$r(s,n||"");if(i?.relative)return oi(Ye.cwd(),o);return o}var bs=Ye.env.CLARITY_LOG_DIR||si(Cs(),"logs"),gn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:bs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},rt={...gn},ua=(async()=>{try{let{loadConfig:n}=await $s().then(()=>qr),i=await n({name:"clarity",alias:"logging",defaultConfig:gn,cwd:Ye.cwd()});if(i)Object.assign(rt,i)}catch{}return rt})();function N(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Es(){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 n=ee.type;if(n==="renderer"||n==="worker")return!1;return!!(ee.versions&&(ee.versions.node||ee.versions.bun))}return!1}class hn{async format(n){let i=await Es(),s=await this.getMetadata(i);return JSON.stringify({timestamp:n.timestamp.toISOString(),level:n.level,name:n.name,message:n.message,metadata:s})}async getMetadata(n){if(n){let{hostname:i}=await import("os");return{pid:ye.pid,hostname:i(),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:(n)=>`\x1B[31m${n}\x1B[0m`,green:(n)=>`\x1B[32m${n}\x1B[0m`,yellow:(n)=>`\x1B[33m${n}\x1B[0m`,blue:(n)=>`\x1B[34m${n}\x1B[0m`,magenta:(n)=>`\x1B[35m${n}\x1B[0m`,cyan:(n)=>`\x1B[36m${n}\x1B[0m`,white:(n)=>`\x1B[37m${n}\x1B[0m`,gray:(n)=>`\x1B[90m${n}\x1B[0m`,bgRed:(n)=>`\x1B[41m${n}\x1B[0m`,bgYellow:(n)=>`\x1B[43m${n}\x1B[0m`,bgGray:(n)=>`\x1B[100m${n}\x1B[0m`,bold:(n)=>`\x1B[1m${n}\x1B[0m`,dim:(n)=>`\x1B[2m${n}\x1B[0m`,italic:(n)=>`\x1B[3m${n}\x1B[0m`,underline:(n)=>`\x1B[4m${n}\x1B[0m`,strikethrough:(n)=>`\x1B[9m${n}\x1B[0m`,reset:"\x1B[0m"},b=D,{red:ga,green:xs,yellow:ha,blue:Ss,magenta:ma,cyan:da,white:Br,gray:pa,bgRed:Ts,bgYellow:ks,bgGray:ya,bold:Ir,dim:wa,italic:va,underline:$a,strikethrough:Ca,reset:ba}=D,St={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},As={debug:"\uD83D\uDD0D",info:Ss("\u2139"),success:xs("\u2713"),warning:ks(Br(Ir(" WARN "))),error:Ts(Br(Ir(" 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(n,i={}){this.name=n,this.config={...rt},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new hn,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let s={...i},o=i.timestamp!==void 0;if(o)delete s.timestamp;if(this.config={...this.config,...s,timestamp:o||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let a=this.generateKeyId(),c=this.generateKey();this.currentKeyId=a,this.keys.set(a,c),this.encryptionKeys.set(a,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(n){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},s=this.fingersCrossedConfig.activationLevel??"error";return i[n]>=i[s]}initializeFingersCrossedConfig(n){if(!n.fingersCrossedEnabled&&n.fingersCrossed)return{...St,...n.fingersCrossed};if(!n.fingersCrossedEnabled)return null;if(!n.fingersCrossed)return{...St};return{...St,...n.fingersCrossed}}normalizeOptions(n){let i={format:"json",level:"info",logDirectory:rt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},s={...i,...Object.fromEntries(Object.entries(n).filter(([,o])=>o!==void 0))};if(!s.level||!["debug","info","success","warning","error"].includes(s.level))s.level=i.level;return s}shouldWriteToFile(){return!N()&&this.config.writeToFile===!0}async writeToFile(n){let s=(async()=>{let a,c=0,l=3,u=1000;while(c<l)try{try{try{await ui(this.config.logDirectory,xr.F_OK|xr.W_OK)}catch(g){if(g instanceof Error&&"code"in g)if(g.code==="ENOENT")await gi(this.config.logDirectory,{recursive:!0,mode:493});else if(g.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw g;else throw g}}catch(g){throw console.error("Debug: [writeToFile] Failed to create log directory:",g),g}let f=this.validateEncryptionConfig()?(await this.encrypt(n)).encrypted:Z.from(n);try{if(!De(this.currentLogFile))await $t(this.currentLogFile,"",{mode:420});if(a=Er(this.currentLogFile,"a",420),fi(a,f,{flag:"a"}),br(a),a!==void 0)vt(a),a=void 0;if((await de(this.currentLogFile)).size===0){if(await $t(this.currentLogFile,f,{flag:"w",mode:420}),(await de(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(g){let h=g;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let m=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,m);let p=u*2**c;await new Promise((d)=>setTimeout(d,p)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(a!==void 0)try{vt(a)}catch(g){console.error("Debug: [writeToFile] Error closing file descriptor:",g)}}}catch(f){if(c===l-1){let h=f,m=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",m),f}c++;let g=u*2**(c-1);await new Promise((h)=>setTimeout(h,g))}})();this.pendingOperations.push(s);let o=this.pendingOperations.length-1;try{await s}catch(a){throw console.error("Debug: [writeToFile] Error in operation:",a),a}finally{this.pendingOperations.splice(o,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 n=new Date().toISOString().split("T")[0];return pe(this.config.logDirectory,`${this.name}-${n}.log`)}setupRotation(){if(N())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let n=this.config.rotation,i;switch(n.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let s=typeof i.interval==="number"?i.interval:60,o=Math.max(s,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((a)=>{console.error("Error rotating keys:",a)})},o)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,s=this.generateKeyId(),o=this.generateKey();this.currentKeyId=s,this.keys.set(s,o),this.encryptionKeys.set(s,{key:o,createdAt:new Date});let a=Array.from(this.encryptionKeys.entries()).sort(([,u],[,f])=>f.createdAt.getTime()-u.createdAt.getTime()),c=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,c);if(a.length>l)for(let[u]of a.slice(l))this.encryptionKeys.delete(u),this.keys.delete(u)}generateKeyId(){return wt(16).toString("hex")}generateKey(){return wt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let n=this.keys.get(this.currentKeyId);if(!n)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:n,id:this.currentKeyId}}encrypt(n){let{key:i}=this.getCurrentKey(),s=wt(16),o=ai("aes-256-gcm",i,s),a=Z.isBuffer(n)?n:Z.from(n,"utf8"),c=o.update(a),l=o.final(),u=c.length+l.length,f=o.getAuthTag(),g=Z.allocUnsafe(16+u+16);return s.copy(g,0),c.copy(g,16),l.copy(g,16+c.length),f.copy(g,16+u),{encrypted:g,iv:s}}async compressData(n){return new Promise((i,s)=>{let o=Tr(),a=[];o.on("data",(c)=>a.push(c)),o.on("end",()=>i(Z.from(Z.concat(a)))),o.on("error",s),o.write(n),o.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let n={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...n,...i}}return n}async rotateLog(){if(N())return;if(!this.shouldWriteToFile())return;let n=await de(this.currentLogFile).catch(()=>null);if(!n)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&n.size>=i.maxSize){let s=this.currentLogFile,o=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let a=await Me(this.config.logDirectory),c=a.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,g)=>{let h=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(g.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,u=`${s}.${l}`;if(await de(s).catch(()=>null))try{if(await Sr(s,u),i.compress)try{let f=`${u}.gz`;await this.compressLogFile(u,f),await je(u)}catch(f){console.error("Error compressing rotated file:",f)}if(c.length===0&&!a.some((f)=>f.endsWith(".log.1")))try{let f=`${s}.1`;await $t(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let a=new Date().toISOString().replace(/[:.]/g,"-"),c=s.replace(/\.log$/,`-${a}.log`);if(await de(s).catch(()=>null))await Sr(s,c)}if(this.currentLogFile=o,i.maxFiles){let c=(await Me(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,u)=>u.localeCompare(l));for(let l of c.slice(i.maxFiles))await je(pe(this.config.logDirectory,l))}}}async compressLogFile(n,i){let s=Cr(n),o=li(i),a=Tr();await di(s,a,o)}async handleFingersCrossedBuffer(n,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(n)&&!this.isActivated){this.isActivated=!0;for(let s of this.logBuffer){let o=await this.formatter.format(s);if(this.shouldWriteToFile())await this.writeToFile(o);console.log(o)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(n){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[n]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((n)=>{if(n instanceof Promise)return n.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),De(this.currentLogFile))try{let n=Er(this.currentLogFile,"r+");br(n),vt(n)}catch(n){console.error(`Error flushing file: ${n}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let n of this.pendingOperations)if(typeof n.cancel==="function")n.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(n){console.error("Error waiting for pending operations:",n)}if(!N()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Me(this.config.logDirectory)).filter((s)=>(s.includes("temp")||s.includes(".tmp"))&&s.includes(this.name));for(let s of i)try{await je(pe(this.config.logDirectory,s))}catch(o){console.error(`Failed to delete temp file ${s}:`,o)}}catch(n){console.error("Error cleaning up temporary files:",n)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(n){if(!n)return"";return`${this.tagFormat.prefix}${n}${this.tagFormat.suffix}`}formatFileTimestamp(n){return`[${n.toISOString()}]`}formatConsoleTimestamp(n){return this.shouldStyleConsole()?b.gray(n.toLocaleTimeString()):n.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N())return!1;let n=typeof x.env.NO_COLOR<"u",i=x.env.FORCE_COLOR==="0";if(n||i)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage(n){let{timestamp:i,icon:s="",tag:o="",message:a,level:c,showTimestamp:l=!0}=n,u=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(l)d.push(i);if(c==="warning")d.push("WARN");else if(c==="error")d.push("ERROR");else if(s)d.push(s.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(o)d.push(o.replace(/[[\]]/g,""));return d.push(a),d.join(" ")}let f=x.stdout.columns||120,g="";if(c==="warning"||c==="error")g=`${s} ${a}`;else if(c==="info"||c==="success")g=`${s} ${o} ${a}`;else g=`${s} ${o} ${b.cyan(a)}`;if(!l)return g.trim();let h=u(g).trim().length,m=u(i).length,p=Math.max(1,f-2-h-m);return`${g.trim()}${" ".repeat(p)}${i}`}formatMessage(n,i){if(i.length===1&&Array.isArray(i[0]))return n.replace(/\{(\d+)\}/g,(c,l)=>{let u=Number.parseInt(l,10);return u<i[0].length?String(i[0][u]):c});let s=/%([sdijfo%])/g,o=0,a=n.replace(s,(c,l)=>{if(l==="%")return"%";if(o>=i.length)return c;let u=i[o++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return c}});if(o<i.length)a+=` ${i.slice(o).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return a}formatMarkdown(n){if(!n)return n;let i=n;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(s,o,a)=>{let c=b.underline(b.blue(o)),l=this.toAbsoluteFilePath(a);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let u=`file://${encodeURI(l)}`,f="\x1B]8;;",g="\x1B\\";return`\x1B]8;;${u}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${a}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),i=i.replace(/`([^`]+)`/g,(s,o)=>b.bgGray(o)),i=i.replace(/\*\*([^*]+)\*\*/g,(s,o)=>b.bold(o)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(s,o)=>b.italic(o)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(s,o)=>b.italic(o)),i=i.replace(/~([^~]+)~/g,(s,o)=>b.strikethrough(o)),i}supportsHyperlinks(){if(N())return!1;let n=x.env;if(!n)return!1;if(n.TERM_PROGRAM==="iTerm.app"||n.TERM_PROGRAM==="vscode"||n.TERM_PROGRAM==="WezTerm")return!0;if(n.WT_SESSION)return!0;if(n.TERM==="xterm-kitty")return!0;let i=n.VTE_VERSION?Number.parseInt(n.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(n){try{let i=n;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let s=x.env.HOME||"";if(s)i=i.replace(/^~(?=$|\/)/,s)}if(hi(i)||i.startsWith("./")||i.startsWith("../"))i=mi(i);else return null;return De(i)?i:null}catch{return null}}buildOutputTexts(n){let i=this.shouldStyleConsole()?this.formatMarkdown(n):n,s=n.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:s}}async log(n,i,...s){if(!this.shouldLog(n))return;let o=new Date,a=this.formatConsoleTimestamp(o),c=this.formatFileTimestamp(o),l,u;if(i instanceof Error)l=i.message,u=i.stack;else l=this.formatMessage(i,s);let{consoleText:f,fileText:g}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":As[n],p=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",d;switch(n){case"debug":d=this.formatConsoleMessage({timestamp:a,icon:m,tag:p,message:b.gray(f),level:n}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:a,icon:m,tag:p,message:f,level:n}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:a,icon:m,tag:p,message:b.green(f),level:n}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:a,icon:m,tag:p,message:f,level:n}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:a,icon:m,tag:p,message:f,level:n}),console.error(d),u){let v=u.split(`
|
|
41
|
+
`);for(let y of v)if(y.trim()&&!y.includes(l))console.error(this.formatConsoleMessage({timestamp:a,message:b.gray(` ${y}`),level:n,showTimestamp:!1}))}break}}else if(!N()){if(console.error(`${c} ${this.environment}.${n.toUpperCase()}: ${l}`),u)console.error(u)}let h=`${c} ${this.environment}.${n.toUpperCase()}: ${g}
|
|
42
|
+
`;if(u)h+=`${u}
|
|
43
|
+
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(n,i=""){let s={update:(u,f)=>{},finish:(u)=>{},interrupt:(u,f)=>{}};if(!this.enabled)return s;let o=30;if(this.activeProgressBar={total:Math.max(1,n||1),current:0,message:i||"",barLength:o,lastRenderedLine:""},this.shouldStyleConsole()&&!N()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(u,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,u),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!N()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(u)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,u)},interrupt:(u,f="info")=>{if(!N()&&x.stdout.isTTY)x.stdout.write(`
|
|
44
|
+
`);if(this[f==="warning"?"warn":f](u),this.activeProgressBar&&this.shouldStyleConsole()&&!N()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(n){let i=performance.now();if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",o=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":b.blue("\u25D0"),tag:s,message:`${b.cyan(n)}...`}))}return async(s)=>{if(!this.enabled)return;let o=performance.now(),a=Math.round(o-i),c=`${n} completed in ${a}ms`,l=new Date,u=this.formatConsoleTimestamp(l),g=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(s)g+=` ${JSON.stringify(s)}`;if(g+=`
|
|
45
|
+
`,g=g.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:u,icon:this.options.showIcons===!1?"":b.green("\u2713"),tag:h,message:`${c}${s?` ${JSON.stringify(s)}`:""}`}))}else if(!N())console.error(g.trim());if(this.shouldWriteToFile())await this.writeToFile(g)}}async debug(n,...i){await this.log("debug",n,...i)}async info(n,...i){await this.log("info",n,...i)}async success(n,...i){await this.log("success",n,...i)}async warn(n,...i){await this.log("warning",n,...i)}async error(n,...i){await this.log("error",n,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let n=this.config.rotation,{encrypt:i}=n;return!!i}async only(n){if(!this.enabled)return;return await n()}isEnabled(){return this.enabled}setEnabled(n){this.enabled=n}extend(n){let i=`${this.name}:${n}`,s=new at(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(s),s}createReadStream(){if(N())throw Error("createReadStream is not supported in browser environments");if(!De(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Cr(this.currentLogFile,{encoding:"utf8"})}async decrypt(n){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let s=this.keys.get(this.currentKeyId);try{let o=Z.isBuffer(n)?n:Z.from(n,"base64"),a=o.subarray(0,16),c=o.subarray(o.length-16),l=o.subarray(16,o.length-16),u=ci("aes-256-gcm",s,a);u.setAuthTag(c);let f=u.update(l),g=u.final(),h=f.length+g.length,m=Z.allocUnsafe(h);return f.copy(m,0),g.copy(m,f.length),m.toString("utf8")}catch(o){throw Error(`Decryption failed: ${o instanceof Error?o.message:String(o)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N()}isServerMode(){return!N()}setTestEncryptionKey(n,i){this.currentKeyId=n,this.keys.set(n,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(n){if(!this.enabled)return;let i=new Date,s=this.formatConsoleTimestamp(i),o=this.formatFileTimestamp(i),{consoleText:a,fileText:c}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let u=a.split(`
|
|
46
|
+
`),f=Math.max(...u.map((p)=>p.length))+2,g=`\u250C${"\u2500".repeat(f)}\u2510`,h=`\u2514${"\u2500".repeat(f)}\u2518`,m=u.map((p)=>this.formatConsoleMessage({timestamp:s,message:b.cyan(p),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:s,message:b.cyan(g),showTimestamp:!1})),m.forEach((p)=>console.error(p)),console.error(this.formatConsoleMessage({timestamp:s,message:b.cyan(h),showTimestamp:!1}))}else if(!N())console.error(`${o} ${this.environment}.INFO: [BOX] ${c}`);let l=`${o} ${this.environment}.INFO: [BOX] ${c}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(n){if(N())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${b.cyan("?")} ${n} (y/n) `);let s=(o)=>{let a=o.toString().trim().toLowerCase();x.stdin.removeListener("data",s);try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!1)}catch{}x.stdin.pause(),console.error(""),i(a==="y"||a==="yes")};try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!0)}catch{}x.stdin.resume(),x.stdin.once("data",s)})}setFancy(n){this.fancy=n}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(n,...i){if(!this.enabled)return;let s=n;if(i&&i.length>0){let f=/%([sdijfo%])/g,g=0;if(s=n.replace(f,(h,m)=>{if(m==="%")return"%";if(g>=i.length)return h;let p=i[g++];switch(m){case"s":return String(p);case"d":case"i":return Number(p).toString();case"j":case"o":return JSON.stringify(p,null,2);default:return h}}),g<i.length)s+=` ${i.slice(g).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:o,fileText:a}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",g=this.options.showIcons===!1?"":`${b.blue("\u25D0")} `;console.error(`${g}${f} ${b.cyan(o)}`)}let u=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${a}
|
|
48
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(u)}renderProgressBar(n,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!x.stdout.isTTY)return;let s=Math.min(100,Math.max(0,Math.round(n.current/n.total*100))),o=Math.round(n.barLength*s/100),a=n.barLength-o,c=b.green("\u2501".repeat(o)),l=b.gray("\u2501".repeat(a)),u=`[${c}${l}]`,f=`${s}%`.padStart(4),g=n.message?` ${n.message}`:"",h=this.options.showIcons===!1?"":i||s===100?b.green("\u2713"):b.blue("\u25B6"),m=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",p=`\r${h}${m} ${u} ${f}${g}`,d=x.stdout.columns||80,v=" ".repeat(Math.max(0,d-p.replace(this.ANSI_PATTERN,"").length));if(n.lastRenderedLine=`${p}${v}`,x.stdout.write(n.lastRenderedLine),i)x.stdout.write(`
|
|
49
|
+
`)}finishProgressBar(n,i){if(!this.enabled||!this.fancy||N()||!x.stdout.isTTY){this.activeProgressBar=null;return}if(n.current<n.total)n.current=n.total;if(i)n.message=i;this.renderProgressBar(n,!0),this.activeProgressBar=null}async clear(n={}){if(N()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Me(this.config.logDirectory),s=[];for(let o of i){if(!(n.name?new RegExp(n.name.replace("*",".*")).test(o):o.startsWith(this.name))||!o.endsWith(".log"))continue;let c=pe(this.config.logDirectory,o);if(n.before)try{if((await de(c)).mtime>=n.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}s.push(c)}if(s.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${s.length} log file(s)...`);for(let o of s)try{await je(o),console.warn(`Deleted log file: ${o}`)}catch(a){console.error(`Failed to delete log file ${o}:`,a)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var Ea=new at("stacks");class G extends Error{timestamp;context;constructor(n,i={}){super(n);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let n=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,s])=>`${i}: ${s}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${n}`}}class we extends G{name="ConfigNotFoundError";code="CONFIG_NOT_FOUND";constructor(n,i,s){let o=s===void 0?[]:Array.isArray(s)?s.filter(Boolean):[s],a="";if(o.length===1)a=` or alias "${o[0]}"`;else if(o.length>1)a=` or aliases ${o.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${n}"${a} not found`,{configName:n,alias:s,searchPaths:i,searchPathCount:i.length})}}class se extends G{name="ConfigLoadError";code="CONFIG_LOAD_ERROR";constructor(n,i,s){super(`Failed to load configuration from "${n}": ${i.message}`,{configPath:n,configName:s,originalError:i.name,originalMessage:i.message});this.cause=i}}class Yt extends G{name="ConfigValidationError";code="CONFIG_VALIDATION_ERROR";constructor(n,i,s){super(`Configuration validation failed for "${n}"`,{configPath:n,configName:s,validationErrors:i,errorCount:i.length})}}class mn extends G{name="ConfigMergeError";code="CONFIG_MERGE_ERROR";constructor(n,i,s,o){super(`Failed to merge configuration from "${n}" with "${i}": ${s.message}`,{sourcePath:n,targetPath:i,configName:o,originalError:s.name,originalMessage:s.message});this.cause=s}}class Ht extends G{name="EnvVarError";code="ENV_VAR_ERROR";constructor(n,i,s,o){super(`Failed to parse environment variable "${n}" with value "${i}" as ${s}`,{envKey:n,envValue:i,expectedType:s,configName:o})}}class dn extends G{name="FileSystemError";code="FILE_SYSTEM_ERROR";constructor(n,i,s){super(`File system ${n} failed for "${i}": ${s.message}`,{operation:n,path:i,originalError:s.name,originalMessage:s.message});this.cause=s}}class pn extends G{name="TypeGenerationError";code="TYPE_GENERATION_ERROR";constructor(n,i,s){super(`Failed to generate types from "${n}" to "${i}": ${s.message}`,{configDir:n,outputPath:i,originalError:s.name,originalMessage:s.message});this.cause=s}}class nt extends G{name="SchemaValidationError";code="SCHEMA_VALIDATION_ERROR";constructor(n,i,s){super(`Schema validation failed${s?` for config "${s}"`:""}`,{schemaPath:n,configName:s,validationErrors:i,errorCount:i.length})}}class yn extends G{name="BrowserConfigError";code="BROWSER_CONFIG_ERROR";constructor(n,i,s,o){super(`Failed to fetch configuration from "${n}": ${i} ${s}`,{endpoint:n,status:i,statusText:s,configName:o})}}class wn extends G{name="PluginError";code="PLUGIN_ERROR";constructor(n,i,s){super(`Plugin "${n}" failed during ${i}: ${s.message}`,{pluginName:n,operation:i,originalError:s.name,originalMessage:s.message});this.cause=s}}var ne={configNotFound(n,i,s){return new we(n,i,s)},configLoad(n,i,s){return new se(n,i,s)},configValidation(n,i,s){return new Yt(n,i,s)},configMerge(n,i,s,o){return new mn(n,i,s,o)},envVar(n,i,s,o){return new Ht(n,i,s,o)},fileSystem(n,i,s){return new dn(n,i,s)},typeGeneration(n,i,s){return new pn(n,i,s)},schemaValidation(n,i,s){return new nt(n,i,s)},browserConfig(n,i,s,o){return new yn(n,i,s,o)},plugin(n,i,s){return new wn(n,i,s)}};async function Fs(n,i={}){let{maxRetries:s=3,retryDelay:o=1000,isRetryable:a=()=>!0,fallback:c}=i,l=Error("Unknown error occurred");for(let u=0;u<=s;u++)try{return await n()}catch(f){if(l=f instanceof Error?f:Error(String(f)),u===s||!a(l))break;if(o>0)await new Promise((g)=>setTimeout(g,o))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class Zt{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(n,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(n.toLowerCase()),parse:(n)=>{let i=n.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(n,i)=>i==="number"||!Number.isNaN(Number(n))&&!Number.isNaN(Number.parseFloat(n)),parse:(n)=>{let i=Number(n);if(Number.isNaN(i))throw TypeError(`Cannot parse "${n}" as number`);return i}},{name:"array",canParse:(n,i)=>i==="array"||n.startsWith("[")||n.includes(","),parse:(n)=>{try{let i=JSON.parse(n);if(Array.isArray(i))return i}catch{}return n.split(",").map((i)=>i.trim())}},{name:"json",canParse:(n,i)=>i==="object"||(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]")),parse:(n)=>{try{return JSON.parse(n)}catch(i){throw Error(`Cannot parse "${n}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(n,i,s={}){let{prefix:o,useCamelCase:a=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:u=!1,trackPerformance:f=!0}=s,g=async()=>{if(!n)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let h=o||this.generateEnvPrefix(n),m={...i};return this.processObject(m,[],h,{useCamelCase:a,useBackwardCompatibility:c,customParsers:l,verbose:u,configName:n}),{config:m,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return Kt.track("applyEnvironmentVariables",g,{configName:n});return g()}generateEnvPrefix(n){return n.toUpperCase().replace(/-/g,"_")}formatEnvKey(n,i){if(!i)return n.toUpperCase();return n.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(n,i,s,o){for(let[a,c]of Object.entries(n)){let l=[...i,a],u=l.map((h)=>this.formatEnvKey(h,o.useCamelCase)),f=`${s}_${u.join("_")}`,g=o.useBackwardCompatibility?`${s}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(o.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,s,o);else{let h=Be.env[f]||(g?Be.env[g]:void 0);if(h!==void 0){if(o.verbose){let m=Be.env[f]?f:g}try{n[a]=this.parseEnvironmentValue(h,typeof c,f,o.customParsers,o.configName)}catch(m){if(m instanceof Ht)throw m;throw ne.envVar(f,h,typeof c,o.configName)}}}}}parseEnvironmentValue(n,i,s,o,a){for(let[c,l]of Object.entries(o))try{return l(n)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(n,i))try{return c.parse(n)}catch{throw ne.envVar(s,n,`${i} (via ${c.name} parser)`,a)}return n}getEnvironmentVariables(n){let i={},s=n.toUpperCase();for(let[o,a]of Object.entries(Be.env))if(o.startsWith(s)&&a!==void 0)i[o]=a;return i}validateEnvironmentVariable(n,i,s){let o=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(n))o.push(`Environment variable key "${n}" should only contain uppercase letters, numbers, and underscores`);if(s)try{this.parseEnvironmentValue(n,i,s,{})}catch(a){o.push(`Cannot parse value "${i}" as ${s}: ${a}`)}return{isValid:o.length===0,errors:o}}generateEnvVarDocs(n,i,s={}){let{prefix:o,format:a="text"}=s,c=o||this.generateEnvPrefix(n),l=[];switch(this.extractEnvVarInfo(i,[],c,l),a){case"markdown":return this.formatAsMarkdown(l,n);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,n)}}extractEnvVarInfo(n,i,s,o){for(let[a,c]of Object.entries(n)){let l=[...i,a],u=`${s}_${l.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,s,o);else o.push({key:u,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}generateExample(n){if(Array.isArray(n))return JSON.stringify(n);if(typeof n==="object"&&n!==null)return JSON.stringify(n);return String(n)}formatAsText(n,i){let s=`Environment Variables for ${i}:
|
|
50
|
+
|
|
51
|
+
`;for(let o of n)s+=`${o.key}
|
|
52
|
+
`,s+=` Type: ${o.type}
|
|
53
|
+
`,s+=` Description: ${o.description}
|
|
54
|
+
`,s+=` Example: ${o.example}
|
|
55
|
+
|
|
56
|
+
`;return s}formatAsMarkdown(n,i){let s=`# Environment Variables for ${i}
|
|
57
|
+
|
|
58
|
+
`;s+=`| Variable | Type | Description | Example |
|
|
59
|
+
`,s+=`|----------|------|-------------|----------|
|
|
60
|
+
`;for(let o of n)s+=`| \`${o.key}\` | ${o.type} | ${o.description} | \`${o.example}\` |
|
|
61
|
+
`;return s}}var _r=Ps(import.meta.url),Ie=new Map,Tt=new Set;function vn(n){return n instanceof Error&&"code"in n&&(n.code==="ENOENT"||n.code==="ENOTDIR")}async function $n(n){let i=Os(n),s=Ie.get(i),o,a=new Promise((c)=>{o=c});Ie.set(i,a),await s;try{if(Rs(i),_r.cache[i]?.loaded===!0||Tt.has(i))delete _r.cache[i];try{let c=await import(Ns(i).href);return Tt.delete(i),c}catch(c){throw Tt.add(i),c}}finally{if(o(),Ie.get(i)===a)Ie.delete(i)}}function Ms(n,i,s={}){return Cn(n,i,s,new WeakMap)}function Cn(n,i,s,o){let{arrayMergeMode:a="replace",skipNullish:c=!1,customMerger:l}=s;if(i===null||i===void 0)return c?n:i;if(l){let u=l(n,i);if(u!==void 0)return u}if(Array.isArray(i)||Array.isArray(n))return bn(n,i,a,o);if(!W(i)||!W(n))return i;return Is(n,i,s,o)}function bn(n,i,s,o){if(Array.isArray(i)&&!Array.isArray(n))return i;if(Array.isArray(n)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(n))switch(s){case"replace":return i;case"concat":return js(n,i);case"smart":return Ls(n,i,o);default:return i}return i}function js(n,i){let s=[...i];for(let o of n)if(!s.some((a)=>_t(a,o)))s.push(o);return s}function Ls(n,i,s){if(i.length===0)return n;if(n.length===0)return i;if(W(i[0])&&W(n[0]))return Bs(n,i,s);if(i.every((o)=>typeof o==="string")&&n.every((o)=>typeof o==="string")){let o=[...i];for(let a of n)if(!o.includes(a))o.push(a);return o}return i}function Bs(n,i,s){let o=[...i];for(let a of n){if(!W(a)){o.push(a);continue}let c=["id","name","key","path","type"],l=!1;for(let u of c)if(u in a){if(o.find((g)=>W(g)&&(u in g)&&g[u]===a[u])){l=!0;break}}if(!l)o.push(a)}return o}function Is(n,i,s,o){let a=i;if(W(a)&&o.has(a))return o.get(a);let c={...n};if(W(a))o.set(a,c);for(let l in a){if(!Object.prototype.hasOwnProperty.call(a,l))continue;let u=a[l],f=c[l];if(s.skipNullish&&(u===null||u===void 0))continue;if(u===null||u===void 0){c[l]=u;continue}if(W(u)&&W(f))c[l]=Cn(f,u,s,o);else if(Array.isArray(u)||Array.isArray(f))c[l]=bn(f,u,s.arrayMergeMode||"smart",o);else c[l]=u}return c}function En(n,i,s="replace"){return Ms(n,i,{arrayMergeMode:s==="replace"?"replace":"smart",skipNullish:!0})}function _t(n,i){if(n===i)return!0;if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(!_t(n[s],i[s]))return!1;return!0}if(W(n)&&W(i)){let s=Object.keys(n),o=Object.keys(i);if(s.length!==o.length)return!1;for(let a of s){if(!Object.prototype.hasOwnProperty.call(i,a))return!1;if(!_t(n[a],i[a]))return!1}return!0}return!1}function W(n){return Boolean(n&&typeof n==="object"&&!Array.isArray(n))}class xn{extensions=zr;async loadFromPath(n,i,s={}){let{arrayStrategy:o="replace",useCache:a=!0,cacheTtl:c,trackPerformance:l=!0,verbose:u=!1,strictDiscovery:f=!1}=s;if(a){let h=Ue.getWithFileCheck("file",n);if(h){if(u)console.log(`Configuration loaded from cache: ${n}`);return h}}let g=async()=>{try{try{Ds(n)}catch(A){if(vn(A)||!f)return null;throw A}let h=await $n(n),m=Object.hasOwn(h,"default"),p=Object.keys(h).length>0,d=m?h.default:h;if(!m&&!p)throw new se(n,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof d!=="object"||d===null||Array.isArray(d))throw new se(n,Error("Configuration must export a valid object"),"unknown");let w={config:En(i,d,o),source:{type:"file",path:n,priority:100,timestamp:new Date}};if(a)Ue.setWithFileCheck("file",w,n,c);return w}catch(h){throw h instanceof Error?ne.configLoad(n,h):ne.configLoad(n,Error(String(h)))}};if(l)return Kt.track("loadFromPath",g,{path:n});return g()}async tryLoadFromPaths(n,i,s={}){for(let o of n)try{let a=await this.loadFromPath(o,i,s);if(a)return a}catch(a){if(a instanceof se)throw a;if(s.verbose)console.warn(`Failed to load config from ${o}:`,a)}return null}generateConfigPaths(n,i,s){return Fn({name:n,directory:i,alias:s})}generateNamePatterns(n,i){return Ur({name:n,alias:i})}checkFileAccess(n){return Fs(async()=>kt(n),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(n,i,s){let o=[];if(!kt(n))return o;if(i||s){let a=this.generateNamePatterns(i||"",s);for(let c of a)for(let l of this.extensions){let u=Kr(n,`${c}${l}`);if(await this.checkFileAccess(u))o.push(u)}}else try{let{readdirSync:a}=await import("fs"),c=a(n);for(let l of c)if(this.looksLikeConfigFile(l)){let u=Kr(n,l);if(await this.checkFileAccess(u))o.push(u)}}catch{return[]}return o}looksLikeConfigFile(n){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((s)=>s.test(n))}async validateConfigFile(n){let i=[];try{if(!kt(n))return i.push("Configuration file does not exist"),i;let s=await import(n),o=s.default||s;if(o===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof o!=="object"||o===null)i.push("Configuration must be an object");else if(Array.isArray(o))i.push("Configuration cannot be an array at the root level");if(n.endsWith(".json"))try{let{readFileSync:a}=await import("fs"),c=a(n,"utf8");JSON.parse(c)}catch(a){i.push(`Invalid JSON syntax: ${a}`)}}catch(s){i.push(`Failed to load configuration file: ${s}`)}return i}async getFileModificationTime(n){try{let{statSync:i}=await import("fs");return i(n).mtime}catch{return null}}async preloadConfigurations(n,i={}){let s=new Map;return await Promise.allSettled(n.map(async(o)=>{try{let a=await this.loadFromPath(o,{},i);if(a)s.set(o,a.config)}catch(a){if(i.verbose)console.warn(`Failed to preload ${o}:`,a)}})),s}}var Ks=/^https?:\/\//;class Sn{async validateConfiguration(n,i,s={}){let{stopOnFirstError:o=!1,validateRequired:a=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:u=!0,verbose:f=!1}=s,g=async()=>{let h=[],m=[],p={stopOnFirstError:o,validateRequired:a,validateTypes:c,customRules:l,trackPerformance:u,verbose:f};try{if(typeof i==="string")return await this.validateWithSchemaFile(n,i,p);else if(Array.isArray(i))return this.validateWithRules(n,[...i,...l],p);else return this.validateWithJSONSchema(n,i,p)}catch(d){return h.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:h,warnings:m}}};if(u)return await Kt.track("validateConfiguration",g);return g()}async validateWithSchemaFile(n,i,s){try{if(!_s(i))throw new nt(i,[{path:"",message:"Schema file does not exist"}]);let o=await $n(i),a=Object.hasOwn(o,"default")?o.default:o;if(Array.isArray(a))return this.validateWithRules(n,a,s);else{if(typeof a!=="object"||a===null)throw Error("Schema must export an object or validation rule array");return this.validateWithJSONSchema(n,a,s)}}catch(o){throw new nt(i,[{path:"",message:`Failed to load schema: ${o}`}])}}validateWithJSONSchema(n,i,s){let o=[],a=[];return this.validateObjectAgainstSchema(n,i,"",o,a,s),{isValid:o.length===0,errors:o,warnings:a}}validateObjectAgainstSchema(n,i,s,o,a,c){if(c.validateTypes&&i.type){let l=Array.isArray(n)?"array":typeof n,u=Array.isArray(i.type)?i.type:[i.type];if(!u.includes(l)){if(o.push({path:s,message:`Expected type ${u.join(" or ")}, got ${l}`,expected:u.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(n)){if(o.push({path:s,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:n,rule:"enum"}),c.stopOnFirstError)return}if(typeof n==="string"){if(i.minLength!==void 0&&n.length<i.minLength)o.push({path:s,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:n.length,rule:"minLength"});if(i.maxLength!==void 0&&n.length>i.maxLength)o.push({path:s,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:n.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(n))o.push({path:s,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:n,rule:"pattern"})}}if(typeof n==="number"){if(i.minimum!==void 0&&n<i.minimum)o.push({path:s,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:n,rule:"minimum"});if(i.maximum!==void 0&&n>i.maximum)o.push({path:s,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:n,rule:"maximum"})}if(Array.isArray(n)&&i.items)for(let l=0;l<n.length;l++){let u=s?`${s}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(n[l],i.items,u,o,a,c),c.stopOnFirstError&&o.length>0)return}if(n&&typeof n==="object"&&!Array.isArray(n)){let l=n;if(c.validateRequired&&i.required){for(let u of i.required)if(!(u in l)){if(o.push({path:s?`${s}.${u}`:u,message:`Missing required property '${u}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(i.properties){for(let[u,f]of Object.entries(i.properties))if(u in l){let g=s?`${s}.${u}`:u;if(this.validateObjectAgainstSchema(l[u],f,g,o,a,c),c.stopOnFirstError&&o.length>0)return}}if(i.additionalProperties===!1){let u=new Set(Object.keys(i.properties||{}));for(let f of Object.keys(l))if(!u.has(f))a.push({path:s?`${s}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(n,i,s){let o=[],a=[];for(let c of i)try{let l=this.getValueByPath(n,c.path),u=this.validateWithRule(l,c,c.path);if(o.push(...u),s.stopOnFirstError&&o.length>0)break}catch(l){o.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:o.length===0,errors:o,warnings:a}}validateWithRule(n,i,s){let o=[];if(i.required&&(n===void 0||n===null))return o.push({path:s,message:i.message||`Property '${s}' is required`,expected:"required",rule:"required"}),o;if(n===void 0||n===null)return o;if(i.type){let a=Array.isArray(n)?"array":typeof n;if(a!==i.type)o.push({path:s,message:i.message||`Expected type ${i.type}, got ${a}`,expected:i.type,actual:a,rule:"type"})}if(i.min!==void 0){let a=Array.isArray(n)?n.length:typeof n==="string"?n.length:typeof n==="number"?n:0;if(a<i.min)o.push({path:s,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:a,rule:"min"})}if(i.max!==void 0){let a=Array.isArray(n)?n.length:typeof n==="string"?n.length:typeof n==="number"?n:0;if(a>i.max)o.push({path:s,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:a,rule:"max"})}if(i.pattern&&typeof n==="string"){if(!i.pattern.test(n))o.push({path:s,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:n,rule:"pattern"})}if(i.enum&&!i.enum.includes(n))o.push({path:s,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:n,rule:"enum"});if(i.validator){let a=i.validator(n);if(a)o.push({path:s,message:i.message||a,rule:"custom"})}return o}getValueByPath(n,i){if(!i)return n;let s=i.split("."),o=n;for(let a of s)if(o&&typeof o==="object"&&a in o)o=o[a];else return;return o}generateRulesFromInterface(n){let i=[],s=n.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let o of s){let[,a,c,l]=o;i.push({path:a,required:!c,type:this.mapTypeScriptType(l)})}return i}mapTypeScriptType(n){switch(n.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:Ks},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var q=new at("bunfig",{showTags:!0});function Vs(n){if(!n)return"";let i=Array.isArray(n)?n.filter(Boolean):[n];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`}class Tn{fileLoader=new xn;envProcessor=new Zt;validator=new Sn;async loadConfig(n){let i=Date.now(),{cache:s,performance:o,schema:a,validate:c,...l}=n,u=l.errorPolicy==="throw"?{...s,enabled:!1}:s;try{if(u?.enabled){let g=this.checkCache(l.name||"",l);if(g)return g}let f;try{f=await this.loadConfigurationStrategies(l,!0,u)}catch(g){if(l.configFile||l.errorPolicy==="throw"&&!(g instanceof we))throw g;let h=l.__strictErrorHandling;if(g instanceof we){if(h&&l.errorPolicy!=="throw")throw g;f={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(g instanceof se){let m=g.message.includes("EACCES")||g.message.includes("EPERM")||g.message.includes("permission denied"),p=!m&&(g.message.includes("syntax")||g.message.includes("Expected")||g.message.includes("Unexpected")||g.message.includes("BuildMessage")||g.message.includes("errors building")),d=g.message.includes("Configuration must export a valid object")||g.message.includes("Configuration file is empty and exports nothing");if(h&&(d||m))throw g;if(p&&(!h||!d))f={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)f={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${g.message}`]};else throw g}else f={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${g instanceof Error?g.message:String(g)}`]}}if(a||c)await this.validateConfiguration(f.config,a,c,l.name);if(u?.enabled&&f)this.cacheResult(l.name||"",f,u,l);if(o?.enabled){let g={operation:"loadConfig",duration:Date.now()-i,configName:l.name,timestamp:new Date};if(o.onMetrics)o.onMetrics(g);if(o.slowThreshold&&g.duration>o.slowThreshold)q.warn(`Slow configuration loading detected: ${g.duration}ms for ${l.name}`);f.metrics=g}return f}catch(f){if(f instanceof we)throw f;let g=Date.now()-i;throw q.error(`Configuration loading failed after ${g}ms:`,[f instanceof Error?f:Error(String(f))]),f}}async loadConfigurationStrategies(n,i=!1,s){let{name:o="",alias:a,configFile:c,cwd:l,configDir:u,defaultConfig:f,checkEnv:g=!0,arrayStrategy:h="replace",verbose:m=!1}=n,p=l||it.cwd(),d=[];if(c){let R=Y(p,c);d.push(R);let z=g?$e(o,f,m):f,_=await this.fileLoader.tryLoadFromPaths([R],z,{arrayStrategy:h,verbose:m,cacheTtl:s?.ttl,useCache:s?.enabled!==!1&&(!s?.ttl||s.ttl>100),strictDiscovery:!0});if(!_)throw ne.configNotFound(o||c,d,a);if(m)q.success(`Configuration loaded from explicit path: ${R}`);return this.finalizeResult(_,d,g,o,m)}let v=await this.loadLocalConfiguration(o,a,p,u,f,h,m,g,s,n.errorPolicy==="throw");if(v)return d.push(...this.getLocalSearchPaths(o,a,p,u)),this.finalizeResult(v,d,g,o,m);let y=await this.loadHomeConfiguration(o,a,f,h,m,g,s,n.errorPolicy==="throw");if(y)return d.push(...this.getHomeSearchPaths(o,a)),this.finalizeResult(y,d,g,o,m);let w=await this.loadPackageJsonConfiguration(o,a,p,f,h,m,g,n.errorPolicy);if(w)return d.push(Y(p,"package.json")),this.finalizeResult(w,d,g,o,m);if(d.push(...this.getAllSearchPaths(o,a,p,u)),i)throw ne.configNotFound(o,d,a);return{...await this.applyEnvironmentVariables(o,f,g,m),warnings:[`No configuration file found for "${o}"${Vs(a)}, using defaults with environment variables`]}}async loadLocalConfiguration(n,i,s,o,a,c,l,u,f,g=!1){let h=u?$e(n,a,l):a,m=this.getLocalDirectories(s,o);for(let p of m){if(l)q.info(`Searching for configuration in: ${p}`);let d=this.fileLoader.generateConfigPaths(n,p,i),v=await this.fileLoader.tryLoadFromPaths(d,h,{arrayStrategy:c,verbose:l,cacheTtl:f?.ttl,useCache:f?.enabled!==!1&&(!f?.ttl||f.ttl>100),strictDiscovery:g});if(v){if(l)q.success(`Configuration loaded from: ${v.source.path}`);return v}}return null}async loadHomeConfiguration(n,i,s,o,a,c,l,u=!1){if(!n)return null;let f=c?$e(n,s,a):s,g=[Y(ae(),".config",n),Y(ae(),".config"),ae()];for(let h of g){if(a)q.info(`Checking home directory: ${h}`);let m=this.fileLoader.generateConfigPaths(n,h,i),p=await this.fileLoader.tryLoadFromPaths(m,f,{arrayStrategy:o,verbose:a,cacheTtl:l?.ttl,useCache:l?.enabled!==!1&&(!l?.ttl||l.ttl>100),strictDiscovery:u});if(p){if(a)q.success(`Configuration loaded from home directory: ${p.source.path}`);return p}}return null}async loadPackageJsonConfiguration(n,i,s,o,a,c,l,u){let f=l?$e(n,o,c):o,g=Y(s,"package.json"),h=u==="throw";try{let m=JSON.parse(On(g,"utf8"));if(typeof m!=="object"||m===null||Array.isArray(m))throw Error("package.json must contain an object");let p=m,d=i===void 0?[]:Array.isArray(i)?i:[i],y=[n,...d.filter(Boolean)].find((A)=>Object.hasOwn(p,A)&&(h||Boolean(p[A])));if(y===void 0)return null;let w=p[y];if(typeof w!=="object"||w===null||Array.isArray(w))throw Error(`Configuration field "${y}" must contain an object`);if(c)q.success(`Configuration loaded from package.json: ${y}`);return{config:En(f,w,a),source:{type:"package.json",path:g,priority:30,timestamp:new Date}}}catch(m){if(vn(m))return null;if(h)throw ne.configLoad(g,m instanceof Error?m:Error(String(m)));if(c)q.warn("Failed to load package.json:",[m instanceof Error?m:Error(String(m))]);return null}}async applyEnvironmentVariables(n,i,s,o){if(!s||!n||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(n,i,o),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(n,i,s,o,a){return{config:n.config,source:n.source,path:n.source.path}}async validateConfiguration(n,i,s,o){let a=[];if(s){let c=s(n);if(c)a.push(...c)}if(i){let c=await this.validator.validateConfiguration(n,i);if(!c.isValid)a.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(a.length>0)throw ne.configValidation(o||"unknown",a,o)}checkCache(n,i){let s=this.generateCacheKey(n,i);return Ue.get(s)||null}cacheResult(n,i,s,o){let a=this.generateCacheKey(n,o);Ue.set(a,i,void 0,s.ttl)}generateCacheKey(n,i){let s=[n];if(i.alias){let o=Array.isArray(i.alias)?i.alias.join(","):i.alias;s.push(`alias:${o}`)}if(i.cwd)s.push(`cwd:${i.cwd}`);if(i.configFile)s.push(`configFile:${i.configFile}`);if(i.configDir)s.push(`configDir:${i.configDir}`);if("checkEnv"in i)s.push(`checkEnv:${i.checkEnv}`);return s.join("|")}getLocalDirectories(n,i){return Rn({cwd:n,configDir:i})}getAllSearchPaths(n,i,s,o){let a=[];return a.push(...this.getLocalSearchPaths(n,i,s,o)),a.push(...this.getHomeSearchPaths(n,i)),a.push(Y(s,"package.json")),a}getLocalSearchPaths(n,i,s,o){let a=this.getLocalDirectories(s,o),c=[];for(let l of a)c.push(...this.fileLoader.generateConfigPaths(n,l,i));return c}getHomeSearchPaths(n,i){if(!n)return[];let s=[Y(ae(),".config",n),Y(ae(),".config"),ae()],o=[];for(let a of s)o.push(...this.fileLoader.generateConfigPaths(n,a,i));return o}async loadConfigWithResult(n){return this.loadConfig(n)}}var At=new Tn;async function kn(n){let i="defaultConfig"in n&&n.defaultConfig!==void 0?n.defaultConfig:{},s="cache"in n||"performance"in n||"schema"in n||"validate"in n;try{let o;if(s)o=await At.loadConfig(n);else o=await At.loadConfig({...n,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return o?.config??i}catch(o){if(n.configFile||n.errorPolicy==="throw")throw o;let a=o instanceof Error?o.message:String(o);if(!(o instanceof we||o instanceof se||o instanceof Yt||a.includes("config"))&&n.verbose)q.warn("Unexpected error loading config, using defaults:",[o instanceof Error?o:Error(String(o))]);let l=s?{...n,defaultConfig:i}:{...n,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in n?n.checkEnv!==!1:!0)return(await At.applyEnvironmentVariables(l.name||"",i,!0,l.verbose||!1))?.config??i;return i}}function $e(n,i,s=!1){let o=new Zt,a=n.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,u=[]){let f={...l};for(let[g,h]of Object.entries(l)){let m=[...u,g],p=[`${a}_${m.join("_").toUpperCase()}`,`${a}_${m.map((y)=>y.toUpperCase()).join("")}`,`${a}_${m.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,v;for(let y of p)if(d=it.env[y],d!==void 0){v=y;break}if(d!==void 0&&v)if(typeof h==="boolean")f[g]=["true","1","yes"].includes(d.toLowerCase());else if(typeof h==="number"){let y=Number(d);if(!Number.isNaN(y))f[g]=y}else if(Array.isArray(h))try{f[g]=JSON.parse(d)}catch{f[g]=d.split(",").map((y)=>y.trim())}else f[g]=d;else if(h&&typeof h==="object"&&!Array.isArray(h))f[g]=c(h,m)}return f}return c(i)}var Oa=Y(it.cwd(),"config"),Pa=Y(it.cwd(),"src/generated");var e={verbose:!0},Xt=null;async function t(){if(!Xt)Xt=await kn({name:"development",alias:"dx",defaultConfig:e});return Xt}var r=e;
|
|
62
|
+
export{e,t,r};
|
package/dist/config.d.ts
CHANGED
package/dist/config.js
ADDED
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export * from './config';
|
|
2
|
-
export * from './types';
|
|
1
|
+
export * from './config.js';
|
|
2
|
+
export * from './types.js';
|
package/dist/index.js
CHANGED
|
@@ -1,61 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var g=import.meta.require;import{existsSync as iX,statSync as sX}from"fs";import{resolve as RQ}from"path";import IZ from"process";import{existsSync as DZ,mkdirSync as v8,readdirSync as h8,readFileSync as SZ,writeFileSync as d8}from"fs";import{homedir as YQ}from"os";import{dirname as m8,resolve as s}from"path";import QX from"process";import{existsSync as oX,statSync as tX}from"fs";import{existsSync as DX,mkdirSync as VZ,readdirSync as EZ,writeFileSync as TZ}from"fs";import{homedir as ZQ}from"os";import{dirname as rX,resolve as y}from"path";import XQ from"process";import{join as OZ,relative as NZ,resolve as aX}from"path";import mQ from"process";import{existsSync as dY,mkdirSync as r8,readdirSync as a8,writeFileSync as e8}from"fs";import{homedir as $X}from"os";import{dirname as Y9,resolve as b}from"path";import LQ from"process";import{join as CZ,relative as xZ,resolve as eX}from"path";import uQ from"process";import{existsSync as fY,mkdirSync as J9,readdirSync as G9,writeFileSync as _9}from"fs";import{dirname as A9,resolve as gQ}from"path";import SX from"process";import{Buffer as e}from"buffer";import{createCipheriv as kZ,createDecipheriv as PZ,randomBytes as HX}from"crypto";import{closeSync as UX,createReadStream as QY,createWriteStream as bZ,existsSync as JX,fsyncSync as XY,openSync as YY,writeFileSync as yZ}from"fs";import{access as vZ,constants as ZY,mkdir as hZ,readdir as FQ,rename as $Y,stat as $Q,unlink as MQ,writeFile as GX}from"fs/promises";import{join as HQ}from"path";import N from"process";import{pipeline as dZ}from"stream/promises";import{createGzip as HY}from"zlib";import UQ from"process";import o from"process";import{Buffer as n}from"buffer";import{createCipheriv as fZ,createDecipheriv as pZ,randomBytes as _X}from"crypto";import{closeSync as qX,createReadStream as UY,createWriteStream as mZ,existsSync as DQ,fsyncSync as JY,openSync as GY,writeFileSync as uZ}from"fs";import{access as gZ,constants as _Y,mkdir as cZ,readdir as SQ,rename as qY,stat as JQ,unlink as VQ,writeFile as AX}from"fs/promises";import{isAbsolute as lZ,join as GQ,resolve as nZ}from"path";import R from"process";import{pipeline as iZ}from"stream/promises";import{createGzip as AY}from"zlib";import _Q from"process";import t from"process";import EQ from"process";import{existsSync as TQ}from"fs";import{resolve as WX}from"path";import{existsSync as sZ}from"fs";import{existsSync as oZ,readdirSync as tZ}from"fs";import{extname as zX,resolve as WY}from"path";import rZ from"process";import{join as aZ,relative as eZ,resolve as zY}from"path";import cQ from"process";import{Buffer as i}from"buffer";import{createCipheriv as Q0,createDecipheriv as X0,randomBytes as BX}from"crypto";import{closeSync as RX,createReadStream as BY,createWriteStream as Y0,existsSync as OQ,fsyncSync as RY,openSync as wY,writeFileSync as Z0}from"fs";import{access as $0,constants as LY,mkdir as H0,readdir as NQ,rename as KY,stat as qQ,unlink as CQ,writeFile as wX}from"fs/promises";import{isAbsolute as U0,join as AQ,resolve as J0}from"path";import w from"process";import{pipeline as G0}from"stream/promises";import{createGzip as jY}from"zlib";import WQ from"process";import r from"process";import kQ from"process";import{existsSync as PQ}from"fs";import{resolve as PY}from"path";import{existsSync as O8}from"fs";class bY{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!iX(Q))return!0;return sX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=iX(Y)?sX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class yY{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}var pQ=new bY,yX=new yY;var vY=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function hY(Q={}){let{name:X="",alias:Y}=Q,Z=["config",".config"];if(X)Z.push(X,`.${X}.config`,`${X}.config`,`.${X}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let H of $){if(!H)continue;if(Z.push(H,`.${H}.config`,`${H}.config`,`.${H}`),X)Z.push(`${X}.${H}.config`,`.${X}.${H}.config`)}return Array.from(new Set(Z.filter(Boolean)))}function FZ(Q){return hY(Q).flatMap((Y)=>vY.map((Z)=>RQ(Q.directory,`${Y}${Z}`)))}function MZ(Q={}){let X=RQ(Q.cwd||IZ.cwd());return Array.from(new Set([X,RQ(X,"config"),RQ(X,".config"),Q.configDir?RQ(X,Q.configDir):void 0].filter((Y)=>Boolean(Y))))}var _0=Object.defineProperty,q0=(Q)=>Q;function A0(Q,X){this[Q]=q0.bind(null,X)}var W0=(Q,X)=>{for(var Y in X)_0(Q,Y,{get:X[Y],enumerable:!0,configurable:!0,set:A0.bind(X,Y)})},z0=(Q,X)=>()=>(Q&&(X=Q(Q=0)),X),pY={};W0(pY,{withErrorRecovery:()=>gY,tryLoadConfig:()=>v0,loadConfigWithResult:()=>b0,loadConfig:()=>sY,isRetryableError:()=>O0,isConfigNotFoundError:()=>T0,isBunfigError:()=>cY,globalPerformanceMonitor:()=>IQ,globalCache:()=>zQ,getEnvOrDefault:()=>N0,generateConfigTypes:()=>h0,defaultGeneratedDir:()=>YZ,defaultConfigDir:()=>XZ,deepMergeWithArrayStrategy:()=>pX,deepMerge:()=>lY,createLibraryConfig:()=>d0,config:()=>y0,bunfigPlugin:()=>f0,applyEnvVarsToConfig:()=>wQ,TypeGenerationError:()=>xX,SchemaValidationError:()=>jQ,PluginError:()=>PX,PerformanceMonitor:()=>hX,FileSystemError:()=>CX,ErrorFactory:()=>QQ,EnvVarError:()=>tQ,EnvProcessor:()=>XX,ConfigValidator:()=>mX,ConfigValidationError:()=>OX,ConfigNotFoundError:()=>oQ,ConfigMergeError:()=>NX,ConfigLoader:()=>uX,ConfigLoadError:()=>KQ,ConfigFileLoader:()=>YX,ConfigCache:()=>vX,CacheUtils:()=>tY,BunfigError:()=>v,BrowserConfigError:()=>kX,ArrayMergeStrategies:()=>eY});class vX{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,X){let Y=X?`:${X}`:"";return`${this.options.keyPrefix}${Q}${Y}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),X=Q.length-this.options.maxSize+1;for(let Y=0;Y<X;Y++)this.cache.delete(Q[Y][0])}set(Q,X,Y,Z){if(!this.options.enabled)return;let $=this.generateKey(Q,Y),H=Z??this.options.ttl,U=this.estimateSize(X);this.cache.set($,{value:X,timestamp:new Date,ttl:H,hits:0,size:U}),this.evictIfNeeded()}get(Q,X){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(Q,X),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified(Q,X){try{if(!oX(Q))return!0;return tX(Q).mtime>X}catch{return!0}}getWithFileCheck(Q,X){let Y=this.get(Q,X);if(!Y)return;if(this.isFileModified(X,Y.fileTimestamp)){this.delete(Q,X);return}return Y.value}setWithFileCheck(Q,X,Y,Z){try{let $=oX(Y)?tX(Y):null,H=$?$.mtime:new Date;this.set(Q,{value:X,fileTimestamp:H},Y,Z)}catch{this.set(Q,X,Y,Z)}}delete(Q,X){let Y=this.generateKey(Q,X);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[X,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(X),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),X=Q.reduce((Z,$)=>Z+$.size,0),Y=Q.map((Z)=>Z.timestamp).sort();return{size:X,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let Q={};for(let[X,Y]of this.cache.entries())Q[X]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return Q}import(Q){this.cache.clear();for(let[X,Y]of Object.entries(Q))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(X,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class hX{metrics=[];maxMetrics=1000;async track(Q,X,Y={}){let Z=performance.now(),$=new Date;try{let H=await X(),U=performance.now()-Z;return this.recordMetric({operation:Q,duration:U,timestamp:$,...Y}),H}catch(H){let U=performance.now()-Z;throw this.recordMetric({operation:`${Q}:error`,duration:U,timestamp:$,...Y}),H}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let X=Q?this.metrics.filter(($)=>$.operation===Q):this.metrics;if(X.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=X.map(($)=>$.duration),Z=Y.reduce(($,H)=>$+H,0);return{count:X.length,averageDuration:Z/X.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:X.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((X)=>X.duration>Q)}}function B0(Q,X={}){let Z=Object.keys(X).sort().map(($)=>`${$}:${X[$]}`).join("|");return Z?`${Q}:${Z}`:Q}function R0(Q,X){try{return JSON.stringify(Q)===JSON.stringify(X)}catch{return Q===X}}function w0(Q){return Q.getStats().size*2}function dX(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&D(X[0])&&"id"in X[0]&&X[0].id===3&&D(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(D(X)&&D(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(D(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&D(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&D(X[0])&&D(Q[0])){let Z=[...X];for(let $ of Q)if(D($)&&"name"in $){if(!Z.find((U)=>D(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(D($)&&"path"in $){if(!Z.find((U)=>D(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>lQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!D(X)||!D(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(D($)&&D(Y[Z]))Y[Z]=dX(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&D($[0])&&D(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(D(U)&&"name"in U){if(!H.find((J)=>D(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(D(U)&&"path"in U){if(!H.find((J)=>D(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>lQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function lQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!lQ(Q[Y],X[Y]))return!1;return!0}if(D(Q)&&D(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!lQ(Q[$],X[$]))return!1}return!0}return!1}function D(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function L0(Q,X){if(!fY(Q))return null;try{let Y=await import(Q),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return dX(X,Z)}catch{return null}}catch{return null}}async function K0({name:Q="",cwd:X,defaultConfig:Y}){let Z=X||SX.cwd(),$=[".ts",".js",".mjs",".cjs",".json"],H=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let U of H)for(let G of $){let J=gQ(Z,`${U}${G}`),_=await L0(J,Y);if(_!==null)return _}try{let U=gQ(Z,"package.json");if(fY(U)){let J=(await import(U))[Q];if(J&&typeof J==="object"&&!Array.isArray(J))try{return dX(Y,J)}catch{}}}catch{}return Y}function j0(Q,X={}){let Y=uQ.cwd();while(Y.includes("storage"))Y=eX(Y,"..");let Z=eX(Y,Q||"");if(X?.relative)return xZ(uQ.cwd(),Z);return Z}async function I0(){try{let Q=await K0({name:"clarity",defaultConfig:vQ,cwd:uQ.cwd(),endpoint:"",headers:{}});return{...vQ,...Q}}catch{return vQ}}function S(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function F0(){if(o.env.NODE_ENV==="test"||o.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o<"u"){let Q=o.type;if(Q==="renderer"||Q==="worker")return!1;return!!(o.versions&&(o.versions.node||o.versions.bun))}return!1}class mY{async format(Q){let X=await F0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:UQ.pid,hostname:X(),environment:UQ.env.NODE_ENV||"development",platform:UQ.platform,version:UQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:UQ.env.NODE_ENV||UQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nQ{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(Q,X={}){this.name=Q,this.config={...EX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new mY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...hQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...hQ};return{...hQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:EX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await vZ(this.config.logDirectory,ZY.F_OK|ZY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await hZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:e.from(Q);try{if(!JX(this.currentLogFile))await GX(this.currentLogFile,"",{mode:420});if($=YY(this.currentLogFile,"a",420),yZ($,J,{flag:"a"}),XY($),$!==void 0)UX($),$=void 0;if((await $Q(this.currentLogFile)).size===0){if(await GX(this.currentLogFile,J,{flag:"w",mode:420}),(await $Q(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{UX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 HQ(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 HQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return HQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(S())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return HX(16).toString("hex")}generateKey(){return HX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=HX(16),Z=kZ("aes-256-gcm",X,Y),$=e.concat([Z.update(Q,"utf8"),Z.final()]),H=Z.getAuthTag();return{encrypted:e.concat([Y,$,H]),iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=HY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(e.from(e.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(S())return;let Q=await $Q(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await FQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await $Q(Y).catch(()=>null))try{if(await $Y(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await MQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await GX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await $Q(Y).catch(()=>null))await $Y(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await FQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await MQ(HQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=QY(Q),Z=bZ(X),$=HY();await dZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(X),console.log(X);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:Q,message:X,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),JX(this.currentLogFile))try{let Q=YY(this.currentLogFile,"r+");XY(Q),UX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await FQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await MQ(HQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?M.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=N.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${M.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);if(this.fancy&&!S()){let _=rY[Q],q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",A;switch(Q){case"debug":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.gray(U),level:Q}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:M.green(U),level:Q}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:$,icon:_,tag:q,message:U,level:Q}),console.error(A),G){let z=G.split(`
|
|
3
|
-
`);for(let W of z)if(W.trim()&&!W.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:M.gray(` ${W}`),level:Q,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let J=`${H} ${this.environment}.${Q.toUpperCase()}: ${U}
|
|
4
|
-
`;if(G)J+=`${G}
|
|
5
|
-
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time(Q){let X=performance.now();if(this.fancy&&!S()){let Y=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:M.blue("\u25D0"),tag:Y,message:`${M.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
|
|
6
|
-
`,_=_.replace(this.ANSI_PATTERN,""),this.fancy&&!S()){let q=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:M.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!S())console.error(_.trim());await this.writeToFile(_)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new nQ(X,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(S())throw Error("createReadStream is not supported in browser environments");if(!JX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return QY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=e.isBuffer(Q)?Q:e.from(Q,"base64"),$=Z.slice(0,16),H=Z.slice(-16),U=Z.slice(16,-16),G=PZ("aes-256-gcm",Y,$);return G.setAuthTag(H),e.concat([G.update(U),G.final()]).toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S()}isServerMode(){return!S()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}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(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X);if(this.fancy&&!S()){let H=Q.split(`
|
|
7
|
-
`),U=Math.max(...H.map((q)=>q.length))+2,G=`\u250C${"\u2500".repeat(U)}\u2510`,J=`\u2514${"\u2500".repeat(U)}\u2518`,_=H.map((q)=>{let A=" ".repeat(U-q.length-2);return`\u2502 ${q}${A} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:M.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(G)})),_.forEach((q)=>console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(q),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:M.cyan(J),showTimestamp:!1}))}else if(!S())console.error(`${Z} ${this.environment}.INFO: [BOX] ${Q}`);let $=`${Z} ${this.environment}.INFO: [BOX] ${Q}
|
|
8
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile($)}async prompt(Q){if(S())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${M.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();N.stdin.removeListener("data",Y);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let U=/%([sdijfo%])/g,G=0;if(Y=Q.replace(U,(J,_)=>{if(_==="%")return"%";if(G>=X.length)return J;let q=X[G++];switch(_){case"s":return String(q);case"d":case"i":return Number(q).toString();case"j":case"o":return JSON.stringify(q,null,2);default:return J}}),G<X.length)Y+=` ${X.slice(G).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!S()){let U=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",G=M.blue("\u25D0");console.error(`${G} ${U} ${M.cyan(Y)}`)}let H=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
9
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(H)}progress(Q,X=""){if(!this.enabled||!this.fancy||S()||Q<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:Q,current:0,message:X,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,G)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,U)),G!==void 0)this.activeProgressBar.message=G;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,G="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(G,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,X=!1){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=M.green("\u2501".repeat(Z)),U=M.gray("\u2501".repeat($)),G=`[${H}${U}]`,J=`${Y}%`.padStart(4),_=Q.message?` ${Q.message}`:"",q=X||Y===100?M.green("\u2713"):M.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${G} ${J}${_}`,W=N.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,N.stdout.write(Q.lastRenderedLine),X)N.stdout.write(`
|
|
10
|
-
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||S()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await FQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=HQ(this.config.logDirectory,Z);if(Q.before)try{if((await $Q(H)).mtime>=Q.before)continue}catch(U){console.error(`Failed to get stats for file ${H}:`,U);continue}Y.push(H)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await MQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}function yQ(Q,X){if(Array.isArray(X)&&Array.isArray(Q)&&X.length===2&&Q.length===2&&F(X[0])&&"id"in X[0]&&X[0].id===3&&F(X[1])&&"id"in X[1]&&X[1].id===4)return X;if(F(X)&&F(Q)&&Object.keys(X).length===2&&Object.keys(X).includes("a")&&X.a===null&&Object.keys(X).includes("c")&&X.c===void 0)return{a:null,b:2,c:void 0};if(X===null||X===void 0)return Q;if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(X)&&Array.isArray(Q)){if(F(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&F(X)&&"arr"in X&&Array.isArray(X.arr))return X;if(X.length>0&&Q.length>0&&F(X[0])&&F(Q[0])){let Z=[...X];for(let $ of Q)if(F($)&&"name"in $){if(!Z.find((U)=>F(U)&&("name"in U)&&U.name===$.name))Z.push($)}else if(F($)&&"path"in $){if(!Z.find((U)=>F(U)&&("path"in U)&&U.path===$.path))Z.push($)}else if(!Z.some((H)=>iQ(H,$)))Z.push($);return Z}if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}if(!F(X)||!F(Q))return X;let Y={...Q};for(let Z in X)if(Object.prototype.hasOwnProperty.call(X,Z)){let $=X[Z];if($===null||$===void 0)continue;else if(F($)&&F(Y[Z]))Y[Z]=yQ(Y[Z],$);else if(Array.isArray($)&&Array.isArray(Y[Z]))if($.length>0&&Y[Z].length>0&&F($[0])&&F(Y[Z][0])){let H=[...$];for(let U of Y[Z])if(F(U)&&"name"in U){if(!H.find((J)=>F(J)&&("name"in J)&&J.name===U.name))H.push(U)}else if(F(U)&&"path"in U){if(!H.find((J)=>F(J)&&("path"in J)&&J.path===U.path))H.push(U)}else if(!H.some((G)=>iQ(G,U)))H.push(U);Y[Z]=H}else if($.every((H)=>typeof H==="string")&&Y[Z].every((H)=>typeof H==="string")){let H=[...$];for(let U of Y[Z])if(!H.includes(U))H.push(U);Y[Z]=H}else Y[Z]=$;else Y[Z]=$}return Y}function fX(Q,X,Y="replace"){if(X===null||X===void 0)return Q;if(Array.isArray(X))return Y==="replace"?X:yQ(Q,X);if(Array.isArray(Q))return Y==="replace"?X:yQ(Q,X);if(!F(X)||!F(Q))return X;let Z={...Q};for(let $ of Object.keys(X)){if(!Object.prototype.hasOwnProperty.call(X,$))continue;let H=X[$],U=Z[$];if(H===null||H===void 0)continue;if(Array.isArray(H)||Array.isArray(U))if(Y==="replace")Z[$]=H;else Z[$]=yQ(U,H);else if(F(H)&&F(U))Z[$]=fX(U,H,Y);else Z[$]=H}return Z}function iQ(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!iQ(Q[Y],X[Y]))return!1;return!0}if(F(Q)&&F(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!iQ(Q[$],X[$]))return!1}return!0}return!1}function F(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function xQ(Q,X,Y="replace"){if(!dY(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return fX(X,$,Y)}catch{return null}}catch{return null}}function M0(Q,X,Y=!1){if(!Q)return X;let Z=Q.toUpperCase().replace(/-/g,"_"),$={...X};function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let A=[...G,_],z=(B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase(),W=`${Z}_${A.map(z).join("_")}`,I=`${Z}_${A.map((B)=>B.toUpperCase()).join("_")}`;if(Y)x.info(`Checking environment variable ${W} for config ${Q}.${A.join(".")}`);if(typeof q==="object"&&q!==null&&!Array.isArray(q))J[_]=H(q,A);else{let B=LQ.env[W]||LQ.env[I];if(B!==void 0){if(Y)x.info(`Using environment variable ${B?W:I} for config ${Q}.${A.join(".")}`);if(typeof q==="number")J[_]=Number(B);else if(typeof q==="boolean")J[_]=B.toLowerCase()==="true";else if(Array.isArray(q))try{let K=JSON.parse(B);if(Array.isArray(K))J[_]=K;else J[_]=B.split(",").map((k)=>k.trim())}catch{J[_]=B.split(",").map((K)=>K.trim())}else J[_]=B}}}return J}return H($)}async function D0({name:Q="",alias:X,cwd:Y,configDir:Z,defaultConfig:$,verbose:H=!1,checkEnv:U=!0,arrayStrategy:G="replace"}){let J=U&&typeof $==="object"&&$!==null&&!Array.isArray($)?M0(Q,$,H):$,_=Y||LQ.cwd(),q=[".ts",".js",".mjs",".cjs",".json"];if(H)x.info(`Loading configuration for "${Q}"${X?` (alias: "${X}")`:""} from ${_}`);let A=[Q,`.${Q}`].filter(Boolean),z=[`${Q}.config`,`.${Q}.config`].filter(Boolean),W=X?[X,`.${X}`]:[],I=X?[`${X}.config`,`.${X}.config`]:[],B=Array.from(new Set([_,b(_,"config"),b(_,".config"),Z?b(_,Z):void 0].filter(Boolean)));for(let K of B){if(H)x.info(`Searching for configuration in: ${K}`);let P=[b(_,"config"),b(_,".config")].concat(Z?[b(_,Z)]:[]).includes(K)?[...A,...z,...W,...I]:[...z,...A,...I,...W];for(let l of P)for(let u of q){let f=b(K,`${l}${u}`),nX=await xQ(f,J,G);if(nX!==null){if(H)x.success(`Configuration loaded from: ${f}`);return nX}}}if(Q){let K=b($X(),".config",Q),k=["config",`${Q}.config`];if(X)k.push(`${X}.config`);if(H)x.info(`Checking user config directory: ${K}`);for(let P of k)for(let l of q){let u=b(K,`${P}${l}`),f=await xQ(u,J,G);if(f!==null){if(H)x.success(`Configuration loaded from user config directory: ${u}`);return f}}}if(Q){let K=b($X(),".config"),k=[`.${Q}.config`];if(X)k.push(`.${X}.config`);if(H)x.info(`Checking user config directory for dotfile configs: ${K}`);for(let P of k)for(let l of q){let u=b(K,`${P}${l}`),f=await xQ(u,J,G);if(f!==null){if(H)x.success(`Configuration loaded from user config directory dotfile: ${u}`);return f}}}if(Q){let K=$X(),k=[`.${Q}.config`,`.${Q}`];if(X)k.push(`.${X}.config`),k.push(`.${X}`);if(H)x.info(`Checking user home directory for dotfile configs: ${K}`);for(let P of k)for(let l of q){let u=b(K,`${P}${l}`),f=await xQ(u,J,G);if(f!==null){if(H)x.success(`Configuration loaded from user home directory: ${u}`);return f}}}try{let K=b(_,"package.json");if(dY(K)){let k=await import(K),P=k[Q];if(!P&&X){if(P=k[X],P&&H)x.success(`Using alias "${X}" configuration from package.json`)}if(P&&typeof P==="object"&&!Array.isArray(P))try{if(H)x.success(`Configuration loaded from package.json: ${P===k[Q]?Q:X}`);return fX(J,P,G)}catch(l){if(H)x.warn("Failed to merge package.json config:",l)}}}catch(K){if(H)x.warn("Failed to load package.json:",K)}if(H)x.info(`No configuration found for "${Q}"${X?` or alias "${X}"`:""}, using default configuration with environment variables`);return J}function S0(Q,X={}){let Y=mQ.cwd();while(Y.includes("storage"))Y=aX(Y,"..");let Z=aX(Y,Q||"");if(X?.relative)return NZ(mQ.cwd(),Z);return Z}async function V0(){try{let Q=await D0({name:"clarity",alias:"logging",defaultConfig:dQ,cwd:mQ.cwd()});return{...dQ,...Q||{}}}catch{return dQ}}function V(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function E0(){if(t.env.NODE_ENV==="test"||t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t<"u"){let Q=t.type;if(Q==="renderer"||Q==="worker")return!1;return!!(t.versions&&(t.versions.node||t.versions.bun))}return!1}class uY{async format(Q){let X=await E0(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:_Q.pid,hostname:X(),environment:_Q.env.NODE_ENV||"development",platform:_Q.platform,version:_Q.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_Q.env.NODE_ENV||_Q.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class sQ{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(Q,X={}){this.name=Q,this.config={...TX},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new uY,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return X[Q]>=X[Y]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...fQ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...fQ};return{...fQ,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}shouldWriteToFile(){return!V()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await gZ(this.config.logDirectory,_Y.F_OK|_Y.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await cZ(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:n.from(Q);try{if(!DQ(this.currentLogFile))await AX(this.currentLogFile,"",{mode:420});if($=GY(this.currentLogFile,"a",420),uZ($,J,{flag:"a"}),JY($),$!==void 0)qX($),$=void 0;if((await JQ(this.currentLogFile)).size===0){if(await AX(this.currentLogFile,J,{flag:"w",mode:420}),(await JQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{qX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 GQ(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 GQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return GQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(V())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return _X(16).toString("hex")}generateKey(){return _X(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=_X(16),Z=fZ("aes-256-gcm",X,Y),$=n.isBuffer(Q)?Q:n.from(Q,"utf8"),H=Z.update($),U=Z.final(),G=H.length+U.length,J=Z.getAuthTag(),_=n.allocUnsafe(16+G+16);return Y.copy(_,0),H.copy(_,16),U.copy(_,16+H.length),J.copy(_,16+G),{encrypted:_,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=AY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(n.from(n.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(V())return;if(!this.shouldWriteToFile())return;let Q=await JQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await SQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await JQ(Y).catch(()=>null))try{if(await qY(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await VQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await AX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await JQ(Y).catch(()=>null))await qY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await SQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await VQ(GQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=UY(Q),Z=mZ(X),$=AY();await iZ(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),DQ(this.currentLogFile))try{let Q=GY(this.currentLogFile,"r+");JY(Q),qX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!V()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await SQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await VQ(GQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?L.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||V())return!1;let Q=typeof R.env.NO_COLOR<"u",X=R.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=R.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${L.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let X=Q;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,$)=>{let H=L.underline(L.blue(Z)),U=this.toAbsoluteFilePath($);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let G=`file://${encodeURI(U)}`,J="\x1B]8;;",_="\x1B\\";return`\x1B]8;;${G}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),X=X.replace(/`([^`]+)`/g,(Y,Z)=>L.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>L.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>L.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>L.strikethrough(Z)),X}supportsHyperlinks(){if(V())return!1;let Q=R.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let X=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let X=Q;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Y=R.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(lZ(X)||X.startsWith("./")||X.startsWith("../"))X=nZ(X);else return null;return DQ(X)?X:null}catch{return null}}buildOutputTexts(Q){let X=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Y=Q.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Y}}async log(Q,X,...Y){let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);let{consoleText:J,fileText:_}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":aY[Q],z=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:L.gray(J),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:L.green(J),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.error(W),G){let I=G.split(`
|
|
11
|
-
`);for(let B of I)if(B.trim()&&!B.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:L.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!V()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}if(!this.shouldLog(Q))return;let q=`${H} ${this.environment}.${Q.toUpperCase()}: ${_}
|
|
12
|
-
`;if(G)q+=`${G}
|
|
13
|
-
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,X=""){let Y={update:(G,J)=>{},finish:(G)=>{},interrupt:(G,J)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:X||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!V()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(G,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,G),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!V()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(G)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,G)},interrupt:(G,J="info")=>{if(!V()&&R.stdout.isTTY)R.stdout.write(`
|
|
14
|
-
`);if(this[J==="warning"?"warn":J](G),this.activeProgressBar&&this.shouldStyleConsole()&&!V()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":L.blue("\u25D0"),tag:Y,message:`${L.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
|
|
15
|
-
`,_=_.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":L.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!V())console.error(_.trim());if(this.shouldWriteToFile())await this.writeToFile(_)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new sQ(X,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(V())throw Error("createReadStream is not supported in browser environments");if(!DQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return UY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=n.isBuffer(Q)?Q:n.from(Q,"base64"),$=Z.subarray(0,16),H=Z.subarray(Z.length-16),U=Z.subarray(16,Z.length-16),G=pZ("aes-256-gcm",Y,$);G.setAuthTag(H);let J=G.update(U),_=G.final(),q=J.length+_.length,A=n.allocUnsafe(q);return J.copy(A,0),_.copy(A,J.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return V()}isServerMode(){return!V()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}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(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X),{consoleText:$,fileText:H}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let G=$.split(`
|
|
16
|
-
`),J=Math.max(...G.map((z)=>z.length))+2,_=`\u250C${"\u2500".repeat(J)}\u2510`,q=`\u2514${"\u2500".repeat(J)}\u2518`,A=G.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:L.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(_),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:L.cyan(q),showTimestamp:!1}))}else if(!V())console.error(`${Z} ${this.environment}.INFO: [BOX] ${H}`);let U=`${Z} ${this.environment}.INFO: [BOX] ${H}
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Q){if(V())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${L.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();R.stdin.removeListener("data",Y);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let J=/%([sdijfo%])/g,_=0;if(Y=Q.replace(J,(q,A)=>{if(A==="%")return"%";if(_>=X.length)return q;let z=X[_++];switch(A){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return q}}),_<X.length)Y+=` ${X.slice(_).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",_=this.options.showIcons===!1?"":`${L.blue("\u25D0")} `;console.error(`${_}${J} ${L.cyan(Z)}`)}let G=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
18
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=L.green("\u2501".repeat(Z)),U=L.gray("\u2501".repeat($)),G=`[${H}${U}]`,J=`${Y}%`.padStart(4),_=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":X||Y===100?L.green("\u2713"):L.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${G} ${J}${_}`,W=R.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,R.stdout.write(Q.lastRenderedLine),X)R.stdout.write(`
|
|
19
|
-
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||V()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(V()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await SQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=GQ(this.config.logDirectory,Z);if(Q.before)try{if((await JQ(H)).mtime>=Q.before)continue}catch(U){console.error(`Failed to get stats for file ${H}:`,U);continue}Y.push(H)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await VQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}async function gY(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,U=Error("Unknown error occurred");for(let G=0;G<=Y;G++)try{return await Q()}catch(J){if(U=J instanceof Error?J:Error(String(J)),G===Y||!$(U))break;if(Z>0)await new Promise((_)=>setTimeout(_,Z))}if(H!==void 0)return H;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function cY(Q){return Q instanceof v}function T0(Q){return Q instanceof oQ}function O0(Q){if(cY(Q))return Q.code==="FILE_SYSTEM_ERROR"||Q.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>Q.message.toLowerCase().includes(Y.toLowerCase()))}class XX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,X)=>X==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let X=Q.toLowerCase();return["true","1","yes"].includes(X)}},{name:"number",canParse:(Q,X)=>X==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let X=Number(Q);if(Number.isNaN(X))throw TypeError(`Cannot parse "${Q}" as number`);return X}},{name:"array",canParse:(Q,X)=>X==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let X=JSON.parse(Q);if(Array.isArray(X))return X}catch{}return Q.split(",").map((X)=>X.trim())}},{name:"json",canParse:(Q,X)=>X==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(X){throw Error(`Cannot parse "${Q}" as JSON: ${X}`)}}}]}async applyEnvironmentVariables(Q,X,Y={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:H=!0,customParsers:U={},verbose:G=!1,trackPerformance:J=!0}=Y,_=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let q=Z||this.generateEnvPrefix(Q),A={...X};return this.processObject(A,[],q,{useCamelCase:$,useBackwardCompatibility:H,customParsers:U,verbose:G,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return IQ.track("applyEnvironmentVariables",_,{configName:Q});return _()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,X){if(!X)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],G=U.map((q)=>this.formatEnvKey(q,Z.useCamelCase)),J=`${Y}_${G.join("_")}`,_=Z.useBackwardCompatibility?`${Y}_${U.map((q)=>q.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,U,Y,Z);else{let q=EQ.env[J]||(_?EQ.env[_]:void 0);if(q!==void 0){if(Z.verbose){let A=EQ.env[J]?J:_}try{Q[$]=this.parseEnvironmentValue(q,typeof H,J,Z.customParsers,Z.configName)}catch(A){if(A instanceof tQ)throw A;throw QQ.envVar(J,q,typeof H,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[H,U]of Object.entries(Z))try{return U(Q)}catch{continue}for(let H of this.defaultParsers)if(H.canParse(Q,X))try{return H.parse(Q)}catch{throw QQ.envVar(Y,Q,`${X} (via ${H.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(EQ.env))if(Z.startsWith(Y)&&$!==void 0)X[Z]=$;return X}validateEnvironmentVariable(Q,X,Y){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Z.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Q,X,Y,{})}catch($){Z.push(`Cannot parse value "${X}" as ${Y}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,X,Y={}){let{prefix:Z,format:$="text"}=Y,H=Z||this.generateEnvPrefix(Q),U=[];switch(this.extractEnvVarInfo(X,[],H,U),$){case"markdown":return this.formatAsMarkdown(U,Q);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],G=`${Y}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,U,Y,Z);else Z.push({key:G,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${U.join(".")}`,example:this.generateExample(H)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,X){let Y=`Environment Variables for ${X}:
|
|
20
|
-
|
|
21
|
-
`;for(let Z of Q)Y+=`${Z.key}
|
|
22
|
-
`,Y+=` Type: ${Z.type}
|
|
23
|
-
`,Y+=` Description: ${Z.description}
|
|
24
|
-
`,Y+=` Example: ${Z.example}
|
|
25
|
-
|
|
26
|
-
`;return Y}formatAsMarkdown(Q,X){let Y=`# Environment Variables for ${X}
|
|
27
|
-
|
|
28
|
-
`;Y+=`| Variable | Type | Description | Example |
|
|
29
|
-
`,Y+=`|----------|------|-------------|----------|
|
|
30
|
-
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
31
|
-
`;return Y}}function N0(Q,X){let Y=oY("process");if(typeof Y>"u"||!Y.env)return X;let Z=Y.env[Q];return Z!==void 0?Z:X}function lY(Q,X,Y={}){return nY(Q,X,Y,new WeakMap)}function nY(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:U}=Y;if(X===null||X===void 0)return H?Q:X;if(U){let G=U(Q,X);if(G!==void 0)return G}if(Array.isArray(X)||Array.isArray(Q))return iY(Q,X,$,Z);if(!h(X)||!h(Q))return X;return P0(Q,X,Y,Z)}function iY(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return C0(Q,X);case"smart":return x0(Q,X,Z);default:return X}return X}function C0(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>VX($,Z)))Y.push(Z);return Y}function x0(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(h(X[0])&&h(Q[0]))return k0(Q,X,Y);if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}function k0(Q,X,Y){let Z=[...X];for(let $ of Q){if(!h($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let G of H)if(G in $){if(Z.find((_)=>h(_)&&(G in _)&&_[G]===$[G])){U=!0;break}}if(!U)Z.push($)}return Z}function P0(Q,X,Y,Z){let $=X;if(h($)&&Z.has($))return Z.get($);let H={...Q};if(h($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let G=$[U],J=H[U];if(Y.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){H[U]=G;continue}if(h(G)&&h(J))H[U]=nY(J,G,Y,Z);else if(Array.isArray(G)||Array.isArray(J))H[U]=iY(J,G,Y.arrayMergeMode||"smart",Z);else H[U]=G}return H}function pX(Q,X,Y="replace"){return lY(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function VX(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!VX(Q[Y],X[Y]))return!1;return!0}if(h(Q)&&h(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!VX(Q[$],X[$]))return!1}return!0}return!1}function h(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class YX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:U=!0,verbose:G=!1}=Y;if($){let _=zQ.getWithFileCheck("file",Q);if(_){if(G)console.log(`Configuration loaded from cache: ${Q}`);return _}}let J=async()=>{if(!TQ(Q))return null;try{let _=`?t=${Date.now()}`,q=await import(Q+_),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new KQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new KQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:pX(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)zQ.setWithFileCheck("file",K,Q,H);return K}catch(_){throw _ instanceof Error?QQ.configLoad(Q,_):QQ.configLoad(Q,Error(String(_)))}};if(U)return IQ.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){let Z=this.generateNamePatterns(Q,Y),$=[];for(let H of Z)for(let U of this.extensions)$.push(WX(X,`${H}${U}`));return $}generateNamePatterns(Q,X){let Y=[];if(Y.push("config",".config"),Q)Y.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(X){if(Y.push(X,`.${X}.config`,`${X}.config`,`.${X}`),Q)Y.push(`${Q}.${X}.config`,`.${Q}.${X}.config`)}return Y.filter(Boolean)}checkFileAccess(Q){return gY(async()=>{return TQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!TQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let G=WX(Q,`${H}${U}`);if(await this.checkFileAccess(G))Z.push(G)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let G=WX(Q,U);if(await this.checkFileAccess(G))Z.push(G)}}catch{return[]}return Z}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!TQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),H=$(Q,"utf8");JSON.parse(H)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}class mX{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:G=!0,verbose:J=!1}=Y,_=async()=>{let q=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:G,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...U],z);else return this.validateWithJSONSchema(Q,X,z)}catch(W){return q.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:q,warnings:A}}};if(G)return await IQ.track("validateConfiguration",_);return _()}async validateWithSchemaFile(Q,X,Y){try{if(!sZ(X))throw new jQ(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new jQ(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,H){if(H.validateTypes&&X.type){let U=Array.isArray(Q)?"array":typeof Q,G=Array.isArray(X.type)?X.type:[X.type];if(!G.includes(U)){if(Z.push({path:Y,message:`Expected type ${G.join(" or ")}, got ${U}`,expected:G.join(" or "),actual:U,rule:"type"}),H.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),H.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let U=0;U<Q.length;U++){let G=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let U=Q;if(H.validateRequired&&X.required){for(let G of X.required)if(!(G in U)){if(Z.push({path:Y?`${Y}.${G}`:G,message:`Missing required property '${G}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[G,J]of Object.entries(X.properties))if(G in U){let _=Y?`${Y}.${G}`:G;if(this.validateObjectAgainstSchema(U[G],J,_,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let G=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!G.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let U=this.getValueByPath(Q,H.path),G=this.validateWithRule(U,H,H.path);if(Z.push(...G),Y.stopOnFirstError&&Z.length>0)break}catch(U){Z.push({path:H.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,H,U]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(U)})}return X}mapTypeScriptType(Q){switch(Q.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:QZ},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class uX{fileLoader=new YX;envProcessor=new XX;validator=new mX;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...U}=Q;try{if(Y?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let G;try{G=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){let _=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(_)throw J;G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let q=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!q&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),z=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(_&&(z||q))throw J;if(A&&(!_||!z))G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!_)G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||H)await this.validateConfiguration(G.config,$,H,U.name);if(Y?.enabled&&G)this.cacheResult(U.name||"",G,Y,U);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:U.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)p.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);G.metrics=J}return G}catch(G){let J=Date.now()-X;throw p.error(`Configuration loading failed after ${J}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:U,defaultConfig:G,checkEnv:J=!0,arrayStrategy:_="replace",verbose:q=!1}=Q,A=H||XQ.cwd(),z=[],W=await this.loadLocalConfiguration(Z,$,A,U,G,_,q,J,Y);if(W)return z.push(...this.getLocalSearchPaths(Z,$,A,U)),this.finalizeResult(W,z,J,Z,q);let I=await this.loadHomeConfiguration(Z,$,G,_,q,J);if(I)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(I,z,J,Z,q);let B=await this.loadPackageJsonConfiguration(Z,$,A,G,_,q,J);if(B)return z.push(y(A,"package.json")),this.finalizeResult(B,z,J,Z,q);if(z.push(...this.getAllSearchPaths(Z,$,A,U)),X)throw QQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,G,J,q),warnings:[`No configuration file found for "${Z}"${$?` or alias "${$}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,G,J){let _=G?wQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let A of q){if(U)p.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,_,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(W){if(U)p.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let U=H?wQ(Q,Y,$):Y,G=[y(ZQ(),".config",Q),y(ZQ(),".config"),ZQ()];for(let J of G){if($)p.info(`Checking home directory: ${J}`);let _=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(_,U,{arrayStrategy:Z,verbose:$});if(q){if($)p.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let G=U?wQ(Q,Z,H):Z;try{let J=y(Y,"package.json");if(!DX(J))return null;let _=await import(J),q=_[Q],A=Q;if(!q&&X)q=_[X],A=X;if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)p.success(`Configuration loaded from package.json: ${A}`);return{config:pX(G,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)p.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:wQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let H=Y(Q);if(H)$.push(...H)}if(X){let H=await this.validator.validateConfiguration(Q,X);if(!H.isValid)$.push(...H.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if($.length>0)throw QQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return zQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);zQ.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias)Y.push(`alias:${X.alias}`);if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return Array.from(new Set([Q,y(Q,"config"),y(Q,".config"),X?y(Q,X):void 0].filter(Boolean)))}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(y(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),H=[];for(let U of $)H.push(...this.fileLoader.generateConfigPaths(Q,U,X));return H}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[y(ZQ(),".config",Q),y(ZQ(),".config"),ZQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function IY(Q){let Y=!(Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"))&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")),Z=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");return Y||Z}async function b0(Q){return a.loadConfig({...Q,__strictErrorHandling:!0})}async function sY(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await a.loadConfig(Q);else Z=await a.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",H=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||H.includes("config"))&&Q.verbose)p.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let G=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await a.applyEnvironmentVariables(G.name||"",X,!0,G.verbose||!1))?.config??X;return X}}async function y0(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:X}=await import("process");try{return(await a.loadConfig({name:Q,cwd:X(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&IY(Y)))return(await a.applyEnvironmentVariables(Q,{},!0,!1)).config;throw Y}}try{return(await a.loadConfig({...Q,cwd:Q.cwd||XQ.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(X){if(X instanceof Error&&(X.name==="ConfigNotFoundError"||X.name==="ConfigLoadError"&&IY(X)))return(await a.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw X}}async function v0(Q,X,Y="replace"){let Z=new YX;try{let $=await Z.loadFromPath(Q,X,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return $?$.config:null}catch{return null}}function wQ(Q,X,Y=!1){let Z=new XX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let A=[...G,_],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,I;for(let B of z)if(W=XQ.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof q==="boolean")J[_]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))J[_]=B}else if(Array.isArray(q))try{J[_]=JSON.parse(W)}catch{J[_]=W.split(",").map((B)=>B.trim())}else J[_]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))J[_]=H(q,A)}return J}return H(X)}function h0(Q){let X=y(XQ.cwd(),Q.configDir),Y=y(XQ.cwd(),Q.generatedDir),Z=y(Y,"config-types.ts");if(!DX(rX(Z)))VZ(rX(Z),{recursive:!0,mode:511});let $=DX(X)?EZ(X).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],H=`// Generated by bunfig v${W8}
|
|
32
|
-
export type ConfigNames = ${$.length?`'${$.join("' | '")}'`:"string"}
|
|
33
|
-
`;TZ(Z,H,{mode:438})}function d0(Q){let X=null,Y=null,Z=()=>{if(!Y)Y=sY(Q).then((H)=>{return X=H,H},(H)=>{let U="defaultConfig"in Q?Q.defaultConfig:{};if(X=U,"verbose"in Q&&Q.verbose)p.warn("Config loading failed, using defaults:",[H instanceof Error?H:Error(String(H))]);return U});return Y},$="defaultConfig"in Q?Q.defaultConfig:{};return X=$,Z(),new Proxy({},{get(H,U){if(X)return X[U];let G=$[U];return Z(),G},has(H,U){return U in(X||$)},ownKeys(){return Object.keys(X||$)},getOwnPropertyDescriptor(H,U){return Object.getOwnPropertyDescriptor(X||$,U)},set(H,U,G){if(!X)X={...$};return X[U]=G,!0}})}function f0(Q){let X=WY(rZ.cwd(),Q?.configDir||"./config");function Y(){if(!oZ(X))return[];let $=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),H=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=tZ(X).filter((J)=>$.has(zX(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),G=new Map;for(let{base:J,file:_}of U){let q=zX(_).toLowerCase(),A=G.get(J);if(!A){G.set(J,_);continue}let z=zX(A).toLowerCase();if(H.indexOf(q)<H.indexOf(z))G.set(J,_)}return Array.from(G.entries()).map(([J,_])=>({base:J,file:_})).sort((J,_)=>J.base.localeCompare(_.base))}function Z(){let $=Y(),H=$.map((_)=>_.base),U=H.length?H.map((_)=>`'${_}'`).join(" | "):"string",G=$.length?`{
|
|
34
|
-
${$.map((_)=>{let q=WY(X,_.file).replace(/\\/g,"/");return` '${_.base}': typeof import('${q}').default`}).join(`,
|
|
35
|
-
`)}
|
|
36
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
37
|
-
export type ConfigByName = ${G}
|
|
38
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
|
-
export type ConfigOf = Config
|
|
40
|
-
`}return{name:"bunfig-plugin",setup($){$.onResolve({filter:/^virtual:bunfig-types$/},(H)=>{return{path:H.path,namespace:"bunfig-virtual"}}),$.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var oY,zQ,IQ,tY,p0,m0,FY,vQ,EX,C,M,u0,MY,g0,DY,c0,l0,LX,n0,SY,VY,KX,i0,s0,o0,t0,hQ,rY,r0,x,a0,e0,EY,dQ,TX,E,L,Q8,TY,X8,OY,Y8,Z8,jX,$8,NY,CY,H8,IX,U8,J8,G8,_8,q8,fQ,aY,A8,W8="0.15.6",v,oQ,KQ,OX,NX,tQ,CX,xX,jQ,kX,PX,QQ,eY,QZ,p,a,XZ,YZ,z8=z0(async()=>{oY=import.meta.require,zQ=new vX,IQ=new hX,tY={createKey:B0,isEquivalent:R0,estimateMemoryUsage:w0},p0=gQ(SX.cwd(),"config"),m0=gQ(SX.cwd(),"src/generated"),FY=uQ.env.CLARITY_LOG_DIR||CZ(j0(),"logs"),vQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:FY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},EX=await I0(),C={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},M=C,u0=C.red,MY=C.green,g0=C.yellow,DY=C.blue,c0=C.magenta,l0=C.cyan,LX=C.white,n0=C.gray,SY=C.bgRed,VY=C.bgYellow,KX=C.bold,i0=C.dim,s0=C.italic,o0=C.underline,t0=C.reset,hQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rY={debug:"\uD83D\uDD0D",info:DY("\u2139"),success:MY("\u2713"),warning:VY(LX(KX(" WARN "))),error:SY(LX(KX(" ERROR ")))},r0=new nQ("stacks"),x=new nQ("bunfig",{showTags:!0}),a0=b(LQ.cwd(),"config"),e0=b(LQ.cwd(),"src/generated"),EY=mQ.env.CLARITY_LOG_DIR||OZ(S0(),"logs"),dQ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:EY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},TX=await V0(),E={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},L=E,Q8=E.red,TY=E.green,X8=E.yellow,OY=E.blue,Y8=E.magenta,Z8=E.cyan,jX=E.white,$8=E.gray,NY=E.bgRed,CY=E.bgYellow,H8=E.bgGray,IX=E.bold,U8=E.dim,J8=E.italic,G8=E.underline,_8=E.strikethrough,q8=E.reset,fQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},aY={debug:"\uD83D\uDD0D",info:OY("\u2139"),success:TY("\u2713"),warning:CY(jX(IX(" WARN "))),error:NY(jX(IX(" ERROR ")))},A8=new sQ("stacks"),v=class extends Error{timestamp;context;constructor(X,Y={}){super(X);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let X=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,Z])=>`${Y}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${X}`}},oQ=class extends v{code="CONFIG_NOT_FOUND";constructor(X,Y,Z){let $=Z?` or alias "${Z}"`:"";super(`Configuration "${X}"${$} not found`,{configName:X,alias:Z,searchPaths:Y,searchPathCount:Y.length})}},KQ=class extends v{code="CONFIG_LOAD_ERROR";constructor(X,Y,Z){super(`Failed to load configuration from "${X}": ${Y.message}`,{configPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},OX=class extends v{code="CONFIG_VALIDATION_ERROR";constructor(X,Y,Z){super(`Configuration validation failed for "${X}"`,{configPath:X,configName:Z,validationErrors:Y,errorCount:Y.length})}},NX=class extends v{code="CONFIG_MERGE_ERROR";constructor(X,Y,Z,$){super(`Failed to merge configuration from "${X}" with "${Y}": ${Z.message}`,{sourcePath:X,targetPath:Y,configName:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},tQ=class extends v{code="ENV_VAR_ERROR";constructor(X,Y,Z,$){super(`Failed to parse environment variable "${X}" with value "${Y}" as ${Z}`,{envKey:X,envValue:Y,expectedType:Z,configName:$})}},CX=class extends v{code="FILE_SYSTEM_ERROR";constructor(X,Y,Z){super(`File system ${X} failed for "${Y}": ${Z.message}`,{operation:X,path:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},xX=class extends v{code="TYPE_GENERATION_ERROR";constructor(X,Y,Z){super(`Failed to generate types from "${X}" to "${Y}": ${Z.message}`,{configDir:X,outputPath:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},jQ=class extends v{code="SCHEMA_VALIDATION_ERROR";constructor(X,Y,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:X,configName:Z,validationErrors:Y,errorCount:Y.length})}},kX=class extends v{code="BROWSER_CONFIG_ERROR";constructor(X,Y,Z,$){super(`Failed to fetch configuration from "${X}": ${Y} ${Z}`,{endpoint:X,status:Y,statusText:Z,configName:$})}},PX=class extends v{code="PLUGIN_ERROR";constructor(X,Y,Z){super(`Plugin "${X}" failed during ${Y}: ${Z.message}`,{pluginName:X,operation:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},QQ={configNotFound(Q,X,Y){return new oQ(Q,X,Y)},configLoad(Q,X,Y){return new KQ(Q,X,Y)},configValidation(Q,X,Y){return new OX(Q,X,Y)},configMerge(Q,X,Y,Z){return new NX(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new tQ(Q,X,Y,Z)},fileSystem(Q,X,Y){return new CX(Q,X,Y)},typeGeneration(Q,X,Y){return new xX(Q,X,Y)},schemaValidation(Q,X,Y){return new jQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new kX(Q,X,Y,Z)},plugin(Q,X,Y){return new PX(Q,X,Y)}},eY={replace:"replace",concat:"concat",smart:"smart"},QZ=/^https?:\/\//,p=new sQ("bunfig",{showTags:!0}),a=new uX,XZ=y(XQ.cwd(),"config"),YZ=y(XQ.cwd(),"src/generated")});function B8(Q,X={}){let Y=cQ.cwd();while(Y.includes("storage"))Y=zY(Y,"..");let Z=zY(Y,Q||"");if(X?.relative)return eZ(cQ.cwd(),Z);return Z}var R8=cQ.env.CLARITY_LOG_DIR||aZ(B8(),"logs"),ZZ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:R8,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},rQ={...ZZ},a9=(async()=>{try{let{loadConfig:Q}=await z8().then(()=>pY),X=await Q({name:"clarity",alias:"logging",defaultConfig:ZZ,cwd:cQ.cwd()});if(X)Object.assign(rQ,X)}catch{}return rQ})();function T(){if(r.env.NODE_ENV==="test"||r.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function w8(){if(r.env.NODE_ENV==="test"||r.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof r<"u"){let Q=r.type;if(Q==="renderer"||Q==="worker")return!1;return!!(r.versions&&(r.versions.node||r.versions.bun))}return!1}class $Z{async format(Q){let X=await w8(),Y=await this.getMetadata(X);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Y})}async getMetadata(Q){if(Q){let{hostname:X}=await import("os");return{pid:WQ.pid,hostname:X(),environment:WQ.env.NODE_ENV||"development",platform:WQ.platform,version:WQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:WQ.env.NODE_ENV||WQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var O={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},j=O,e9=O.red,L8=O.green,Q$=O.yellow,K8=O.blue,X$=O.magenta,Y$=O.cyan,xY=O.white,Z$=O.gray,j8=O.bgRed,I8=O.bgYellow,$$=O.bgGray,kY=O.bold,H$=O.dim,U$=O.italic,J$=O.underline,G$=O.strikethrough,_$=O.reset,FX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},F8={debug:"\uD83D\uDD0D",info:K8("\u2139"),success:L8("\u2713"),warning:I8(xY(kY(" WARN "))),error:j8(xY(kY(" ERROR ")))};class ZX{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(Q,X={}){this.name=Q,this.config={...rQ},this.options=this.normalizeOptions(X),this.formatter=this.options.formatter||new $Z,this.enabled=X.enabled??!0,this.fancy=X.fancy??!0,this.tagFormat=X.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=X.timestampPosition??"right",this.environment=X.environment??w.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(X);let Y={...X},Z=X.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let $=this.generateKeyId(),H=this.generateKey();this.currentKeyId=$,this.keys.set($,H),this.encryptionKeys.set($,{key:H,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let X={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return X[Q]>=X[Y]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...FX,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...FX};return{...FX,...Q.fingersCrossed}}normalizeOptions(Q){let X={format:"json",level:"info",logDirectory:rQ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...X,...Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=X.level;return Y}shouldWriteToFile(){return!T()&&this.config.writeToFile===!0}async writeToFile(Q){let Y=(async()=>{let $,H=0,U=3,G=1000;while(H<U)try{try{try{await $0(this.config.logDirectory,LY.F_OK|LY.W_OK)}catch(_){if(_ instanceof Error&&"code"in _)if(_.code==="ENOENT")await H0(this.config.logDirectory,{recursive:!0,mode:493});else if(_.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw _;else throw _}}catch(_){throw console.error("Debug: [writeToFile] Failed to create log directory:",_),_}let J=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:i.from(Q);try{if(!OQ(this.currentLogFile))await wX(this.currentLogFile,"",{mode:420});if($=wY(this.currentLogFile,"a",420),Z0($,J,{flag:"a"}),RY($),$!==void 0)RX($),$=void 0;if((await qQ(this.currentLogFile)).size===0){if(await wX(this.currentLogFile,J,{flag:"w",mode:420}),(await qQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(_){let q=_;if(q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(q.code)){if(H<U-1){let A=typeof q.message==="string"?q.message:"Unknown error";console.error(`Network error during write attempt ${H+1}/${U}:`,A);let z=G*2**H;await new Promise((W)=>setTimeout(W,z)),H++;continue}}if(q?.code&&["ENOSPC","EDQUOT"].includes(q.code))throw Error(`Disk quota exceeded or no space left on device: ${q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",q),q}finally{if($!==void 0)try{RX($)}catch(_){console.error("Debug: [writeToFile] Error closing file descriptor:",_)}}}catch(J){if(H===U-1){let q=J,A=typeof q.message==="string"?q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),J}H++;let _=G*2**(H-1);await new Promise((q)=>setTimeout(q,_))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch($){throw console.error("Debug: [writeToFile] Error in operation:",$),$}finally{this.pendingOperations.splice(Z,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 AQ(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 AQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return AQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(T())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,X;switch(Q.frequency){case"daily":X=86400000;break;case"weekly":X=604800000;break;case"monthly":X=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},X)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let X=this.config.rotation.keyRotation;if(!X?.enabled)return;let Y=typeof X.interval==="number"?X.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch(($)=>{console.error("Error rotating keys:",$)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let X=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let $=Array.from(this.encryptionKeys.entries()).sort(([,G],[,J])=>J.createdAt.getTime()-G.createdAt.getTime()),H=typeof X.maxKeys==="number"?X.maxKeys:1,U=Math.max(1,H);if($.length>U)for(let[G]of $.slice(U))this.encryptionKeys.delete(G),this.keys.delete(G)}generateKeyId(){return BX(16).toString("hex")}generateKey(){return BX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:X}=this.getCurrentKey(),Y=BX(16),Z=Q0("aes-256-gcm",X,Y),$=i.isBuffer(Q)?Q:i.from(Q,"utf8"),H=Z.update($),U=Z.final(),G=H.length+U.length,J=Z.getAuthTag(),_=i.allocUnsafe(16+G+16);return Y.copy(_,0),H.copy(_,16),U.copy(_,16+H.length),J.copy(_,16+G),{encrypted:_,iv:Y}}async compressData(Q){return new Promise((X,Y)=>{let Z=jY(),$=[];Z.on("data",(H)=>$.push(H)),Z.on("end",()=>X(i.from(i.concat($)))),Z.on("error",Y),Z.write(Q),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let X=this.config.rotation.encrypt;return{...Q,...X}}return Q}async rotateLog(){if(T())return;if(!this.shouldWriteToFile())return;let Q=await qQ(this.currentLogFile).catch(()=>null);if(!Q)return;let X=this.config.rotation;if(typeof X==="boolean")return;if(X.maxSize&&Q.size>=X.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let $=await NQ(this.config.logDirectory),H=$.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,_)=>{let q=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(_.match(/\.log\.(\d+)$/)?.[1]||"0")-q}),U=H.length>0?Number.parseInt(H[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,G=`${Y}.${U}`;if(await qQ(Y).catch(()=>null))try{if(await KY(Y,G),X.compress)try{let J=`${G}.gz`;await this.compressLogFile(G,J),await CQ(G)}catch(J){console.error("Error compressing rotated file:",J)}if(H.length===0&&!$.some((J)=>J.endsWith(".log.1")))try{let J=`${Y}.1`;await wX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let $=new Date().toISOString().replace(/[:.]/g,"-"),H=Y.replace(/\.log$/,`-${$}.log`);if(await qQ(Y).catch(()=>null))await KY(Y,H)}if(this.currentLogFile=Z,X.maxFiles){let H=(await NQ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,G)=>G.localeCompare(U));for(let U of H.slice(X.maxFiles))await CQ(AQ(this.config.logDirectory,U))}}}async compressLogFile(Q,X){let Y=BY(Q),Z=Y0(X),$=jY();await G0(Y,$,Z)}async handleFingersCrossedBuffer(Q,X){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(X);console.log(X)}}shouldLog(Q){if(!this.enabled)return!1;let X={debug:0,info:1,success:2,warning:3,error:4};return X[Q]>=X[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((X)=>{console.error("Error in pending write operation:",X)});return Promise.resolve()})),OQ(this.currentLogFile))try{let Q=wY(this.currentLogFile,"r+");RY(Q),RX(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!T()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let X=(await NQ(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of X)try{await CQ(AQ(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?j.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T())return!1;let Q=typeof w.env.NO_COLOR<"u",X=w.env.FORCE_COLOR==="0";if(Q||X)return!1;return!!(typeof w.stderr<"u"&&w.stderr.isTTY||typeof w.stdout<"u"&&w.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:X,icon:Y="",tag:Z="",message:$,level:H,showTimestamp:U=!0}=Q,G=(W)=>W.replace(this.ANSI_PATTERN,"");if(!this.fancy){let W=[];if(U)W.push(X);if(H==="warning")W.push("WARN");else if(H==="error")W.push("ERROR");else if(Y)W.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)W.push(Z.replace(/[[\]]/g,""));return W.push($),W.join(" ")}let J=w.stdout.columns||120,_="";if(H==="warning"||H==="error")_=`${Y} ${$}`;else if(H==="info"||H==="success")_=`${Y} ${Z} ${$}`;else _=`${Y} ${Z} ${j.cyan($)}`;if(!U)return _.trim();let q=G(_).trim().length,A=G(X).length,z=Math.max(1,J-2-q-A);return`${_.trim()}${" ".repeat(z)}${X}`}formatMessage(Q,X){if(X.length===1&&Array.isArray(X[0]))return Q.replace(/\{(\d+)\}/g,(H,U)=>{let G=Number.parseInt(U,10);return G<X[0].length?String(X[0][G]):H});let Y=/%([sdijfo%])/g,Z=0,$=Q.replace(Y,(H,U)=>{if(U==="%")return"%";if(Z>=X.length)return H;let G=X[Z++];switch(U){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return H}});if(Z<X.length)$+=` ${X.slice(Z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`;return $}formatMarkdown(Q){if(!Q)return Q;let X=Q;return X=X.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,$)=>{let H=j.underline(j.blue(Z)),U=this.toAbsoluteFilePath($);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let G=`file://${encodeURI(U)}`,J="\x1B]8;;",_="\x1B\\";return`\x1B]8;;${G}\x1B\\${H}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${$}\x1B\\${H}\x1B]8;;\x1B\\`;return H}),X=X.replace(/`([^`]+)`/g,(Y,Z)=>j.bgGray(Z)),X=X.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>j.bold(Z)),X=X.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>j.italic(Z)),X=X.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>j.italic(Z)),X=X.replace(/~([^~]+)~/g,(Y,Z)=>j.strikethrough(Z)),X}supportsHyperlinks(){if(T())return!1;let Q=w.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let X=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(X)&&X>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let X=Q;if(X.startsWith("file://"))X=X.replace(/^file:\/\//,"");if(X.startsWith("~")){let Y=w.env.HOME||"";if(Y)X=X.replace(/^~(?=$|\/)/,Y)}if(U0(X)||X.startsWith("./")||X.startsWith("../"))X=J0(X);else return null;return OQ(X)?X:null}catch{return null}}buildOutputTexts(Q){let X=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Y=Q.replace(this.ANSI_PATTERN,"");return{consoleText:X,fileText:Y}}async log(Q,X,...Y){if(!this.shouldLog(Q))return;let Z=new Date,$=this.formatConsoleTimestamp(Z),H=this.formatFileTimestamp(Z),U,G;if(X instanceof Error)U=X.message,G=X.stack;else U=this.formatMessage(X,Y);let{consoleText:J,fileText:_}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let A=this.options.showIcons===!1?"":F8[Q],z=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",W;switch(Q){case"debug":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:j.gray(J),level:Q}),console.error(W);break;case"info":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"success":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:j.green(J),level:Q}),console.error(W);break;case"warning":W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.warn(W);break;case"error":if(W=this.formatConsoleMessage({timestamp:$,icon:A,tag:z,message:J,level:Q}),console.error(W),G){let I=G.split(`
|
|
41
|
-
`);for(let B of I)if(B.trim()&&!B.includes(U))console.error(this.formatConsoleMessage({timestamp:$,message:j.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!T()){if(console.error(`${H} ${this.environment}.${Q.toUpperCase()}: ${U}`),G)console.error(G)}let q=`${H} ${this.environment}.${Q.toUpperCase()}: ${_}
|
|
42
|
-
`;if(G)q+=`${G}
|
|
43
|
-
`;if(q=q.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(q)}progress(Q,X=""){let Y={update:(G,J)=>{},finish:(G)=>{},interrupt:(G,J)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:X||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(G,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,G),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(G)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,G)},interrupt:(G,J="info")=>{if(!T()&&w.stdout.isTTY)w.stdout.write(`
|
|
44
|
-
`);if(this[J==="warning"?"warn":J](G),this.activeProgressBar&&this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let X=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:this.options.showIcons===!1?"":j.blue("\u25D0"),tag:Y,message:`${j.cyan(Q)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),$=Math.round(Z-X),H=`${Q} completed in ${$}ms`,U=new Date,G=this.formatConsoleTimestamp(U),_=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${H}`;if(Y)_+=` ${JSON.stringify(Y)}`;if(_+=`
|
|
45
|
-
`,_=_.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let q=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:G,icon:this.options.showIcons===!1?"":j.green("\u2713"),tag:q,message:`${H}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T())console.error(_.trim());if(this.shouldWriteToFile())await this.writeToFile(_)}}async debug(Q,...X){await this.log("debug",Q,...X)}async info(Q,...X){await this.log("info",Q,...X)}async success(Q,...X){await this.log("success",Q,...X)}async warn(Q,...X){await this.log("warning",Q,...X)}async error(Q,...X){await this.log("error",Q,...X)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:X}=Q;return!!X}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let X=`${this.name}:${Q}`,Y=new ZX(X,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(T())throw Error("createReadStream is not supported in browser environments");if(!OQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return BY(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let X=this.config.rotation;if(!X.encrypt||typeof X.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let Z=i.isBuffer(Q)?Q:i.from(Q,"base64"),$=Z.subarray(0,16),H=Z.subarray(Z.length-16),U=Z.subarray(16,Z.length-16),G=X0("aes-256-gcm",Y,$);G.setAuthTag(H);let J=G.update(U),_=G.final(),q=J.length+_.length,A=i.allocUnsafe(q);return J.copy(A,0),_.copy(A,J.length),A.toString("utf8")}catch(Z){throw Error(`Decryption failed: ${Z instanceof Error?Z.message:String(Z)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T()}isServerMode(){return!T()}setTestEncryptionKey(Q,X){this.currentKeyId=Q,this.keys.set(Q,X)}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(Q){if(!this.enabled)return;let X=new Date,Y=this.formatConsoleTimestamp(X),Z=this.formatFileTimestamp(X),{consoleText:$,fileText:H}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let G=$.split(`
|
|
46
|
-
`),J=Math.max(...G.map((z)=>z.length))+2,_=`\u250C${"\u2500".repeat(J)}\u2510`,q=`\u2514${"\u2500".repeat(J)}\u2518`,A=G.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:j.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(_),showTimestamp:!1})),A.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:j.cyan(q),showTimestamp:!1}))}else if(!T())console.error(`${Z} ${this.environment}.INFO: [BOX] ${H}`);let U=`${Z} ${this.environment}.INFO: [BOX] ${H}
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(Q){if(T())return Promise.resolve(!0);return new Promise((X)=>{console.error(`${j.cyan("?")} ${Q} (y/n) `);let Y=(Z)=>{let $=Z.toString().trim().toLowerCase();w.stdin.removeListener("data",Y);try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!1)}catch{}w.stdin.pause(),console.error(""),X($==="y"||$==="yes")};try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!0)}catch{}w.stdin.resume(),w.stdin.once("data",Y)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...X){if(!this.enabled)return;let Y=Q;if(X&&X.length>0){let J=/%([sdijfo%])/g,_=0;if(Y=Q.replace(J,(q,A)=>{if(A==="%")return"%";if(_>=X.length)return q;let z=X[_++];switch(A){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return q}}),_<X.length)Y+=` ${X.slice(_).map((q)=>typeof q==="object"?JSON.stringify(q,null,2):String(q)).join(" ")}`}let{consoleText:Z,fileText:$}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",_=this.options.showIcons===!1?"":`${j.blue("\u25D0")} `;console.error(`${_}${J} ${j.cyan(Z)}`)}let G=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${$}
|
|
48
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}renderProgressBar(Q,X=!1){if(!this.enabled||!this.shouldStyleConsole()||!w.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),Z=Math.round(Q.barLength*Y/100),$=Q.barLength-Z,H=j.green("\u2501".repeat(Z)),U=j.gray("\u2501".repeat($)),G=`[${H}${U}]`,J=`${Y}%`.padStart(4),_=Q.message?` ${Q.message}`:"",q=this.options.showIcons===!1?"":X||Y===100?j.green("\u2713"):j.blue("\u25B6"),A=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",z=`\r${q}${A} ${G} ${J}${_}`,W=w.stdout.columns||80,I=" ".repeat(Math.max(0,W-z.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${z}${I}`,w.stdout.write(Q.lastRenderedLine),X)w.stdout.write(`
|
|
49
|
-
`)}finishProgressBar(Q,X){if(!this.enabled||!this.fancy||T()||!w.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(X)Q.message=X;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(T()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let X=await NQ(this.config.logDirectory),Y=[];for(let Z of X){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test(Z):Z.startsWith(this.name))||!Z.endsWith(".log"))continue;let H=AQ(this.config.logDirectory,Z);if(Q.before)try{if((await qQ(H)).mtime>=Q.before)continue}catch(U){console.error(`Failed to get stats for file ${H}:`,U);continue}Y.push(H)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let Z of Y)try{await CQ(Z),console.warn(`Deleted log file: ${Z}`)}catch($){console.error(`Failed to delete log file ${Z}:`,$)}console.warn("Log clearing process finished.")}catch(X){console.error("Error during log clearing process:",X)}}}var q$=new ZX("stacks");class m extends Error{timestamp;context;constructor(Q,X={}){super(Q);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=X,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 Q=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([X,Y])=>`${X}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Q}`}}class HZ extends m{code="CONFIG_NOT_FOUND";constructor(Q,X,Y){let Z=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],$="";if(Z.length===1)$=` or alias "${Z[0]}"`;else if(Z.length>1)$=` or aliases ${Z.map((H)=>`"${H}"`).join(", ")}`;super(`Configuration "${Q}"${$} not found`,{configName:Q,alias:Y,searchPaths:X,searchPathCount:X.length})}}class aQ extends m{code="CONFIG_LOAD_ERROR";constructor(Q,X,Y){super(`Failed to load configuration from "${Q}": ${X.message}`,{configPath:Q,configName:Y,originalError:X.name,originalMessage:X.message});this.cause=X}}class UZ extends m{code="CONFIG_VALIDATION_ERROR";constructor(Q,X,Y){super(`Configuration validation failed for "${Q}"`,{configPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class JZ extends m{code="CONFIG_MERGE_ERROR";constructor(Q,X,Y,Z){super(`Failed to merge configuration from "${Q}" with "${X}": ${Y.message}`,{sourcePath:Q,targetPath:X,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class gX extends m{code="ENV_VAR_ERROR";constructor(Q,X,Y,Z){super(`Failed to parse environment variable "${Q}" with value "${X}" as ${Y}`,{envKey:Q,envValue:X,expectedType:Y,configName:Z})}}class GZ extends m{code="FILE_SYSTEM_ERROR";constructor(Q,X,Y){super(`File system ${Q} failed for "${X}": ${Y.message}`,{operation:Q,path:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class _Z extends m{code="TYPE_GENERATION_ERROR";constructor(Q,X,Y){super(`Failed to generate types from "${Q}" to "${X}": ${Y.message}`,{configDir:Q,outputPath:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class eQ extends m{code="SCHEMA_VALIDATION_ERROR";constructor(Q,X,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:Q,configName:Y,validationErrors:X,errorCount:X.length})}}class qZ extends m{code="BROWSER_CONFIG_ERROR";constructor(Q,X,Y,Z){super(`Failed to fetch configuration from "${Q}": ${X} ${Y}`,{endpoint:Q,status:X,statusText:Y,configName:Z})}}class AZ extends m{code="PLUGIN_ERROR";constructor(Q,X,Y){super(`Plugin "${Q}" failed during ${X}: ${Y.message}`,{pluginName:Q,operation:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}var BQ={configNotFound(Q,X,Y){return new HZ(Q,X,Y)},configLoad(Q,X,Y){return new aQ(Q,X,Y)},configValidation(Q,X,Y){return new UZ(Q,X,Y)},configMerge(Q,X,Y,Z){return new JZ(Q,X,Y,Z)},envVar(Q,X,Y,Z){return new gX(Q,X,Y,Z)},fileSystem(Q,X,Y){return new GZ(Q,X,Y)},typeGeneration(Q,X,Y){return new _Z(Q,X,Y)},schemaValidation(Q,X,Y){return new eQ(Q,X,Y)},browserConfig(Q,X,Y,Z){return new qZ(Q,X,Y,Z)},plugin(Q,X,Y){return new AZ(Q,X,Y)}};async function M8(Q,X={}){let{maxRetries:Y=3,retryDelay:Z=1000,isRetryable:$=()=>!0,fallback:H}=X,U=Error("Unknown error occurred");for(let G=0;G<=Y;G++)try{return await Q()}catch(J){if(U=J instanceof Error?J:Error(String(J)),G===Y||!$(U))break;if(Z>0)await new Promise((_)=>setTimeout(_,Z))}if(H!==void 0)return H;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class cX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,X)=>X==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let X=Q.toLowerCase();return["true","1","yes"].includes(X)}},{name:"number",canParse:(Q,X)=>X==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let X=Number(Q);if(Number.isNaN(X))throw TypeError(`Cannot parse "${Q}" as number`);return X}},{name:"array",canParse:(Q,X)=>X==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let X=JSON.parse(Q);if(Array.isArray(X))return X}catch{}return Q.split(",").map((X)=>X.trim())}},{name:"json",canParse:(Q,X)=>X==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(X){throw Error(`Cannot parse "${Q}" as JSON: ${X}`)}}}]}async applyEnvironmentVariables(Q,X,Y={}){let{prefix:Z,useCamelCase:$=!0,useBackwardCompatibility:H=!0,customParsers:U={},verbose:G=!1,trackPerformance:J=!0}=Y,_=async()=>{if(!Q)return{config:X,source:{type:"environment",priority:50,timestamp:new Date}};let q=Z||this.generateEnvPrefix(Q),A={...X};return this.processObject(A,[],q,{useCamelCase:$,useBackwardCompatibility:H,customParsers:U,verbose:G,configName:Q}),{config:A,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return yX.track("applyEnvironmentVariables",_,{configName:Q});return _()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,X){if(!X)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],G=U.map((q)=>this.formatEnvKey(q,Z.useCamelCase)),J=`${Y}_${G.join("_")}`,_=Z.useBackwardCompatibility?`${Y}_${U.map((q)=>q.toUpperCase()).join("_")}`:null;if(Z.verbose);if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.processObject(H,U,Y,Z);else{let q=kQ.env[J]||(_?kQ.env[_]:void 0);if(q!==void 0){if(Z.verbose){let A=kQ.env[J]?J:_}try{Q[$]=this.parseEnvironmentValue(q,typeof H,J,Z.customParsers,Z.configName)}catch(A){if(A instanceof gX)throw A;throw BQ.envVar(J,q,typeof H,Z.configName)}}}}}parseEnvironmentValue(Q,X,Y,Z,$){for(let[H,U]of Object.entries(Z))try{return U(Q)}catch{continue}for(let H of this.defaultParsers)if(H.canParse(Q,X))try{return H.parse(Q)}catch{throw BQ.envVar(Y,Q,`${X} (via ${H.name} parser)`,$)}return Q}getEnvironmentVariables(Q){let X={},Y=Q.toUpperCase();for(let[Z,$]of Object.entries(kQ.env))if(Z.startsWith(Y)&&$!==void 0)X[Z]=$;return X}validateEnvironmentVariable(Q,X,Y){let Z=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))Z.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(Q,X,Y,{})}catch($){Z.push(`Cannot parse value "${X}" as ${Y}: ${$}`)}return{isValid:Z.length===0,errors:Z}}generateEnvVarDocs(Q,X,Y={}){let{prefix:Z,format:$="text"}=Y,H=Z||this.generateEnvPrefix(Q),U=[];switch(this.extractEnvVarInfo(X,[],H,U),$){case"markdown":return this.formatAsMarkdown(U,Q);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,Q)}}extractEnvVarInfo(Q,X,Y,Z){for(let[$,H]of Object.entries(Q)){let U=[...X,$],G=`${Y}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof H==="object"&&H!==null&&!Array.isArray(H))this.extractEnvVarInfo(H,U,Y,Z);else Z.push({key:G,type:Array.isArray(H)?"array":typeof H,description:`Configuration for ${U.join(".")}`,example:this.generateExample(H)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,X){let Y=`Environment Variables for ${X}:
|
|
50
|
-
|
|
51
|
-
`;for(let Z of Q)Y+=`${Z.key}
|
|
52
|
-
`,Y+=` Type: ${Z.type}
|
|
53
|
-
`,Y+=` Description: ${Z.description}
|
|
54
|
-
`,Y+=` Example: ${Z.example}
|
|
55
|
-
|
|
56
|
-
`;return Y}formatAsMarkdown(Q,X){let Y=`# Environment Variables for ${X}
|
|
57
|
-
|
|
58
|
-
`;Y+=`| Variable | Type | Description | Example |
|
|
59
|
-
`,Y+=`|----------|------|-------------|----------|
|
|
60
|
-
`;for(let Z of Q)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
61
|
-
`;return Y}}function D8(Q,X,Y={}){return WZ(Q,X,Y,new WeakMap)}function WZ(Q,X,Y,Z){let{arrayMergeMode:$="replace",skipNullish:H=!1,customMerger:U}=Y;if(X===null||X===void 0)return H?Q:X;if(U){let G=U(Q,X);if(G!==void 0)return G}if(Array.isArray(X)||Array.isArray(Q))return zZ(Q,X,$,Z);if(!d(X)||!d(Q))return X;return T8(Q,X,Y,Z)}function zZ(Q,X,Y,Z){if(Array.isArray(X)&&!Array.isArray(Q))return X;if(Array.isArray(Q)&&!Array.isArray(X))return X;if(Array.isArray(X)&&Array.isArray(Q))switch(Y){case"replace":return X;case"concat":return S8(Q,X);case"smart":return V8(Q,X,Z);default:return X}return X}function S8(Q,X){let Y=[...X];for(let Z of Q)if(!Y.some(($)=>bX($,Z)))Y.push(Z);return Y}function V8(Q,X,Y){if(X.length===0)return Q;if(Q.length===0)return X;if(d(X[0])&&d(Q[0]))return E8(Q,X,Y);if(X.every((Z)=>typeof Z==="string")&&Q.every((Z)=>typeof Z==="string")){let Z=[...X];for(let $ of Q)if(!Z.includes($))Z.push($);return Z}return X}function E8(Q,X,Y){let Z=[...X];for(let $ of Q){if(!d($)){Z.push($);continue}let H=["id","name","key","path","type"],U=!1;for(let G of H)if(G in $){if(Z.find((_)=>d(_)&&(G in _)&&_[G]===$[G])){U=!0;break}}if(!U)Z.push($)}return Z}function T8(Q,X,Y,Z){let $=X;if(d($)&&Z.has($))return Z.get($);let H={...Q};if(d($))Z.set($,H);for(let U in $){if(!Object.prototype.hasOwnProperty.call($,U))continue;let G=$[U],J=H[U];if(Y.skipNullish&&(G===null||G===void 0))continue;if(G===null||G===void 0){H[U]=G;continue}if(d(G)&&d(J))H[U]=WZ(J,G,Y,Z);else if(Array.isArray(G)||Array.isArray(J))H[U]=zZ(J,G,Y.arrayMergeMode||"smart",Z);else H[U]=G}return H}function BZ(Q,X,Y="replace"){return D8(Q,X,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function bX(Q,X){if(Q===X)return!0;if(Array.isArray(Q)&&Array.isArray(X)){if(Q.length!==X.length)return!1;for(let Y=0;Y<Q.length;Y++)if(!bX(Q[Y],X[Y]))return!1;return!0}if(d(Q)&&d(X)){let Y=Object.keys(Q),Z=Object.keys(X);if(Y.length!==Z.length)return!1;for(let $ of Y){if(!Object.prototype.hasOwnProperty.call(X,$))return!1;if(!bX(Q[$],X[$]))return!1}return!0}return!1}function d(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class RZ{extensions=vY;async loadFromPath(Q,X,Y={}){let{arrayStrategy:Z="replace",useCache:$=!0,cacheTtl:H,trackPerformance:U=!0,verbose:G=!1}=Y;if($){let _=pQ.getWithFileCheck("file",Q);if(_){if(G)console.log(`Configuration loaded from cache: ${Q}`);return _}}let J=async()=>{if(!PQ(Q))return null;try{let _=`?t=${Date.now()}`,q=await import(Q+_),A=q.default||q,z="default"in q,W=Object.keys(q).length>0;if(!z&&!W)throw new aQ(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof A!=="object"||A===null||Array.isArray(A))throw new aQ(Q,Error("Configuration must export a valid object"),"unknown");let K={config:BZ(X,A,Z),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if($)pQ.setWithFileCheck("file",K,Q,H);return K}catch(_){throw _ instanceof Error?BQ.configLoad(Q,_):BQ.configLoad(Q,Error(String(_)))}};if(U)return yX.track("loadFromPath",J,{path:Q});return J()}async tryLoadFromPaths(Q,X,Y={}){for(let Z of Q)try{let $=await this.loadFromPath(Z,X,Y);if($)return $}catch($){if($ instanceof Error&&$.name==="ConfigLoadError")throw $;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,$)}return null}generateConfigPaths(Q,X,Y){return FZ({name:Q,directory:X,alias:Y})}generateNamePatterns(Q,X){return hY({name:Q,alias:X})}checkFileAccess(Q){return M8(async()=>{return PQ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,X,Y){let Z=[];if(!PQ(Q))return Z;if(X||Y){let $=this.generateNamePatterns(X||"",Y);for(let H of $)for(let U of this.extensions){let G=PY(Q,`${H}${U}`);if(await this.checkFileAccess(G))Z.push(G)}}else try{let{readdirSync:$}=await import("fs"),H=$(Q);for(let U of H)if(this.looksLikeConfigFile(U)){let G=PY(Q,U);if(await this.checkFileAccess(G))Z.push(G)}}catch{return[]}return Z}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(Q))}async validateConfigFile(Q){let X=[];try{if(!PQ(Q))return X.push("Configuration file does not exist"),X;let Y=await import(Q),Z=Y.default||Y;if(Z===void 0)X.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)X.push("Configuration must be an object");else if(Array.isArray(Z))X.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:$}=await import("fs"),H=$(Q,"utf8");JSON.parse(H)}catch($){X.push(`Invalid JSON syntax: ${$}`)}}catch(Y){X.push(`Failed to load configuration file: ${Y}`)}return X}async getFileModificationTime(Q){try{let{statSync:X}=await import("fs");return X(Q).mtime}catch{return null}}async preloadConfigurations(Q,X={}){let Y=new Map;return await Promise.allSettled(Q.map(async(Z)=>{try{let $=await this.loadFromPath(Z,{},X);if($)Y.set(Z,$.config)}catch($){if(X.verbose)console.warn(`Failed to preload ${Z}:`,$)}})),Y}}var N8=/^https?:\/\//;class wZ{async validateConfiguration(Q,X,Y={}){let{stopOnFirstError:Z=!1,validateRequired:$=!0,validateTypes:H=!0,customRules:U=[],trackPerformance:G=!0,verbose:J=!1}=Y,_=async()=>{let q=[],A=[],z={stopOnFirstError:Z,validateRequired:$,validateTypes:H,customRules:U,trackPerformance:G,verbose:J};try{if(typeof X==="string")return await this.validateWithSchemaFile(Q,X,z);else if(Array.isArray(X))return this.validateWithRules(Q,[...X,...U],z);else return this.validateWithJSONSchema(Q,X,z)}catch(W){return q.push({path:"",message:`Validation failed: ${W}`,rule:"system"}),{isValid:!1,errors:q,warnings:A}}};if(G)return await yX.track("validateConfiguration",_);return _()}async validateWithSchemaFile(Q,X,Y){try{if(!O8(X))throw new eQ(X,[{path:"",message:"Schema file does not exist"}]);let Z=await import(X),$=Z.default||Z;if(Array.isArray($))return this.validateWithRules(Q,$,Y);else return this.validateWithJSONSchema(Q,$,Y)}catch(Z){throw new eQ(X,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema(Q,X,Y){let Z=[],$=[];return this.validateObjectAgainstSchema(Q,X,"",Z,$,Y),{isValid:Z.length===0,errors:Z,warnings:$}}validateObjectAgainstSchema(Q,X,Y,Z,$,H){if(H.validateTypes&&X.type){let U=Array.isArray(Q)?"array":typeof Q,G=Array.isArray(X.type)?X.type:[X.type];if(!G.includes(U)){if(Z.push({path:Y,message:`Expected type ${G.join(" or ")}, got ${U}`,expected:G.join(" or "),actual:U,rule:"type"}),H.stopOnFirstError)return}}if(X.enum&&!X.enum.includes(Q)){if(Z.push({path:Y,message:`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"}),H.stopOnFirstError)return}if(typeof Q==="string"){if(X.minLength!==void 0&&Q.length<X.minLength)Z.push({path:Y,message:`String length must be at least ${X.minLength}`,expected:`>= ${X.minLength}`,actual:Q.length,rule:"minLength"});if(X.maxLength!==void 0&&Q.length>X.maxLength)Z.push({path:Y,message:`String length must not exceed ${X.maxLength}`,expected:`<= ${X.maxLength}`,actual:Q.length,rule:"maxLength"});if(X.pattern){if(!new RegExp(X.pattern).test(Q))Z.push({path:Y,message:`String does not match pattern ${X.pattern}`,expected:X.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(X.minimum!==void 0&&Q<X.minimum)Z.push({path:Y,message:`Value must be at least ${X.minimum}`,expected:`>= ${X.minimum}`,actual:Q,rule:"minimum"});if(X.maximum!==void 0&&Q>X.maximum)Z.push({path:Y,message:`Value must not exceed ${X.maximum}`,expected:`<= ${X.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&X.items)for(let U=0;U<Q.length;U++){let G=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(Q[U],X.items,G,Z,$,H),H.stopOnFirstError&&Z.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let U=Q;if(H.validateRequired&&X.required){for(let G of X.required)if(!(G in U)){if(Z.push({path:Y?`${Y}.${G}`:G,message:`Missing required property '${G}'`,expected:"required",rule:"required"}),H.stopOnFirstError)return}}if(X.properties){for(let[G,J]of Object.entries(X.properties))if(G in U){let _=Y?`${Y}.${G}`:G;if(this.validateObjectAgainstSchema(U[G],J,_,Z,$,H),H.stopOnFirstError&&Z.length>0)return}}if(X.additionalProperties===!1){let G=new Set(Object.keys(X.properties||{}));for(let J of Object.keys(U))if(!G.has(J))$.push({path:Y?`${Y}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,X,Y){let Z=[],$=[];for(let H of X)try{let U=this.getValueByPath(Q,H.path),G=this.validateWithRule(U,H,H.path);if(Z.push(...G),Y.stopOnFirstError&&Z.length>0)break}catch(U){Z.push({path:H.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:$}}validateWithRule(Q,X,Y){let Z=[];if(X.required&&(Q===void 0||Q===null))return Z.push({path:Y,message:X.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if(Q===void 0||Q===null)return Z;if(X.type){let $=Array.isArray(Q)?"array":typeof Q;if($!==X.type)Z.push({path:Y,message:X.message||`Expected type ${X.type}, got ${$}`,expected:X.type,actual:$,rule:"type"})}if(X.min!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($<X.min)Z.push({path:Y,message:X.message||`Value must be at least ${X.min}`,expected:`>= ${X.min}`,actual:$,rule:"min"})}if(X.max!==void 0){let $=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if($>X.max)Z.push({path:Y,message:X.message||`Value must not exceed ${X.max}`,expected:`<= ${X.max}`,actual:$,rule:"max"})}if(X.pattern&&typeof Q==="string"){if(!X.pattern.test(Q))Z.push({path:Y,message:X.message||`Value does not match pattern ${X.pattern}`,expected:X.pattern.toString(),actual:Q,rule:"pattern"})}if(X.enum&&!X.enum.includes(Q))Z.push({path:Y,message:X.message||`Value must be one of: ${X.enum.join(", ")}`,expected:X.enum.join(", "),actual:Q,rule:"enum"});if(X.validator){let $=X.validator(Q);if($)Z.push({path:Y,message:X.message||$,rule:"custom"})}return Z}getValueByPath(Q,X){if(!X)return Q;let Y=X.split("."),Z=Q;for(let $ of Y)if(Z&&typeof Z==="object"&&$ in Z)Z=Z[$];else return;return Z}generateRulesFromInterface(Q){let X=[],Y=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,$,H,U]=Z;X.push({path:$,required:!H,type:this.mapTypeScriptType(U)})}return X}mapTypeScriptType(Q){switch(Q.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:N8},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var c=new ZX("bunfig",{showTags:!0});function C8(Q){if(!Q)return"";let X=Array.isArray(Q)?Q.filter(Boolean):[Q];if(X.length===0)return"";if(X.length===1)return` or alias "${X[0]}"`;return` or aliases ${X.map((Y)=>`"${Y}"`).join(", ")}`}class LZ{fileLoader=new RZ;envProcessor=new cX;validator=new wZ;async loadConfig(Q){let X=Date.now(),{cache:Y,performance:Z,schema:$,validate:H,...U}=Q;try{if(Y?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let G;try{G=await this.loadConfigurationStrategies(U,!0,Y)}catch(J){let _=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(_)throw J;G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let q=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),A=!q&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),z=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(_&&(z||q))throw J;if(A&&(!_||!z))G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!_)G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else G={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if($||H)await this.validateConfiguration(G.config,$,H,U.name);if(Y?.enabled&&G)this.cacheResult(U.name||"",G,Y,U);if(Z?.enabled){let J={operation:"loadConfig",duration:Date.now()-X,configName:U.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(J);if(Z.slowThreshold&&J.duration>Z.slowThreshold)c.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);G.metrics=J}return G}catch(G){if(G instanceof Error&&G.name==="ConfigNotFoundError")throw G;let J=Date.now()-X;throw c.error(`Configuration loading failed after ${J}ms:`,[G instanceof Error?G:Error(String(G))]),G}}async loadConfigurationStrategies(Q,X=!1,Y){let{name:Z="",alias:$,cwd:H,configDir:U,defaultConfig:G,checkEnv:J=!0,arrayStrategy:_="replace",verbose:q=!1}=Q,A=H||QX.cwd(),z=[],W=await this.loadLocalConfiguration(Z,$,A,U,G,_,q,J,Y);if(W)return z.push(...this.getLocalSearchPaths(Z,$,A,U)),this.finalizeResult(W,z,J,Z,q);let I=await this.loadHomeConfiguration(Z,$,G,_,q,J);if(I)return z.push(...this.getHomeSearchPaths(Z,$)),this.finalizeResult(I,z,J,Z,q);let B=await this.loadPackageJsonConfiguration(Z,$,A,G,_,q,J);if(B)return z.push(s(A,"package.json")),this.finalizeResult(B,z,J,Z,q);if(z.push(...this.getAllSearchPaths(Z,$,A,U)),X)throw BQ.configNotFound(Z,z,$);return{...await this.applyEnvironmentVariables(Z,G,J,q),warnings:[`No configuration file found for "${Z}"${C8($)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,X,Y,Z,$,H,U,G,J){let _=G?bQ(Q,$,U):$,q=this.getLocalDirectories(Y,Z);for(let A of q){if(U)c.info(`Searching for configuration in: ${A}`);let z=this.fileLoader.generateConfigPaths(Q,A,X),W=await this.fileLoader.tryLoadFromPaths(z,_,{arrayStrategy:H,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(W){if(U)c.success(`Configuration loaded from: ${W.source.path}`);return W}}return null}async loadHomeConfiguration(Q,X,Y,Z,$,H){if(!Q)return null;let U=H?bQ(Q,Y,$):Y,G=[s(YQ(),".config",Q),s(YQ(),".config"),YQ()];for(let J of G){if($)c.info(`Checking home directory: ${J}`);let _=this.fileLoader.generateConfigPaths(Q,J,X),q=await this.fileLoader.tryLoadFromPaths(_,U,{arrayStrategy:Z,verbose:$});if(q){if($)c.success(`Configuration loaded from home directory: ${q.source.path}`);return q}}return null}async loadPackageJsonConfiguration(Q,X,Y,Z,$,H,U){let G=U?bQ(Q,Z,H):Z;try{let J=s(Y,"package.json");if(!DZ(J))return null;let _={};try{_=JSON.parse(SZ(J,"utf8"))}catch(z){if(H)c.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let q=_[Q],A=Q;if(!q&&X){let z=Array.isArray(X)?X:[X];for(let W of z){if(!W)continue;if(_[W]){q=_[W],A=W;break}}}if(q&&typeof q==="object"&&!Array.isArray(q)){if(H)c.success(`Configuration loaded from package.json: ${A}`);return{config:BZ(G,q,$),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(H)c.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables(Q,X,Y,Z){if(!Y||!Q||typeof X!=="object"||X===null||Array.isArray(X))return{config:X,source:{type:"default",priority:10,timestamp:new Date}};return{config:bQ(Q,X,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,X,Y,Z,$){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,X,Y,Z){let $=[];if(Y){let H=Y(Q);if(H)$.push(...H)}if(X){let H=await this.validator.validateConfiguration(Q,X);if(!H.isValid)$.push(...H.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if($.length>0)throw BQ.configValidation(Z||"unknown",$,Z)}checkCache(Q,X){let Y=this.generateCacheKey(Q,X);return pQ.get(Y)||null}cacheResult(Q,X,Y,Z){let $=this.generateCacheKey(Q,Z);pQ.set($,X,void 0,Y.ttl)}generateCacheKey(Q,X){let Y=[Q];if(X.alias){let Z=Array.isArray(X.alias)?X.alias.join(","):X.alias;Y.push(`alias:${Z}`)}if(X.cwd)Y.push(`cwd:${X.cwd}`);if(X.configDir)Y.push(`configDir:${X.configDir}`);if("checkEnv"in X)Y.push(`checkEnv:${X.checkEnv}`);return Y.join("|")}getLocalDirectories(Q,X){return MZ({cwd:Q,configDir:X})}getAllSearchPaths(Q,X,Y,Z){let $=[];return $.push(...this.getLocalSearchPaths(Q,X,Y,Z)),$.push(...this.getHomeSearchPaths(Q,X)),$.push(s(Y,"package.json")),$}getLocalSearchPaths(Q,X,Y,Z){let $=this.getLocalDirectories(Y,Z),H=[];for(let U of $)H.push(...this.fileLoader.generateConfigPaths(Q,U,X));return H}getHomeSearchPaths(Q,X){if(!Q)return[];let Y=[s(YQ(),".config",Q),s(YQ(),".config"),YQ()],Z=[];for(let $ of Y)Z.push(...this.fileLoader.generateConfigPaths(Q,$,X));return Z}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var MX=new LZ;async function KZ(Q){let X="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Y="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let Z;if(Y)Z=await MX.loadConfig(Q);else Z=await MX.loadConfig({...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??X}catch(Z){let $=Z instanceof Error?Z.name:"UnknownError",H=Z instanceof Error?Z.message:String(Z);if(!($==="ConfigNotFoundError"||$==="ConfigLoadError"||$==="ConfigValidationError"||H.includes("config"))&&Q.verbose)c.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let G=Y?{...Q,defaultConfig:X}:{...Q,defaultConfig:X,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await MX.applyEnvironmentVariables(G.name||"",X,!0,G.verbose||!1))?.config??X;return X}}function bQ(Q,X,Y=!1){let Z=new cX,$=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function H(U,G=[]){let J={...U};for(let[_,q]of Object.entries(U)){let A=[...G,_],z=[`${$}_${A.join("_").toUpperCase()}`,`${$}_${A.map((B)=>B.toUpperCase()).join("")}`,`${$}_${A.map((B)=>B.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],W,I;for(let B of z)if(W=QX.env[B],W!==void 0){I=B;break}if(W!==void 0&&I)if(typeof q==="boolean")J[_]=["true","1","yes"].includes(W.toLowerCase());else if(typeof q==="number"){let B=Number(W);if(!Number.isNaN(B))J[_]=B}else if(Array.isArray(q))try{J[_]=JSON.parse(W)}catch{J[_]=W.split(",").map((B)=>B.trim())}else J[_]=W;else if(q&&typeof q==="object"&&!Array.isArray(q))J[_]=H(q,A)}return J}return H(X)}var R$=s(QX.cwd(),"config"),w$=s(QX.cwd(),"src/generated");var jZ={verbose:!0},lX=null;async function j$(){if(!lX)lX=await KZ({name:"development",alias:"dx",defaultConfig:jZ});return lX}var I$=jZ;export{j$ as getConfig,jZ as defaultConfig,I$ as config};
|
|
2
|
+
import{e,t,r}from"./chunk-1ts3tqy6.js";export{r as config,e as defaultConfig,t as getConfig};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
// @bun
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "better-dx",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.2.
|
|
5
|
+
"version": "0.2.39",
|
|
6
6
|
"description": "All the development dependencies you need.",
|
|
7
7
|
"author": "Chris Breuer <chris@stacksjs.org>",
|
|
8
8
|
"license": "MIT",
|
|
@@ -26,6 +26,14 @@
|
|
|
26
26
|
"types": "./dist/index.d.ts",
|
|
27
27
|
"import": "./dist/index.js"
|
|
28
28
|
},
|
|
29
|
+
"./config": {
|
|
30
|
+
"types": "./dist/config.d.ts",
|
|
31
|
+
"import": "./dist/config.js"
|
|
32
|
+
},
|
|
33
|
+
"./types": {
|
|
34
|
+
"types": "./dist/types.d.ts",
|
|
35
|
+
"import": "./dist/types.js"
|
|
36
|
+
},
|
|
29
37
|
"./*": {
|
|
30
38
|
"import": "./dist/*"
|
|
31
39
|
}
|
|
@@ -33,6 +41,7 @@
|
|
|
33
41
|
"module": "./dist/index.js",
|
|
34
42
|
"types": "./dist/index.d.ts",
|
|
35
43
|
"files": [
|
|
44
|
+
"CHANGELOG.md",
|
|
36
45
|
"README.md",
|
|
37
46
|
"dist"
|
|
38
47
|
],
|
|
@@ -55,6 +64,7 @@
|
|
|
55
64
|
"fresh": "bun x rimraf node_modules/ bun.lock && bun i",
|
|
56
65
|
"prepublishOnly": "bun --bun run build && bun run compile:all && bun run zip",
|
|
57
66
|
"test": "bun test",
|
|
67
|
+
"test:sdk": "bun scripts/verify-sdk.ts",
|
|
58
68
|
"lint": "bun x --bun pickier .",
|
|
59
69
|
"lint:fix": "bun x --bun pickier . --fix",
|
|
60
70
|
"format": "bun x --bun pickier . --format",
|
|
@@ -70,23 +80,23 @@
|
|
|
70
80
|
"typecheck": "bun --bun tsc --noEmit"
|
|
71
81
|
},
|
|
72
82
|
"dependencies": {
|
|
73
|
-
"@buddysh/buddy": "^0.11.
|
|
74
|
-
"@
|
|
75
|
-
"@stacksjs/
|
|
76
|
-
"@stacksjs/
|
|
77
|
-
"@stacksjs/
|
|
78
|
-
"@stacksjs/
|
|
79
|
-
"@stacksjs/
|
|
80
|
-
"@
|
|
81
|
-
"bun
|
|
82
|
-
"bun-
|
|
83
|
-
"bunfig": "^0.15.
|
|
84
|
-
"pickier": "^0.1.
|
|
85
|
-
"ts-error-handling": "^0.1.
|
|
86
|
-
"typescript": "
|
|
83
|
+
"@buddysh/buddy": "^0.11.15",
|
|
84
|
+
"@dtsx/bun": "^0.11.55",
|
|
85
|
+
"@stacksjs/bumpx": "^0.2.35",
|
|
86
|
+
"@stacksjs/bunpress": "^0.2.31",
|
|
87
|
+
"@stacksjs/clapp": "^0.2.17",
|
|
88
|
+
"@stacksjs/clarity": "^0.3.33",
|
|
89
|
+
"@stacksjs/gitlint": "^0.1.8",
|
|
90
|
+
"@stacksjs/logsmith": "^0.2.16",
|
|
91
|
+
"@types/bun": "^1.4.4",
|
|
92
|
+
"bun-git-hooks": "^0.3.3",
|
|
93
|
+
"bunfig": "^0.15.21",
|
|
94
|
+
"pickier": "^0.1.93",
|
|
95
|
+
"ts-error-handling": "^0.1.4",
|
|
96
|
+
"typescript": "7.1.0-dev.20261011.1"
|
|
87
97
|
},
|
|
88
98
|
"overrides": {
|
|
89
|
-
"typescript": "
|
|
99
|
+
"typescript": "7.1.0-dev.20261011.1"
|
|
90
100
|
},
|
|
91
101
|
"git-hooks": {
|
|
92
102
|
"pre-commit": {
|