@stacksjs/bun-router 0.1.6 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-4wd1d6ay.js +416 -0
- package/dist/{chunk-nf3kv7kv.js → chunk-8rrs7556.js} +1 -1
- package/dist/{chunk-3y4gaz7v.js → chunk-m4aaj9ay.js} +1 -1
- package/dist/cli.js +30 -59
- package/dist/container/index.js +1 -1
- package/dist/index.js +12 -12
- package/dist/request/macros.d.ts +13 -0
- package/package.json +9 -1
- package/dist/chunk-03m2j6h7.js +0 -2
- package/dist/chunk-08cw7ejr.js +0 -3
- package/dist/chunk-0e4g0fyv.js +0 -62
- package/dist/chunk-0mmn02yw.js +0 -2
- package/dist/chunk-126c9qm3.js +0 -2
- package/dist/chunk-12p13817.js +0 -2
- package/dist/chunk-14v65c37.js +0 -4
- package/dist/chunk-1b6a7t3v.js +0 -231
- package/dist/chunk-1wenkmk0.js +0 -2
- package/dist/chunk-2152npfd.js +0 -2
- package/dist/chunk-26w23krx.js +0 -2
- package/dist/chunk-2g8m379z.js +0 -10
- package/dist/chunk-2rr178et.js +0 -1654
- package/dist/chunk-2w8f3swz.js +0 -29
- package/dist/chunk-4r1x4afz.js +0 -12
- package/dist/chunk-4wyw66zk.js +0 -2
- package/dist/chunk-4z5sf8ag.js +0 -2
- package/dist/chunk-58tfvayh.js +0 -4
- package/dist/chunk-5be9x5cq.js +0 -3
- package/dist/chunk-5dp83qcx.js +0 -397
- package/dist/chunk-5f0d9j9a.js +0 -2
- package/dist/chunk-5z52b0fc.js +0 -28
- package/dist/chunk-5zrnk2kq.js +0 -4
- package/dist/chunk-6bbmkwng.js +0 -3
- package/dist/chunk-6dmqtdnq.js +0 -2
- package/dist/chunk-6e91956t.js +0 -3
- package/dist/chunk-6rv8w5jk.js +0 -2
- package/dist/chunk-6x1feysm.js +0 -3
- package/dist/chunk-7qnxdedn.js +0 -321
- package/dist/chunk-7y72hm1x.js +0 -2
- package/dist/chunk-8hbhfh6b.js +0 -194
- package/dist/chunk-8kfzygg5.js +0 -3
- package/dist/chunk-8wpj3fqe.js +0 -351
- package/dist/chunk-8wydx2we.js +0 -2
- package/dist/chunk-8zjnjvv7.js +0 -2
- package/dist/chunk-9805tt8n.js +0 -341
- package/dist/chunk-988h4bzr.js +0 -2
- package/dist/chunk-9b6a58ac.js +0 -2
- package/dist/chunk-a8fcaywb.js +0 -2
- package/dist/chunk-bfjwn7yg.js +0 -2
- package/dist/chunk-bp2522mm.js +0 -2
- package/dist/chunk-brpgjyqg.js +0 -3
- package/dist/chunk-bswe62q4.js +0 -48
- package/dist/chunk-c3v796c8.js +0 -943
- package/dist/chunk-ccqmwdry.js +0 -2
- package/dist/chunk-ck0crwnx.js +0 -2
- package/dist/chunk-cqgkxcb4.js +0 -2
- package/dist/chunk-dntnakjy.js +0 -2
- package/dist/chunk-dxg045wj.js +0 -5
- package/dist/chunk-e3qej0jr.js +0 -4
- package/dist/chunk-ettdpnrw.js +0 -60
- package/dist/chunk-ezqwq17j.js +0 -185
- package/dist/chunk-ezx3qsez.js +0 -2
- package/dist/chunk-f72nnjy4.js +0 -15413
- package/dist/chunk-fna5n0ey.js +0 -246
- package/dist/chunk-fqhckdt8.js +0 -2
- package/dist/chunk-fr6hbx25.js +0 -2
- package/dist/chunk-g9cwng6w.js +0 -3
- package/dist/chunk-gd3za5x0.js +0 -2
- package/dist/chunk-gf28608k.js +0 -2
- package/dist/chunk-h1dj6v8q.js +0 -3
- package/dist/chunk-hjxe7k2g.js +0 -2
- package/dist/chunk-hrkgznbn.js +0 -2
- package/dist/chunk-j6h5v0br.js +0 -2
- package/dist/chunk-kjtjbcq4.js +0 -71
- package/dist/chunk-mgb01qdv.js +0 -14
- package/dist/chunk-n24c9whp.js +0 -2
- package/dist/chunk-n2j24b0h.js +0 -4540
- package/dist/chunk-nhmtg01n.js +0 -84
- package/dist/chunk-p0qhpnqh.js +0 -70
- package/dist/chunk-p0w1x8y2.js +0 -3
- package/dist/chunk-p3dk1w2w.js +0 -216
- package/dist/chunk-q4e9pxs7.js +0 -3
- package/dist/chunk-q5dv1kyy.js +0 -2
- package/dist/chunk-qnqgf9tq.js +0 -2
- package/dist/chunk-qvwy1808.js +0 -898
- package/dist/chunk-r18f77vc.js +0 -12
- package/dist/chunk-r63za1mr.js +0 -2
- package/dist/chunk-rft8gw92.js +0 -7851
- package/dist/chunk-ryvmyskt.js +0 -4211
- package/dist/chunk-sa6mx308.js +0 -2
- package/dist/chunk-sw0chtw4.js +0 -4
- package/dist/chunk-va0pc7hx.js +0 -2
- package/dist/chunk-vcp8dnjq.js +0 -412
- package/dist/chunk-vg1erq1q.js +0 -2
- package/dist/chunk-vsh4390q.js +0 -358
- package/dist/chunk-w0jv49ch.js +0 -11
- package/dist/chunk-wm805tte.js +0 -35
- package/dist/chunk-xg9xscqz.js +0 -1
- package/dist/chunk-xj9h6mc9.js +0 -2
- package/dist/chunk-ytvzwrq3.js +0 -51
- package/dist/chunk-zde7ebc4.js +0 -288
- package/dist/chunk-zmqsv2xy.js +0 -2
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{yb as Y}from"./chunk-8rrs7556.js";import Fo from"process";import{existsSync as Br,statSync as Ur}from"fs";import{resolve as De}from"path";import bn from"process";import{existsSync as Sn,mkdirSync as Sa,readdirSync as Ra,readFileSync as Rn,writeFileSync as Ca}from"fs";import{homedir as fe}from"os";import{dirname as $a,resolve as X}from"path";import Ct from"process";import{existsSync as qr,statSync as _r}from"fs";import{existsSync as cr,mkdirSync as Cn,readdirSync as En,writeFileSync as Tn}from"fs";import{homedir as de}from"os";import{dirname as Vr,resolve as L}from"path";import le from"process";import{join as $n,relative as kn,resolve as Hr}from"path";import ft from"process";import{existsSync as As,mkdirSync as ja,readdirSync as La,writeFileSync as Ba}from"fs";import{homedir as Vt}from"os";import{dirname as _a,resolve as j}from"path";import Le from"process";import{join as Pn,relative as An,resolve as Kr}from"path";import dt from"process";import{existsSync as Fs,mkdirSync as Wa,readdirSync as Ja,writeFileSync as Ga}from"fs";import{dirname as Ya,resolve as mt}from"path";import lr from"process";import{Buffer as ie}from"buffer";import{createCipheriv as Fn,createDecipheriv as Mn,randomBytes as Ht}from"crypto";import{closeSync as Kt,createReadStream as zr,createWriteStream as Nn,existsSync as zt,fsyncSync as Wr,openSync as Jr,writeFileSync as In}from"fs";import{access as On,constants as Gr,mkdir as Dn,readdir as ze,rename as Xr,stat as me,unlink as We,writeFile as Wt}from"fs/promises";import{join as he}from"path";import N from"process";import{pipeline as jn}from"stream/promises";import{createGzip as Yr}from"zlib";import pe from"process";import te from"process";import{Buffer as Q}from"buffer";import{createCipheriv as Ln,createDecipheriv as Bn,randomBytes as Jt}from"crypto";import{closeSync as Gt,createReadStream as Zr,createWriteStream as Un,existsSync as Je,fsyncSync as Qr,openSync as es,writeFileSync as qn}from"fs";import{access as _n,constants as ts,mkdir as Vn,readdir as Ge,rename as rs,stat as ge,unlink as Xe,writeFile as Xt}from"fs/promises";import{isAbsolute as Hn,join as ye,resolve as Kn}from"path";import y from"process";import{pipeline as zn}from"stream/promises";import{createGzip as ss}from"zlib";import we from"process";import re from"process";import Ye from"process";import{existsSync as Ze}from"fs";import{resolve as Yt}from"path";import{existsSync as Wn}from"fs";import{existsSync as Jn,readdirSync as Gn}from"fs";import{extname as Zt,resolve as ns}from"path";import Xn from"process";import{join as Yn,relative as Zn,resolve as is}from"path";import ht from"process";import{Buffer as ee}from"buffer";import{createCipheriv as Qn,createDecipheriv as ei,randomBytes as Qt}from"crypto";import{closeSync as er,createReadStream as os,createWriteStream as ti,existsSync as Qe,fsyncSync as as,openSync as cs,writeFileSync as ri}from"fs";import{access as si,constants as ls,mkdir as ni,readdir as et,rename as us,stat as be,unlink as tt,writeFile as tr}from"fs/promises";import{isAbsolute as ii,join as ve,resolve as oi}from"path";import w from"process";import{pipeline as ai}from"stream/promises";import{createGzip as fs}from"zlib";import xe from"process";import se from"process";import st from"process";import{existsSync as nt}from"fs";import{resolve as Es}from"path";import{existsSync as ko}from"fs";class Ts{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,s])=>r.timestamp.getTime()-s.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,s){if(!this.options.enabled)return;let n=this.generateKey(e,r),i=s??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),s=this.cache.get(r);if(!s){this.totalMisses++;return}if(this.isExpired(s)){this.cache.delete(r),this.totalMisses++;return}return s.hits++,this.totalHits++,s.value}isFileModified(e,t){try{if(!Br(e))return!0;return Ur(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,s){try{let n=Br(r)?Ur(r):null,i=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},r,s)}catch{this.set(e,t,r,s)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((s,n)=>s+n.size,0),r=e.map((s)=>s.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let s=r;this.cache.set(t,{value:s.value,timestamp:new Date(s.timestamp),ttl:s.ttl,hits:s.hits,size:s.size})}}}class $s{metrics=[];maxMetrics=1000;async track(e,t,r={}){let s=performance.now(),n=new Date;try{let i=await t(),o=performance.now()-s;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),i}catch(i){let o=performance.now()-s;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),i}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),s=r.reduce((n,i)=>n+i,0);return{count:t.length,averageDuration:s/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:s,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var ut=new Ts,vr=new $s;var ks=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Ps(e={}){let{name:t="",alias:r}=e,s=["config",".config"];if(t)s.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=r===void 0?[]:Array.isArray(r)?r:[r];for(let i of n){if(!i)continue;if(s.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)s.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return Array.from(new Set(s.filter(Boolean)))}function vn(e){return Ps(e).flatMap((r)=>ks.map((s)=>De(e.directory,`${r}${s}`)))}function xn(e={}){let t=De(e.cwd||bn.cwd());return Array.from(new Set([t,De(t,"config"),De(t,".config"),e.configDir?De(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var ci=Object.defineProperty,li=(e)=>e;function ui(e,t){this[e]=li.bind(null,t)}var fi=(e,t)=>{for(var r in t)ci(e,r,{get:t[r],enumerable:!0,configurable:!0,set:ui.bind(t,r)})},di=(e,t)=>()=>(e&&(t=e(e=0)),t),Ms={};fi(Ms,{withErrorRecovery:()=>Os,tryLoadConfig:()=>Oi,loadConfigWithResult:()=>Ni,loadConfig:()=>Us,isRetryableError:()=>$i,isConfigNotFoundError:()=>Ti,isBunfigError:()=>Ds,globalPerformanceMonitor:()=>qe,globalCache:()=>Se,getEnvOrDefault:()=>ki,generateConfigTypes:()=>Di,defaultGeneratedDir:()=>Js,defaultConfigDir:()=>Ws,deepMergeWithArrayStrategy:()=>Er,deepMerge:()=>js,createLibraryConfig:()=>ji,config:()=>Ii,bunfigPlugin:()=>Li,applyEnvVarsToConfig:()=>je,TypeGenerationError:()=>gr,SchemaValidationError:()=>Ue,PluginError:()=>wr,PerformanceMonitor:()=>Sr,FileSystemError:()=>pr,ErrorFactory:()=>oe,EnvVarError:()=>vt,EnvProcessor:()=>Et,ConfigValidator:()=>Tr,ConfigValidationError:()=>mr,ConfigNotFoundError:()=>bt,ConfigMergeError:()=>hr,ConfigLoader:()=>$r,ConfigLoadError:()=>Be,ConfigFileLoader:()=>Tt,ConfigCache:()=>xr,CacheUtils:()=>_s,BunfigError:()=>_,BrowserConfigError:()=>yr,ArrayMergeStrategies:()=>Ks});class xr{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,s])=>r.timestamp.getTime()-s.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,s){if(!this.options.enabled)return;let n=this.generateKey(e,r),i=s??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),s=this.cache.get(r);if(!s){this.totalMisses++;return}if(this.isExpired(s)){this.cache.delete(r),this.totalMisses++;return}return s.hits++,this.totalHits++,s.value}isFileModified(e,t){try{if(!qr(e))return!0;return _r(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,s){try{let n=qr(r)?_r(r):null,i=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},r,s)}catch{this.set(e,t,r,s)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((s,n)=>s+n.size,0),r=e.map((s)=>s.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let s=r;this.cache.set(t,{value:s.value,timestamp:new Date(s.timestamp),ttl:s.ttl,hits:s.hits,size:s.size})}}}class Sr{metrics=[];maxMetrics=1000;async track(e,t,r={}){let s=performance.now(),n=new Date;try{let i=await t(),o=performance.now()-s;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),i}catch(i){let o=performance.now()-s;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),i}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),s=r.reduce((n,i)=>n+i,0);return{count:t.length,averageDuration:s/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:s,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function mi(e,t={}){let s=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return s?`${e}:${s}`:e}function hi(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function pi(e){return e.getStats().size*2}function Rr(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&C(t[0])&&"id"in t[0]&&t[0].id===3&&C(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(C(t)&&C(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(C(e)&&"arr"in e&&Array.isArray(e.arr)&&C(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&C(t[0])&&C(e[0])){let s=[...t];for(let n of e)if(C(n)&&"name"in n){if(!s.find((o)=>C(o)&&("name"in o)&&o.name===n.name))s.push(n)}else if(C(n)&&"path"in n){if(!s.find((o)=>C(o)&&("path"in o)&&o.path===n.path))s.push(n)}else if(!s.some((i)=>pt(i,n)))s.push(n);return s}if(t.every((s)=>typeof s==="string")&&e.every((s)=>typeof s==="string")){let s=[...t];for(let n of e)if(!s.includes(n))s.push(n);return s}return t}if(!C(t)||!C(e))return t;let r={...e};for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s)){let n=t[s];if(n===null||n===void 0)continue;else if(C(n)&&C(r[s]))r[s]=Rr(r[s],n);else if(Array.isArray(n)&&Array.isArray(r[s]))if(n.length>0&&r[s].length>0&&C(n[0])&&C(r[s][0])){let i=[...n];for(let o of r[s])if(C(o)&&"name"in o){if(!i.find((a)=>C(a)&&("name"in a)&&a.name===o.name))i.push(o)}else if(C(o)&&"path"in o){if(!i.find((a)=>C(a)&&("path"in a)&&a.path===o.path))i.push(o)}else if(!i.some((c)=>pt(c,o)))i.push(o);r[s]=i}else if(n.every((i)=>typeof i==="string")&&r[s].every((i)=>typeof i==="string")){let i=[...n];for(let o of r[s])if(!i.includes(o))i.push(o);r[s]=i}else r[s]=n;else r[s]=n}return r}function pt(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!pt(e[r],t[r]))return!1;return!0}if(C(e)&&C(t)){let r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!pt(e[n],t[n]))return!1}return!0}return!1}function C(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function gi(e,t){if(!Fs(e))return null;try{let r=await import(e),s=r.default||r;if(typeof s!=="object"||s===null||Array.isArray(s))return null;try{return Rr(t,s)}catch{return null}}catch{return null}}async function yi({name:e="",cwd:t,defaultConfig:r}){let s=t||lr.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],i=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of i)for(let c of n){let a=mt(s,`${o}${c}`),l=await gi(a,r);if(l!==null)return l}try{let o=mt(s,"package.json");if(Fs(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return Rr(r,a)}catch{}}}catch{}return r}function wi(e,t={}){let r=dt.cwd();while(r.includes("storage"))r=Kr(r,"..");let s=Kr(r,e||"");if(t?.relative)return An(dt.cwd(),s);return s}async function bi(){try{let e=await yi({name:"clarity",defaultConfig:ot,cwd:dt.cwd(),endpoint:"",headers:{}});return{...ot,...e}}catch{return ot}}function T(){if(te.env.NODE_ENV==="test"||te.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vi(){if(te.env.NODE_ENV==="test"||te.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof te<"u"){let e=te.type;if(e==="renderer"||e==="worker")return!1;return!!(te.versions&&(te.versions.node||te.versions.bun))}return!1}class Ns{async format(e){let t=await vi(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:pe.pid,hostname:t(),environment:pe.env.NODE_ENV||"development",platform:pe.platform,version:pe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pe.env.NODE_ENV||pe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class gt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...fr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ns,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},s=t.timestamp!==void 0;if(s)delete r.timestamp;if(this.config={...this.config,...r,timestamp:s||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...at,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...at};return{...at,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:fr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let n,i=0,o=3,c=1000;while(i<o)try{try{try{await On(this.config.logDirectory,Gr.F_OK|Gr.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Dn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ie.from(e);try{if(!zt(this.currentLogFile))await Wt(this.currentLogFile,"",{mode:420});if(n=Jr(this.currentLogFile,"a",420),In(n,a,{flag:"a"}),Wr(n),n!==void 0)Kt(n),n=void 0;if((await me(this.currentLogFile)).size===0){if(await Wt(this.currentLogFile,a,{flag:"w",mode:420}),(await me(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(i<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,f);let m=c*2**i;await new Promise((d)=>setTimeout(d,m)),i++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{Kt(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(i===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}i++;let l=c*2**(i-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let s=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(s,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 e=new Date().toISOString().split("T")[0];return he(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(T())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,s=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},s)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),s=this.generateKey();this.currentKeyId=r,this.keys.set(r,s),this.encryptionKeys.set(r,{key:s,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}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 e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Ht(16),s=Fn("aes-256-gcm",t,r),n=ie.concat([s.update(e,"utf8"),s.final()]),i=s.getAuthTag();return{encrypted:ie.concat([r,n,i]),iv:r}}async compressData(e){return new Promise((t,r)=>{let s=Yr(),n=[];s.on("data",(i)=>n.push(i)),s.on("end",()=>t(ie.from(ie.concat(n)))),s.on("error",r),s.write(e),s.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(T())return;let e=await me(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,s=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await ze(this.config.logDirectory),i=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await me(r).catch(()=>null))try{if(await Xr(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await We(c)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Wt(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),i=r.replace(/\.log$/,`-${n}.log`);if(await me(r).catch(()=>null))await Xr(r,i)}if(this.currentLogFile=s,t.maxFiles){let i=(await ze(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of i.slice(t.maxFiles))await We(he(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=zr(e),s=Nn(t),n=Yr();await jn(r,n,s)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let s=await this.formatter.format(r);await this.writeToFile(s),console.log(s)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),zt(this.currentLogFile))try{let e=Jr(this.currentLogFile,"r+");Wr(e),Kt(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!T()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await ze(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await We(he(this.config.logDirectory,r))}catch(s){console.error(`Failed to delete temp file ${r}:`,s)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?R.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:s="",message:n,level:i,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(i==="warning")d.push("WARN");else if(i==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(s)d.push(s.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=N.stdout.columns||120,l="";if(i==="warning"||i==="error")l=`${r} ${n}`;else if(i==="info"||i==="success")l=`${r} ${s} ${n}`;else l=`${r} ${s} ${R.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,m=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):i});let r=/%([sdijfo%])/g,s=0,n=e.replace(r,(i,o)=>{if(o==="%")return"%";if(s>=t.length)return i;let c=t[s++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return i}});if(s<t.length)n+=` ${t.slice(s).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return n}async log(e,t,...r){let s=new Date,n=this.formatConsoleTimestamp(s),i=this.formatFileTimestamp(s),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!T()){let l=Vs[e],u=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:R.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:R.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f),c){let m=c.split(`
|
|
3
|
+
`);for(let d of m)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:R.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!T()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${i} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
4
|
+
`;if(c)a+=`${c}
|
|
5
|
+
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!T()){let r=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",s=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:s,icon:R.blue("\u25D0"),tag:r,message:`${R.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let s=performance.now(),n=Math.round(s-t),i=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
6
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!T()){let u=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:R.green("\u2713"),tag:u,message:`${i}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!T())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new gt(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(T())throw Error("createReadStream is not supported in browser environments");if(!zt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return zr(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let s=ie.isBuffer(e)?e:ie.from(e,"base64"),n=s.slice(0,16),i=s.slice(-16),o=s.slice(16,-16),c=Mn("aes-256-gcm",r,n);return c.setAuthTag(i),ie.concat([c.update(o),c.final()]).toString("utf8")}catch(s){throw Error(`Decryption failed: ${s instanceof Error?s.message:String(s)}`)}}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(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),s=this.formatFileTimestamp(t);if(this.fancy&&!T()){let i=e.split(`
|
|
7
|
+
`),o=Math.max(...i.map((u)=>u.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,a=`\u2514${"\u2500".repeat(o)}\u2518`,l=i.map((u)=>{let f=" ".repeat(o-u.length-2);return`\u2502 ${u}${f} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:R.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(c)})),l.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(a),showTimestamp:!1}))}else if(!T())console.error(`${s} ${this.environment}.INFO: [BOX] ${e}`);let n=`${s} ${this.environment}.INFO: [BOX] ${e}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(T())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${R.cyan("?")} ${e} (y/n) `);let r=(s)=>{let n=s.toString().trim().toLowerCase();N.stdin.removeListener("data",r);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!T()){let o=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",c=R.blue("\u25D0");console.error(`${c} ${o} ${R.cyan(r)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
9
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||T()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||T())return;N.stdout.write(`${"\r".padEnd(N.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||T()||!N.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),s=Math.round(e.barLength*r/100),n=e.barLength-s,i=R.green("\u2501".repeat(s)),o=R.gray("\u2501".repeat(n)),c=`[${i}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=t||r===100?R.green("\u2713"):R.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${R.gray(this.formatTag(this.name))}`:"",m=`\r${u}${f} ${c} ${a}${l}`,d=N.stdout.columns||80,p=" ".repeat(Math.max(0,d-m.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${m}${p}`,N.stdout.write(e.lastRenderedLine),t)N.stdout.write(`
|
|
10
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||T()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(T()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ze(this.config.logDirectory),r=[];for(let s of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(s):s.startsWith(this.name))||!s.endsWith(".log"))continue;let i=he(this.config.logDirectory,s);if(e.before)try{if((await me(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let s of r)try{await We(s),console.warn(`Deleted log file: ${s}`)}catch(n){console.error(`Failed to delete log file ${s}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function it(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&S(t[0])&&"id"in t[0]&&t[0].id===3&&S(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(S(t)&&S(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(S(e)&&"arr"in e&&Array.isArray(e.arr)&&S(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&S(t[0])&&S(e[0])){let s=[...t];for(let n of e)if(S(n)&&"name"in n){if(!s.find((o)=>S(o)&&("name"in o)&&o.name===n.name))s.push(n)}else if(S(n)&&"path"in n){if(!s.find((o)=>S(o)&&("path"in o)&&o.path===n.path))s.push(n)}else if(!s.some((i)=>yt(i,n)))s.push(n);return s}if(t.every((s)=>typeof s==="string")&&e.every((s)=>typeof s==="string")){let s=[...t];for(let n of e)if(!s.includes(n))s.push(n);return s}return t}if(!S(t)||!S(e))return t;let r={...e};for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s)){let n=t[s];if(n===null||n===void 0)continue;else if(S(n)&&S(r[s]))r[s]=it(r[s],n);else if(Array.isArray(n)&&Array.isArray(r[s]))if(n.length>0&&r[s].length>0&&S(n[0])&&S(r[s][0])){let i=[...n];for(let o of r[s])if(S(o)&&"name"in o){if(!i.find((a)=>S(a)&&("name"in a)&&a.name===o.name))i.push(o)}else if(S(o)&&"path"in o){if(!i.find((a)=>S(a)&&("path"in a)&&a.path===o.path))i.push(o)}else if(!i.some((c)=>yt(c,o)))i.push(o);r[s]=i}else if(n.every((i)=>typeof i==="string")&&r[s].every((i)=>typeof i==="string")){let i=[...n];for(let o of r[s])if(!i.includes(o))i.push(o);r[s]=i}else r[s]=n;else r[s]=n}return r}function Cr(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:it(e,t);if(Array.isArray(e))return r==="replace"?t:it(e,t);if(!S(t)||!S(e))return t;let s={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let i=t[n],o=s[n];if(i===null||i===void 0)continue;if(Array.isArray(i)||Array.isArray(o))if(r==="replace")s[n]=i;else s[n]=it(o,i);else if(S(i)&&S(o))s[n]=Cr(o,i,r);else s[n]=i}return s}function yt(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!yt(e[r],t[r]))return!1;return!0}if(S(e)&&S(t)){let r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!yt(e[n],t[n]))return!1}return!0}return!1}function S(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function rt(e,t,r="replace"){if(!As(e))return null;try{let s=await import(e),n=s.default||s;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Cr(t,n,r)}catch{return null}}catch{return null}}function xi(e,t,r=!1){if(!e)return t;let s=e.toUpperCase().replace(/-/g,"_"),n={...t};function i(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],m=(h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${s}_${f.map(m).join("_")}`,p=`${s}_${f.map((h)=>h.toUpperCase()).join("_")}`;if(r)O.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=i(u,f);else{let h=Le.env[d]||Le.env[p];if(h!==void 0){if(r)O.info(`Using environment variable ${h?d:p} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(h);else if(typeof u==="boolean")a[l]=h.toLowerCase()==="true";else if(Array.isArray(u))try{let g=JSON.parse(h);if(Array.isArray(g))a[l]=g;else a[l]=h.split(",").map((k)=>k.trim())}catch{a[l]=h.split(",").map((g)=>g.trim())}else a[l]=h}}}return a}return i(n)}async function Si({name:e="",alias:t,cwd:r,configDir:s,defaultConfig:n,verbose:i=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?xi(e,n,i):n,l=r||Le.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(i)O.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),m=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],p=t?[`${t}.config`,`.${t}.config`]:[],h=Array.from(new Set([l,j(l,"config"),j(l,".config"),s?j(l,s):void 0].filter(Boolean)));for(let g of h){if(i)O.info(`Searching for configuration in: ${g}`);let E=[j(l,"config"),j(l,".config")].concat(s?[j(l,s)]:[]).includes(g)?[...f,...m,...d,...p]:[...m,...f,...p,...d];for(let U of E)for(let D of u){let q=j(g,`${U}${D}`),Ne=await rt(q,a,c);if(Ne!==null){if(i)O.success(`Configuration loaded from: ${q}`);return Ne}}}if(e){let g=j(Vt(),".config",e),k=["config",`${e}.config`];if(t)k.push(`${t}.config`);if(i)O.info(`Checking user config directory: ${g}`);for(let E of k)for(let U of u){let D=j(g,`${E}${U}`),q=await rt(D,a,c);if(q!==null){if(i)O.success(`Configuration loaded from user config directory: ${D}`);return q}}}if(e){let g=j(Vt(),".config"),k=[`.${e}.config`];if(t)k.push(`.${t}.config`);if(i)O.info(`Checking user config directory for dotfile configs: ${g}`);for(let E of k)for(let U of u){let D=j(g,`${E}${U}`),q=await rt(D,a,c);if(q!==null){if(i)O.success(`Configuration loaded from user config directory dotfile: ${D}`);return q}}}if(e){let g=Vt(),k=[`.${e}.config`,`.${e}`];if(t)k.push(`.${t}.config`),k.push(`.${t}`);if(i)O.info(`Checking user home directory for dotfile configs: ${g}`);for(let E of k)for(let U of u){let D=j(g,`${E}${U}`),q=await rt(D,a,c);if(q!==null){if(i)O.success(`Configuration loaded from user home directory: ${D}`);return q}}}try{let g=j(l,"package.json");if(As(g)){let k=await import(g),E=k[e];if(!E&&t){if(E=k[t],E&&i)O.success(`Using alias "${t}" configuration from package.json`)}if(E&&typeof E==="object"&&!Array.isArray(E))try{if(i)O.success(`Configuration loaded from package.json: ${E===k[e]?e:t}`);return Cr(a,E,c)}catch(U){if(i)O.warn("Failed to merge package.json config:",U)}}}catch(g){if(i)O.warn("Failed to load package.json:",g)}if(i)O.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function Ri(e,t={}){let r=ft.cwd();while(r.includes("storage"))r=Hr(r,"..");let s=Hr(r,e||"");if(t?.relative)return kn(ft.cwd(),s);return s}async function Ci(){try{let e=await Si({name:"clarity",alias:"logging",defaultConfig:ct,cwd:ft.cwd()});return{...ct,...e||{}}}catch{return ct}}function P(){if(re.env.NODE_ENV==="test"||re.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ei(){if(re.env.NODE_ENV==="test"||re.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof re<"u"){let e=re.type;if(e==="renderer"||e==="worker")return!1;return!!(re.versions&&(re.versions.node||re.versions.bun))}return!1}class Is{async format(e){let t=await Ei(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:we.pid,hostname:t(),environment:we.env.NODE_ENV||"development",platform:we.platform,version:we.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:we.env.NODE_ENV||we.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class wt{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...dr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Is,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??y.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},s=t.timestamp!==void 0;if(s)delete r.timestamp;if(this.config={...this.config,...r,timestamp:s||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...lt,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...lt};return{...lt,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:dr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,i=0,o=3,c=1000;while(i<o)try{try{try{await _n(this.config.logDirectory,ts.F_OK|ts.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Vn(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Q.from(e);try{if(!Je(this.currentLogFile))await Xt(this.currentLogFile,"",{mode:420});if(n=es(this.currentLogFile,"a",420),qn(n,a,{flag:"a"}),Qr(n),n!==void 0)Gt(n),n=void 0;if((await ge(this.currentLogFile)).size===0){if(await Xt(this.currentLogFile,a,{flag:"w",mode:420}),(await ge(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(i<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,f);let m=c*2**i;await new Promise((d)=>setTimeout(d,m)),i++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{Gt(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(i===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}i++;let l=c*2**(i-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let s=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(s,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 ye(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 ye(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ye(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,s=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},s)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),s=this.generateKey();this.currentKeyId=r,this.keys.set(r,s),this.encryptionKeys.set(r,{key:s,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Jt(16).toString("hex")}generateKey(){return Jt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Jt(16),s=Ln("aes-256-gcm",t,r),n=Q.isBuffer(e)?e:Q.from(e,"utf8"),i=s.update(n),o=s.final(),c=i.length+o.length,a=s.getAuthTag(),l=Q.allocUnsafe(16+c+16);return r.copy(l,0),i.copy(l,16),o.copy(l,16+i.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let s=ss(),n=[];s.on("data",(i)=>n.push(i)),s.on("end",()=>t(Q.from(Q.concat(n)))),s.on("error",r),s.write(e),s.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let e=await ge(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,s=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Ge(this.config.logDirectory),i=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ge(r).catch(()=>null))try{if(await rs(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Xe(c)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Xt(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),i=r.replace(/\.log$/,`-${n}.log`);if(await ge(r).catch(()=>null))await rs(r,i)}if(this.currentLogFile=s,t.maxFiles){let i=(await Ge(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of i.slice(t.maxFiles))await Xe(ye(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Zr(e),s=Un(t),n=ss();await zn(r,n,s)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let s=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(s);console.log(s)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Je(this.currentLogFile))try{let e=es(this.currentLogFile,"r+");Qr(e),Gt(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ge(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Xe(ye(this.config.logDirectory,r))}catch(s){console.error(`Failed to delete temp file ${r}:`,s)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?b.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let e=typeof y.env.NO_COLOR<"u",t=y.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof y.stderr<"u"&&y.stderr.isTTY||typeof y.stdout<"u"&&y.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:s="",message:n,level:i,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(i==="warning")d.push("WARN");else if(i==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(s)d.push(s.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=y.stdout.columns||120,l="";if(i==="warning"||i==="error")l=`${r} ${n}`;else if(i==="info"||i==="success")l=`${r} ${s} ${n}`;else l=`${r} ${s} ${b.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,m=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):i});let r=/%([sdijfo%])/g,s=0,n=e.replace(r,(i,o)=>{if(o==="%")return"%";if(s>=t.length)return i;let c=t[s++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return i}});if(s<t.length)n+=` ${t.slice(s).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,s,n)=>{let i=b.underline(b.blue(s)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${i}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${i}\x1B]8;;\x1B\\`;return i}),t=t.replace(/`([^`]+)`/g,(r,s)=>b.bgGray(s)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,s)=>b.bold(s)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,s)=>b.italic(s)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,s)=>b.italic(s)),t=t.replace(/~([^~]+)~/g,(r,s)=>b.strikethrough(s)),t}supportsHyperlinks(){if(P())return!1;let e=y.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=y.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Hn(t)||t.startsWith("./")||t.startsWith("../"))t=Kn(t);else return null;return Je(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let s=new Date,n=this.formatConsoleTimestamp(s),i=this.formatFileTimestamp(s),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Hs[e],m=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:m,message:b.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:m,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:m,message:b.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:m,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:m,message:a,level:e}),console.error(d),c){let p=c.split(`
|
|
11
|
+
`);for(let h of p)if(h.trim()&&!h.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:b.gray(` ${h}`),level:e,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${i} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
12
|
+
`;if(c)u+=`${c}
|
|
13
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let s=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:s,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!P()&&y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!P()&&y.stdout.isTTY)y.stdout.write(`
|
|
14
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&y.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",s=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:s,icon:this.options.showIcons===!1?"":b.blue("\u25D0"),tag:r,message:`${b.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let s=performance.now(),n=Math.round(s-t),i=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
15
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":b.green("\u2713"),tag:u,message:`${i}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!P())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new wt(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!Je(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Zr(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let s=Q.isBuffer(e)?e:Q.from(e,"base64"),n=s.subarray(0,16),i=s.subarray(s.length-16),o=s.subarray(16,s.length-16),c=Bn("aes-256-gcm",r,n);c.setAuthTag(i);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Q.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(s){throw Error(`Decryption failed: ${s instanceof Error?s.message:String(s)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),s=this.formatFileTimestamp(t),{consoleText:n,fileText:i}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
|
|
16
|
+
`),a=Math.max(...c.map((m)=>m.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,u=`\u2514${"\u2500".repeat(a)}\u2518`,f=c.map((m)=>this.formatConsoleMessage({timestamp:r,message:b.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:b.cyan(l),showTimestamp:!1})),f.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:r,message:b.cyan(u),showTimestamp:!1}))}else if(!P())console.error(`${s} ${this.environment}.INFO: [BOX] ${i}`);let o=`${s} ${this.environment}.INFO: [BOX] ${i}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(P())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${b.cyan("?")} ${e} (y/n) `);let r=(s)=>{let n=s.toString().trim().toLowerCase();y.stdin.removeListener("data",r);try{if(typeof y.stdin.setRawMode==="function")y.stdin.setRawMode(!1)}catch{}y.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof y.stdin.setRawMode==="function")y.stdin.setRawMode(!0)}catch{}y.stdin.resume(),y.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let m=t[l++];switch(f){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:s,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${b.blue("\u25D0")} `;console.error(`${l}${a} ${b.cyan(s)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
18
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!y.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),s=Math.round(e.barLength*r/100),n=e.barLength-s,i=b.green("\u2501".repeat(s)),o=b.gray("\u2501".repeat(n)),c=`[${i}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?b.green("\u2713"):b.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",m=`\r${u}${f} ${c} ${a}${l}`,d=y.stdout.columns||80,p=" ".repeat(Math.max(0,d-m.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${m}${p}`,y.stdout.write(e.lastRenderedLine),t)y.stdout.write(`
|
|
19
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||P()||!y.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ge(this.config.logDirectory),r=[];for(let s of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(s):s.startsWith(this.name))||!s.endsWith(".log"))continue;let i=ye(this.config.logDirectory,s);if(e.before)try{if((await ge(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let s of r)try{await Xe(s),console.warn(`Deleted log file: ${s}`)}catch(n){console.error(`Failed to delete log file ${s}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Os(e,t={}){let{maxRetries:r=3,retryDelay:s=1000,isRetryable:n=()=>!0,fallback:i}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!n(o))break;if(s>0)await new Promise((l)=>setTimeout(l,s))}if(i!==void 0)return i;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Ds(e){return e instanceof _}function Ti(e){return e instanceof bt}function $i(e){if(Ds(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class Et{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:s,useCamelCase:n=!0,useBackwardCompatibility:i=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=s||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:n,useBackwardCompatibility:i,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return qe.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,s){for(let[n,i]of Object.entries(e)){let o=[...t,n],c=o.map((u)=>this.formatEnvKey(u,s.useCamelCase)),a=`${r}_${c.join("_")}`,l=s.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(s.verbose);if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.processObject(i,o,r,s);else{let u=Ye.env[a]||(l?Ye.env[l]:void 0);if(u!==void 0){if(s.verbose){let f=Ye.env[a]?a:l}try{e[n]=this.parseEnvironmentValue(u,typeof i,a,s.customParsers,s.configName)}catch(f){if(f instanceof vt)throw f;throw oe.envVar(a,u,typeof i,s.configName)}}}}}parseEnvironmentValue(e,t,r,s,n){for(let[i,o]of Object.entries(s))try{return o(e)}catch{continue}for(let i of this.defaultParsers)if(i.canParse(e,t))try{return i.parse(e)}catch{throw oe.envVar(r,e,`${t} (via ${i.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[s,n]of Object.entries(Ye.env))if(s.startsWith(r)&&n!==void 0)t[s]=n;return t}validateEnvironmentVariable(e,t,r){let s=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))s.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){s.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:s.length===0,errors:s}}generateEnvVarDocs(e,t,r={}){let{prefix:s,format:n="text"}=r,i=s||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],i,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,s){for(let[n,i]of Object.entries(e)){let o=[...t,n],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.extractEnvVarInfo(i,o,r,s);else s.push({key:c,type:Array.isArray(i)?"array":typeof i,description:`Configuration for ${o.join(".")}`,example:this.generateExample(i)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
20
|
+
|
|
21
|
+
`;for(let s of e)r+=`${s.key}
|
|
22
|
+
`,r+=` Type: ${s.type}
|
|
23
|
+
`,r+=` Description: ${s.description}
|
|
24
|
+
`,r+=` Example: ${s.example}
|
|
25
|
+
|
|
26
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
27
|
+
|
|
28
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
29
|
+
`,r+=`|----------|------|-------------|----------|
|
|
30
|
+
`;for(let s of e)r+=`| \`${s.key}\` | ${s.type} | ${s.description} | \`${s.example}\` |
|
|
31
|
+
`;return r}}function ki(e,t){let r=qs("process");if(typeof r>"u"||!r.env)return t;let s=r.env[e];return s!==void 0?s:t}function js(e,t,r={}){return Ls(e,t,r,new WeakMap)}function Ls(e,t,r,s){let{arrayMergeMode:n="replace",skipNullish:i=!1,customMerger:o}=r;if(t===null||t===void 0)return i?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Bs(e,t,n,s);if(!H(t)||!H(e))return t;return Mi(e,t,r,s)}function Bs(e,t,r,s){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Pi(e,t);case"smart":return Ai(e,t,s);default:return t}return t}function Pi(e,t){let r=[...t];for(let s of e)if(!r.some((n)=>ur(n,s)))r.push(s);return r}function Ai(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(H(t[0])&&H(e[0]))return Fi(e,t,r);if(t.every((s)=>typeof s==="string")&&e.every((s)=>typeof s==="string")){let s=[...t];for(let n of e)if(!s.includes(n))s.push(n);return s}return t}function Fi(e,t,r){let s=[...t];for(let n of e){if(!H(n)){s.push(n);continue}let i=["id","name","key","path","type"],o=!1;for(let c of i)if(c in n){if(s.find((l)=>H(l)&&(c in l)&&l[c]===n[c])){o=!0;break}}if(!o)s.push(n)}return s}function Mi(e,t,r,s){let n=t;if(H(n)&&s.has(n))return s.get(n);let i={...e};if(H(n))s.set(n,i);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=i[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){i[o]=c;continue}if(H(c)&&H(a))i[o]=Ls(a,c,r,s);else if(Array.isArray(c)||Array.isArray(a))i[o]=Bs(a,c,r.arrayMergeMode||"smart",s);else i[o]=c}return i}function Er(e,t,r="replace"){return js(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ur(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ur(e[r],t[r]))return!1;return!0}if(H(e)&&H(t)){let r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ur(e[n],t[n]))return!1}return!0}return!1}function H(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Tt{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:s="replace",useCache:n=!0,cacheTtl:i,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=Se.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Ze(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,m="default"in u,d=Object.keys(u).length>0;if(!m&&!d)throw new Be(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Be(e,Error("Configuration must export a valid object"),"unknown");let g={config:Er(t,f,s),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Se.setWithFileCheck("file",g,e,i);return g}catch(l){throw l instanceof Error?oe.configLoad(e,l):oe.configLoad(e,Error(String(l)))}};if(o)return qe.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let s of e)try{let n=await this.loadFromPath(s,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${s}:`,n)}return null}generateConfigPaths(e,t,r){let s=this.generateNamePatterns(e,r),n=[];for(let i of s)for(let o of this.extensions)n.push(Yt(t,`${i}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Os(async()=>Ze(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let s=[];if(!Ze(e))return s;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let i of n)for(let o of this.extensions){let c=Yt(e,`${i}${o}`);if(await this.checkFileAccess(c))s.push(c)}}else try{let{readdirSync:n}=await import("fs"),i=n(e);for(let o of i)if(this.looksLikeConfigFile(o)){let c=Yt(e,o);if(await this.checkFileAccess(c))s.push(c)}}catch{return[]}return s}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!Ze(e))return t.push("Configuration file does not exist"),t;let r=await import(e),s=r.default||r;if(s===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof s!=="object"||s===null)t.push("Configuration must be an object");else if(Array.isArray(s))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),i=n(e,"utf8");JSON.parse(i)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(s)=>{try{let n=await this.loadFromPath(s,{},t);if(n)r.set(s,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${s}:`,n)}})),r}}class Tr{async validateConfiguration(e,t,r={}){let{stopOnFirstError:s=!1,validateRequired:n=!0,validateTypes:i=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],m={stopOnFirstError:s,validateRequired:n,validateTypes:i,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],m);else return this.validateWithJSONSchema(e,t,m)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await qe.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Wn(t))throw new Ue(t,[{path:"",message:"Schema file does not exist"}]);let s=await import(t),n=s.default||s;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(s){throw new Ue(t,[{path:"",message:`Failed to load schema: ${s}`}])}}validateWithJSONSchema(e,t,r){let s=[],n=[];return this.validateObjectAgainstSchema(e,t,"",s,n,r),{isValid:s.length===0,errors:s,warnings:n}}validateObjectAgainstSchema(e,t,r,s,n,i){if(i.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(s.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),i.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(s.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),i.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)s.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)s.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))s.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)s.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)s.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,s,n,i),i.stopOnFirstError&&s.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(i.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(s.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),i.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,s,n,i),i.stopOnFirstError&&s.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let s=[],n=[];for(let i of t)try{let o=this.getValueByPath(e,i.path),c=this.validateWithRule(o,i,i.path);if(s.push(...c),r.stopOnFirstError&&s.length>0)break}catch(o){s.push({path:i.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:s.length===0,errors:s,warnings:n}}validateWithRule(e,t,r){let s=[];if(t.required&&(e===void 0||e===null))return s.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),s;if(e===void 0||e===null)return s;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)s.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)s.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)s.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))s.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))s.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)s.push({path:r,message:t.message||n,rule:"custom"})}return s}getValueByPath(e,t){if(!t)return e;let r=t.split("."),s=e;for(let n of r)if(s&&typeof s==="object"&&n in s)s=s[n];else return;return s}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let s of r){let[,n,i,o]=s;t.push({path:n,required:!i,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:zs},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class $r{fileLoader=new Tt;envProcessor=new Et;validator=new Tr;async loadConfig(e){let t=Date.now(),{cache:r,performance:s,schema:n,validate:i,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),m=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(m||u))throw a;if(f&&(!l||!m))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||i)await this.validateConfiguration(c.config,n,i,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(s?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(s.onMetrics)s.onMetrics(a);if(s.slowThreshold&&a.duration>s.slowThreshold)W.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw W.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:s="",alias:n,cwd:i,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=i||le.cwd(),m=[],d=await this.loadLocalConfiguration(s,n,f,o,c,l,u,a,r);if(d)return m.push(...this.getLocalSearchPaths(s,n,f,o)),this.finalizeResult(d,m,a,s,u);let p=await this.loadHomeConfiguration(s,n,c,l,u,a);if(p)return m.push(...this.getHomeSearchPaths(s,n)),this.finalizeResult(p,m,a,s,u);let h=await this.loadPackageJsonConfiguration(s,n,f,c,l,u,a);if(h)return m.push(L(f,"package.json")),this.finalizeResult(h,m,a,s,u);if(m.push(...this.getAllSearchPaths(s,n,f,o)),t)throw oe.configNotFound(s,m,n);return{...await this.applyEnvironmentVariables(s,c,a,u),warnings:[`No configuration file found for "${s}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,s,n,i,o,c,a){let l=c?je(e,n,o):n,u=this.getLocalDirectories(r,s);for(let f of u){if(o)W.info(`Searching for configuration in: ${f}`);let m=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(m,l,{arrayStrategy:i,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)W.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,s,n,i){if(!e)return null;let o=i?je(e,r,n):r,c=[L(de(),".config",e),L(de(),".config"),de()];for(let a of c){if(n)W.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:s,verbose:n});if(u){if(n)W.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,s,n,i,o){let c=o?je(e,s,i):s;try{let a=L(r,"package.json");if(!cr(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(i)W.success(`Configuration loaded from package.json: ${f}`);return{config:Er(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(i)W.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,s){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:je(e,t,s),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,s,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,s){let n=[];if(r){let i=r(e);if(i)n.push(...i)}if(t){let i=await this.validator.validateConfiguration(e,t);if(!i.isValid)n.push(...i.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw oe.configValidation(s||"unknown",n,s)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Se.get(r)||null}cacheResult(e,t,r,s){let n=this.generateCacheKey(e,s);Se.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,L(e,"config"),L(e,".config"),t?L(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,s){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,s)),n.push(...this.getHomeSearchPaths(e,t)),n.push(L(r,"package.json")),n}getLocalSearchPaths(e,t,r,s){let n=this.getLocalDirectories(r,s),i=[];for(let o of n)i.push(...this.fileLoader.generateConfigPaths(e,o,t));return i}getHomeSearchPaths(e,t){if(!e)return[];let r=[L(de(),".config",e),L(de(),".config"),de()],s=[];for(let n of r)s.push(...this.fileLoader.generateConfigPaths(e,n,t));return s}async loadConfigWithResult(e){return this.loadConfig(e)}}function ds(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),s=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||s}async function Ni(e){return ne.loadConfig({...e,__strictErrorHandling:!0})}async function Us(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let s;if(r)s=await ne.loadConfig(e);else s=await ne.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return s?.config??t}catch(s){let n=s instanceof Error?s.name:"UnknownError",i=s instanceof Error?s.message:String(s);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||i.includes("config"))&&e.verbose)W.warn("Unexpected error loading config, using defaults:",[s instanceof Error?s:Error(String(s))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await ne.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Ii(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await ne.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&ds(r)))return(await ne.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await ne.loadConfig({...e,cwd:e.cwd||le.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ds(t)))return(await ne.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Oi(e,t,r="replace"){let s=new Tt;try{let n=await s.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function je(e,t,r=!1){let s=new Et,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function i(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],m=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((h)=>h.toUpperCase()).join("")}`,`${n}_${f.map((h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,p;for(let h of m)if(d=le.env[h],d!==void 0){p=h;break}if(d!==void 0&&p)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let h=Number(d);if(!Number.isNaN(h))a[l]=h}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((h)=>h.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=i(u,f)}return a}return i(t)}function Di(e){let t=L(le.cwd(),e.configDir),r=L(le.cwd(),e.generatedDir),s=L(r,"config-types.ts");if(!cr(Vr(s)))Cn(Vr(s),{recursive:!0,mode:511});let n=cr(t)?En(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],i=`// Generated by bunfig v${fo}
|
|
32
|
+
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
33
|
+
`;Tn(s,i,{mode:438})}function ji(e){let t=null,r=null,s=()=>{if(!r)r=Us(e).then((i)=>(t=i,i),(i)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)W.warn("Config loading failed, using defaults:",[i instanceof Error?i:Error(String(i))]);return o});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,s(),new Proxy({},{get(i,o){if(t)return t[o];let c=n[o];return s(),c},has(i,o){return o in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(i,o){return Object.getOwnPropertyDescriptor(t||n,o)},set(i,o,c){if(!t)t={...n};return t[o]=c,!0}})}function Li(e){let t=ns(Xn.cwd(),e?.configDir||"./config");function r(){if(!Jn(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),i=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Gn(t).filter((a)=>n.has(Zt(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=Zt(l).toLowerCase(),f=c.get(a);if(!f){c.set(a,l);continue}let m=Zt(f).toLowerCase();if(i.indexOf(u)<i.indexOf(m))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function s(){let n=r(),i=n.map((l)=>l.base),o=i.length?i.map((l)=>`'${l}'`).join(" | "):"string",c=n.length?`{
|
|
34
|
+
${n.map((l)=>{let u=ns(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${u}').default`}).join(`,
|
|
35
|
+
`)}
|
|
36
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
37
|
+
export type ConfigByName = ${c}
|
|
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(n){n.onResolve({filter:/^virtual:bunfig-types$/},(i)=>({path:i.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:s(),loader:"ts"}))}}}var qs,Se,qe,_s,Bi,Ui,ms,ot,fr,I,R,qi,hs,_i,ps,Vi,Hi,rr,Ki,gs,ys,sr,zi,Wi,Ji,Gi,at,Vs,Xi,O,Yi,Zi,ws,ct,dr,A,b,Qi,bs,eo,vs,to,ro,nr,so,xs,Ss,no,ir,io,oo,ao,co,lo,lt,Hs,uo,fo="0.15.6",_,bt,Be,mr,hr,vt,pr,gr,Ue,yr,wr,oe,Ks,zs,W,ne,Ws,Js,mo=di(async()=>{qs=import.meta.require,Se=new xr,qe=new Sr,_s={createKey:mi,isEquivalent:hi,estimateMemoryUsage:pi},Bi=mt(lr.cwd(),"config"),Ui=mt(lr.cwd(),"src/generated"),ms=dt.env.CLARITY_LOG_DIR||Pn(wi(),"logs"),ot={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ms,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},fr=await bi(),I={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},R=I,qi=I.red,hs=I.green,_i=I.yellow,ps=I.blue,Vi=I.magenta,Hi=I.cyan,rr=I.white,Ki=I.gray,gs=I.bgRed,ys=I.bgYellow,sr=I.bold,zi=I.dim,Wi=I.italic,Ji=I.underline,Gi=I.reset,at={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Vs={debug:"\uD83D\uDD0D",info:ps("\u2139"),success:hs("\u2713"),warning:ys(rr(sr(" WARN "))),error:gs(rr(sr(" ERROR ")))},Xi=new gt("stacks"),O=new gt("bunfig",{showTags:!0}),Yi=j(Le.cwd(),"config"),Zi=j(Le.cwd(),"src/generated"),ws=ft.env.CLARITY_LOG_DIR||$n(Ri(),"logs"),ct={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ws,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},dr=await Ci(),A={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},b=A,Qi=A.red,bs=A.green,eo=A.yellow,vs=A.blue,to=A.magenta,ro=A.cyan,nr=A.white,so=A.gray,xs=A.bgRed,Ss=A.bgYellow,no=A.bgGray,ir=A.bold,io=A.dim,oo=A.italic,ao=A.underline,co=A.strikethrough,lo=A.reset,lt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Hs={debug:"\uD83D\uDD0D",info:vs("\u2139"),success:bs("\u2713"),warning:Ss(nr(ir(" WARN "))),error:xs(nr(ir(" ERROR ")))},uo=new wt("stacks"),_=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,s])=>`${r}: ${s}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},bt=class extends _{code="CONFIG_NOT_FOUND";constructor(t,r,s){let n=s?` or alias "${s}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:s,searchPaths:r,searchPathCount:r.length})}},Be=class extends _{code="CONFIG_LOAD_ERROR";constructor(t,r,s){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:s,originalError:r.name,originalMessage:r.message});this.cause=r}},mr=class extends _{code="CONFIG_VALIDATION_ERROR";constructor(t,r,s){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:s,validationErrors:r,errorCount:r.length})}},hr=class extends _{code="CONFIG_MERGE_ERROR";constructor(t,r,s,n){super(`Failed to merge configuration from "${t}" with "${r}": ${s.message}`,{sourcePath:t,targetPath:r,configName:n,originalError:s.name,originalMessage:s.message});this.cause=s}},vt=class extends _{code="ENV_VAR_ERROR";constructor(t,r,s,n){super(`Failed to parse environment variable "${t}" with value "${r}" as ${s}`,{envKey:t,envValue:r,expectedType:s,configName:n})}},pr=class extends _{code="FILE_SYSTEM_ERROR";constructor(t,r,s){super(`File system ${t} failed for "${r}": ${s.message}`,{operation:t,path:r,originalError:s.name,originalMessage:s.message});this.cause=s}},gr=class extends _{code="TYPE_GENERATION_ERROR";constructor(t,r,s){super(`Failed to generate types from "${t}" to "${r}": ${s.message}`,{configDir:t,outputPath:r,originalError:s.name,originalMessage:s.message});this.cause=s}},Ue=class extends _{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,s){super(`Schema validation failed${s?` for config "${s}"`:""}`,{schemaPath:t,configName:s,validationErrors:r,errorCount:r.length})}},yr=class extends _{code="BROWSER_CONFIG_ERROR";constructor(t,r,s,n){super(`Failed to fetch configuration from "${t}": ${r} ${s}`,{endpoint:t,status:r,statusText:s,configName:n})}},wr=class extends _{code="PLUGIN_ERROR";constructor(t,r,s){super(`Plugin "${t}" failed during ${r}: ${s.message}`,{pluginName:t,operation:r,originalError:s.name,originalMessage:s.message});this.cause=s}},oe={configNotFound(e,t,r){return new bt(e,t,r)},configLoad(e,t,r){return new Be(e,t,r)},configValidation(e,t,r){return new mr(e,t,r)},configMerge(e,t,r,s){return new hr(e,t,r,s)},envVar(e,t,r,s){return new vt(e,t,r,s)},fileSystem(e,t,r){return new pr(e,t,r)},typeGeneration(e,t,r){return new gr(e,t,r)},schemaValidation(e,t,r){return new Ue(e,t,r)},browserConfig(e,t,r,s){return new yr(e,t,r,s)},plugin(e,t,r){return new wr(e,t,r)}},Ks={replace:"replace",concat:"concat",smart:"smart"},zs=/^https?:\/\//,W=new wt("bunfig",{showTags:!0}),ne=new $r,Ws=L(le.cwd(),"config"),Js=L(le.cwd(),"src/generated")});function ho(e,t={}){let r=ht.cwd();while(r.includes("storage"))r=is(r,"..");let s=is(r,e||"");if(t?.relative)return Zn(ht.cwd(),s);return s}var po=ht.env.CLARITY_LOG_DIR||Yn(ho(),"logs"),Gs={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:po,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},xt={...Gs},Lc=(async()=>{try{let{loadConfig:e}=await mo().then(()=>Ms),t=await e({name:"clarity",alias:"logging",defaultConfig:Gs,cwd:ht.cwd()});if(t)Object.assign(xt,t)}catch{}return xt})();function F(){if(se.env.NODE_ENV==="test"||se.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function go(){if(se.env.NODE_ENV==="test"||se.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof se<"u"){let e=se.type;if(e==="renderer"||e==="worker")return!1;return!!(se.versions&&(se.versions.node||se.versions.bun))}return!1}class Xs{async format(e){let t=await go(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:xe.pid,hostname:t(),environment:xe.env.NODE_ENV||"development",platform:xe.platform,version:xe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xe.env.NODE_ENV||xe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var M={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},x=M,Bc=M.red,yo=M.green,Uc=M.yellow,wo=M.blue,qc=M.magenta,_c=M.cyan,Rs=M.white,Vc=M.gray,bo=M.bgRed,vo=M.bgYellow,Hc=M.bgGray,Cs=M.bold,Kc=M.dim,zc=M.italic,Wc=M.underline,Jc=M.strikethrough,Gc=M.reset,or={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xo={debug:"\uD83D\uDD0D",info:wo("\u2139"),success:yo("\u2713"),warning:vo(Rs(Cs(" WARN "))),error:bo(Rs(Cs(" ERROR ")))};class $t{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...xt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Xs,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??w.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},s=t.timestamp!==void 0;if(s)delete r.timestamp;if(this.config={...this.config,...r,timestamp:s||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...or,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...or};return{...or,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:xt.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!F()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,i=0,o=3,c=1000;while(i<o)try{try{try{await si(this.config.logDirectory,ls.F_OK|ls.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await ni(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ee.from(e);try{if(!Qe(this.currentLogFile))await tr(this.currentLogFile,"",{mode:420});if(n=cs(this.currentLogFile,"a",420),ri(n,a,{flag:"a"}),as(n),n!==void 0)er(n),n=void 0;if((await be(this.currentLogFile)).size===0){if(await tr(this.currentLogFile,a,{flag:"w",mode:420}),(await be(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(i<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,f);let m=c*2**i;await new Promise((d)=>setTimeout(d,m)),i++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{er(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(i===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}i++;let l=c*2**(i-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let s=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(s,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 ve(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 ve(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ve(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(F())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,s=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},s)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),s=this.generateKey();this.currentKeyId=r,this.keys.set(r,s),this.encryptionKeys.set(r,{key:s,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Qt(16).toString("hex")}generateKey(){return Qt(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Qt(16),s=Qn("aes-256-gcm",t,r),n=ee.isBuffer(e)?e:ee.from(e,"utf8"),i=s.update(n),o=s.final(),c=i.length+o.length,a=s.getAuthTag(),l=ee.allocUnsafe(16+c+16);return r.copy(l,0),i.copy(l,16),o.copy(l,16+i.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let s=fs(),n=[];s.on("data",(i)=>n.push(i)),s.on("end",()=>t(ee.from(ee.concat(n)))),s.on("error",r),s.write(e),s.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(F())return;if(!this.shouldWriteToFile())return;let e=await be(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,s=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await et(this.config.logDirectory),i=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await be(r).catch(()=>null))try{if(await us(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await tt(c)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await tr(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),i=r.replace(/\.log$/,`-${n}.log`);if(await be(r).catch(()=>null))await us(r,i)}if(this.currentLogFile=s,t.maxFiles){let i=(await et(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of i.slice(t.maxFiles))await tt(ve(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=os(e),s=ti(t),n=fs();await ai(r,n,s)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let s=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(s);console.log(s)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Qe(this.currentLogFile))try{let e=cs(this.currentLogFile,"r+");as(e),er(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!F()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await et(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await tt(ve(this.config.logDirectory,r))}catch(s){console.error(`Failed to delete temp file ${r}:`,s)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?x.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F())return!1;let e=typeof w.env.NO_COLOR<"u",t=w.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof w.stderr<"u"&&w.stderr.isTTY||typeof w.stdout<"u"&&w.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:s="",message:n,level:i,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(i==="warning")d.push("WARN");else if(i==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(s)d.push(s.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=w.stdout.columns||120,l="";if(i==="warning"||i==="error")l=`${r} ${n}`;else if(i==="info"||i==="success")l=`${r} ${s} ${n}`;else l=`${r} ${s} ${x.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,m=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):i});let r=/%([sdijfo%])/g,s=0,n=e.replace(r,(i,o)=>{if(o==="%")return"%";if(s>=t.length)return i;let c=t[s++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return i}});if(s<t.length)n+=` ${t.slice(s).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,s,n)=>{let i=x.underline(x.blue(s)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${i}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${i}\x1B]8;;\x1B\\`;return i}),t=t.replace(/`([^`]+)`/g,(r,s)=>x.bgGray(s)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,s)=>x.bold(s)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,s)=>x.italic(s)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,s)=>x.italic(s)),t=t.replace(/~([^~]+)~/g,(r,s)=>x.strikethrough(s)),t}supportsHyperlinks(){if(F())return!1;let e=w.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=w.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ii(t)||t.startsWith("./")||t.startsWith("../"))t=oi(t);else return null;return Qe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let s=new Date,n=this.formatConsoleTimestamp(s),i=this.formatFileTimestamp(s),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":xo[e],m=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:m,message:x.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:m,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:m,message:x.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:m,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:m,message:a,level:e}),console.error(d),c){let p=c.split(`
|
|
41
|
+
`);for(let h of p)if(h.trim()&&!h.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:x.gray(` ${h}`),level:e,showTimestamp:!1}))}break}}else if(!F()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${i} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
42
|
+
`;if(c)u+=`${c}
|
|
43
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let s=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:s,lastRenderedLine:""},this.shouldStyleConsole()&&!F()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!F()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!F()&&w.stdout.isTTY)w.stdout.write(`
|
|
44
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!F()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",s=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:s,icon:this.options.showIcons===!1?"":x.blue("\u25D0"),tag:r,message:`${x.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let s=performance.now(),n=Math.round(s-t),i=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
45
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":x.green("\u2713"),tag:u,message:`${i}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!F())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new $t(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(F())throw Error("createReadStream is not supported in browser environments");if(!Qe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return os(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let s=ee.isBuffer(e)?e:ee.from(e,"base64"),n=s.subarray(0,16),i=s.subarray(s.length-16),o=s.subarray(16,s.length-16),c=ei("aes-256-gcm",r,n);c.setAuthTag(i);let a=c.update(o),l=c.final(),u=a.length+l.length,f=ee.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(s){throw Error(`Decryption failed: ${s instanceof Error?s.message:String(s)}`)}}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(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),s=this.formatFileTimestamp(t),{consoleText:n,fileText:i}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
|
|
46
|
+
`),a=Math.max(...c.map((m)=>m.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,u=`\u2514${"\u2500".repeat(a)}\u2518`,f=c.map((m)=>this.formatConsoleMessage({timestamp:r,message:x.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(l),showTimestamp:!1})),f.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(u),showTimestamp:!1}))}else if(!F())console.error(`${s} ${this.environment}.INFO: [BOX] ${i}`);let o=`${s} ${this.environment}.INFO: [BOX] ${i}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(F())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${x.cyan("?")} ${e} (y/n) `);let r=(s)=>{let n=s.toString().trim().toLowerCase();w.stdin.removeListener("data",r);try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!1)}catch{}w.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!0)}catch{}w.stdin.resume(),w.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let m=t[l++];switch(f){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:s,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${x.blue("\u25D0")} `;console.error(`${l}${a} ${x.cyan(s)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
48
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!w.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),s=Math.round(e.barLength*r/100),n=e.barLength-s,i=x.green("\u2501".repeat(s)),o=x.gray("\u2501".repeat(n)),c=`[${i}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?x.green("\u2713"):x.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",m=`\r${u}${f} ${c} ${a}${l}`,d=w.stdout.columns||80,p=" ".repeat(Math.max(0,d-m.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${m}${p}`,w.stdout.write(e.lastRenderedLine),t)w.stdout.write(`
|
|
49
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||F()||!w.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(F()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await et(this.config.logDirectory),r=[];for(let s of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(s):s.startsWith(this.name))||!s.endsWith(".log"))continue;let i=ve(this.config.logDirectory,s);if(e.before)try{if((await be(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let s of r)try{await tt(s),console.warn(`Deleted log file: ${s}`)}catch(n){console.error(`Failed to delete log file ${s}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var Xc=new $t("stacks");class J extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class Ys extends J{code="CONFIG_NOT_FOUND";constructor(e,t,r){let s=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(s.length===1)n=` or alias "${s[0]}"`;else if(s.length>1)n=` or aliases ${s.map((i)=>`"${i}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class St extends J{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class Zs extends J{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Qs extends J{code="CONFIG_MERGE_ERROR";constructor(e,t,r,s){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:s,originalError:r.name,originalMessage:r.message});this.cause=r}}class kr extends J{code="ENV_VAR_ERROR";constructor(e,t,r,s){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:s})}}class en extends J{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class tn extends J{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Rt extends J{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class rn extends J{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,s){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:s})}}class sn extends J{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var ce={configNotFound(e,t,r){return new Ys(e,t,r)},configLoad(e,t,r){return new St(e,t,r)},configValidation(e,t,r){return new Zs(e,t,r)},configMerge(e,t,r,s){return new Qs(e,t,r,s)},envVar(e,t,r,s){return new kr(e,t,r,s)},fileSystem(e,t,r){return new en(e,t,r)},typeGeneration(e,t,r){return new tn(e,t,r)},schemaValidation(e,t,r){return new Rt(e,t,r)},browserConfig(e,t,r,s){return new rn(e,t,r,s)},plugin(e,t,r){return new sn(e,t,r)}};async function So(e,t={}){let{maxRetries:r=3,retryDelay:s=1000,isRetryable:n=()=>!0,fallback:i}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!n(o))break;if(s>0)await new Promise((l)=>setTimeout(l,s))}if(i!==void 0)return i;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class Pr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:s,useCamelCase:n=!0,useBackwardCompatibility:i=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=s||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:n,useBackwardCompatibility:i,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return vr.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,s){for(let[n,i]of Object.entries(e)){let o=[...t,n],c=o.map((u)=>this.formatEnvKey(u,s.useCamelCase)),a=`${r}_${c.join("_")}`,l=s.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(s.verbose);if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.processObject(i,o,r,s);else{let u=st.env[a]||(l?st.env[l]:void 0);if(u!==void 0){if(s.verbose){let f=st.env[a]?a:l}try{e[n]=this.parseEnvironmentValue(u,typeof i,a,s.customParsers,s.configName)}catch(f){if(f instanceof kr)throw f;throw ce.envVar(a,u,typeof i,s.configName)}}}}}parseEnvironmentValue(e,t,r,s,n){for(let[i,o]of Object.entries(s))try{return o(e)}catch{continue}for(let i of this.defaultParsers)if(i.canParse(e,t))try{return i.parse(e)}catch{throw ce.envVar(r,e,`${t} (via ${i.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[s,n]of Object.entries(st.env))if(s.startsWith(r)&&n!==void 0)t[s]=n;return t}validateEnvironmentVariable(e,t,r){let s=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))s.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){s.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:s.length===0,errors:s}}generateEnvVarDocs(e,t,r={}){let{prefix:s,format:n="text"}=r,i=s||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],i,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,s){for(let[n,i]of Object.entries(e)){let o=[...t,n],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.extractEnvVarInfo(i,o,r,s);else s.push({key:c,type:Array.isArray(i)?"array":typeof i,description:`Configuration for ${o.join(".")}`,example:this.generateExample(i)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
50
|
+
|
|
51
|
+
`;for(let s of e)r+=`${s.key}
|
|
52
|
+
`,r+=` Type: ${s.type}
|
|
53
|
+
`,r+=` Description: ${s.description}
|
|
54
|
+
`,r+=` Example: ${s.example}
|
|
55
|
+
|
|
56
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
57
|
+
|
|
58
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
59
|
+
`,r+=`|----------|------|-------------|----------|
|
|
60
|
+
`;for(let s of e)r+=`| \`${s.key}\` | ${s.type} | ${s.description} | \`${s.example}\` |
|
|
61
|
+
`;return r}}function Ro(e,t,r={}){return nn(e,t,r,new WeakMap)}function nn(e,t,r,s){let{arrayMergeMode:n="replace",skipNullish:i=!1,customMerger:o}=r;if(t===null||t===void 0)return i?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return on(e,t,n,s);if(!K(t)||!K(e))return t;return $o(e,t,r,s)}function on(e,t,r,s){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Co(e,t);case"smart":return Eo(e,t,s);default:return t}return t}function Co(e,t){let r=[...t];for(let s of e)if(!r.some((n)=>br(n,s)))r.push(s);return r}function Eo(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(K(t[0])&&K(e[0]))return To(e,t,r);if(t.every((s)=>typeof s==="string")&&e.every((s)=>typeof s==="string")){let s=[...t];for(let n of e)if(!s.includes(n))s.push(n);return s}return t}function To(e,t,r){let s=[...t];for(let n of e){if(!K(n)){s.push(n);continue}let i=["id","name","key","path","type"],o=!1;for(let c of i)if(c in n){if(s.find((l)=>K(l)&&(c in l)&&l[c]===n[c])){o=!0;break}}if(!o)s.push(n)}return s}function $o(e,t,r,s){let n=t;if(K(n)&&s.has(n))return s.get(n);let i={...e};if(K(n))s.set(n,i);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=i[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){i[o]=c;continue}if(K(c)&&K(a))i[o]=nn(a,c,r,s);else if(Array.isArray(c)||Array.isArray(a))i[o]=on(a,c,r.arrayMergeMode||"smart",s);else i[o]=c}return i}function an(e,t,r="replace"){return Ro(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function br(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!br(e[r],t[r]))return!1;return!0}if(K(e)&&K(t)){let r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!br(e[n],t[n]))return!1}return!0}return!1}function K(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class cn{extensions=ks;async loadFromPath(e,t,r={}){let{arrayStrategy:s="replace",useCache:n=!0,cacheTtl:i,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=ut.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!nt(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,m="default"in u,d=Object.keys(u).length>0;if(!m&&!d)throw new St(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new St(e,Error("Configuration must export a valid object"),"unknown");let g={config:an(t,f,s),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)ut.setWithFileCheck("file",g,e,i);return g}catch(l){throw l instanceof Error?ce.configLoad(e,l):ce.configLoad(e,Error(String(l)))}};if(o)return vr.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let s of e)try{let n=await this.loadFromPath(s,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${s}:`,n)}return null}generateConfigPaths(e,t,r){return vn({name:e,directory:t,alias:r})}generateNamePatterns(e,t){return Ps({name:e,alias:t})}checkFileAccess(e){return So(async()=>nt(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let s=[];if(!nt(e))return s;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let i of n)for(let o of this.extensions){let c=Es(e,`${i}${o}`);if(await this.checkFileAccess(c))s.push(c)}}else try{let{readdirSync:n}=await import("fs"),i=n(e);for(let o of i)if(this.looksLikeConfigFile(o)){let c=Es(e,o);if(await this.checkFileAccess(c))s.push(c)}}catch{return[]}return s}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!nt(e))return t.push("Configuration file does not exist"),t;let r=await import(e),s=r.default||r;if(s===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof s!=="object"||s===null)t.push("Configuration must be an object");else if(Array.isArray(s))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),i=n(e,"utf8");JSON.parse(i)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(s)=>{try{let n=await this.loadFromPath(s,{},t);if(n)r.set(s,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${s}:`,n)}})),r}}var Po=/^https?:\/\//;class ln{async validateConfiguration(e,t,r={}){let{stopOnFirstError:s=!1,validateRequired:n=!0,validateTypes:i=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],m={stopOnFirstError:s,validateRequired:n,validateTypes:i,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],m);else return this.validateWithJSONSchema(e,t,m)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await vr.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!ko(t))throw new Rt(t,[{path:"",message:"Schema file does not exist"}]);let s=await import(t),n=s.default||s;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(s){throw new Rt(t,[{path:"",message:`Failed to load schema: ${s}`}])}}validateWithJSONSchema(e,t,r){let s=[],n=[];return this.validateObjectAgainstSchema(e,t,"",s,n,r),{isValid:s.length===0,errors:s,warnings:n}}validateObjectAgainstSchema(e,t,r,s,n,i){if(i.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(s.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),i.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(s.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),i.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)s.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)s.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))s.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)s.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)s.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,s,n,i),i.stopOnFirstError&&s.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(i.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(s.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),i.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,s,n,i),i.stopOnFirstError&&s.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let s=[],n=[];for(let i of t)try{let o=this.getValueByPath(e,i.path),c=this.validateWithRule(o,i,i.path);if(s.push(...c),r.stopOnFirstError&&s.length>0)break}catch(o){s.push({path:i.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:s.length===0,errors:s,warnings:n}}validateWithRule(e,t,r){let s=[];if(t.required&&(e===void 0||e===null))return s.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),s;if(e===void 0||e===null)return s;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)s.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)s.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)s.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))s.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))s.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)s.push({path:r,message:t.message||n,rule:"custom"})}return s}getValueByPath(e,t){if(!t)return e;let r=t.split("."),s=e;for(let n of r)if(s&&typeof s==="object"&&n in s)s=s[n];else return;return s}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let s of r){let[,n,i,o]=s;t.push({path:n,required:!i,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Po},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var z=new $t("bunfig",{showTags:!0});function Ao(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class un{fileLoader=new cn;envProcessor=new Pr;validator=new ln;async loadConfig(e){let t=Date.now(),{cache:r,performance:s,schema:n,validate:i,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){if(o.configFile)throw a;let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),m=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(m||u))throw a;if(f&&(!l||!m))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||i)await this.validateConfiguration(c.config,n,i,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(s?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(s.onMetrics)s.onMetrics(a);if(s.slowThreshold&&a.duration>s.slowThreshold)z.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw z.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:s="",alias:n,configFile:i,cwd:o,configDir:c,defaultConfig:a,checkEnv:l=!0,arrayStrategy:u="replace",verbose:f=!1}=e,m=o||Ct.cwd(),d=[];if(i){let E=X(m,i);d.push(E);let U=l?Oe(s,a,f):a,D=await this.fileLoader.tryLoadFromPaths([E],U,{arrayStrategy:u,verbose:f,cacheTtl:r?.ttl,useCache:!r?.ttl||r.ttl>100});if(!D)throw ce.configNotFound(s||i,d,n);if(f)z.success(`Configuration loaded from explicit path: ${E}`);return this.finalizeResult(D,d,l,s,f)}let p=await this.loadLocalConfiguration(s,n,m,c,a,u,f,l,r);if(p)return d.push(...this.getLocalSearchPaths(s,n,m,c)),this.finalizeResult(p,d,l,s,f);let h=await this.loadHomeConfiguration(s,n,a,u,f,l);if(h)return d.push(...this.getHomeSearchPaths(s,n)),this.finalizeResult(h,d,l,s,f);let g=await this.loadPackageJsonConfiguration(s,n,m,a,u,f,l);if(g)return d.push(X(m,"package.json")),this.finalizeResult(g,d,l,s,f);if(d.push(...this.getAllSearchPaths(s,n,m,c)),t)throw ce.configNotFound(s,d,n);return{...await this.applyEnvironmentVariables(s,a,l,f),warnings:[`No configuration file found for "${s}"${Ao(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,s,n,i,o,c,a){let l=c?Oe(e,n,o):n,u=this.getLocalDirectories(r,s);for(let f of u){if(o)z.info(`Searching for configuration in: ${f}`);let m=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(m,l,{arrayStrategy:i,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)z.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,s,n,i){if(!e)return null;let o=i?Oe(e,r,n):r,c=[X(fe(),".config",e),X(fe(),".config"),fe()];for(let a of c){if(n)z.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:s,verbose:n});if(u){if(n)z.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,s,n,i,o){let c=o?Oe(e,s,i):s;try{let a=X(r,"package.json");if(!Sn(a))return null;let l={};try{l=JSON.parse(Rn(a,"utf8"))}catch(m){if(i)z.warn("Failed to parse package.json:",[m instanceof Error?m:Error(String(m))]);return null}let u=l[e],f=e;if(!u&&t){let m=Array.isArray(t)?t:[t];for(let d of m){if(!d)continue;if(l[d]){u=l[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(i)z.success(`Configuration loaded from package.json: ${f}`);return{config:an(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(i)z.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,s){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Oe(e,t,s),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,s,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,s){let n=[];if(r){let i=r(e);if(i)n.push(...i)}if(t){let i=await this.validator.validateConfiguration(e,t);if(!i.isValid)n.push(...i.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw ce.configValidation(s||"unknown",n,s)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ut.get(r)||null}cacheResult(e,t,r,s){let n=this.generateCacheKey(e,s);ut.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let s=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${s}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configFile)r.push(`configFile:${t.configFile}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return xn({cwd:e,configDir:t})}getAllSearchPaths(e,t,r,s){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,s)),n.push(...this.getHomeSearchPaths(e,t)),n.push(X(r,"package.json")),n}getLocalSearchPaths(e,t,r,s){let n=this.getLocalDirectories(r,s),i=[];for(let o of n)i.push(...this.fileLoader.generateConfigPaths(e,o,t));return i}getHomeSearchPaths(e,t){if(!e)return[];let r=[X(fe(),".config",e),X(fe(),".config"),fe()],s=[];for(let n of r)s.push(...this.fileLoader.generateConfigPaths(e,n,t));return s}async loadConfigWithResult(e){return this.loadConfig(e)}}var ar=new un;async function fn(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let s;if(r)s=await ar.loadConfig(e);else s=await ar.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return s?.config??t}catch(s){if(e.configFile)throw s;let n=s instanceof Error?s.name:"UnknownError",i=s instanceof Error?s.message:String(s);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||i.includes("config"))&&e.verbose)z.warn("Unexpected error loading config, using defaults:",[s instanceof Error?s:Error(String(s))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await ar.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function Oe(e,t,r=!1){let s=new Pr,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function i(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],m=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((h)=>h.toUpperCase()).join("")}`,`${n}_${f.map((h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,p;for(let h of m)if(d=Ct.env[h],d!==void 0){p=h;break}if(d!==void 0&&p)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let h=Number(d);if(!Number.isNaN(h))a[l]=h}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((h)=>h.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=i(u,f)}return a}return i(t)}var tl=X(Ct.cwd(),"config"),rl=X(Ct.cwd(),"src/generated");var dn={verbose:!1,routesPath:"routes",apiRoutesPath:"routes/api.ts",webRoutesPath:"routes/web.ts",apiPrefix:"/api",webPrefix:"",defaultMiddleware:{api:["security","helmet","cors","rate_limit","json_body","request_id"],web:["security","helmet","ddos_protection","session","csrf"]},docs:{output:"api-reference.md",groupBy:"path",includeExamples:!0,title:"API Reference",description:"API documentation for the application.",version:"1.0.0",baseUrl:"http://localhost:3000",contact:{name:"API Support",email:"support@example.com",url:"https://example.com/support"},security:{bearer:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}},server:{port:3000,hostname:"localhost",development:Fo.env.NODE_ENV!=="production",cors:{enabled:!0,origin:"*",methods:["GET","POST","PUT","DELETE","PATCH"],allowedHeaders:["Content-Type","Authorization"],exposedHeaders:["X-Request-Id"],credentials:!1,maxAge:86400},rateLimit:{enabled:!0,max:100,timeWindow:60000,message:"Too many requests, please try again later"},compression:{enabled:!0,level:6,threshold:1024},static:{enabled:!0,dir:"public",maxAge:86400},performance:{cache:{enabled:!1,type:"memory",ttl:3600},prefetch:{enabled:!1,paths:[],maxConcurrent:5},optimization:{minify:!1,compress:!1,treeshake:!1,lazyLoad:!1,chunkSize:50000},monitoring:{enabled:!1,metrics:{responseTime:!0,memoryUsage:!0,cpuUsage:!0,errorRate:!0,requestRate:!0,cacheStats:!0},tracing:{enabled:!1,sampleRate:0.1,exporters:["console"],propagation:["w3c"]},logging:{level:"info",format:"json",destination:"console"}}},security:{schemes:{},rateLimit:{enabled:!0,max:100,timeWindow:60000},cors:{enabled:!0,origin:"*",methods:["GET","POST","PUT","DELETE","PATCH"]},csrf:{enabled:!0,secret:"csrf-secret",cookie:{name:"csrf-token",options:{httpOnly:!0,secure:!0,sameSite:"strict"}}},helmet:{enabled:!0,contentSecurityPolicy:{directives:{"default-src":["'self'"],"script-src":["'self'","'unsafe-inline'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","https:"],"font-src":["'self'"],"connect-src":["'self'"],"media-src":["'self'"],"object-src":["'none'"],"child-src":["'self'"],"worker-src":["'self'"],"frame-ancestors":["'none'"],"form-action":["'self'"],"base-uri":["'self'"],"manifest-src":["'self'"]}},xssFilter:!0,noSniff:!0,frameOptions:"DENY",hidePoweredBy:!0,hsts:{maxAge:31536000,includeSubDomains:!0,preload:!0},referrerPolicy:"strict-origin-when-cross-origin"},ddos:{enabled:!0,maxRequestsPerSecond:10,maxRequestsPerMinute:100,maxRequestsPerHour:1000,burstLimit:20,windowSize:60000,blockDuration:300000,whitelistedIPs:[],blacklistedIPs:[],trustProxy:!0,store:"memory"},inputValidation:{enabled:!0,sanitizeByDefault:!0,strictMode:!1,allowUnknownFields:!0,maxDepth:10},attackPrevention:{enabled:!0,sqlInjection:!0,xss:!0,pathTraversal:!0,commandInjection:!0,ldapInjection:!0,xxe:!0,customPatterns:[]},requestFiltering:{enabled:!0,blockSuspiciousPatterns:!0,maxRequestsPerMinute:1000,blockUserAgents:["sqlmap","nikto","nessus","openvas","nmap","masscan","zap","w3af"],allowedMethods:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],requireUserAgent:!1,maxBodySize:10485760,maxUrlLength:2048,maxHeaderSize:8192,allowedContentTypes:["application/json","application/x-www-form-urlencoded","multipart/form-data","text/plain","text/html","application/xml","text/xml"]},ipFiltering:{enabled:!1,whitelist:[],blacklist:[],blockPrivateIPs:!1,blockCloudProviders:!1,geoBlocking:{enabled:!1,allowedCountries:[],blockedCountries:[]}},responseSecurity:{enabled:!0,removeServerHeaders:!0,addSecurityHeaders:!0,sanitizeErrors:!0,preventInfoDisclosure:!0},auth:{jwt:{secret:"jwt-secret",expiresIn:"1h",algorithm:"HS256"},session:{enabled:!1,secret:"session-secret",name:"session",resave:!1,rolling:!0,saveUninitialized:!1,cookie:{maxAge:86400000,secure:!0,httpOnly:!0,sameSite:"strict"}}}},cluster:{enabled:!1,workers:"auto",sticky:!0},gracefulShutdown:{enabled:!0,timeout:30000,signals:["SIGTERM","SIGINT"],forceTimeout:1e4},middleware:{order:[],global:[]},hooks:{}}},Ar=null;async function ol(){if(!Ar)Ar=await fn({name:"router",defaultConfig:dn});return Ar}var v=dn;function mn(e){if(!e||!e.startsWith("Basic "))return null;try{let t=e.split(" ")[1],r=atob(t),[s,n]=r.split(":");return{username:s,password:n}}catch(t){return null}}function Fr(e){if(!e||!e.startsWith("Bearer "))return null;return e.split(" ")[1]}function hn(e,t="header",r="X-API-Key"){switch(t){case"header":return e.headers.get(r)||null;case"query":return new URL(e.url).searchParams.get(r);case"cookie":if(e.cookies){if(typeof e.cookies.get==="function")return e.cookies.get(r)||null;return e.cookies[r]||null}return null;default:return null}}class G{options;constructor(e){this.options={source:"header",key:"Authorization",attachUser:!0,...e}}async handle(e,t){let r=null;if(this.options.credentialsExtractor)r=await this.options.credentialsExtractor(e);else switch(this.options.type){case"basic":{let i=e.headers.get(this.options.key||"Authorization");r=mn(i||"");break}case"bearer":case"jwt":{let i=e.headers.get(this.options.key||"Authorization");r=Fr(i||"");break}case"api-key":{r=hn(e,this.options.source,this.options.key);break}case"oauth2":{let i=e.headers.get(this.options.key||"Authorization");r=Fr(i||"");break}}if(!r){let i={};if(this.options.type==="basic"){let o=this.options.realm||"Secure Area";i["WWW-Authenticate"]=`Basic realm="${o}"`}return new Response("Unauthorized",{status:401,headers:i})}if(!await this.options.validator(r,e))return new Response("Unauthorized",{status:401});if(this.options.userExtractor&&this.options.attachUser){let i=await this.options.userExtractor(r,e);e.user=i}return await t()||new Response("Not Found",{status:404})}}function Mo(e,t={}){return new G({type:"basic",validator:e,...t})}function No(e,t={}){return new G({type:"bearer",validator:e,...t})}function Io(e,t={}){return new G({type:"jwt",validator:e,...t})}function Oo(e,t={}){return new G({type:"api-key",validator:e,...t})}function Do(e,t={}){return new G({type:"oauth2",validator:e,...t})}var Mr={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With, Accept, Origin","Access-Control-Max-Age":"86400"};class Re{resolveAllowOrigin(e,t,r){if(Array.isArray(e)){if(r&&e.includes(r))return{value:r,vary:!0};return{value:null,vary:!0}}let s=e||"*";if(s==="*"){if(t){if(r)return{value:r,vary:!0};return{value:null,vary:!0}}return{value:"*",vary:!1}}return{value:s,vary:!1}}getCorsHeaders(e){let t=v.server?.cors,r=e.headers.get("origin");if(t&&t.enabled){let s=Boolean(t.credentials),{value:n,vary:i}=this.resolveAllowOrigin(t.origin,s,r),o={"Access-Control-Allow-Methods":Array.isArray(t.methods)?t.methods.join(", "):Mr["Access-Control-Allow-Methods"],"Access-Control-Allow-Headers":Array.isArray(t.allowedHeaders)?t.allowedHeaders.join(", "):Mr["Access-Control-Allow-Headers"],"Access-Control-Max-Age":String(t.maxAge||86400)};if(n!==null)o["Access-Control-Allow-Origin"]=n;if(s&&n!==null&&n!=="*")o["Access-Control-Allow-Credentials"]="true";if(i)o.Vary="Origin";return o}return{...Mr}}async handle(e,t){let r=this.getCorsHeaders(e);if(e.method==="OPTIONS")return new Response(null,{status:204,headers:r});let s=(n)=>{let i=new Headers(n.headers);return Object.entries(r).forEach(([o,c])=>{i.set(o,c)}),new Response(n.body,{status:n.status,statusText:n.statusText,headers:i})};try{let n=await t();if(!n)return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{...r,"Content-Type":"application/json"}});return s(n)}catch(n){return console.error("[CORS] Error in middleware chain:",n),new Response(JSON.stringify({error:"Internal Server Error",message:n instanceof Error?n.message:String(n)}),{status:500,headers:{...r,"Content-Type":"application/json"}})}}}import{createHash as jo,randomBytes as Lo,timingSafeEqual as Bo}from"crypto";var Uo=1e4,qo=7200000;class B{static tokens=new Map;async handle(e,t){let r=v.server?.security?.csrf??{},s=e.method.toUpperCase();if(["GET","HEAD","OPTIONS",...r?.ignoreMethods||[]].includes(s)){let f=this.generateToken(r?.secret||"csrf-secret"),m=await t();if(!m)return new Response("Not Found",{status:404});let d=r?.cookie?.name||"csrf-token",p=[];if(p.push(`${d}=${f}`),p.push("Path=/"),r?.cookie?.options?.httpOnly)p.push("HttpOnly");if(r?.cookie?.options?.secure)p.push("Secure");if(r?.cookie?.options?.sameSite)p.push(`SameSite=${r.cookie.options.sameSite}`);let h=new Headers(m.headers);return h.append("Set-Cookie",p.join("; ")),B.storeToken(f),new Response(m.body,{status:m.status,statusText:m.statusText,headers:h})}let i=e.headers.get("authorization")??e.headers.get("Authorization");if(i&&/^Bearer\s+\S/i.test(i))return await t()||new Response("Not Found",{status:404});let o=e.headers.get("X-CSRF-TOKEN")||e.jsonBody?.csrf_token||e.jsonBody?._token||null,c=typeof o==="string"?o:null,l=this.parseCookies(e)[r?.cookie?.name||"csrf-token"];if(!c||!l||!B.safeCompare(c,l)||!B.isTokenValid(c))return new Response(JSON.stringify({error:"CSRF token validation failed"}),{status:403,headers:{"Content-Type":"application/json"}});return await t()||new Response("Not Found",{status:404})}static safeCompare(e,t){let r=Buffer.from(e),s=Buffer.from(t);if(r.length!==s.length)return!1;return Bo(r,s)}static storeToken(e){if(B.tokens.size>=Uo){let t=B.tokens.keys().next().value;if(t!==void 0)B.tokens.delete(t)}B.tokens.set(e,Date.now())}static isTokenValid(e){let t=B.tokens.get(e);if(t===void 0)return!1;if(Date.now()-t>qo)return B.tokens.delete(e),!1;return!0}generateToken(e){let t=Lo(16).toString("hex");return jo("sha256").update(`${t}${e}`).digest("hex")}parseCookies(e){let t=e.headers.get("cookie");if(!t)return{};let r={};for(let s of t.split(";")){let n=s.indexOf("=");if(n===-1)continue;let i=s.slice(0,n).trim();if(!i)continue;r[i]=s.slice(n+1).trim()}return r}}class Ce{async handle(e,t){let r=e.headers.get("content-type");if(r&&r.includes("application/json"))try{let i=await e.clone().json();Object.defineProperty(e,"jsonBody",{value:i,writable:!0,enumerable:!0,configurable:!0})}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}return await t()||new Response("Not Found",{status:404})}}import{createRateLimiter as _o}from"ts-rate-limiter";function Vo(e={}){let t=new kt(e);return async(s,n)=>t.handle(s,n)}class kt{limiter;options;constructor(e={}){let t=v.server?.rateLimit||{},r=v.server?.security?.rateLimit||{};if(this.options={windowMs:e.windowMs||t.timeWindow||r.timeWindow||60000,maxRequests:e.maxRequests||t.max||r.max||100,standardHeaders:e.standardHeaders??!0,legacyHeaders:e.legacyHeaders??!1,skipFailedRequests:e.skipFailedRequests??t.advanced?.skipFailedRequests??r.advanced?.skipFailedRequests??!1,draftMode:e.draftMode??!1,keyGenerator:e.keyGenerator,handler:e.handler||(t.message?(s,n)=>new Response(t.message,{status:429}):void 0),skip:e.skip,algorithm:e.algorithm||"fixed-window",storage:e.storage},!this.options.storage&&t.stores?.type==="redis"&&t.stores.redis){if(this.options.storage="redis",t.stores.redis)this.options.redis={url:t.stores.redis.url,prefix:t.stores.redis.prefix||"ratelimit:"}}if(t.advanced){if(t.advanced.tokensPerInterval&&this.options.algorithm==="token-bucket")this.options.tokenBucket={tokensPerInterval:t.advanced.tokensPerInterval,interval:t.advanced.interval||this.options.windowMs,burst:t.advanced.burst}}this.initLimiter()}async initLimiter(){let e={...this.options};e.windowMs=this.options.windowMs,e.maxRequests=this.options.maxRequests,e.standardHeaders=this.options.standardHeaders,e.legacyHeaders=this.options.legacyHeaders,e.skipFailedRequests=this.options.skipFailedRequests,e.keyGenerator=this.options.keyGenerator,e.skip=this.options.skip,e.algorithm=this.options.algorithm,e.draftMode=this.options.draftMode,e.handler=this.options.handler?async(s,n)=>this.options.handler?.(s,{remaining:n.remaining,limit:n.limit,resetTime:n.resetTime})||this.defaultHandler(s,n):void 0;let{log:t,warn:r}=console;console.log=()=>{},console.warn=()=>{};try{this.limiter=await _o(e)}finally{console.log=t,console.warn=r}}defaultHandler(e,t){let r={};if(this.options.standardHeaders)r["RateLimit-Limit"]=String(t.limit),r["RateLimit-Remaining"]=String(Math.max(0,t.limit-t.current)),r["RateLimit-Reset"]=String(Math.ceil(t.resetTime/1000));if(this.options.legacyHeaders)r["X-RateLimit-Limit"]=String(t.limit),r["X-RateLimit-Remaining"]=String(Math.max(0,t.limit-t.current)),r["X-RateLimit-Reset"]=String(Math.ceil(t.resetTime/1000)),r["Retry-After"]=String(Math.ceil(t.remaining/1000));let s=v.server?.rateLimit?.message||"Too Many Requests";return new Response(s,{status:429,headers:r})}async handle(e,t){if(v.server?.rateLimit?.enabled===!1)return await t()||new Response("Not Found",{status:404});if(!this.limiter){if(await new Promise((r)=>setTimeout(r,50)),!this.limiter)return await t()||new Response("Not Found",{status:404})}try{let r=await this.limiter.check(e);if(!r.allowed)return this.options.handler?await this.options.handler(e,{remaining:r.remaining,limit:r.limit,resetTime:r.resetTime}):this.defaultHandler(e,r);let s=await t();if(!s)return new Response("Not Found",{status:404});let n=new Headers(s.headers);if(this.options.standardHeaders)n.set("RateLimit-Limit",String(r.limit)),n.set("RateLimit-Remaining",String(Math.max(0,r.limit-r.current))),n.set("RateLimit-Reset",String(Math.ceil(r.resetTime/1000)));if(this.options.legacyHeaders)n.set("X-RateLimit-Limit",String(r.limit)),n.set("X-RateLimit-Remaining",String(Math.max(0,r.limit-r.current))),n.set("X-RateLimit-Reset",String(Math.ceil(r.resetTime/1000)));return new Response(s.body,{status:s.status,statusText:s.statusText,headers:n})}catch(r){return console.error("[RateLimit] Error during rate limiting:",r),await t()||new Response("Not Found",{status:404})}}}function Nr(e={}){return Vo(e)}import{randomUUID as Ho}from"crypto";class Ee{async handle(e,t){let r=e.headers.get("X-Request-ID")||Ho();Object.defineProperty(e,"requestId",{value:r,writable:!1,enumerable:!0,configurable:!1});let s=await t();if(!s)return new Response("Not Found",{status:404});let n=new Headers(s.headers);if(!n.has("X-Request-ID"))n.set("X-Request-ID",r);return new Response(s.body,{status:s.status,statusText:s.statusText,headers:n})}}class V extends Error{code;statusCode;constructor(e,t){super(t);this.name="SignatureError",this.code=e,this.statusCode=401}}class pn{nonces=new Map;cleanupInterval=null;constructor(e=60000){this.cleanupInterval=setInterval(()=>this.cleanup(),e),this.cleanupInterval.unref?.()}has(e){let t=this.nonces.get(e);if(t===void 0)return!1;if(Date.now()>t)return this.nonces.delete(e),!1;return!0}set(e,t=300){this.nonces.set(e,Date.now()+t*1000)}cleanup(){let e=Date.now();for(let[t,r]of this.nonces.entries())if(e>r)this.nonces.delete(t)}destroy(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.nonces.clear()}}class Te{options;constructor(e){this.options={secret:e.secret,algorithm:e.algorithm??"sha256",signatureHeader:e.signatureHeader??"X-Signature",timestampHeader:e.timestampHeader??"X-Timestamp",keyIdHeader:e.keyIdHeader??"X-Key-Id",nonceHeader:e.nonceHeader??"X-Nonce",maxAge:e.maxAge??300,requireTimestamp:e.requireTimestamp??!0,requireNonce:e.requireNonce??!1,signedParts:e.signedParts??["method","path","timestamp","body"],signedHeaders:e.signedHeaders??[],encoding:e.encoding??"hex",onError:e.onError,exclude:e.exclude,nonceStore:e.nonceStore,stringToSign:e.stringToSign}}async handle(e,t){if(this.shouldSkip(e))return t();try{return await this.verifySignature(e),t()}catch(r){if(r instanceof V){if(this.options.onError)return this.options.onError(r,e);return this.defaultErrorResponse(r)}throw r}}shouldSkip(e){if(!this.options.exclude)return!1;if(typeof this.options.exclude==="function")return this.options.exclude(e);let t=new URL(e.url);return this.options.exclude.some((r)=>t.pathname===r||t.pathname.startsWith(`${r}/`))}async verifySignature(e){let t=e.headers.get(this.options.signatureHeader);if(!t)throw new V("MISSING_SIGNATURE",`Missing ${this.options.signatureHeader} header`);let r=e.headers.get(this.options.timestampHeader);if(this.options.requireTimestamp){if(!r)throw new V("MISSING_TIMESTAMP",`Missing ${this.options.timestampHeader} header`);this.validateTimestamp(r)}let s=e.headers.get(this.options.nonceHeader);if(this.options.requireNonce){if(!s)throw new V("MISSING_NONCE",`Missing ${this.options.nonceHeader} header`);await this.validateNonce(s)}let n=await this.getSecret(e);if(!n)throw new V("INVALID_KEY","Invalid or missing API key");let i=await this.buildStringToSign(e,r||"",s||void 0),o=await this.calculateSignature(i,n);if(!this.timingSafeEqual(t,o))throw new V("SIGNATURE_MISMATCH","Invalid signature");if(this.options.requireNonce&&s&&this.options.nonceStore)await this.options.nonceStore.set(s,this.options.maxAge)}async getSecret(e){if(typeof this.options.secret==="string")return this.options.secret;let t=e.headers.get(this.options.keyIdHeader);if(!t)throw new V("MISSING_KEY_ID",`Missing ${this.options.keyIdHeader} header`);return this.options.secret(t)}validateTimestamp(e){let t=Number.parseInt(e,10);if(Number.isNaN(t))throw new V("EXPIRED_TIMESTAMP","Invalid timestamp format");let s=Math.floor(Date.now()/1000)-t;if(s>this.options.maxAge)throw new V("EXPIRED_TIMESTAMP",`Request timestamp expired (${s}s old, max ${this.options.maxAge}s)`);if(s<-30)throw new V("FUTURE_TIMESTAMP","Request timestamp is in the future")}async validateNonce(e){if(!this.options.nonceStore)return;if(await this.options.nonceStore.has(e))throw new V("NONCE_REUSED","Nonce has already been used (possible replay attack)")}async buildStringToSign(e,t,r){if(this.options.stringToSign)return this.options.stringToSign(e,t,r);let s=new URL(e.url),n=[];for(let i of this.options.signedParts)switch(i){case"method":n.push(e.method.toUpperCase());break;case"path":n.push(s.pathname);break;case"query":n.push(s.search);break;case"timestamp":n.push(t);break;case"nonce":if(r)n.push(r);break;case"body":if(e.body){let o=await e.clone().text();n.push(o)}break;case"headers":for(let o of this.options.signedHeaders){let c=e.headers.get(o);if(c)n.push(`${o.toLowerCase()}:${c}`)}break}return n.join(`
|
|
62
|
+
`)}async calculateSignature(e,t){let r=new TextEncoder,s=r.encode(t),n=r.encode(e),i={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"}[this.options.algorithm],o=await crypto.subtle.importKey("raw",s,{name:"HMAC",hash:i},!1,["sign"]),c=await crypto.subtle.sign("HMAC",o,n);if(this.options.encoding==="base64")return btoa(String.fromCharCode(...new Uint8Array(c)));return Array.from(new Uint8Array(c)).map((a)=>a.toString(16).padStart(2,"0")).join("")}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let s=0;s<e.length;s++)r|=e.charCodeAt(s)^t.charCodeAt(s);return r===0}defaultErrorResponse(e){return new Response(JSON.stringify({error:{code:e.code,message:e.message}}),{status:e.statusCode,headers:{"Content-Type":"application/json","WWW-Authenticate":"HMAC-SHA256"}})}}function Ko(e){return new Te(e)}async function zo(e,t,r={}){let{algorithm:s="sha256",signedParts:n=["method","path","timestamp","body"],signedHeaders:i=[],signatureHeader:o="X-Signature",timestampHeader:c="X-Timestamp",nonceHeader:a="X-Nonce",keyId:l,keyIdHeader:u="X-Key-Id",encoding:f="hex"}=r,m=Math.floor(Date.now()/1000).toString(),d=crypto.randomUUID(),p=new URL(e.url),h=[];for(let _t of n)switch(_t){case"method":h.push(e.method.toUpperCase());break;case"path":h.push(p.pathname);break;case"query":h.push(p.search);break;case"timestamp":h.push(m);break;case"nonce":h.push(d);break;case"body":if(e.body){let Ke=await e.clone().text();h.push(Ke)}break;case"headers":for(let Ke of i){let Lr=e.headers.get(Ke);if(Lr)h.push(`${Ke.toLowerCase()}:${Lr}`)}break}let g=h.join(`
|
|
63
|
+
`),k=new TextEncoder,E=k.encode(t),U=k.encode(g),D={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"}[s],q=await crypto.subtle.importKey("raw",E,{name:"HMAC",hash:D},!1,["sign"]),Ne=await crypto.subtle.sign("HMAC",q,U),qt;if(f==="base64")qt=btoa(String.fromCharCode(...new Uint8Array(Ne)));else qt=Array.from(new Uint8Array(Ne)).map((_t)=>_t.toString(16).padStart(2,"0")).join("");let Ie=new Headers(e.headers);if(Ie.set(o,qt),Ie.set(c,m),Ie.set(a,d),l)Ie.set(u,l);return new Request(e.url,{method:e.method,headers:Ie,body:e.body,redirect:e.redirect,integrity:e.integrity,signal:e.signal})}async function Wo(e,t,r,s="sha256",n="hex"){let i=new TextEncoder,o=i.encode(r),c=i.encode(e),a={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"}[s],l=await crypto.subtle.importKey("raw",o,{name:"HMAC",hash:a},!1,["sign"]),u=await crypto.subtle.sign("HMAC",l,c),f;if(n==="base64")f=btoa(String.fromCharCode(...new Uint8Array(u)));else f=Array.from(new Uint8Array(u)).map((d)=>d.toString(16).padStart(2,"0")).join("");if(t.length!==f.length)return!1;let m=0;for(let d=0;d<t.length;d++)m|=t.charCodeAt(d)^f.charCodeAt(d);return m===0}class ue{defaultTtl;sessions=new Map;cleanupInterval=null;constructor(e=86400){this.defaultTtl=e;this.cleanupInterval=setInterval(()=>this.cleanup(),300000)}async get(e){let t=this.sessions.get(e);if(!t)return null;if(Date.now()>t.expiresAt)return this.sessions.delete(e),null;return t.data}async set(e,t,r){let s=Date.now()+(r??this.defaultTtl)*1000;this.sessions.set(e,{data:t,expiresAt:s})}async destroy(e){this.sessions.delete(e)}async touch(e,t,r){let s=this.sessions.get(e);if(s)s.expiresAt=Date.now()+(r??this.defaultTtl)*1000,s.data=t}async all(){let e={},t=Date.now();for(let[r,s]of this.sessions)if(t<=s.expiresAt)e[r]=s.data;return e}async length(){return this.sessions.size}async clear(){this.sessions.clear()}cleanup(){let e=Date.now();for(let[t,r]of this.sessions)if(e>r.expiresAt)this.sessions.delete(t)}dispose(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.sessions.clear()}}import{existsSync as Pt,mkdirSync as Jo,readdirSync as At,unlinkSync as Ft,writeFileSync as gn,readFileSync as Ir}from"fs";import{join as _e}from"path";import{tmpdir as Go}from"os";class Mt{defaultTtl;dir;cleanupInterval=null;constructor(e=86400,t){this.defaultTtl=e;if(this.dir=t||_e(Go(),"bun-router-sessions"),!Pt(this.dir))Jo(this.dir,{recursive:!0});this.cleanupInterval=setInterval(()=>this.cleanup(),600000)}filePath(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"");return _e(this.dir,`${t}.json`)}async get(e){let t=this.filePath(e);if(!Pt(t))return null;try{let r=Ir(t,"utf-8"),s=JSON.parse(r);if(Date.now()>s.expiresAt)return Ft(t),null;return s.data}catch{return null}}async set(e,t,r){let s={data:t,expiresAt:Date.now()+(r??this.defaultTtl)*1000};gn(this.filePath(e),JSON.stringify(s),"utf-8")}async destroy(e){let t=this.filePath(e);if(Pt(t))Ft(t)}async touch(e,t,r){let s=this.filePath(e);if(!Pt(s))return;let n={data:t,expiresAt:Date.now()+(r??this.defaultTtl)*1000};gn(s,JSON.stringify(n),"utf-8")}async all(){let e={},t=Date.now();try{let r=At(this.dir).filter((s)=>s.endsWith(".json"));for(let s of r){let n=Ir(_e(this.dir,s),"utf-8"),i=JSON.parse(n);if(t<=i.expiresAt){let o=s.replace(".json","");e[o]=i.data}}}catch{}return e}async length(){try{return At(this.dir).filter((e)=>e.endsWith(".json")).length}catch{return 0}}async clear(){try{let e=At(this.dir).filter((t)=>t.endsWith(".json"));for(let t of e)Ft(_e(this.dir,t))}catch{}}cleanup(){let e=Date.now();try{let t=At(this.dir).filter((r)=>r.endsWith(".json"));for(let r of t){let s=_e(this.dir,r),n=Ir(s,"utf-8"),i=JSON.parse(n);if(e>i.expiresAt)Ft(s)}}catch{}}dispose(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}}class Nt{client;defaultTtl;prefix;constructor(e,t=86400,r="sess:"){this.client=e;this.defaultTtl=t;this.prefix=r}key(e){return`${this.prefix}${e}`}async get(e){let t=await this.client.get(this.key(e));if(!t)return null;try{return JSON.parse(t)}catch{return null}}async set(e,t,r){let s=this.key(e),n=r??this.defaultTtl;await this.client.set(s,JSON.stringify(t),"EX",n)}async destroy(e){await this.client.del(this.key(e))}async touch(e,t,r){let s=this.key(e),n=r??this.defaultTtl;await this.client.set(s,JSON.stringify(t),"EX",n)}async all(){let e=await this.client.keys(`${this.prefix}*`),t={};for(let r of e){let s=await this.client.get(r);if(s)try{let n=r.slice(this.prefix.length);t[n]=JSON.parse(s)}catch{}}return t}async length(){return(await this.client.keys(`${this.prefix}*`)).length}async clear(){let e=await this.client.keys(`${this.prefix}*`);if(e.length>0)await this.client.del(e)}}class It{adapter;defaultTtl;cleanupInterval=null;constructor(e,t=86400){this.adapter=e;this.defaultTtl=t;this.cleanupInterval=setInterval(()=>{let r=Date.now()-this.defaultTtl*1000;this.adapter.deleteExpiredSessions(r)},1800000)}async get(e){let t=await this.adapter.findSession(e);if(!t)return null;let r=Date.now()-this.defaultTtl*1000;if(t.last_activity<r)return await this.adapter.deleteSession(e),null;try{return JSON.parse(t.payload)}catch{return null}}async set(e,t,r){await this.adapter.upsertSession(e,JSON.stringify(t),Date.now())}async destroy(e){await this.adapter.deleteSession(e)}async touch(e,t,r){await this.adapter.upsertSession(e,JSON.stringify(t),Date.now())}async all(){let e=await this.adapter.getAllSessions(),t={},r=Date.now()-this.defaultTtl*1000;for(let s of e)if(s.last_activity>=r)try{t[s.id]=JSON.parse(s.payload)}catch{}return t}async length(){return this.adapter.countSessions()}async clear(){await this.adapter.clearAllSessions()}dispose(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}}function Ml(e){let t=e.ttl??86400;switch(e.driver){case"memory":return new ue(t);case"file":return new Mt(t,e.file?.dir);case"redis":{if(!e.redis?.client)throw Error("Redis client is required for redis session driver");return new Nt(e.redis.client,t,e.redis.prefix)}case"database":{if(!e.database?.adapter)throw Error("Database adapter is required for database session driver");return new It(e.database.adapter,t)}default:return new ue(t)}}class Or{sessionId;data;store;flashedKeys=[];previousFlash={};dirty=!1;constructor(e,t,r){this.sessionId=e,this.data=t,this.store=r,this.previousFlash={...t.flash||{}}}get id(){return this.sessionId}get(e){if(this.data.flash&&e in this.data.flash)return this.data.flash[e];if(this.data.data&&e in this.data.data)return this.data.data[e];return}set(e,t){if(!this.data.data)this.data.data={};this.data.data[e]=t,this.dirty=!0}has(e){return this.data.data&&e in this.data.data||this.data.flash&&e in this.data.flash||!1}forget(e){if(this.data.data)delete this.data.data[e],this.dirty=!0}all(){return{...this.data.data||{},...this.data.flash||{}}}flash(e,t){if(!this.data.flash)this.data.flash={};this.data.flash[e]=t,this.flashedKeys.push(e),this.dirty=!0}getFlash(e){return this.previousFlash[e]}keep(e){for(let t of e)if(t in this.previousFlash)this.flash(t,this.previousFlash[t])}reflash(){for(let[e,t]of Object.entries(this.previousFlash))this.flash(e,t)}async regenerate(){let e=this.sessionId;return this.sessionId=Ot(),await this.store.set(this.sessionId,this.data),await this.store.destroy(e),this.sessionId}async invalidate(){let e=this.sessionId;return this.sessionId=Ot(),this.data={id:this.sessionId},await this.store.destroy(e),await this.store.set(this.sessionId,this.data),this.sessionId}async save(){if(this.data.flash){let e={};for(let t of this.flashedKeys)if(this.data.flash[t]!==void 0)e[t]=this.data.flash[t];this.data.flash=Object.keys(e).length>0?e:void 0}await this.store.set(this.sessionId,this.data)}async destroy(){await this.store.destroy(this.sessionId),this.data={}}}function Ot(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join("")}class $e{store;constructor(e){this.store=e?.store||new ue}async handle(e,t){let r=v.server?.security?.auth?.session,s=r?.name||"session",n=e.cookies?.get(s)||"",i=!1;if(!n)n=Ot(),i=!0;let o=i?null:await this.store.get(n);if(!o)o={id:n},i=!0;let c=new Or(n,o,this.store);e.session=c;let a=await t();await c.save();let l={maxAge:r?.cookie?.maxAge||86400000,path:r?.cookie?.path||"/"};if(r?.cookie?.httpOnly!==!1)l.httpOnly=!0;if(r?.cookie?.secure)l.secure=!0;if(r?.cookie?.sameSite)l.sameSite=r.cookie.sameSite;if(!e._cookiesToSet)e._cookiesToSet=[];return e._cookiesToSet.push({name:s,value:c.id,options:l}),a||new Response("Not Found",{status:404})}}class ke{options;nonces=new Map;constructor(e={}){let t=v.server?.security?.helmet?.contentSecurityPolicy,r={"default-src":["'self'"],"script-src":["'self'"],"style-src":["'self'"],"img-src":["'self'","data:","https:"],"font-src":["'self'"],"connect-src":["'self'"],"media-src":["'self'"],"object-src":["'none'"],"child-src":["'self'"],"worker-src":["'self'"],"frame-ancestors":["'none'"],"form-action":["'self'"],"base-uri":["'self'"],"manifest-src":["'self'"]};this.options={directives:e.directives||typeof t==="object"&&t.directives||r,reportOnly:e.reportOnly??(typeof t==="object"&&t.reportOnly)??!1,reportUri:e.reportUri,reportTo:e.reportTo,useNonces:e.useNonces??!1,nonceLength:e.nonceLength??16,upgradeInsecureRequests:e.upgradeInsecureRequests??!0,blockAllMixedContent:e.blockAllMixedContent??!1}}generateNonce(){let t="";for(let r=0;r<(this.options.nonceLength||16);r++)t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(Math.floor(Math.random()*64));return t}buildCSPHeader(){let e=[],t=this.options.directives||{};for(let[r,s]of Object.entries(t)){if(r==="upgrade-insecure-requests"||r==="block-all-mixed-content"||r==="disown-opener"){if(s===!0)e.push(r.replace(/([A-Z])/g,"-$1").toLowerCase());continue}if(Array.isArray(s)&&s.length>0){let n=r.replace(/([A-Z])/g,"-$1").toLowerCase();e.push(`${n} ${s.join(" ")}`)}}if(this.options.upgradeInsecureRequests)e.push("upgrade-insecure-requests");if(this.options.blockAllMixedContent)e.push("block-all-mixed-content");if(this.options.reportUri)e.push(`report-uri ${this.options.reportUri}`);if(this.options.reportTo)e.push(`report-to ${this.options.reportTo}`);return e.join("; ")}async handle(e,t){if((v.server?.security?.helmet||{}).contentSecurityPolicy===!1)return await t()||new Response("Not Found",{status:404});let s;if(this.options.useNonces){if(s=this.generateNonce(),this.nonces.set(e.url,s),this.options.directives?.["script-src"])this.options.directives["script-src"]=[...this.options.directives["script-src"],`'nonce-${s}'`];if(this.options.directives?.["style-src"])this.options.directives["style-src"]=[...this.options.directives["style-src"],`'nonce-${s}'`]}if(s)e.nonce=s;let n=await t();if(!n)return new Response("Not Found",{status:404});let i=new Headers(n.headers),o=this.buildCSPHeader();if(o){let c=this.options.reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy";i.set(c,o)}if(this.options.reportTo)i.set("Report-To",JSON.stringify({group:this.options.reportTo,max_age:10886400,endpoints:[{url:this.options.reportUri||"/csp-report"}]}));if(s)this.nonces.delete(e.url);return new Response(n.body,{status:n.status,statusText:n.statusText,headers:i})}getNonce(e){return this.nonces.get(e)}}function Xo(e={}){let t=new ke(e);return async(r,s)=>t.handle(r,s)}class Pe{options;requestStore=new Map;cleanupInterval=null;constructor(e={}){let t=v.server?.security?.ddos||{};if(this.options={enabled:e.enabled??t.enabled??!0,maxRequestsPerSecond:e.maxRequestsPerSecond??t.maxRequestsPerSecond??10,maxRequestsPerMinute:e.maxRequestsPerMinute??t.maxRequestsPerMinute??100,maxRequestsPerHour:e.maxRequestsPerHour??t.maxRequestsPerHour??1000,burstLimit:e.burstLimit??t.burstLimit??20,windowSize:e.windowSize??t.windowSize??60000,blockDuration:e.blockDuration??t.blockDuration??300000,whitelistedIPs:e.whitelistedIPs??t.whitelistedIPs??[],blacklistedIPs:e.blacklistedIPs??t.blacklistedIPs??[],trustProxy:e.trustProxy??t.trustProxy??!0,skipSuccessfulRequests:e.skipSuccessfulRequests??t.skipSuccessfulRequests??!1,skipFailedRequests:e.skipFailedRequests??t.skipFailedRequests??!1,keyGenerator:e.keyGenerator??this.defaultKeyGenerator.bind(this),onLimitReached:e.onLimitReached,store:e.store??t.store??"memory",redis:e.redis??t.redis},this.options.store==="memory")this.startCleanupInterval()}defaultKeyGenerator(e){let t=e.headers.get("x-forwarded-for"),r=e.headers.get("x-real-ip"),s=e.headers.get("cf-connecting-ip");if(this.options.trustProxy&&t)return t.split(",")[0].trim();return r||s||"unknown"}startCleanupInterval(){this.cleanupInterval=setInterval(()=>{let e=Date.now();for(let[t,r]of this.requestStore.entries()){if(e-r.lastRequest>this.options.windowSize*2)this.requestStore.delete(t);if(r.blocked&&r.blockExpires&&e>r.blockExpires)r.blocked=!1,r.blockExpires=void 0}},this.options.windowSize/2),this.cleanupInterval.unref?.()}isWhitelisted(e){return this.options.whitelistedIPs?.includes(e)??!1}isBlacklisted(e){return this.options.blacklistedIPs?.includes(e)??!1}getRateLimitInfo(e,t){let r=this.requestStore.get(e);if(!r){if(this.requestStore.size>=1e5){let s=Math.ceil(this.requestStore.size/10);for(let n of this.requestStore.keys())if(this.requestStore.delete(n),--s<=0)break}r={count:0,firstRequest:t,lastRequest:t,blocked:!1},this.requestStore.set(e,r)}if(t-r.firstRequest>this.options.windowSize)r.count=0,r.firstRequest=t;return r}shouldBlock(e,t){if(e.blocked&&e.blockExpires&&t<e.blockExpires)return!0;let r=1000;if(e.count>this.options.burstLimit)return!0;if(e.count>this.options.maxRequestsPerMinute)return!0;return!1}blockIP(e,t){e.blocked=!0,e.blockExpires=t+this.options.blockDuration}createBlockedResponse(e,t){let r=Math.ceil((t.blockExpires-Date.now())/1000),s={"Retry-After":r.toString(),"X-RateLimit-Limit":this.options.maxRequestsPerMinute.toString(),"X-RateLimit-Remaining":"0","X-RateLimit-Reset":Math.ceil(t.blockExpires/1000).toString()};if(this.options.onLimitReached)return this.options.onLimitReached(e,{...t,retryAfter:r});return new Response(JSON.stringify({error:"Too Many Requests",message:"Rate limit exceeded. Please try again later.",retryAfter:r}),{status:429,headers:{"Content-Type":"application/json",...s}})}async handle(e,t){if(!this.options.enabled)return await t()||new Response("Not Found",{status:404});let r=Date.now(),s=this.options.keyGenerator(e);if(this.isWhitelisted(s))return await t()||new Response("Not Found",{status:404});if(this.isBlacklisted(s))return new Response("Access Denied",{status:403});let n=this.getRateLimitInfo(s,r);if(this.shouldBlock(n,r))return this.blockIP(n,r),this.createBlockedResponse(e,n);n.count++,n.lastRequest=r;let i=await t();if(!i)return new Response("Not Found",{status:404});if(this.options.skipSuccessfulRequests&&i.status<400)n.count--;if(this.options.skipFailedRequests&&i.status>=400)n.count--;let o=new Headers(i.headers);return o.set("X-RateLimit-Limit",this.options.maxRequestsPerMinute.toString()),o.set("X-RateLimit-Remaining",Math.max(0,this.options.maxRequestsPerMinute-n.count).toString()),o.set("X-RateLimit-Reset",Math.ceil((n.firstRequest+this.options.windowSize)/1000).toString()),new Response(i.body,{status:i.status,statusText:i.statusText,headers:o})}destroy(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.requestStore.clear()}}function Yo(e={}){let t=new Pe(e);return async(r,s)=>t.handle(r,s)}class Ve{config;FILE_SIGNATURES={"image/jpeg":[new Uint8Array([255,216,255])],"image/png":[new Uint8Array([137,80,78,71,13,10,26,10])],"image/gif":[new Uint8Array([71,73,70,56,55,97]),new Uint8Array([71,73,70,56,57,97])],"application/pdf":[new Uint8Array([37,80,68,70])],"application/zip":[new Uint8Array([80,75,3,4]),new Uint8Array([80,75,5,6]),new Uint8Array([80,75,7,8])]};EXECUTABLE_EXTENSIONS=[".exe",".bat",".cmd",".com",".pif",".scr",".vbs",".js",".jar",".app",".deb",".pkg",".dmg",".sh",".ps1",".msi",".dll"];constructor(e={}){this.config={scanForMalware:e.scanForMalware??!1,checkMagicNumbers:e.checkMagicNumbers??!0,sanitizeFilenames:e.sanitizeFilenames??!0,preventExecutableUploads:e.preventExecutableUploads??!0,maxFilenameLength:e.maxFilenameLength??255}}validateFile(e){let t=[];if(e.originalName.length>this.config.maxFilenameLength)t.push(`Filename too long (max ${this.config.maxFilenameLength} characters)`);if(this.config.sanitizeFilenames){let r=this.sanitizeFilename(e.originalName);if(!r||r.length===0)t.push("Filename is invalid or empty after sanitization")}if(this.config.preventExecutableUploads){let r=this.getFileExtension(e.originalName).toLowerCase();if(this.EXECUTABLE_EXTENSIONS.includes(r))t.push("Executable files are not allowed")}if(this.config.checkMagicNumbers){if(!this.validateFileSignature(e))t.push("File signature does not match declared MIME type")}if(this.config.scanForMalware){if(this.basicMalwareScan(e))t.push("Potential malware detected")}return{isValid:t.length===0,errors:t}}validateFileSignature(e){let t=this.FILE_SIGNATURES[e.mimetype];if(!t)return!0;let r=new Uint8Array(e.buffer.slice(0,16));return t.some((s)=>{if(r.length<s.length)return!1;for(let n=0;n<s.length;n++)if(r[n]!==s[n])return!1;return!0})}sanitizeFilename(e){return e.replace(/[<>:"/\\|?*\u0000-\u001F]/u,"_").replace(/^\.+/,"").replace(/\.+$/,"").replace(/\s+/g,"_").substring(0,this.config.maxFilenameLength)}getFileExtension(e){let t=e.lastIndexOf(".");return t===-1?"":e.substring(t)}basicMalwareScan(e){let t=new Uint8Array(e.buffer),r=new TextDecoder("utf-8",{fatal:!1}).decode(t);return[/eval\s*\(/gi,/document\.write/gi,/window\.location/gi,/<script[^>]*>/gi,/javascript:/gi,/vbscript:/gi,/onload\s*=/gi,/onerror\s*=/gi].some((n)=>n.test(r))}getSafeFilename(e){return this.sanitizeFilename(e)}isAllowedFileType(e,t){if(t.length===0)return!0;return t.includes(e)}isWithinSizeLimit(e,t){return e<=t}}import{randomUUID as Zo}from"crypto";import{existsSync as Qo,mkdirSync as ea,writeFileSync as ta}from"fs";import{basename as ra,extname as yn,join as sa}from"path";class ae{config;fileSecurity;constructor(e={}){if(this.config={destination:e.destination||"./uploads",maxFileSize:e.maxFileSize||10485760,maxFiles:e.maxFiles||10,allowedMimeTypes:e.allowedMimeTypes||[],allowedExtensions:e.allowedExtensions||[],preserveOriginalName:e.preserveOriginalName??!1,generateUniqueFilename:e.generateUniqueFilename??!0,createDestination:e.createDestination??!0,scanForMalware:e.scanForMalware??!1,checkMagicNumbers:e.checkMagicNumbers??!0,sanitizeFilenames:e.sanitizeFilenames??!0,preventExecutableUploads:e.preventExecutableUploads??!0,maxFilenameLength:e.maxFilenameLength??255},this.fileSecurity=new Ve(e),this.config.createDestination&&!Qo(this.config.destination))ea(this.config.destination,{recursive:!0})}async handle(e,t){let r=e.headers.get("content-type");if(!r||!r.includes("multipart/form-data"))return await t()||new Response("Not Found",{status:404});try{let s=await e.formData(),n=[],i={};for(let[c,a]of s.entries())if(a instanceof File){if(n.length>=this.config.maxFiles)return this.createErrorResponse(`Maximum ${this.config.maxFiles} files allowed`,400);if(a.size>this.config.maxFileSize)return this.createErrorResponse(`File ${a.name} exceeds maximum size of ${this.formatBytes(this.config.maxFileSize)}`,413);if(this.config.allowedMimeTypes.length>0){let h=a.type.split(";")[0];if(!this.config.allowedMimeTypes.includes(h))return this.createErrorResponse(`File type ${h} not allowed. Allowed types: ${this.config.allowedMimeTypes.join(", ")}`,415)}let l=yn(a.name).toLowerCase();if(this.config.allowedExtensions.length>0&&!this.config.allowedExtensions.includes(l))return this.createErrorResponse(`File extension ${l} not allowed. Allowed extensions: ${this.config.allowedExtensions.join(", ")}`,415);let u=this.generateFilename(a.name),f=sa(this.config.destination,u),m=await a.arrayBuffer(),d={fieldName:c,originalName:a.name,filename:u,path:f,size:a.size,mimetype:a.type,buffer:m},p=this.fileSecurity.validateFile(d);if(!p.isValid)return this.createErrorResponse(`Security validation failed: ${p.errors.join(", ")}`,400);ta(f,new Uint8Array(m)),n.push(d)}else if(i[c])if(Array.isArray(i[c]))i[c].push(a);else i[c]=[i[c],a];else i[c]=a;return Object.defineProperty(e,"files",{value:n,writable:!0,enumerable:!0,configurable:!0}),Object.defineProperty(e,"file",{value:(c)=>n.find((a)=>a.fieldName===c)??null,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"formBody",{value:i,writable:!0,enumerable:!0,configurable:!0}),await t()||new Response("Not Found",{status:404})}catch(s){return this.createErrorResponse(`File upload failed: ${s instanceof Error?s.message:"Unknown error"}`,500)}}generateFilename(e){let t=this.fileSecurity.getSafeFilename(e);if(this.config.preserveOriginalName&&!this.config.generateUniqueFilename)return t;let r=yn(t),s=ra(t,r);if(this.config.generateUniqueFilename){let n=Zo();return this.config.preserveOriginalName?`${s}_${n}${r}`:`${n}${r}`}return t}formatBytes(e){if(e===0)return"0 Bytes";let t=1024,r=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${Number.parseFloat((e/t**s).toFixed(2))} ${r[s]}`}createErrorResponse(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}}function na(e={}){return new ae(e)}function ia(e,t={}){return new ae({...t,maxFiles:1})}function oa(e=10,t={}){return new ae({...t,maxFiles:e})}function aa(e={}){return new ae({...e,allowedMimeTypes:["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/svg+xml"],allowedExtensions:[".jpg",".jpeg",".png",".gif",".webp",".svg"]})}function ca(e={}){return new ae({...e,allowedMimeTypes:["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain"],allowedExtensions:[".pdf",".doc",".docx",".txt"]})}class He{options;constructor(e={}){let t=v.server?.security?.helmet||{};this.options={contentSecurityPolicy:e.contentSecurityPolicy??t.contentSecurityPolicy??{directives:{"default-src":["'self'"],"script-src":["'self'","'unsafe-inline'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","https:"],"font-src":["'self'"],"connect-src":["'self'"],"media-src":["'self'"],"object-src":["'none'"],"child-src":["'self'"],"worker-src":["'self'"],"frame-ancestors":["'none'"],"form-action":["'self'"],"base-uri":["'self'"],"manifest-src":["'self'"]}},crossOriginEmbedderPolicy:e.crossOriginEmbedderPolicy??!0,crossOriginOpenerPolicy:e.crossOriginOpenerPolicy??!0,crossOriginResourcePolicy:e.crossOriginResourcePolicy??!0,dnsPrefetchControl:e.dnsPrefetchControl??!0,expectCt:e.expectCt??t.expectCt??!1,frameguard:e.frameguard??{action:t.frameOptions?.toLowerCase()||"deny"},hidePoweredBy:e.hidePoweredBy??t.hidePoweredBy??!0,hsts:e.hsts??t.hsts??{maxAge:31536000,includeSubDomains:!0,preload:!0},ieNoOpen:e.ieNoOpen??!0,noSniff:e.noSniff??t.noSniff??!0,originAgentCluster:e.originAgentCluster??!0,permittedCrossDomainPolicies:e.permittedCrossDomainPolicies??{permittedPolicies:"none"},referrerPolicy:e.referrerPolicy??t.referrerPolicy??{policy:"strict-origin-when-cross-origin"},xssFilter:e.xssFilter??t.xssFilter??!0}}async handle(e,t){if((v.server?.security?.helmet||{}).enabled===!1)return await t()||new Response("Not Found",{status:404});let s=await t();if(!s)return new Response("Not Found",{status:404});let n=new Headers(s.headers);if(this.options.contentSecurityPolicy){let i=this.options.contentSecurityPolicy;if(typeof i==="object"&&i.directives){let o=Object.entries(i.directives).map(([a,l])=>`${a} ${l.join(" ")}`).join("; "),c=i.reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy";if(n.set(c,o),i.reportUri)n.set("Report-To",JSON.stringify({group:"csp-endpoint",max_age:10886400,endpoints:[{url:i.reportUri}]}))}}if(this.options.crossOriginEmbedderPolicy){let i=this.options.crossOriginEmbedderPolicy,o=typeof i==="object"?i.policy||"require-corp":"require-corp";n.set("Cross-Origin-Embedder-Policy",o)}if(this.options.crossOriginOpenerPolicy){let i=this.options.crossOriginOpenerPolicy,o=typeof i==="object"?i.policy||"same-origin":"same-origin";n.set("Cross-Origin-Opener-Policy",o)}if(this.options.crossOriginResourcePolicy){let i=this.options.crossOriginResourcePolicy,o=typeof i==="object"?i.policy||"same-origin":"same-origin";n.set("Cross-Origin-Resource-Policy",o)}if(this.options.dnsPrefetchControl){let i=this.options.dnsPrefetchControl,o=typeof i==="object"?i.allow:!1;n.set("X-DNS-Prefetch-Control",o?"on":"off")}if(this.options.expectCt){let i=this.options.expectCt;if(typeof i==="object"){let o=[];if(i.enforce)o.push("enforce");if(i.maxAge)o.push(`max-age=${i.maxAge}`);if(i.reportUri)o.push(`report-uri="${i.reportUri}"`);n.set("Expect-CT",o.join(", "))}}if(this.options.frameguard){let i=this.options.frameguard;if(typeof i==="object"){let o=i.action||"deny",c=o==="sameorigin"&&i.domain?`ALLOW-FROM ${i.domain}`:o.toUpperCase();n.set("X-Frame-Options",c)}}if(this.options.hidePoweredBy)n.delete("X-Powered-By");if(this.options.hsts){let i=this.options.hsts;if(typeof i==="object"){let o=[`max-age=${i.maxAge||31536000}`];if(i.includeSubDomains)o.push("includeSubDomains");if(i.preload)o.push("preload");n.set("Strict-Transport-Security",o.join("; "))}}if(this.options.ieNoOpen)n.set("X-Download-Options","noopen");if(this.options.noSniff)n.set("X-Content-Type-Options","nosniff");if(this.options.originAgentCluster)n.set("Origin-Agent-Cluster","?1");if(this.options.permittedCrossDomainPolicies){let i=this.options.permittedCrossDomainPolicies,o=typeof i==="object"?i.permittedPolicies||"none":"none";n.set("X-Permitted-Cross-Domain-Policies",o)}if(this.options.referrerPolicy){let i=this.options.referrerPolicy;if(typeof i==="object"){let o=Array.isArray(i.policy)?i.policy.join(", "):i.policy||"strict-origin-when-cross-origin";n.set("Referrer-Policy",o)}else n.set("Referrer-Policy","strict-origin-when-cross-origin")}if(this.options.xssFilter){let i=this.options.xssFilter,o=typeof i==="object"&&i.setOnOldIE?"1; mode=block":"0";n.set("X-XSS-Protection",o)}return new Response(s.body,{status:s.status,statusText:s.statusText,headers:n})}}var la=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/,ua=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;class Ae{options;constructor(e={}){let t=v.server?.security?.inputValidation||{};this.options={enabled:e.enabled??t.enabled??!0,schemas:e.schemas??t.schemas??{},sanitizeByDefault:e.sanitizeByDefault??t.sanitizeByDefault??!0,strictMode:e.strictMode??t.strictMode??!1,allowUnknownFields:e.allowUnknownFields??t.allowUnknownFields??!0,maxDepth:e.maxDepth??t.maxDepth??10,onValidationError:e.onValidationError}}validateValue(e,t,r){let s=[];if(t.required&&(e===void 0||e===null||e===""))return s.push({field:r,message:"Field is required",value:e,rule:"required"}),s;if(e===void 0||e===null)return s;switch(t.type){case"string":if(typeof e!=="string")s.push({field:r,message:"Must be a string",value:e,rule:"type"});else{if(t.min!==void 0&&e.length<t.min)s.push({field:r,message:`Must be at least ${t.min} characters`,value:e,rule:"min"});if(t.max!==void 0&&e.length>t.max)s.push({field:r,message:`Must be at most ${t.max} characters`,value:e,rule:"max"})}break;case"number":{let n=Number(e);if(Number.isNaN(n))s.push({field:r,message:"Must be a number",value:e,rule:"type"});else{if(t.min!==void 0&&n<t.min)s.push({field:r,message:`Must be at least ${t.min}`,value:e,rule:"min"});if(t.max!==void 0&&n>t.max)s.push({field:r,message:`Must be at most ${t.max}`,value:e,rule:"max"})}break}case"boolean":if(typeof e!=="boolean"&&e!=="true"&&e!=="false")s.push({field:r,message:"Must be a boolean",value:e,rule:"type"});break;case"email":{if(typeof e==="string"&&!la.test(e))s.push({field:r,message:"Must be a valid email address",value:e,rule:"format"});break}case"url":try{new URL(e)}catch{s.push({field:r,message:"Must be a valid URL",value:e,rule:"format"})}break;case"uuid":{if(typeof e==="string"&&!ua.test(e))s.push({field:r,message:"Must be a valid UUID",value:e,rule:"format"});break}case"date":{let n=new Date(e);if(Number.isNaN(n.getTime()))s.push({field:r,message:"Must be a valid date",value:e,rule:"format"});break}case"regex":if(t.pattern&&typeof e==="string"&&!t.pattern.test(e))s.push({field:r,message:"Does not match required pattern",value:e,rule:"pattern"});break;case"custom":if(t.custom){let n=t.custom(e);if(n!==!0)s.push({field:r,message:typeof n==="string"?n:"Custom validation failed",value:e,rule:"custom"})}break}if(t.enum&&!t.enum.includes(e))s.push({field:r,message:`Must be one of: ${t.enum.join(", ")}`,value:e,rule:"enum"});if(t.type!=="regex"&&t.pattern&&typeof e==="string"&&!t.pattern.test(e))s.push({field:r,message:"Does not match required pattern",value:e,rule:"pattern"});return s}sanitizeValue(e,t){if(!t.sanitize&&!this.options.sanitizeByDefault)return e;if(typeof e==="string")e=e.replace(/[<>'"&]/g,(r)=>({"<":"<",">":">",'"':""","'":"'","&":"&"})[r]||r).trim();if(t.transform)e=t.transform(e);return e}validateObject(e,t,r="",s=0){let n=[];if(s>this.options.maxDepth)return n.push({field:r,message:"Maximum nesting depth exceeded",value:e,rule:"depth"}),n;if(this.options.strictMode&&!this.options.allowUnknownFields){for(let i in e)if(!(i in t))n.push({field:r?`${r}.${i}`:i,message:"Unknown field",value:e[i],rule:"unknown"})}for(let[i,o]of Object.entries(t)){let c=r?`${r}.${i}`:i,a=e?.[i];if(typeof o==="object"&&!("type"in o)){if(a&&typeof a==="object")n.push(...this.validateObject(a,o,c,s+1))}else{let l=o;if(n.push(...this.validateValue(a,l,c)),e&&(l.sanitize||this.options.sanitizeByDefault))e[i]=this.sanitizeValue(a,l)}}return n}async parseRequestBody(e){let t=e.headers.get("content-type")||"";try{if(t.includes("application/json"))return await e.json();else if(t.includes("application/x-www-form-urlencoded")){let r=await e.formData(),s={};for(let[n,i]of r.entries())s[n]=i;return s}else if(t.includes("multipart/form-data")){let r=await e.formData(),s={};for(let[n,i]of r.entries())s[n]=i;return s}}catch(r){throw console.error(r),Error("Invalid request body format")}return{}}async handle(e,t){if(!this.options.enabled)return await t()||new Response("Not Found",{status:404});let r=[],s=new URL(e.url);try{if(this.options.schemas?.query){let i={};for(let[c,a]of s.searchParams.entries())i[c]=a;let o=this.validateObject(i,this.options.schemas.query);r.push(...o)}if(this.options.schemas?.body&&e.method!=="GET"&&e.method!=="HEAD")try{let i=await this.parseRequestBody(e),o=this.validateObject(i,this.options.schemas.body);r.push(...o),e.validatedBody=i}catch(i){r.push({field:"body",message:i instanceof Error?i.message:"Invalid request body",value:null,rule:"parse"})}if(this.options.schemas?.headers){let i={};for(let[c,a]of e.headers.entries())i[c]=a;let o=this.validateObject(i,this.options.schemas.headers);r.push(...o)}if(this.options.schemas?.params&&e.params){let i=this.validateObject(e.params,this.options.schemas.params);r.push(...i)}if(r.length>0){if(this.options.onValidationError)return this.options.onValidationError(r);return new Response(JSON.stringify({error:"Validation Error",message:"Request validation failed",errors:r}),{status:400,headers:{"Content-Type":"application/json"}})}return await t()||new Response("Not Found",{status:404})}catch(n){return console.error("Input validation error:",n),new Response("Internal Server Error",{status:500})}}}function fa(e={}){let t=new Ae(e);return async(r,s)=>t.handle(r,s)}class Dt{options;rules=new Map;channels=[];notifications=[];lastAlertTimes=new Map;metricsBuffer=[];checkInterval;constructor(e={}){if(this.options={enabled:e.enabled??!0,defaultCooldown:e.defaultCooldown??300000,maxAlerts:e.maxAlerts??1000,autoResolve:e.autoResolve??!0,autoResolveTimeout:e.autoResolveTimeout??600000,...e},e.rules)for(let t of e.rules)this.rules.set(t.id,t);if(this.channels=e.channels||[],this.rules.size===0)this.addDefaultRules();if(this.channels.length===0)this.channels.push({type:"console",enabled:!0,config:{}});if(this.options.enabled)this.startAlertingEngine()}addDefaultRules(){let e=[{id:"high-response-time",name:"High Response Time",description:"Alert when average response time exceeds threshold",enabled:!0,metric:"responseTime",condition:"gt",threshold:1000,duration:60000,severity:"warning"},{id:"critical-response-time",name:"Critical Response Time",description:"Alert when response time is critically high",enabled:!0,metric:"responseTime",condition:"gt",threshold:5000,duration:30000,severity:"critical"},{id:"high-error-rate",name:"High Error Rate",description:"Alert when error rate exceeds threshold",enabled:!0,metric:"errorRate",condition:"gt",threshold:0.05,duration:120000,severity:"warning"},{id:"critical-error-rate",name:"Critical Error Rate",description:"Alert when error rate is critically high",enabled:!0,metric:"errorRate",condition:"gt",threshold:0.1,duration:60000,severity:"critical"},{id:"high-memory-usage",name:"High Memory Usage",description:"Alert when memory usage exceeds threshold",enabled:!0,metric:"memoryUsage",condition:"gt",threshold:536870912,duration:300000,severity:"warning"},{id:"low-request-rate",name:"Low Request Rate",description:"Alert when request rate drops significantly",enabled:!1,metric:"requestRate",condition:"lt",threshold:1,duration:300000,severity:"info"}];for(let t of e)this.rules.set(t.id,t)}startAlertingEngine(){this.checkInterval=setInterval(()=>{this.evaluateRules(),this.cleanupOldNotifications(),this.autoResolveAlerts()},1e4),this.checkInterval.unref?.()}evaluateRules(){let e=Date.now();for(let t of this.rules.values()){if(!t.enabled)continue;let r=this.lastAlertTimes.get(t.id),s=t.cooldown||this.options.defaultCooldown||300000;if(r&&e-r<s)continue;let n=t.duration||60000,i=this.metricsBuffer.filter((a)=>e-a.timestamp<=n);if(i.length===0)continue;let o=!1,c;if(t.metric==="custom"&&t.customEvaluator)o=t.customEvaluator(i),c="custom condition";else{let a=this.extractMetricValues(i,t.metric);if(a.length===0)continue;let l=a.reduce((u,f)=>u+f,0)/a.length;c=l,o=this.evaluateCondition(l,t.condition,t.threshold)}if(o)this.triggerAlert(t,c,i),this.lastAlertTimes.set(t.id,e)}}extractMetricValues(e,t){switch(t){case"responseTime":return e.map((r)=>r.responseTime);case"errorRate":return e.map((r)=>r.statusCode>=400?1:0);case"memoryUsage":return e.map((r)=>r.memoryUsage.heapUsed);case"cpuUsage":return e.map((r)=>r.cpuUsage.user+r.cpuUsage.system);case"requestRate":{if(e.length<2)return[];let r=(e[e.length-1].timestamp-e[0].timestamp)/1000;return[e.length/Math.max(r,1)]}default:return[]}}evaluateCondition(e,t,r){switch(t){case"gt":return e>r;case"gte":return e>=r;case"lt":return e<r;case"lte":return e<=r;case"eq":return Math.abs(e-r)<0.001;default:return!1}}async triggerAlert(e,t,r){let s={id:this.generateId(),ruleId:e.id,ruleName:e.name,severity:e.severity,message:this.formatAlertMessage(e,t,r),timestamp:Date.now(),resolved:!1,metadata:{rule:e,value:t,threshold:e.threshold,condition:e.condition,metricsCount:r.length}};this.notifications.push(s);for(let n of this.channels){if(!n.enabled)continue;if(n.filters?.severities&&!n.filters.severities.includes(e.severity))continue;if(n.filters?.rules&&!n.filters.rules.includes(e.id))continue;try{await this.sendNotification(n,s)}catch(i){console.error(`Failed to send alert to ${n.type}:`,i)}}if(this.notifications.length>(this.options.maxAlerts||1000))this.notifications=this.notifications.slice(-(this.options.maxAlerts||1000))}formatAlertMessage(e,t,r){let s=(o,c)=>{switch(c){case"responseTime":return`${Math.round(o)}ms`;case"errorRate":return`${Math.round(o*100)}%`;case"memoryUsage":return`${Math.round(o/1024/1024)}MB`;case"cpuUsage":return`${Math.round(o)}%`;case"requestRate":return`${Math.round(o)}/s`;default:return String(o)}},n=typeof t==="number"?s(t,e.metric):String(t),i=s(e.threshold,e.metric);return`${e.name}: ${n} ${e.condition} ${i} (${r.length} samples)`}async sendNotification(e,t){switch(e.type){case"console":this.sendConsoleNotification(t);break;case"webhook":await this.sendWebhookNotification(e,t);break;case"slack":await this.sendSlackNotification(e,t);break;case"email":await this.sendEmailNotification(e,t);break;case"custom":if(e.config.customHandler)await e.config.customHandler(t);break}}sendConsoleNotification(e){let t=e.severity==="critical"?"\uD83D\uDEA8":e.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";console.log(`${t} ALERT [${e.severity.toUpperCase()}]: ${e.message}`),console.log(` Rule: ${e.ruleName} (${e.ruleId})`),console.log(` Time: ${new Date(e.timestamp).toISOString()}`)}async sendWebhookNotification(e,t){if(!e.config.url)return;let r={alert:t,timestamp:new Date(t.timestamp).toISOString(),service:"bun-router"};await fetch(e.config.url,{method:"POST",headers:{"Content-Type":"application/json",...e.config.token&&{Authorization:`Bearer ${e.config.token}`}},body:JSON.stringify(r)})}async sendSlackNotification(e,t){if(!e.config.url)return;let r=t.severity==="critical"?"danger":t.severity==="warning"?"warning":"good",s=t.severity==="critical"?":rotating_light:":t.severity==="warning"?":warning:":":information_source:",n=(()=>({channel:e.config.channel,username:"Performance Monitor",icon_emoji:":chart_with_upwards_trend:",attachments:[{color:r,title:`${s} ${t.ruleName}`,text:t.message,fields:[{title:"Severity",value:t.severity.toUpperCase(),short:!0},{title:"Time",value:new Date(t.timestamp).toISOString(),short:!0}],footer:"bun-router Performance Monitor",ts:Math.floor(t.timestamp/1000)}]}))();await fetch(e.config.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async sendEmailNotification(e,t){console.log(`Email notification would be sent to ${e.config.email}:`,t.message)}cleanupOldNotifications(){let t=Date.now()-86400000;this.notifications=this.notifications.filter((r)=>r.timestamp>t)}autoResolveAlerts(){if(!this.options.autoResolve)return;let e=this.options.autoResolveTimeout||600000,t=Date.now()-e;for(let r of this.notifications)if(!r.resolved&&r.timestamp<t)r.resolved=!0,r.resolvedAt=Date.now()}generateId(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}addMetrics(e){this.metricsBuffer.push(e);let t=3600000,r=Date.now()-t;this.metricsBuffer=this.metricsBuffer.filter((s)=>s.timestamp>r)}addRule(e){this.rules.set(e.id,e)}removeRule(e){this.rules.delete(e)}updateRule(e,t){let r=this.rules.get(e);if(r)this.rules.set(e,{...r,...t})}addChannel(e){this.channels.push(e)}removeChannel(e){this.channels.splice(e,1)}getActiveAlerts(){return this.notifications.filter((e)=>!e.resolved)}getAllNotifications(){return[...this.notifications]}resolveAlert(e){let t=this.notifications.find((r)=>r.id===e);if(t&&!t.resolved)t.resolved=!0,t.resolvedAt=Date.now()}async handle(e,t){let r=await t();if(r)return r;return new Response("No response from next middleware",{status:500})}destroy(){if(this.checkInterval)clearInterval(this.checkInterval);this.rules.clear(),this.channels=[],this.notifications=[],this.lastAlertTimes.clear(),this.metricsBuffer=[]}}function da(e={}){return new Dt(e)}import Fe from"process";class jt{options;metricsHistory=[];alerts=[];startTime=Date.now();constructor(e={}){this.options={enabled:e.enabled??!0,path:e.path??"/performance",title:e.title??"Performance Dashboard",refreshInterval:e.refreshInterval??5000,maxMetrics:e.maxMetrics??1000,authentication:{enabled:!1,...e.authentication},features:{realTimeMetrics:!0,historicalCharts:!0,alertsPanel:!0,tracingView:!0,systemMetrics:!0,...e.features}}}isAuthenticated(e){if(!this.options.authentication?.enabled)return!0;let t=e.headers.get("authorization"),r=e.headers.get("x-api-key");if(this.options.authentication.apiKey&&r===this.options.authentication.apiKey)return!0;if(t&&this.options.authentication.username&&this.options.authentication.password){let[s,n]=t.split(" ");if(s==="Basic"){let i=atob(n),[o,c]=i.split(":");return o===this.options.authentication.username&&c===this.options.authentication.password}}return!1}generateDashboardHTML(e){return`
|
|
64
|
+
<!DOCTYPE html>
|
|
65
|
+
<html lang="en">
|
|
66
|
+
<head>
|
|
67
|
+
<meta charset="UTF-8">
|
|
68
|
+
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
|
|
69
|
+
<title>${this.options.title}</title>
|
|
70
|
+
<style>
|
|
71
|
+
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
72
|
+
body {
|
|
73
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
74
|
+
background: #f5f5f5;
|
|
75
|
+
color: #333;
|
|
76
|
+
line-height: 1.6;
|
|
77
|
+
}
|
|
78
|
+
.header {
|
|
79
|
+
background: #2c3e50;
|
|
80
|
+
color: white;
|
|
81
|
+
padding: 1rem 2rem;
|
|
82
|
+
display: flex;
|
|
83
|
+
justify-content: space-between;
|
|
84
|
+
align-items: center;
|
|
85
|
+
}
|
|
86
|
+
.header h1 { font-size: 1.5rem; }
|
|
87
|
+
.status {
|
|
88
|
+
display: flex;
|
|
89
|
+
gap: 1rem;
|
|
90
|
+
align-items: center;
|
|
91
|
+
}
|
|
92
|
+
.status-item {
|
|
93
|
+
display: flex;
|
|
94
|
+
flex-direction: column;
|
|
95
|
+
align-items: center;
|
|
96
|
+
font-size: 0.8rem;
|
|
97
|
+
}
|
|
98
|
+
.status-value {
|
|
99
|
+
font-size: 1.2rem;
|
|
100
|
+
font-weight: bold;
|
|
101
|
+
}
|
|
102
|
+
.container {
|
|
103
|
+
max-width: 1400px;
|
|
104
|
+
margin: 0 auto;
|
|
105
|
+
padding: 2rem;
|
|
106
|
+
display: grid;
|
|
107
|
+
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
|
108
|
+
gap: 2rem;
|
|
109
|
+
}
|
|
110
|
+
.card {
|
|
111
|
+
background: white;
|
|
112
|
+
border-radius: 8px;
|
|
113
|
+
padding: 1.5rem;
|
|
114
|
+
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
|
115
|
+
}
|
|
116
|
+
.card h2 {
|
|
117
|
+
margin-bottom: 1rem;
|
|
118
|
+
color: #2c3e50;
|
|
119
|
+
font-size: 1.2rem;
|
|
120
|
+
}
|
|
121
|
+
.metric {
|
|
122
|
+
display: flex;
|
|
123
|
+
justify-content: space-between;
|
|
124
|
+
align-items: center;
|
|
125
|
+
padding: 0.5rem 0;
|
|
126
|
+
border-bottom: 1px solid #eee;
|
|
127
|
+
}
|
|
128
|
+
.metric:last-child { border-bottom: none; }
|
|
129
|
+
.metric-label { font-weight: 500; }
|
|
130
|
+
.metric-value {
|
|
131
|
+
font-weight: bold;
|
|
132
|
+
color: #27ae60;
|
|
133
|
+
}
|
|
134
|
+
.metric-value.warning { color: #f39c12; }
|
|
135
|
+
.metric-value.critical { color: #e74c3c; }
|
|
136
|
+
.alert {
|
|
137
|
+
padding: 0.75rem;
|
|
138
|
+
margin: 0.5rem 0;
|
|
139
|
+
border-radius: 4px;
|
|
140
|
+
border-left: 4px solid;
|
|
141
|
+
}
|
|
142
|
+
.alert.warning {
|
|
143
|
+
background: #fff3cd;
|
|
144
|
+
border-color: #f39c12;
|
|
145
|
+
color: #856404;
|
|
146
|
+
}
|
|
147
|
+
.alert.critical {
|
|
148
|
+
background: #f8d7da;
|
|
149
|
+
border-color: #e74c3c;
|
|
150
|
+
color: #721c24;
|
|
151
|
+
}
|
|
152
|
+
.chart-container {
|
|
153
|
+
height: 200px;
|
|
154
|
+
background: #f8f9fa;
|
|
155
|
+
border-radius: 4px;
|
|
156
|
+
display: flex;
|
|
157
|
+
align-items: center;
|
|
158
|
+
justify-content: center;
|
|
159
|
+
color: #666;
|
|
160
|
+
}
|
|
161
|
+
.distribution {
|
|
162
|
+
display: grid;
|
|
163
|
+
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
|
|
164
|
+
gap: 1rem;
|
|
165
|
+
margin-top: 1rem;
|
|
166
|
+
}
|
|
167
|
+
.distribution-item {
|
|
168
|
+
text-align: center;
|
|
169
|
+
padding: 1rem;
|
|
170
|
+
background: #f8f9fa;
|
|
171
|
+
border-radius: 4px;
|
|
172
|
+
}
|
|
173
|
+
.distribution-value {
|
|
174
|
+
font-size: 1.5rem;
|
|
175
|
+
font-weight: bold;
|
|
176
|
+
color: #2c3e50;
|
|
177
|
+
}
|
|
178
|
+
.distribution-label {
|
|
179
|
+
font-size: 0.8rem;
|
|
180
|
+
color: #666;
|
|
181
|
+
margin-top: 0.5rem;
|
|
182
|
+
}
|
|
183
|
+
.trace {
|
|
184
|
+
padding: 0.75rem;
|
|
185
|
+
margin: 0.5rem 0;
|
|
186
|
+
background: #f8f9fa;
|
|
187
|
+
border-radius: 4px;
|
|
188
|
+
border-left: 4px solid #3498db;
|
|
189
|
+
}
|
|
190
|
+
.trace-header {
|
|
191
|
+
display: flex;
|
|
192
|
+
justify-content: space-between;
|
|
193
|
+
align-items: center;
|
|
194
|
+
margin-bottom: 0.5rem;
|
|
195
|
+
}
|
|
196
|
+
.trace-operation {
|
|
197
|
+
font-weight: bold;
|
|
198
|
+
color: #2c3e50;
|
|
199
|
+
}
|
|
200
|
+
.trace-duration {
|
|
201
|
+
color: #666;
|
|
202
|
+
font-size: 0.9rem;
|
|
203
|
+
}
|
|
204
|
+
.trace-details {
|
|
205
|
+
font-size: 0.8rem;
|
|
206
|
+
color: #666;
|
|
207
|
+
}
|
|
208
|
+
.refresh-indicator {
|
|
209
|
+
position: fixed;
|
|
210
|
+
top: 1rem;
|
|
211
|
+
right: 1rem;
|
|
212
|
+
background: #27ae60;
|
|
213
|
+
color: white;
|
|
214
|
+
padding: 0.5rem 1rem;
|
|
215
|
+
border-radius: 4px;
|
|
216
|
+
font-size: 0.8rem;
|
|
217
|
+
opacity: 0;
|
|
218
|
+
transition: opacity 0.3s;
|
|
219
|
+
}
|
|
220
|
+
.refresh-indicator.active { opacity: 1; }
|
|
221
|
+
@media (max-width: 768px) {
|
|
222
|
+
.container {
|
|
223
|
+
grid-template-columns: 1fr;
|
|
224
|
+
padding: 1rem;
|
|
225
|
+
}
|
|
226
|
+
.header {
|
|
227
|
+
padding: 1rem;
|
|
228
|
+
flex-direction: column;
|
|
229
|
+
gap: 1rem;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
</style>
|
|
233
|
+
</head>
|
|
234
|
+
<body>
|
|
235
|
+
<div class='header'>
|
|
236
|
+
<h1>${this.options.title}</h1>
|
|
237
|
+
<div class='status'>
|
|
238
|
+
<div class='status-item'>
|
|
239
|
+
<div class='status-value'>${e.metrics.current.totalRequests}</div>
|
|
240
|
+
<div>Total Requests</div>
|
|
241
|
+
</div>
|
|
242
|
+
<div class='status-item'>
|
|
243
|
+
<div class='status-value'>${Math.round(e.metrics.current.averageResponseTime)}ms</div>
|
|
244
|
+
<div>Avg Response</div>
|
|
245
|
+
</div>
|
|
246
|
+
<div class='status-item'>
|
|
247
|
+
<div class='status-value'>${Math.round(e.metrics.current.errorRate*100)}%</div>
|
|
248
|
+
<div>Error Rate</div>
|
|
249
|
+
</div>
|
|
250
|
+
<div class='status-item'>
|
|
251
|
+
<div class='status-value'>${Math.round(e.metrics.current.requestsPerSecond)}/s</div>
|
|
252
|
+
<div>Requests/sec</div>
|
|
253
|
+
</div>
|
|
254
|
+
</div>
|
|
255
|
+
</div>
|
|
256
|
+
|
|
257
|
+
<div class='container'>
|
|
258
|
+
${this.options.features?.realTimeMetrics?`
|
|
259
|
+
<div class='card'>
|
|
260
|
+
<h2>Real-time Metrics</h2>
|
|
261
|
+
<div class='metric'>
|
|
262
|
+
<span class='metric-label'>Response Time</span>
|
|
263
|
+
<span class='metric-value'>${Math.round(e.metrics.current.averageResponseTime)}ms</span>
|
|
264
|
+
</div>
|
|
265
|
+
<div class='metric'>
|
|
266
|
+
<span class='metric-label'>Memory Usage</span>
|
|
267
|
+
<span class='metric-value'>${Math.round(e.metrics.current.memoryUsage/1024/1024)}MB</span>
|
|
268
|
+
</div>
|
|
269
|
+
<div class='metric'>
|
|
270
|
+
<span class='metric-label'>CPU Usage</span>
|
|
271
|
+
<span class='metric-value'>${Math.round(e.metrics.current.cpuUsage)}%</span>
|
|
272
|
+
</div>
|
|
273
|
+
<div class='metric'>
|
|
274
|
+
<span class='metric-label'>Requests/sec</span>
|
|
275
|
+
<span class='metric-value'>${Math.round(e.metrics.current.requestsPerSecond)}</span>
|
|
276
|
+
</div>
|
|
277
|
+
<div class='metric'>
|
|
278
|
+
<span class='metric-label'>Error Rate</span>
|
|
279
|
+
<span class='metric-value ${e.metrics.current.errorRate>0.1?"critical":e.metrics.current.errorRate>0.05?"warning":""}'>${Math.round(e.metrics.current.errorRate*100)}%</span>
|
|
280
|
+
</div>
|
|
281
|
+
</div>
|
|
282
|
+
`:""}
|
|
283
|
+
|
|
284
|
+
${this.options.features?.historicalCharts?`
|
|
285
|
+
<div class='card'>
|
|
286
|
+
<h2>Historical Performance</h2>
|
|
287
|
+
<div class='chart-container'>
|
|
288
|
+
Response Time Chart (${e.metrics.historical.length} data points)
|
|
289
|
+
</div>
|
|
290
|
+
</div>
|
|
291
|
+
`:""}
|
|
292
|
+
|
|
293
|
+
<div class='card'>
|
|
294
|
+
<h2>Request Distribution</h2>
|
|
295
|
+
<div class='distribution'>
|
|
296
|
+
${Object.entries(e.metrics.distribution.statusCodes).map(([t,r])=>`
|
|
297
|
+
<div class='distribution-item'>
|
|
298
|
+
<div class='distribution-value'>${r}</div>
|
|
299
|
+
<div class='distribution-label'>HTTP ${t}</div>
|
|
300
|
+
</div>
|
|
301
|
+
`).join("")}
|
|
302
|
+
</div>
|
|
303
|
+
</div>
|
|
304
|
+
|
|
305
|
+
<div class='card'>
|
|
306
|
+
<h2>Top Endpoints</h2>
|
|
307
|
+
${Object.entries(e.metrics.distribution.paths).sort(([,t],[,r])=>r-t).slice(0,10).map(([t,r])=>`
|
|
308
|
+
<div class='metric'>
|
|
309
|
+
<span class='metric-label'>${t}</span>
|
|
310
|
+
<span class='metric-value'>${r}</span>
|
|
311
|
+
</div>
|
|
312
|
+
`).join("")}
|
|
313
|
+
</div>
|
|
314
|
+
|
|
315
|
+
${this.options.features?.alertsPanel?`
|
|
316
|
+
<div class='card'>
|
|
317
|
+
<h2>Active Alerts</h2>
|
|
318
|
+
${e.alerts.length===0?"<p>No active alerts</p>":""}
|
|
319
|
+
${e.alerts.filter((t)=>!t.resolved).map((t)=>`
|
|
320
|
+
<div class='${t.type} alert'>
|
|
321
|
+
<strong>${t.type.toUpperCase()}:</strong> ${t.message}
|
|
322
|
+
<br><small>${new Date(t.timestamp).toLocaleString()}</small>
|
|
323
|
+
</div>
|
|
324
|
+
`).join("")}
|
|
325
|
+
</div>
|
|
326
|
+
`:""}
|
|
327
|
+
|
|
328
|
+
${this.options.features?.tracingView?`
|
|
329
|
+
<div class='card'>
|
|
330
|
+
<h2>Recent Traces</h2>
|
|
331
|
+
${e.traces.slice(0,10).map((t)=>`
|
|
332
|
+
<div class='trace'>
|
|
333
|
+
<div class='trace-header'>
|
|
334
|
+
<span class='trace-operation'>${t.operationName}</span>
|
|
335
|
+
<span class='trace-duration'>${Math.round((t.duration||0)*100)/100}ms</span>
|
|
336
|
+
</div>
|
|
337
|
+
<div class='trace-details'>
|
|
338
|
+
Trace ID: ${t.traceId} | Status: ${t.status}
|
|
339
|
+
${t.error?` | Error: ${t.error}`:""}
|
|
340
|
+
</div>
|
|
341
|
+
</div>
|
|
342
|
+
`).join("")}
|
|
343
|
+
</div>
|
|
344
|
+
`:""}
|
|
345
|
+
|
|
346
|
+
${this.options.features?.systemMetrics?`
|
|
347
|
+
<div class='card'>
|
|
348
|
+
<h2>System Information</h2>
|
|
349
|
+
<div class='metric'>
|
|
350
|
+
<span class='metric-label'>Uptime</span>
|
|
351
|
+
<span class='metric-value'>${Math.round(e.system.uptime/1000/60)} minutes</span>
|
|
352
|
+
</div>
|
|
353
|
+
<div class='metric'>
|
|
354
|
+
<span class='metric-label'>Node.js</span>
|
|
355
|
+
<span class='metric-value'>${e.system.nodeVersion}</span>
|
|
356
|
+
</div>
|
|
357
|
+
<div class='metric'>
|
|
358
|
+
<span class='metric-label'>Platform</span>
|
|
359
|
+
<span class='metric-value'>${e.system.platform} ${e.system.arch}</span>
|
|
360
|
+
</div>
|
|
361
|
+
<div class='metric'>
|
|
362
|
+
<span class='metric-label'>Heap Used</span>
|
|
363
|
+
<span class='metric-value'>${Math.round(e.system.memory.heapUsed/1024/1024)}MB</span>
|
|
364
|
+
</div>
|
|
365
|
+
<div class='metric'>
|
|
366
|
+
<span class='metric-label'>RSS</span>
|
|
367
|
+
<span class='metric-value'>${Math.round(e.system.memory.rss/1024/1024)}MB</span>
|
|
368
|
+
</div>
|
|
369
|
+
</div>
|
|
370
|
+
`:""}
|
|
371
|
+
</div>
|
|
372
|
+
|
|
373
|
+
<div class='refresh-indicator' id='refreshIndicator'>Updated</div>
|
|
374
|
+
|
|
375
|
+
<script>
|
|
376
|
+
let refreshInterval;
|
|
377
|
+
|
|
378
|
+
function startAutoRefresh() {
|
|
379
|
+
refreshInterval = setInterval(async () => {
|
|
380
|
+
try {
|
|
381
|
+
const response = await fetch('${this.options.path}/api/data');
|
|
382
|
+
if (response.ok) {
|
|
383
|
+
const indicator = document.getElementById('refreshIndicator');
|
|
384
|
+
indicator.classList.add('active');
|
|
385
|
+
setTimeout(() => indicator.classList.remove('active'), 1000);
|
|
386
|
+
|
|
387
|
+
// In a real implementation, we would update the DOM with new data
|
|
388
|
+
// For now, we'll just refresh the page
|
|
389
|
+
setTimeout(() => window.location.reload(), ${this.options.refreshInterval});
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
console.error('Failed to refresh data:', error);
|
|
394
|
+
}
|
|
395
|
+
}, ${this.options.refreshInterval});
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// Start auto-refresh
|
|
399
|
+
startAutoRefresh();
|
|
400
|
+
|
|
401
|
+
// Stop refresh when page is hidden
|
|
402
|
+
document.addEventListener('visibilitychange', () => {
|
|
403
|
+
if (document.hidden) {
|
|
404
|
+
clearInterval(refreshInterval);
|
|
405
|
+
}
|
|
406
|
+
else {
|
|
407
|
+
startAutoRefresh();
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
</script>
|
|
411
|
+
</body>
|
|
412
|
+
</html>
|
|
413
|
+
`}async getDashboardData(e,t){let r=Date.now(),s={current:{totalRequests:0,averageResponseTime:0,errorRate:0,requestsPerSecond:0,memoryUsage:0,cpuUsage:0},historical:this.metricsHistory,distribution:{statusCodes:{},paths:{},methods:{},responseTimes:[]}};if(e&&typeof e.getAggregatedMetrics==="function"){let o=e.getAggregatedMetrics(60000);s.current={totalRequests:o.totalRequests,averageResponseTime:o.averageResponseTime,errorRate:o.errorRate,requestsPerSecond:o.requestsPerSecond,memoryUsage:o.averageMemoryUsage,cpuUsage:0},s.distribution.statusCodes=o.statusCodeDistribution,s.distribution.paths=o.pathDistribution}let n=[];if(t&&typeof t.getActiveSpans==="function")n=t.getActiveSpans();let i={uptime:r-this.startTime,nodeVersion:Fe.version,bunVersion:Fe.versions.bun||"N/A",platform:Fe.platform,arch:Fe.arch,memory:Fe.memoryUsage(),cpu:Fe.cpuUsage()};return{metrics:s,alerts:this.alerts,traces:n,system:i}}async handle(e,t){if(!this.options.enabled)return await t()||new Response("Internal Server Error",{status:500});let r=new URL(e.url);if(r.pathname===this.options.path){if(!this.isAuthenticated(e))return new Response("Unauthorized",{status:401,headers:{"WWW-Authenticate":'Basic realm="Performance Dashboard"'}});let s=await this.getDashboardData(),n=this.generateDashboardHTML(s);return new Response(n,{headers:{"Content-Type":"text/html","Cache-Control":"no-cache, no-store, must-revalidate"}})}if(r.pathname===`${this.options.path}/api/data`){if(!this.isAuthenticated(e))return new Response("Unauthorized",{status:401});let s=await this.getDashboardData();return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json","Cache-Control":"no-cache, no-store, must-revalidate"}})}return await t()}addAlert(e,t){if(this.alerts.push({id:Math.random().toString(36).substring(2,15),type:e,message:t,timestamp:Date.now(),resolved:!1}),this.alerts.length>100)this.alerts=this.alerts.slice(-100)}resolveAlert(e){let t=this.alerts.find((r)=>r.id===e);if(t)t.resolved=!0}updateMetricsHistory(e){this.metricsHistory.push({timestamp:Date.now(),...e});let t=this.options.maxMetrics||1000;if(this.metricsHistory.length>t)this.metricsHistory=this.metricsHistory.slice(-t)}}function ma(e={}){let t=new jt(e);return async(r,s)=>t.handle(r,s)}import wn from"crypto";import Z from"process";class Lt{options;metrics=[];lastAlertTime={};requestsThisSecond=0;lastSecondTimestamp=Date.now();requestContexts=new Map;samplingCounter=0;alertCooldowns=new Map;cleanupInterval;constructor(e={}){let t=v.server?.performance?.monitoring||{};if(this.options={enabled:e.enabled??t.enabled??!0,sampleRate:e.sampleRate??e.sampling?.rate??1,collectMetrics:{responseTime:!0,memoryUsage:!0,cpuUsage:!0,requestDetails:!0,headers:!1,queryParams:!0,...e.collectMetrics},sampling:{rate:e.sampling?.rate??e.sampleRate??1,maxRequestsPerSecond:e.sampling?.maxRequestsPerSecond??1000,...e.sampling},thresholds:{responseTime:{warning:1000,critical:5000},memoryUsage:{warning:536870912,critical:1073741824},errorRate:{warning:0.05,critical:0.1}},profiling:{enabled:!1,sampleInterval:100,maxSamples:10,includeStackTrace:!1,maxStackDepth:10},alerts:{enabled:!1,thresholds:{responseTime:1000,memoryUsage:104857600,errorRate:0.05},cooldown:60000},...e},this.options.storage?.type==="memory")this.startCleanupInterval()}startCleanupInterval(){this.cleanupInterval=setInterval(()=>{this.cleanupOldMetrics()},60000),this.cleanupInterval.unref?.()}cleanupOldMetrics(){let e=Date.now(),t=this.options.storage?.retentionPeriod||86400000;this.metrics=this.metrics.filter((s)=>e-s.timestamp<t);let r=this.options.storage?.maxEntries||1e4;if(this.metrics.length>r)this.metrics=this.metrics.slice(-r)}shouldSample(){let e=this.options.sampling?.rate||this.options.sampleRate||1;return Math.random()<e}generateTraceId(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}generateSpanId(){return Math.random().toString(36).substring(2,10)}getClientIP(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||e.headers.get("cf-connecting-ip")||"unknown"}async collectSystemMetrics(){let e=Z.memoryUsage(),t=Z.cpuUsage();return{memory:e,cpu:t}}takeSample(e){let t=Z.memoryUsage(),r=Z.cpuUsage(),s=Date.now();if(!e.systemSamples)e.systemSamples=[];if(!e.samples)e.samples=[];e.systemSamples.push({timestamp:s,memory:t,cpu:r}),e.samples.push({timestamp:s,memory:t,cpu:r,stack:this.options.profiling?.includeStackTrace?Error("Profile sample").stack?.slice(0,this.options.profiling.maxStackDepth||10):void 0})}calculateCpuPercent(e,t,r){let s=t.user-e.user,n=t.system-e.system;return{user:s/r*100,system:n/r*100}}async storeMetrics(e){if(this.metrics.push(e),console.warn(`[PerformanceMonitor] Stored metric: ${e.path} ${e.method} ${e.responseTime}ms`),console.warn(`[PerformanceMonitor] Added metric to internal array: ${e.path} ${e.method} ${e.responseTime}ms`),this.options.storage?.type)switch(this.options.storage.type){case"file":if(this.options.storage.filePath){let t=`${JSON.stringify(e)}
|
|
414
|
+
`;await Bun.write(this.options.storage.filePath,t,{createPath:!0})}break;case"custom":if(this.options.storage.customHandler)await this.options.storage.customHandler(e);break;case"memory":default:break}}async checkThresholds(e){let t=typeof this.options.alerts?.customHandler==="function";if(!this.options.alerts?.enabled&&!t)return;let r=this.options.alerts?.thresholds,s=this.options.thresholds;if(console.warn(`[PerformanceMonitor] Checking thresholds for ${e.path}: responseTime=${e.responseTime}ms, threshold=${r?.responseTime||s?.responseTime?.warning||"none"}`),r?.responseTime&&e.responseTime>r.responseTime)await this.sendAlert({type:"responseTime",message:`Response time threshold exceeded: ${e.responseTime}ms > ${r.responseTime}ms`,value:e.responseTime,threshold:r.responseTime,path:e.path,method:e.method,statusCode:e.statusCode,timestamp:e.timestamp,severity:"warning"});else if(s?.responseTime?.warning&&e.responseTime>s.responseTime.warning)await this.sendAlert({type:"responseTime",message:`Response time threshold exceeded: ${e.responseTime}ms > ${s.responseTime.warning}ms`,value:e.responseTime,threshold:s.responseTime.warning,path:e.path,method:e.method,statusCode:e.statusCode,timestamp:e.timestamp,severity:"warning"});let n=e.memoryUsage.heapUsed;if(r?.memoryUsage&&n>r.memoryUsage)await this.sendAlert({type:"memoryUsage",message:`Memory usage threshold exceeded: ${n} bytes > ${r.memoryUsage} bytes`,value:n,threshold:r.memoryUsage,path:e.path,method:e.method,statusCode:e.statusCode,timestamp:e.timestamp,severity:"warning"});else if(s?.memoryUsage?.warning&&n>s.memoryUsage.warning)await this.sendAlert({type:"memoryUsage",message:`Memory usage threshold exceeded: ${n} bytes > ${s.memoryUsage.warning} bytes`,value:n,threshold:s.memoryUsage.warning,path:e.path,method:e.method,statusCode:e.statusCode,timestamp:e.timestamp,severity:"warning"});if((r?.errorRate||s?.errorRate?.warning)&&e.statusCode>=500){let i=this.metrics.filter((u)=>u.timestamp>Date.now()-60000),o=i.length,c=i.filter((u)=>u.statusCode>=500).length,a=o>0?c/o:0,l=r?.errorRate||s?.errorRate?.warning;if(l&&a>l)await this.sendAlert({type:"errorRate",message:`Error rate threshold exceeded: ${a.toFixed(2)} > ${l.toFixed(2)}`,value:a,threshold:l,path:e.path,method:e.method,statusCode:e.statusCode,timestamp:e.timestamp,severity:"critical"})}}async sendAlert(e){let t=typeof this.options.alerts?.customHandler==="function";if(!t){let r=`${e.type}:${e.path}`,s=Date.now(),n=this.alertCooldowns.get(r)||0,i=this.options.alerts?.cooldown||60000;if(s-n<i)return;this.alertCooldowns.set(r,s)}if(t)try{await this.options.alerts.customHandler(e)}catch(r){console.error("Error in custom alert handler:",r)}if(this.options.alerts?.handler)try{await this.options.alerts.handler(e)}catch(r){console.error("Error in alert handler:",r)}console.warn(`[PerformanceMonitor] Alert: ${e.message} (${e.severity})`)}async sendAlerts(e,t){let r=`${t.path}-${e.join(",")}`,s=Date.now(),n=300000,i=this.alertCooldowns.get(r);if(i&&s-i<300000)return;this.alertCooldowns.set(r,s);let o={timestamp:new Date(t.timestamp).toISOString(),requestId:t.requestId,path:t.path,method:t.method,alerts:e,metrics:{responseTime:t.responseTime,memoryUsage:Math.round(t.memoryUsage.heapUsed/1024/1024),statusCode:t.statusCode}};if(this.options.alerts?.webhookUrl)try{await fetch(this.options.alerts.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(c){console.error("Failed to send webhook alert:",c)}if(this.options.alerts?.slackConfig?.webhookUrl)try{await fetch(this.options.alerts.slackConfig.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:this.options.alerts.slackConfig.channel,text:`\uD83D\uDEA8 Performance Alert: ${e.join(", ")}`,attachments:[{color:"danger",fields:[{title:"Path",value:t.path,short:!0},{title:"Response Time",value:`${t.responseTime}ms`,short:!0},{title:"Memory Usage",value:`${Math.round(t.memoryUsage.heapUsed/1024/1024)}MB`,short:!0},{title:"Status Code",value:t.statusCode.toString(),short:!0}]}]})})}catch(c){console.error("Failed to send Slack alert:",c)}}async collectMetrics(e){let{req:t,res:r,startTime:s,startMemory:n,startCPU:i,error:o}=e,c=performance.now(),a=Z.memoryUsage(),l=Z.cpuUsage(i),u=new URL(t.url),f=t.requestId||wn.randomUUID(),m={user:l.user,system:l.system},d={requestId:f,timestamp:Date.now(),responseTime:c-s,memoryUsage:{rss:a.rss,heapTotal:a.heapTotal,heapUsed:a.heapUsed,external:a.external,arrayBuffers:a.arrayBuffers},cpuUsage:m,statusCode:r?.status||500,method:t.method,path:u.pathname};if(o)d.error=o.message||String(o);if(t.traceId)d.traceId=t.traceId;if(t.spanId)d.spanId=t.spanId;if(r){let p=r.headers.get("content-length");if(p)d.contentLength=Number.parseInt(p,10)}return console.warn(`[PerformanceMonitor] Collected metrics for ${t.method} ${u.pathname}: responseTime=${d.responseTime}ms, memory=${d.memoryUsage.heapUsed} bytes`),d}async handle(e,t){if(!this.options.enabled)return t();let r=this.options.sampling?.rate??this.options.sampleRate??1,s=Math.random();if(r<=0||s>r)return t();let n=Date.now();if(n-this.lastSecondTimestamp>1000)this.lastSecondTimestamp=n,this.requestsThisSecond=0;if(this.options.maxRequestsPerSecond&&this.requestsThisSecond>=this.options.maxRequestsPerSecond)return t();this.requestsThisSecond++,console.warn(`[PerformanceMonitor] Handling request: ${e.method} ${new URL(e.url).pathname}`);let i=performance.now(),o=Z.memoryUsage(),c=Z.cpuUsage(),a=[],l;if(this.options.profiling?.enabled){let m=e.requestId||wn.randomUUID();if(!e.profiling)e.profiling={requestId:m,samples:[],systemSamples:[]};if(this.takeSample(e.profiling),this.options.profiling.sampleInterval)l=setInterval(()=>{if(e.profiling&&e.profiling.samples.length<(this.options.profiling?.maxSamples||100))this.takeSample(e.profiling)},this.options.profiling.sampleInterval)}let u=null,f;try{u=await t()}catch(m){throw f=m instanceof Error?m:Error(String(m)),f}finally{if(l)clearInterval(l);let m=await this.collectMetrics({req:e,res:u||new Response("Internal Server Error",{status:500}),startTime:i,startMemory:o,startCPU:c,profilingSamples:a,error:f});await this.storeMetrics(m),await this.checkThresholds(m)}if(!u)return new Response("Internal Server Error",{status:500});return u}addMetrics(e){this.metrics.push(e),console.warn(`[PerformanceMonitor] Added metric to internal array: ${e.path} ${e.method} ${e.responseTime}ms`)}async checkThresholdsPublic(e){return this.checkThresholds(e)}getMetrics(e){let t=this.metrics;if(e?.startTime)t=t.filter((r)=>r.timestamp>=e.startTime);if(e?.endTime)t=t.filter((r)=>r.timestamp<=e.endTime);if(e?.path)t=t.filter((r)=>r.path===e.path);if(e?.method)t=t.filter((r)=>r.method===e.method);if(e?.statusCode)t=t.filter((r)=>r.statusCode===e.statusCode);if(e?.limit)t=t.slice(-e.limit);return t}getAggregatedMetrics(e=60000){let r=Date.now()-e,s=this.metrics.filter((l)=>l.timestamp>=r);if(s.length===0)return{totalRequests:0,averageResponseTime:0,medianResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,errorRate:0,averageMemoryUsage:0,requestsPerSecond:0,statusCodeDistribution:{},pathDistribution:{}};let n=s.map((l)=>l.responseTime).sort((l,u)=>l-u),i=s.filter((l)=>l.statusCode>=400).length,o=s.map((l)=>l.memoryUsage.heapUsed),c={},a={};return s.forEach((l)=>{c[l.statusCode]=(c[l.statusCode]||0)+1,a[l.path]=(a[l.path]||0)+1}),{totalRequests:s.length,averageResponseTime:n.reduce((l,u)=>l+u,0)/n.length,medianResponseTime:n[Math.floor(n.length/2)],p95ResponseTime:n[Math.floor(n.length*0.95)],p99ResponseTime:n[Math.floor(n.length*0.99)],errorRate:i/s.length,averageMemoryUsage:o.reduce((l,u)=>l+u,0)/o.length,requestsPerSecond:s.length/(e/1000),statusCodeDistribution:c,pathDistribution:a}}getProfiles(){let e=[],t=Z.memoryUsage(),r=Z.cpuUsage();e.push({timestamp:Date.now(),memoryUsage:t,cpuUsage:r});for(let s of this.requestContexts.values())if(s.samples&&s.samples.length>0)for(let n of s.samples)e.push({timestamp:n.timestamp,memoryUsage:n.memory,cpuUsage:n.cpu});return e}destroy(){if(this.cleanupInterval)clearInterval(this.cleanupInterval);this.requestContexts.clear(),this.alertCooldowns.clear()}}function ha(e={}){let t=new Lt(e);return async(r,s)=>t.handle(r,s)}class Bt{options;spans=new Map;activeSpans=new Map;exportQueue=[];exportInterval;constructor(e={}){let t=v.server?.performance?.monitoring?.tracing||{};if(this.options={enabled:e.enabled??t.enabled??!1,sampleRate:e.sampleRate??t.sampleRate??1,maxSpans:e.maxSpans??1e4,includeHeaders:e.includeHeaders??!1,includeQueryParams:e.includeQueryParams??!0,includeRequestBody:e.includeRequestBody??!1,includeResponseBody:e.includeResponseBody??!1,maxBodySize:e.maxBodySize??1048576,exporters:e.exporters??[{type:"console"}],propagation:{enabled:!0,headers:["x-trace-id","x-span-id","x-parent-span-id"],...e.propagation}},this.options.enabled)this.startExportInterval()}startExportInterval(){this.exportInterval=setInterval(async()=>{try{await this.exportSpans()}catch(e){console.warn("Error exporting spans:",e)}},100),this.exportInterval.unref?.()}shouldSample(){return Math.random()<(this.options.sampleRate||1)}generateId(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}extractPropagationHeaders(e){if(!this.options.propagation?.enabled)return{};let t=this.options.propagation.headers||[],r;for(let n of t){let i=e.headers.get(n);if(i){r=i;break}}let s=e.headers.get("x-parent-span-id")||void 0;return{traceId:r,parentSpanId:s}}async captureRequestBody(e){if(!this.options.includeRequestBody)return;try{let t=e.headers.get("content-type")||"",r=Number.parseInt(e.headers.get("content-length")||"0",10);if(r>(this.options.maxBodySize||1048576))return{truncated:!0,reason:"Body too large",size:r};if(t.includes("application/json"))return await e.clone().json();else if(t.includes("application/x-www-form-urlencoded")){let n=await e.clone().formData(),i={};for(let[o,c]of n.entries())i[o]=c;return i}else if(t.includes("text/"))return await e.clone().text()}catch(t){return{error:"Failed to capture body",message:t instanceof Error?t.message:String(t)}}return}async captureResponseBody(e){if(!this.options.includeResponseBody)return;try{let t=e.headers.get("content-type")||"",r=Number.parseInt(e.headers.get("content-length")||"0",10);if(r>(this.options.maxBodySize||1048576))return{truncated:!0,reason:"Body too large",size:r};if(t.includes("application/json"))return await e.clone().json();else if(t.includes("text/"))return await e.clone().text()}catch(t){return{error:"Failed to capture body",message:t instanceof Error?t.message:String(t)}}return}createSpan(e,t,r,s){return{traceId:e,spanId:t,parentSpanId:s,operationName:r,startTime:performance.now(),tags:{},logs:[],status:"ok"}}addSpanTag(e,t,r){let s=this.spans.get(e);if(s)s.tags[t]=r}addSpanLog(e,t,r,s){let n=this.spans.get(e);if(n)n.logs.push({timestamp:performance.now(),level:t,message:r,fields:s})}finishSpan(e,t="ok",r){let s=this.spans.get(e);if(s){if(s.endTime=performance.now(),s.duration=s.endTime-s.startTime,s.status=t,r){if(s.error=r,this.options.includeHeaders)s.stackTrace=Error("Trace error stack").stack?.split(`
|
|
415
|
+
`)}this.exportQueue.push(s),this.spans.delete(e)}}async exportSpans(){if(this.spans.size>0){let r=performance.now()-60000;for(let[s,n]of this.spans)if(n.endTime===void 0&&n.startTime<r)this.spans.delete(s)}if(this.exportQueue.length===0){let r=Array.from(this.spans.values()).filter((s)=>s.endTime!==void 0);if(r.length>0){this.exportQueue.push(...r);for(let s of r)this.spans.delete(s.spanId)}if(this.exportQueue.length===0)return}let e=[...this.exportQueue];this.exportQueue=[];let t=this.options.exporters||[];if(t.length===0){this.exportToConsole(e);return}for(let r of t)try{switch(r.type){case"console":this.exportToConsole(e);break;case"jaeger":await this.exportToJaeger(e,r);break;case"zipkin":await this.exportToZipkin(e,r);break;case"custom":if(typeof r.customExporter==="function")await r.customExporter(e);break}}catch(s){console.warn(`Failed to export spans to ${r.type}:`,s)}}exportToConsole(e){for(let t of e)console.warn("Trace Span:",{traceId:t.traceId,spanId:t.spanId,operation:t.operationName,duration:`${Math.round((t.duration||0)*100)/100}ms`,status:t.status,tags:t.tags,logs:t.logs.length,error:t.error})}async exportToJaeger(e,t){if(!t.endpoint)return;let r=e.map((s)=>({traceID:s.traceId,spanID:s.spanId,parentSpanID:s.parentSpanId,operationName:s.operationName,startTime:Math.floor(s.startTime*1000),duration:Math.floor((s.duration||0)*1000),tags:Object.entries(s.tags).map(([n,i])=>({key:n,type:typeof i==="string"?"string":"number",value:String(i)})),logs:s.logs.map((n)=>({timestamp:Math.floor(n.timestamp*1000),fields:[{key:"level",value:n.level},{key:"message",value:n.message},...n.fields?Object.entries(n.fields).map(([i,o])=>({key:i,value:String(o)})):[]]})),process:{serviceName:"bun-router",tags:[{key:"hostname",value:Bun.env.HOSTNAME||"localhost"},{key:"pid",value:String(123)}]}}));await fetch(`${t.endpoint}/api/traces`,{method:"POST",headers:{"Content-Type":"application/json",...t.headers},body:JSON.stringify({data:[{spans:r}]})})}async exportToZipkin(e,t){if(!t.endpoint)return;let r=e.map((s)=>({traceId:s.traceId,id:s.spanId,parentId:s.parentSpanId,name:s.operationName,timestamp:Math.floor(s.startTime*1000),duration:Math.floor((s.duration||0)*1000),kind:"SERVER",localEndpoint:{serviceName:"bun-router"},tags:s.tags,annotations:s.logs.map((n)=>({timestamp:Math.floor(n.timestamp*1000),value:`${n.level}: ${n.message}`}))}));await fetch(`${t.endpoint}/api/v2/spans`,{method:"POST",headers:{"Content-Type":"application/json",...t.headers},body:JSON.stringify(r)})}async handle(e,t){if(!this.options.enabled||!this.shouldSample())return await t()||new Response("Internal Server Error",{status:500});let r=e.requestId||this.generateId(),s=this.extractPropagationHeaders(e),n=s.traceId||this.generateId(),i=this.generateId(),o=new URL(e.url);console.warn(`[RequestTracer] Creating span for ${e.method} ${o.pathname}, traceId=${n}, spanId=${i}`);let c=this.createSpan(n,i,`${e.method} ${o.pathname}`,s.parentSpanId);if(this.spans.set(i,c),this.activeSpans.set(r,i),e.traceId=n,e.spanId=i,Object.defineProperties(e,{traceId:{value:n,writable:!0,enumerable:!0,configurable:!0},spanId:{value:i,writable:!0,enumerable:!0,configurable:!0}}),this.addSpanTag(i,"http.method",e.method),this.addSpanTag(i,"http.url",e.url),this.addSpanTag(i,"http.path",o.pathname),this.addSpanTag(i,"user_agent",e.headers.get("user-agent")),this.options.includeHeaders){let u={};for(let[f,m]of e.headers.entries())u[f]=m;this.addSpanTag(i,"http.headers",u)}if(this.options.includeQueryParams&&o.searchParams.size>0){let u={};for(let[f,m]of o.searchParams.entries())u[f]=m;this.addSpanTag(i,"http.query_params",u)}if(this.options.includeRequestBody&&e.method!=="GET"&&e.method!=="HEAD")try{let u=await this.captureRequestBody(e);if(u!==void 0)this.addSpanTag(i,"http.request_body",u)}catch(u){this.addSpanLog(i,"warn","Failed to capture request body",{error:String(u)})}this.addSpanLog(i,"info","Request started");let a,l;try{if(a=await t()||new Response("Internal Server Error",{status:500}),this.addSpanTag(i,"http.status_code",a.status),this.addSpanTag(i,"http.status_text",a.statusText),this.options.includeResponseBody)try{let m=await this.captureResponseBody(a);if(m!==void 0)this.addSpanTag(i,"http.response_body",m)}catch(m){this.addSpanLog(i,"warn","Failed to capture response body",{error:String(m)})}this.addSpanLog(i,"info","Request completed",{status:a.status,statusText:a.statusText});let f=a.status>=400;if(f)this.addSpanTag(i,"error",!0),this.addSpanTag(i,"error.status_code",a.status);this.finishSpan(i,f?"error":"ok",f?`HTTP ${a.status}`:void 0)}catch(u){l=u instanceof Error?u.message:String(u),this.addSpanTag(i,"error",!0),this.addSpanTag(i,"error.message",l),this.addSpanTag(i,"error.type",u instanceof Error?u.constructor.name:"Unknown"),this.addSpanLog(i,"error","Request failed",{error:l}),this.finishSpan(i,"error",l);let f=this.spans.get(i);if(f){if(f.endTime===void 0)f.endTime=performance.now(),f.duration=f.endTime-f.startTime,f.status="error",f.error=l;this.exportQueue.push(f),this.spans.delete(i),this.exportSpans().catch((m)=>{console.warn("Failed to export error span:",m)})}a=new Response("Internal Server Error",{status:500})}if(this.activeSpans.delete(r),this.options.propagation?.enabled)a.headers.set("x-trace-id",n),a.headers.set("x-span-id",i);return a}getActiveSpans(){return Array.from(this.spans.values())}getSpanById(e){return this.spans.get(e)}createChildSpan(e,t){let r=this.spans.get(e);if(!r)return null;let s=this.generateId(),n=this.createSpan(r.traceId,s,t,e);return this.spans.set(s,n),s}addTag(e,t,r){this.addSpanTag(e,t,r)}addLog(e,t,r,s){this.addSpanLog(e,t,r,s)}finish(e,t="ok",r){this.finishSpan(e,t,r)}async flush(){let e=Array.from(this.spans.keys());console.warn(`[RequestTracer] Flushing ${e.length} active spans`);for(let t of e){let r=this.spans.get(t);if(r&&!r.endTime)this.finishSpan(t,"ok")}await this.exportSpans()}destroy(){if(this.exportInterval)clearInterval(this.exportInterval);this.spans.clear(),this.activeSpans.clear(),this.exportQueue=[]}}function pa(e={}){let t=new Bt(e);return async(r,s)=>t.handle(r,s)}class Me{options;suspiciousPatterns=[];sqlInjectionPatterns=[];xssPatterns=[];pathTraversalPatterns=[];commandInjectionPatterns=[];constructor(e={}){let t=v.server?.security||{};this.options={inputValidation:{enabled:!0,maxBodySize:10485760,maxUrlLength:2048,maxHeaderSize:8192,allowedContentTypes:["application/json","application/x-www-form-urlencoded","multipart/form-data","text/plain","text/html","application/xml","text/xml"],sanitizeInput:!0,validateEncoding:!0,...e.inputValidation},requestFiltering:{enabled:!0,blockSuspiciousPatterns:!0,maxRequestsPerMinute:1000,blockUserAgents:["sqlmap","nikto","nessus","openvas","nmap","masscan","zap","w3af"],allowedMethods:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],requireUserAgent:!1,...e.requestFiltering},ipFiltering:{enabled:!1,whitelist:[],blacklist:[],blockPrivateIPs:!1,blockCloudProviders:!1,geoBlocking:{enabled:!1,allowedCountries:[],blockedCountries:[]},...e.ipFiltering},attackPrevention:{enabled:!0,sqlInjection:!0,xss:!0,pathTraversal:!0,commandInjection:!0,ldapInjection:!0,xxe:!0,customPatterns:[],...e.attackPrevention},responseSecurity:{enabled:!0,removeServerHeaders:!0,addSecurityHeaders:!0,sanitizeErrors:!0,preventInfoDisclosure:!0,...e.responseSecurity}},this.initializePatterns()}initializePatterns(){this.suspiciousPatterns=[/\.\.\//g,/\.\.\\/g,/%2e%2e%2f/gi,/%2e%2e%5c/gi,/\/etc\/passwd/gi,/\/proc\/self\/environ/gi,/cmd\.exe/gi,/powershell/gi,/<script/gi,/javascript:/gi,/vbscript:/gi,/onload=/gi,/onerror=/gi],this.sqlInjectionPatterns=[/(\bunion\b.+\bselect\b)|(\bselect\b.+\bunion\b)/gi,/\b(select|insert|update|delete|drop|create|alter|exec|execute)\b.+\b(from|into|set|where|table|database|schema)\b/gi,/(\bor\b|\band\b).+['"]\s*=\s*['"]|['"]\s*=\s*['"].+(\bor\b|\band\b)/gi,/\b(sleep|benchmark|waitfor)\s*\(/gi,/\b(information_schema|sys\.databases|sysobjects)\b/gi,/('|(\\')).+(or|and)\s+(?:\S.*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])[=><]/gi,/\b(concat|group_concat|load_file|into\s+outfile)\b/gi],this.xssPatterns=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/<object[^>]*>.*?<\/object>/gi,/<embed[^>]*>/gi,/<link[^>]*>/gi,/<meta[^>]*>/gi,/javascript:/gi,/vbscript:/gi,/on\w+\s*=/gi,/<[^>]*\son\w+\s*=.*?>/gi,/expression\s*\(/gi,/url\s*\(\s*javascript:/gi],this.pathTraversalPatterns=[/\.\.\//g,/\.\.\\/g,/%2e%2e%2f/gi,/%2e%2e%5c/gi,/\.\.%2f/gi,/\.\.%5c/gi,/%252e%252e%252f/gi,/\.\/%2e%2e%2f/gi],this.commandInjectionPatterns=[/[;&|`${}[\]]/g,/\b(cat|ls|pwd|id|whoami|uname|ps|netstat|ifconfig|ping|nslookup|dig|curl|wget)\s/gi,/\b(cmd|powershell|bash|sh|zsh|fish)\s/gi,/\b(exec|system|shell_exec|passthru|eval)\s*\(/gi,/\$\{.*\}/g,/#\{.*\}/g]}getClientIP(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||e.headers.get("cf-connecting-ip")||e.headers.get("x-client-ip")||"unknown"}isPrivateIP(e){return[/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^127\./,/^169\.254\./,/^::1$/,/^fc00:/,/^fe80:/].some((r)=>r.test(e))}validateInput(e){let t=[];if(!this.options.attackPrevention?.enabled)return{isValid:!0,threats:t};if(this.options.attackPrevention.sqlInjection){for(let r of this.sqlInjectionPatterns)if(r.test(e)){t.push("SQL Injection");break}}if(this.options.attackPrevention.xss){for(let r of this.xssPatterns)if(r.test(e)){t.push("XSS");break}}if(this.options.attackPrevention.pathTraversal){for(let r of this.pathTraversalPatterns)if(r.test(e)){t.push("Path Traversal");break}}if(this.options.attackPrevention.commandInjection){for(let r of this.commandInjectionPatterns)if(r.test(e)){t.push("Command Injection");break}}if(this.options.attackPrevention.customPatterns){for(let r of this.options.attackPrevention.customPatterns)if(r.pattern.test(e))t.push(r.name)}return{isValid:t.length===0,threats:t}}sanitizeInput(e){if(!this.options.inputValidation?.sanitizeInput)return e;return e.replace(/[<>'"&]/g,(t)=>({"<":"<",">":">",'"':""","'":"'","&":"&"})[t]||t).replace(/javascript:/gi,"blocked:").replace(/vbscript:/gi,"blocked:").replace(/on\w+=/gi,"blocked=")}async handle(e,t){let r=this.getClientIP(e),s=e.headers.get("user-agent")||"",n=new URL(e.url);if(this.options.ipFiltering?.enabled){let o=this.options.ipFiltering;if(o.whitelist?.length&&!o.whitelist.includes(r))return new Response("Access Denied",{status:403});if(o.blacklist?.includes(r))return new Response("Access Denied",{status:403});if(o.blockPrivateIPs&&this.isPrivateIP(r))return new Response("Access Denied",{status:403})}if(this.options.requestFiltering?.enabled){let o=this.options.requestFiltering;if(o.allowedMethods&&!o.allowedMethods.includes(e.method))return new Response("Method Not Allowed",{status:405});if(o.requireUserAgent&&!s)return new Response("Bad Request",{status:400});if(o.blockUserAgents){if(o.blockUserAgents.some((a)=>s.toLowerCase().includes(a.toLowerCase())))return new Response("Access Denied",{status:403})}if(o.blockSuspiciousPatterns){let c=n.pathname+n.search;for(let a of this.suspiciousPatterns)if(a.test(c))return new Response("Suspicious Request Blocked",{status:400})}}if(this.options.inputValidation?.enabled){let o=this.options.inputValidation;if(o.maxUrlLength&&e.url.length>o.maxUrlLength)return new Response("URL Too Long",{status:414});let c=e.headers.get("content-type");if(c&&o.allowedContentTypes){if(!o.allowedContentTypes.some((l)=>c.toLowerCase().startsWith(l.toLowerCase())))return new Response("Unsupported Media Type",{status:415})}for(let[a,l]of n.searchParams.entries()){let u=this.validateInput(l);if(!u.isValid)return console.warn(`Security threat detected in query param ${a}:`,u.threats),new Response(`Security threat detected: ${u.threats.join(", ")}`,{status:400})}for(let[a,l]of e.headers.entries()){if(o.maxHeaderSize&&l.length>o.maxHeaderSize)return new Response("Header Too Large",{status:431});let u=this.validateInput(l);if(!u.isValid)return console.warn(`Security threat detected in header ${a}:`,u.threats),new Response(`Security threat detected: ${u.threats.join(", ")}`,{status:400})}}if(e.method!=="GET"&&e.method!=="HEAD"&&e.method!=="OPTIONS")try{let o=e.headers.get("content-length");if(o&&this.options.inputValidation?.maxBodySize){if(Number.parseInt(o,10)>this.options.inputValidation.maxBodySize)return new Response("Payload Too Large",{status:413})}}catch(o){console.error("Error checking content length:",o)}let i=await t();if(!i)return new Response("Not Found",{status:404});if(this.options.responseSecurity?.enabled){let o=new Headers(i.headers),c=this.options.responseSecurity;if(c.removeServerHeaders)o.delete("Server"),o.delete("X-Powered-By"),o.delete("X-AspNet-Version"),o.delete("X-AspNetMvc-Version");if(c.addSecurityHeaders)o.set("X-Content-Type-Options","nosniff"),o.set("X-Frame-Options","DENY"),o.set("X-XSS-Protection","0"),o.set("Referrer-Policy","strict-origin-when-cross-origin");return new Response(i.body,{status:i.status,statusText:i.statusText,headers:o})}return i}}function ga(e={}){let t=new Me(e);return async(r,s)=>t.handle(r,s)}class Ut{middlewares=[];constructor(e={}){let t=v.server?.security||{},r=["ddosProtection","security","helmet","contentSecurityPolicy","inputValidation"],s=e.order||r;for(let n of s)switch(n){case"ddosProtection":if(e.ddosProtection!==!1&&t.ddos?.enabled!==!1){let i=typeof e.ddosProtection==="object"?e.ddosProtection:{},o=new Pe(i);this.middlewares.push((c,a)=>o.handle(c,a))}break;case"security":if(e.security!==!1){let i=typeof e.security==="object"?e.security:{},o=new Me(i);this.middlewares.push((c,a)=>o.handle(c,a))}break;case"helmet":if(e.helmet!==!1&&t.helmet?.enabled!==!1){let i=typeof e.helmet==="object"?e.helmet:{},o=new He(i);this.middlewares.push((c,a)=>o.handle(c,a))}break;case"contentSecurityPolicy":if(e.contentSecurityPolicy!==!1&&t.helmet?.contentSecurityPolicy!==!1){let i=typeof e.contentSecurityPolicy==="object"?e.contentSecurityPolicy:{},o=new ke(i);this.middlewares.push((c,a)=>o.handle(c,a))}break;case"inputValidation":if(e.inputValidation!==!1&&t.inputValidation?.enabled!==!1){let i=typeof e.inputValidation==="object"?e.inputValidation:{},o=new Ae(i);this.middlewares.push((c,a)=>o.handle(c,a))}break}}async handle(e,t){let r=0,s=async()=>{if(r>=this.middlewares.length)return await t();let n=this.middlewares[r++];return await n(e,s)};return await s()}}function ya(e={}){let t=new Ut(e);return async(r,s)=>t.handle(r,s)}var ku=()=>new Re,Pu=()=>new Ce,Au=()=>new Ee,Fu=()=>new $e,Mu=()=>new B;function Nu(){return new G({type:"bearer",validator:()=>!0})}var Dr=null;function jr(){if(!Dr)Dr={"Middleware/Cors":new Re,"Middleware/JsonBody":new Ce,"Middleware/RequestId":new Ee,"Middleware/Session":new $e,"Middleware/Csrf":new B,"Middleware/Auth":new G({type:"bearer",validator:()=>!0}),"Middleware/RateLimit":Nr(),"Middleware/RequestSigning":new Te({secret:""})};return Dr}var Iu=new Proxy({},{get(e,t){return jr()[t]},ownKeys(){return Object.keys(jr())},getOwnPropertyDescriptor(e,t){let r=jr()[t];if(r!==void 0)return{configurable:!0,enumerable:!0,value:r};return}});
|
|
416
|
+
export{dn as a,ol as b,v as c,mn as d,Fr as e,hn as f,Mo as g,No as h,Io as i,Oo as j,Do as k,Re as l,B as m,Ce as n,kt as o,Nr as p,Ee as q,V as r,pn as s,Te as t,Ko as u,zo as v,Wo as w,ue as x,Mt as y,Nt as z,It as A,Ml as B,Or as C,Ot as D,$e as E,ke as F,Xo as G,Pe as H,Yo as I,Ve as J,ae as K,na as L,ia as M,oa as N,aa as O,ca as P,He as Q,Ae as R,fa as S,Dt as T,da as U,jt as V,ma as W,Lt as X,ha as Y,Bt as Z,pa as _,Me as $,ga as aa,Ut as ba,ya as ca,ku as da,Pu as ea,Au as fa,Fu as ga,Mu as ha,Nu as ia,Iu as ja};
|