@stacksjs/bun-router 0.1.0 → 0.1.2

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.
Files changed (150) hide show
  1. package/dist/chunk-03m2j6h7.js +2 -0
  2. package/dist/chunk-08cw7ejr.js +3 -0
  3. package/dist/chunk-0e4g0fyv.js +62 -0
  4. package/dist/chunk-0mmn02yw.js +2 -0
  5. package/dist/chunk-126c9qm3.js +2 -0
  6. package/dist/chunk-12p13817.js +2 -0
  7. package/dist/chunk-14v65c37.js +4 -0
  8. package/dist/{chunk-s3dn1kwx.js → chunk-1b6a7t3v.js} +2 -2
  9. package/dist/chunk-1wenkmk0.js +2 -0
  10. package/dist/chunk-2152npfd.js +2 -0
  11. package/dist/chunk-26w23krx.js +2 -0
  12. package/dist/chunk-2g8m379z.js +10 -0
  13. package/dist/{chunk-5mxby3fd.js → chunk-2rr178et.js} +2 -2
  14. package/dist/chunk-2w8f3swz.js +29 -0
  15. package/dist/chunk-3y4gaz7v.js +82 -0
  16. package/dist/chunk-4r1x4afz.js +12 -0
  17. package/dist/chunk-4wyw66zk.js +2 -0
  18. package/dist/chunk-4z5sf8ag.js +2 -0
  19. package/dist/{chunk-krkchy8v.js → chunk-58tfvayh.js} +3 -3
  20. package/dist/{chunk-ex5fkjah.js → chunk-5dp83qcx.js} +43 -43
  21. package/dist/chunk-5f0d9j9a.js +2 -0
  22. package/dist/{chunk-zhx0hxdd.js → chunk-5z52b0fc.js} +7 -7
  23. package/dist/{chunk-kc659vhx.js → chunk-5zrnk2kq.js} +3 -3
  24. package/dist/chunk-6dmqtdnq.js +2 -0
  25. package/dist/{chunk-5s1pr62n.js → chunk-6e91956t.js} +2 -2
  26. package/dist/{chunk-jrf5a2ap.js → chunk-6rv8w5jk.js} +1 -1
  27. package/dist/{chunk-5n0ckcmc.js → chunk-6x1feysm.js} +2 -2
  28. package/dist/chunk-7y72hm1x.js +2 -0
  29. package/dist/{chunk-zetqzgf3.js → chunk-8hbhfh6b.js} +6 -6
  30. package/dist/{chunk-5ncn73tp.js → chunk-8kfzygg5.js} +2 -2
  31. package/dist/chunk-8wydx2we.js +2 -0
  32. package/dist/chunk-8zjnjvv7.js +2 -0
  33. package/dist/chunk-988h4bzr.js +2 -0
  34. package/dist/chunk-9b6a58ac.js +2 -0
  35. package/dist/chunk-a8fcaywb.js +2 -0
  36. package/dist/chunk-bfjwn7yg.js +2 -0
  37. package/dist/chunk-bp2522mm.js +2 -0
  38. package/dist/chunk-bswe62q4.js +48 -0
  39. package/dist/chunk-c3v796c8.js +943 -0
  40. package/dist/chunk-ccqmwdry.js +2 -0
  41. package/dist/chunk-ck0crwnx.js +2 -0
  42. package/dist/chunk-cqgkxcb4.js +2 -0
  43. package/dist/chunk-dntnakjy.js +2 -0
  44. package/dist/{chunk-67wgad4f.js → chunk-ettdpnrw.js} +2 -2
  45. package/dist/{chunk-csfrpsp7.js → chunk-ezqwq17j.js} +10 -10
  46. package/dist/chunk-ezx3qsez.js +2 -0
  47. package/dist/{chunk-73k79n7q.js → chunk-f72nnjy4.js} +360 -360
  48. package/dist/chunk-fna5n0ey.js +246 -0
  49. package/dist/chunk-fqhckdt8.js +2 -0
  50. package/dist/chunk-fr6hbx25.js +2 -0
  51. package/dist/{chunk-vr10sbbh.js → chunk-g9cwng6w.js} +1 -1
  52. package/dist/chunk-gd3za5x0.js +2 -0
  53. package/dist/chunk-gf28608k.js +2 -0
  54. package/dist/chunk-h1dj6v8q.js +3 -0
  55. package/dist/chunk-hjxe7k2g.js +2 -0
  56. package/dist/chunk-hrkgznbn.js +2 -0
  57. package/dist/chunk-j6h5v0br.js +2 -0
  58. package/dist/{chunk-0gjq8ttx.js → chunk-mgb01qdv.js} +2 -2
  59. package/dist/chunk-n24c9whp.js +2 -0
  60. package/dist/{chunk-kxp888dn.js → chunk-n2j24b0h.js} +244 -244
  61. package/dist/{chunk-vv3gb1m5.js → chunk-nhmtg01n.js} +2 -2
  62. package/dist/chunk-p0qhpnqh.js +70 -0
  63. package/dist/chunk-p0w1x8y2.js +3 -0
  64. package/dist/{chunk-9ght4n4r.js → chunk-p3dk1w2w.js} +11 -11
  65. package/dist/{chunk-6sjvhy5f.js → chunk-q4e9pxs7.js} +2 -2
  66. package/dist/chunk-q5dv1kyy.js +2 -0
  67. package/dist/chunk-qnqgf9tq.js +2 -0
  68. package/dist/chunk-qvwy1808.js +898 -0
  69. package/dist/{chunk-5s0pnsd6.js → chunk-r18f77vc.js} +4 -4
  70. package/dist/chunk-r63za1mr.js +2 -0
  71. package/dist/{chunk-6s1kbajm.js → chunk-rft8gw92.js} +1 -1
  72. package/dist/chunk-ryvmyskt.js +4211 -0
  73. package/dist/chunk-sa6mx308.js +2 -0
  74. package/dist/chunk-va0pc7hx.js +2 -0
  75. package/dist/chunk-vcp8dnjq.js +412 -0
  76. package/dist/chunk-vg1erq1q.js +2 -0
  77. package/dist/{chunk-hmgedrmr.js → chunk-w0jv49ch.js} +3 -3
  78. package/dist/{chunk-0t5vz87j.js → chunk-wm805tte.js} +19 -19
  79. package/dist/chunk-xj9h6mc9.js +2 -0
  80. package/dist/chunk-ytvzwrq3.js +51 -0
  81. package/dist/{chunk-w4r464v5.js → chunk-zde7ebc4.js} +2 -2
  82. package/dist/chunk-zmqsv2xy.js +2 -0
  83. package/dist/cli.js +57 -66
  84. package/dist/container/index.js +1 -1
  85. package/dist/index.d.ts +1 -0
  86. package/dist/index.js +29 -29
  87. package/dist/typed/client.d.ts +89 -0
  88. package/dist/typed/contract.d.ts +34 -0
  89. package/dist/typed/endpoint.d.ts +90 -0
  90. package/dist/typed/index.d.ts +14 -0
  91. package/dist/typed/router.d.ts +141 -0
  92. package/package.json +1 -1
  93. package/dist/chunk-30rkn2ym.js +0 -2
  94. package/dist/chunk-38cmrard.js +0 -2
  95. package/dist/chunk-3qna6dwd.js +0 -2
  96. package/dist/chunk-4d5fmta0.js +0 -2
  97. package/dist/chunk-4x3b4b4q.js +0 -2
  98. package/dist/chunk-6xed4va1.js +0 -2
  99. package/dist/chunk-748n6ydj.js +0 -2
  100. package/dist/chunk-7rsf8tes.js +0 -898
  101. package/dist/chunk-8aspmtf1.js +0 -2
  102. package/dist/chunk-8yfdg595.js +0 -2
  103. package/dist/chunk-90eze7av.js +0 -3
  104. package/dist/chunk-9dvwyej7.js +0 -2
  105. package/dist/chunk-a2w45krb.js +0 -2
  106. package/dist/chunk-a547f2ab.js +0 -48
  107. package/dist/chunk-bqdycvtc.js +0 -2
  108. package/dist/chunk-cd03rk3x.js +0 -2
  109. package/dist/chunk-ct0m17q5.js +0 -2
  110. package/dist/chunk-dhbvvr5h.js +0 -2
  111. package/dist/chunk-dhptcsya.js +0 -943
  112. package/dist/chunk-dq93zag9.js +0 -2
  113. package/dist/chunk-edrtesh7.js +0 -2
  114. package/dist/chunk-ejcws37w.js +0 -2
  115. package/dist/chunk-ex890p45.js +0 -51
  116. package/dist/chunk-f69cpnhw.js +0 -2
  117. package/dist/chunk-fjf53b44.js +0 -2
  118. package/dist/chunk-fjzye4qj.js +0 -2
  119. package/dist/chunk-gfd23b6t.js +0 -2
  120. package/dist/chunk-habv0vef.js +0 -12
  121. package/dist/chunk-hz6fc788.js +0 -2
  122. package/dist/chunk-jff6j9y3.js +0 -10
  123. package/dist/chunk-jmeb7n8k.js +0 -70
  124. package/dist/chunk-jy2jhcpy.js +0 -246
  125. package/dist/chunk-m249t3je.js +0 -3
  126. package/dist/chunk-m9yabnjx.js +0 -2
  127. package/dist/chunk-mekrq9wd.js +0 -2
  128. package/dist/chunk-mmxv535f.js +0 -82
  129. package/dist/chunk-mypn7jss.js +0 -2
  130. package/dist/chunk-n18x1k3c.js +0 -2
  131. package/dist/chunk-nkddjzsa.js +0 -2
  132. package/dist/chunk-pjmhqmr9.js +0 -2
  133. package/dist/chunk-qyrnsaq1.js +0 -2
  134. package/dist/chunk-r19ff2qm.js +0 -62
  135. package/dist/chunk-r338fssq.js +0 -2
  136. package/dist/chunk-s36z58x2.js +0 -29
  137. package/dist/chunk-s79dd325.js +0 -471
  138. package/dist/chunk-ta38j9em.js +0 -2
  139. package/dist/chunk-tpfgntwj.js +0 -4211
  140. package/dist/chunk-vw8rwv6e.js +0 -2
  141. package/dist/chunk-wcrqs5z9.js +0 -2
  142. package/dist/chunk-x6d1rmwa.js +0 -2
  143. package/dist/chunk-x7ft15zz.js +0 -2
  144. package/dist/chunk-x8trwn7j.js +0 -3
  145. package/dist/chunk-xhepdj1f.js +0 -2
  146. package/dist/chunk-xv2em0q4.js +0 -4
  147. package/dist/chunk-ypw6g0te.js +0 -2
  148. package/dist/chunk-z8szsm21.js +0 -2
  149. package/dist/chunk-zfbh14qe.js +0 -2
  150. /package/dist/{chunk-a3wahyg7.js → chunk-nf3kv7kv.js} +0 -0
@@ -1,471 +0,0 @@
1
- // @bun
2
- import{Zu as m}from"./chunk-a3wahyg7.js";import LJ from"process";import{existsSync as n8,statSync as i8}from"fs";import{existsSync as W0,mkdirSync as _G,readdirSync as AG,readFileSync as U0,writeFileSync as BG}from"fs";import{homedir as EQ}from"os";import{dirname as jG,resolve as a}from"path";import aY from"process";import{existsSync as s8,statSync as o8}from"fs";import{existsSync as iZ,mkdirSync as z0,readdirSync as H0,writeFileSync as _0}from"fs";import{homedir as OQ}from"os";import{dirname as a8,resolve as p}from"path";import VQ from"process";import{join as A0,relative as B0,resolve as t8}from"path";import hY from"process";import{existsSync as b9,mkdirSync as qG,readdirSync as TG,writeFileSync as NG}from"fs";import{homedir as TZ}from"os";import{dirname as xG,resolve as g}from"path";import ZY from"process";import{join as R0,relative as L0,resolve as r8}from"path";import dY from"process";import{existsSync as y9,mkdirSync as vG,readdirSync as hG,writeFileSync as dG}from"fs";import{dirname as mG,resolve as fY}from"path";import sZ from"process";import{Buffer as KQ}from"buffer";import{createCipheriv as j0,createDecipheriv as K0,randomBytes as NZ}from"crypto";import{closeSync as SZ,createReadStream as e8,createWriteStream as F0,existsSync as CZ,fsyncSync as Q9,openSync as Y9,writeFileSync as M0}from"fs";import{access as I0,constants as Z9,mkdir as V0,readdir as KY,rename as $9,stat as qQ,unlink as FY,writeFile as xZ}from"fs/promises";import{join as TQ}from"path";import h from"process";import{pipeline as D0}from"stream/promises";import{createGzip as X9}from"zlib";import NQ from"process";import zQ from"process";import{Buffer as WQ}from"buffer";import{createCipheriv as w0,createDecipheriv as E0,randomBytes as kZ}from"crypto";import{closeSync as PZ,createReadStream as J9,createWriteStream as O0,existsSync as MY,fsyncSync as G9,openSync as W9,writeFileSync as q0}from"fs";import{access as T0,constants as U9,mkdir as N0,readdir as IY,rename as z9,stat as SQ,unlink as VY,writeFile as bZ}from"fs/promises";import{isAbsolute as S0,join as CQ,resolve as C0}from"path";import F from"process";import{pipeline as x0}from"stream/promises";import{createGzip as H9}from"zlib";import xQ from"process";import HQ from"process";import DY from"process";import{existsSync as wY}from"fs";import{resolve as yZ}from"path";import{existsSync as k0}from"fs";import{existsSync as P0,readdirSync as b0}from"fs";import{extname as vZ,resolve as _9}from"path";import y0 from"process";import{join as v0,relative as h0,resolve as A9}from"path";import mY from"process";import{Buffer as UQ}from"buffer";import{createCipheriv as d0,createDecipheriv as f0,randomBytes as hZ}from"crypto";import{closeSync as dZ,createReadStream as B9,createWriteStream as m0,existsSync as EY,fsyncSync as R9,openSync as L9,writeFileSync as g0}from"fs";import{access as p0,constants as j9,mkdir as u0,readdir as OY,rename as K9,stat as kQ,unlink as qY,writeFile as fZ}from"fs/promises";import{isAbsolute as c0,join as PQ,resolve as l0}from"path";import M from"process";import{pipeline as n0}from"stream/promises";import{createGzip as F9}from"zlib";import bQ from"process";import _Q from"process";import NY from"process";import{existsSync as SY}from"fs";import{resolve as lZ}from"path";import{existsSync as AJ}from"fs";class k9{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,Y){let Z=Y?`:${Y}`:"";return`${this.options.keyPrefix}${Q}${Z}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Z],[,$])=>Z.timestamp.getTime()-$.timestamp.getTime()),Y=Q.length-this.options.maxSize+1;for(let Z=0;Z<Y;Z++)this.cache.delete(Q[Z][0])}set(Q,Y,Z,$){if(!this.options.enabled)return;let X=this.generateKey(Q,Z),J=$??this.options.ttl,G=this.estimateSize(Y);this.cache.set(X,{value:Y,timestamp:new Date,ttl:J,hits:0,size:G}),this.evictIfNeeded()}get(Q,Y){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(Q,Y),$=this.cache.get(Z);if(!$){this.totalMisses++;return}if(this.isExpired($)){this.cache.delete(Z),this.totalMisses++;return}return $.hits++,this.totalHits++,$.value}isFileModified(Q,Y){try{if(!n8(Q))return!0;return i8(Q).mtime>Y}catch{return!0}}getWithFileCheck(Q,Y){let Z=this.get(Q,Y);if(!Z)return;if(this.isFileModified(Y,Z.fileTimestamp)){this.delete(Q,Y);return}return Z.value}setWithFileCheck(Q,Y,Z,$){try{let X=n8(Z)?i8(Z):null,J=X?X.mtime:new Date;this.set(Q,{value:Y,fileTimestamp:J},Z,$)}catch{this.set(Q,Y,Z,$)}}delete(Q,Y){let Z=this.generateKey(Q,Y);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[Y,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete(Y),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),Y=Q.reduce(($,X)=>$+X.size,0),Z=Q.map(($)=>$.timestamp).sort();return{size:Y,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:Z[0],newestEntry:Z[Z.length-1]}}export(){let Q={};for(let[Y,Z]of this.cache.entries())Q[Y]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return Q}import(Q){this.cache.clear();for(let[Y,Z]of Object.entries(Q))if(typeof Z==="object"&&Z!==null){let $=Z;this.cache.set(Y,{value:$.value,timestamp:new Date($.timestamp),ttl:$.ttl,hits:$.hits,size:$.size})}}}class P9{metrics=[];maxMetrics=1000;async track(Q,Y,Z={}){let $=performance.now(),X=new Date;try{let J=await Y(),G=performance.now()-$;return this.recordMetric({operation:Q,duration:G,timestamp:X,...Z}),J}catch(J){let G=performance.now()-$;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:X,...Z}),J}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let Y=Q?this.metrics.filter((X)=>X.operation===Q):this.metrics;if(Y.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=Y.map((X)=>X.duration),$=Z.reduce((X,J)=>X+J,0);return{count:Y.length,averageDuration:$/Y.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:$,recentMetrics:Y.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((Y)=>Y.duration>Q)}}var vY=new k9,J8=new P9;var i0=Object.defineProperty,s0=(Q)=>Q;function o0(Q,Y){this[Q]=s0.bind(null,Y)}var a0=(Q,Y)=>{for(var Z in Y)i0(Q,Z,{get:Y[Z],enumerable:!0,configurable:!0,set:o0.bind(Y,Z)})},t0=(Q,Y)=>()=>(Q&&(Y=Q(Q=0)),Y),v9={};a0(v9,{withErrorRecovery:()=>f9,tryLoadConfig:()=>IX,loadConfigWithResult:()=>FX,loadConfig:()=>c9,isRetryableError:()=>AX,isConfigNotFoundError:()=>_X,isBunfigError:()=>m9,globalPerformanceMonitor:()=>JY,globalCache:()=>yQ,getEnvOrDefault:()=>BX,generateConfigTypes:()=>VX,defaultGeneratedDir:()=>r9,defaultConfigDir:()=>t9,deepMergeWithArrayStrategy:()=>H8,deepMerge:()=>g9,createLibraryConfig:()=>DX,config:()=>MX,bunfigPlugin:()=>wX,applyEnvVarsToConfig:()=>YY,TypeGenerationError:()=>Y8,SchemaValidationError:()=>XY,PluginError:()=>$8,PerformanceMonitor:()=>W8,FileSystemError:()=>Q8,ErrorFactory:()=>FQ,EnvVarError:()=>nY,EnvProcessor:()=>tY,ConfigValidator:()=>_8,ConfigValidationError:()=>rZ,ConfigNotFoundError:()=>lY,ConfigMergeError:()=>eZ,ConfigLoader:()=>A8,ConfigLoadError:()=>$Y,ConfigFileLoader:()=>rY,ConfigCache:()=>G8,CacheUtils:()=>n9,BunfigError:()=>n,BrowserConfigError:()=>Z8,ArrayMergeStrategies:()=>o9});class G8{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,Y){let Z=Y?`:${Y}`:"";return`${this.options.keyPrefix}${Q}${Z}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Z],[,$])=>Z.timestamp.getTime()-$.timestamp.getTime()),Y=Q.length-this.options.maxSize+1;for(let Z=0;Z<Y;Z++)this.cache.delete(Q[Z][0])}set(Q,Y,Z,$){if(!this.options.enabled)return;let X=this.generateKey(Q,Z),J=$??this.options.ttl,G=this.estimateSize(Y);this.cache.set(X,{value:Y,timestamp:new Date,ttl:J,hits:0,size:G}),this.evictIfNeeded()}get(Q,Y){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(Q,Y),$=this.cache.get(Z);if(!$){this.totalMisses++;return}if(this.isExpired($)){this.cache.delete(Z),this.totalMisses++;return}return $.hits++,this.totalHits++,$.value}isFileModified(Q,Y){try{if(!s8(Q))return!0;return o8(Q).mtime>Y}catch{return!0}}getWithFileCheck(Q,Y){let Z=this.get(Q,Y);if(!Z)return;if(this.isFileModified(Y,Z.fileTimestamp)){this.delete(Q,Y);return}return Z.value}setWithFileCheck(Q,Y,Z,$){try{let X=s8(Z)?o8(Z):null,J=X?X.mtime:new Date;this.set(Q,{value:Y,fileTimestamp:J},Z,$)}catch{this.set(Q,Y,Z,$)}}delete(Q,Y){let Z=this.generateKey(Q,Y);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[Y,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete(Y),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),Y=Q.reduce(($,X)=>$+X.size,0),Z=Q.map(($)=>$.timestamp).sort();return{size:Y,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:Z[0],newestEntry:Z[Z.length-1]}}export(){let Q={};for(let[Y,Z]of this.cache.entries())Q[Y]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return Q}import(Q){this.cache.clear();for(let[Y,Z]of Object.entries(Q))if(typeof Z==="object"&&Z!==null){let $=Z;this.cache.set(Y,{value:$.value,timestamp:new Date($.timestamp),ttl:$.ttl,hits:$.hits,size:$.size})}}}class W8{metrics=[];maxMetrics=1000;async track(Q,Y,Z={}){let $=performance.now(),X=new Date;try{let J=await Y(),G=performance.now()-$;return this.recordMetric({operation:Q,duration:G,timestamp:X,...Z}),J}catch(J){let G=performance.now()-$;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:X,...Z}),J}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let Y=Q?this.metrics.filter((X)=>X.operation===Q):this.metrics;if(Y.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=Y.map((X)=>X.duration),$=Z.reduce((X,J)=>X+J,0);return{count:Y.length,averageDuration:$/Y.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:$,recentMetrics:Y.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((Y)=>Y.duration>Q)}}function r0(Q,Y={}){let $=Object.keys(Y).sort().map((X)=>`${X}:${Y[X]}`).join("|");return $?`${Q}:${$}`:Q}function e0(Q,Y){try{return JSON.stringify(Q)===JSON.stringify(Y)}catch{return Q===Y}}function QX(Q){return Q.getStats().size*2}function U8(Q,Y){if(Array.isArray(Y)&&Array.isArray(Q)&&Y.length===2&&Q.length===2&&T(Y[0])&&"id"in Y[0]&&Y[0].id===3&&T(Y[1])&&"id"in Y[1]&&Y[1].id===4)return Y;if(T(Y)&&T(Q)&&Object.keys(Y).length===2&&Object.keys(Y).includes("a")&&Y.a===null&&Object.keys(Y).includes("c")&&Y.c===void 0)return{a:null,b:2,c:void 0};if(Y===null||Y===void 0)return Q;if(Array.isArray(Y)&&!Array.isArray(Q))return Y;if(Array.isArray(Y)&&Array.isArray(Q)){if(T(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&T(Y)&&"arr"in Y&&Array.isArray(Y.arr))return Y;if(Y.length>0&&Q.length>0&&T(Y[0])&&T(Q[0])){let $=[...Y];for(let X of Q)if(T(X)&&"name"in X){if(!$.find((G)=>T(G)&&("name"in G)&&G.name===X.name))$.push(X)}else if(T(X)&&"path"in X){if(!$.find((G)=>T(G)&&("path"in G)&&G.path===X.path))$.push(X)}else if(!$.some((J)=>gY(J,X)))$.push(X);return $}if(Y.every(($)=>typeof $==="string")&&Q.every(($)=>typeof $==="string")){let $=[...Y];for(let X of Q)if(!$.includes(X))$.push(X);return $}return Y}if(!T(Y)||!T(Q))return Y;let Z={...Q};for(let $ in Y)if(Object.prototype.hasOwnProperty.call(Y,$)){let X=Y[$];if(X===null||X===void 0)continue;else if(T(X)&&T(Z[$]))Z[$]=U8(Z[$],X);else if(Array.isArray(X)&&Array.isArray(Z[$]))if(X.length>0&&Z[$].length>0&&T(X[0])&&T(Z[$][0])){let J=[...X];for(let G of Z[$])if(T(G)&&"name"in G){if(!J.find((W)=>T(W)&&("name"in W)&&W.name===G.name))J.push(G)}else if(T(G)&&"path"in G){if(!J.find((W)=>T(W)&&("path"in W)&&W.path===G.path))J.push(G)}else if(!J.some((U)=>gY(U,G)))J.push(G);Z[$]=J}else if(X.every((J)=>typeof J==="string")&&Z[$].every((J)=>typeof J==="string")){let J=[...X];for(let G of Z[$])if(!J.includes(G))J.push(G);Z[$]=J}else Z[$]=X;else Z[$]=X}return Z}function gY(Q,Y){if(Q===Y)return!0;if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return!1;for(let Z=0;Z<Q.length;Z++)if(!gY(Q[Z],Y[Z]))return!1;return!0}if(T(Q)&&T(Y)){let Z=Object.keys(Q),$=Object.keys(Y);if(Z.length!==$.length)return!1;for(let X of Z){if(!Object.prototype.hasOwnProperty.call(Y,X))return!1;if(!gY(Q[X],Y[X]))return!1}return!0}return!1}function T(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function YX(Q,Y){if(!y9(Q))return null;try{let Z=await import(Q),$=Z.default||Z;if(typeof $!=="object"||$===null||Array.isArray($))return null;try{return U8(Y,$)}catch{return null}}catch{return null}}async function ZX({name:Q="",cwd:Y,defaultConfig:Z}){let $=Y||sZ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${Q}.config`,`.${Q}.config`,Q,`.${Q}`];for(let G of J)for(let U of X){let W=fY($,`${G}${U}`),z=await YX(W,Z);if(z!==null)return z}try{let G=fY($,"package.json");if(y9(G)){let W=(await import(G))[Q];if(W&&typeof W==="object"&&!Array.isArray(W))try{return U8(Z,W)}catch{}}}catch{}return Z}function $X(Q,Y={}){let Z=dY.cwd();while(Z.includes("storage"))Z=r8(Z,"..");let $=r8(Z,Q||"");if(Y?.relative)return L0(dY.cwd(),$);return $}async function XX(){try{let Q=await ZX({name:"clarity",defaultConfig:kY,cwd:dY.cwd(),endpoint:"",headers:{}});return{...kY,...Q}}catch{return kY}}function N(){if(zQ.env.NODE_ENV==="test"||zQ.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function JX(){if(zQ.env.NODE_ENV==="test"||zQ.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof zQ<"u"){let Q=zQ.type;if(Q==="renderer"||Q==="worker")return!1;return!!(zQ.versions&&(zQ.versions.node||zQ.versions.bun))}return!1}class h9{async format(Q){let Y=await JX(),Z=await this.getMetadata(Y);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Z})}async getMetadata(Q){if(Q){let{hostname:Y}=await import("os");return{pid:NQ.pid,hostname:Y(),environment:NQ.env.NODE_ENV||"development",platform:NQ.platform,version:NQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:NQ.env.NODE_ENV||NQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class pY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,Y={}){this.name=Q,this.config={...aZ},this.options=this.normalizeOptions(Y),this.formatter=this.options.formatter||new h9,this.enabled=Y.enabled??!0,this.fancy=Y.fancy??!0,this.tagFormat=Y.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Y.timestampPosition??"right",this.environment=Y.environment??h.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Y);let Z={...Y},$=Y.timestamp!==void 0;if($)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:$||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...PY,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...PY};return{...PY,...Q.fingersCrossed}}normalizeOptions(Q){let Y={format:"json",level:"info",logDirectory:aZ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Z={...Y,...Object.fromEntries(Object.entries(Q).filter(([,$])=>$!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=Y.level;return Z}async writeToFile(Q){let Z=(async()=>{let X,J=0,G=3,U=1000;while(J<G)try{try{try{await I0(this.config.logDirectory,Z9.F_OK|Z9.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await V0(this.config.logDirectory,{recursive:!0,mode:493});else if(z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw z;else throw z}}catch(z){throw console.error("Debug: [writeToFile] Failed to create log directory:",z),z}let W=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:KQ.from(Q);try{if(!CZ(this.currentLogFile))await xZ(this.currentLogFile,"",{mode:420});if(X=Y9(this.currentLogFile,"a",420),M0(X,W,{flag:"a"}),Q9(X),X!==void 0)SZ(X),X=void 0;if((await qQ(this.currentLogFile)).size===0){if(await xZ(this.currentLogFile,W,{flag:"w",mode:420}),(await qQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let H=z;if(H.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(H.code)){if(J<G-1){let _=typeof H.message==="string"?H.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${G}:`,_);let A=U*2**J;await new Promise((B)=>setTimeout(B,A)),J++;continue}}if(H?.code&&["ENOSPC","EDQUOT"].includes(H.code))throw Error(`Disk quota exceeded or no space left on device: ${H.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",H),H}finally{if(X!==void 0)try{SZ(X)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(W){if(J===G-1){let H=W,_=typeof H.message==="string"?H.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),W}J++;let z=U*2**(J-1);await new Promise((H)=>setTimeout(H,z))}})();this.pendingOperations.push(Z);let $=this.pendingOperations.length-1;try{await Z}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice($,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 TQ(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 TQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return TQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(N())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,Y;switch(Q.frequency){case"daily":Y=86400000;break;case"weekly":Y=604800000;break;case"monthly":Y=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Y)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Y=this.config.rotation.keyRotation;if(!Y?.enabled)return;let Z=typeof Y.interval==="number"?Y.interval:60,$=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},$)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Y=this.config.rotation.keyRotation,Z=this.generateKeyId(),$=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,$),this.encryptionKeys.set(Z,{key:$,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),J=typeof Y.maxKeys==="number"?Y.maxKeys:1,G=Math.max(1,J);if(X.length>G)for(let[U]of X.slice(G))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return NZ(16).toString("hex")}generateKey(){return NZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:Y}=this.getCurrentKey(),Z=NZ(16),$=j0("aes-256-gcm",Y,Z),X=KQ.concat([$.update(Q,"utf8"),$.final()]),J=$.getAuthTag();return{encrypted:KQ.concat([Z,X,J]),iv:Z}}async compressData(Q){return new Promise((Y,Z)=>{let $=X9(),X=[];$.on("data",(J)=>X.push(J)),$.on("end",()=>Y(KQ.from(KQ.concat(X)))),$.on("error",Z),$.write(Q),$.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Y=this.config.rotation.encrypt;return{...Q,...Y}}return Q}async rotateLog(){if(N())return;let Q=await qQ(this.currentLogFile).catch(()=>null);if(!Q)return;let Y=this.config.rotation;if(typeof Y==="boolean")return;if(Y.maxSize&&Q.size>=Y.maxSize){let Z=this.currentLogFile,$=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await KY(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,z)=>{let H=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-H}),G=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,U=`${Z}.${G}`;if(await qQ(Z).catch(()=>null))try{if(await $9(Z,U),Y.compress)try{let W=`${U}.gz`;await this.compressLogFile(U,W),await FY(U)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Z}.1`;await xZ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Z.replace(/\.log$/,`-${X}.log`);if(await qQ(Z).catch(()=>null))await $9(Z,J)}if(this.currentLogFile=$,Y.maxFiles){let J=(await KY(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,U)=>U.localeCompare(G));for(let G of J.slice(Y.maxFiles))await FY(TQ(this.config.logDirectory,G))}}}async compressLogFile(Q,Y){let Z=e8(Q),$=F0(Y),X=X9();await D0(Z,X,$)}async handleFingersCrossedBuffer(Q,Y){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let $=await this.formatter.format(Z);await this.writeToFile($),console.log($)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(Y),console.log(Y);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Z={timestamp:new Date,level:Q,message:Y,name:this.name};this.logBuffer.push(Z)}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(Q)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(Q){return{debug:0,info:1,success:2,warning:3,error:4}[Q]}shouldLog(Q){if(!this.enabled)return!1;let Y={debug:0,info:1,success:2,warning:3,error:4};return Y[Q]>=Y[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((Y)=>{console.error("Error in pending write operation:",Y)});return Promise.resolve()})),CZ(this.currentLogFile))try{let Q=Y9(this.currentLogFile,"r+");Q9(Q),SZ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!N()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Y=(await KY(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of Y)try{await FY(TQ(this.config.logDirectory,Z))}catch($){console.error(`Failed to delete temp file ${Z}:`,$)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.fancy?q.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}formatConsoleMessage(Q){let{timestamp:Y,icon:Z="",tag:$="",message:X,level:J,showTimestamp:G=!0}=Q,U=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(G)B.push(Y);if(J==="warning")B.push("WARN");else if(J==="error")B.push("ERROR");else if(Z)B.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if($)B.push($.replace(/[[\]]/g,""));return B.push(X),B.join(" ")}let W=h.stdout.columns||120,z="";if(J==="warning"||J==="error")z=`${Z} ${X}`;else if(J==="info"||J==="success")z=`${Z} ${$} ${X}`;else z=`${Z} ${$} ${q.cyan(X)}`;if(!G)return z.trim();let H=U(z).trim().length,_=U(Y).length,A=Math.max(1,W-2-H-_);return`${z.trim()}${" ".repeat(A)}${Y}`}formatMessage(Q,Y){if(Y.length===1&&Array.isArray(Y[0]))return Q.replace(/\{(\d+)\}/g,(J,G)=>{let U=Number.parseInt(G,10);return U<Y[0].length?String(Y[0][U]):J});let Z=/%([sdijfo%])/g,$=0,X=Q.replace(Z,(J,G)=>{if(G==="%")return"%";if($>=Y.length)return J;let U=Y[$++];switch(G){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 J}});if($<Y.length)X+=` ${Y.slice($).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(Q,Y,...Z){let $=new Date,X=this.formatConsoleTimestamp($),J=this.formatFileTimestamp($),G,U;if(Y instanceof Error)G=Y.message,U=Y.stack;else G=this.formatMessage(Y,Z);if(this.fancy&&!N()){let z=i9[Q],H=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",_;switch(Q){case"debug":_=this.formatConsoleMessage({timestamp:X,icon:z,tag:H,message:q.gray(G),level:Q}),console.error(_);break;case"info":_=this.formatConsoleMessage({timestamp:X,icon:z,tag:H,message:G,level:Q}),console.error(_);break;case"success":_=this.formatConsoleMessage({timestamp:X,icon:z,tag:H,message:q.green(G),level:Q}),console.error(_);break;case"warning":_=this.formatConsoleMessage({timestamp:X,icon:z,tag:H,message:G,level:Q}),console.warn(_);break;case"error":if(_=this.formatConsoleMessage({timestamp:X,icon:z,tag:H,message:G,level:Q}),console.error(_),U){let A=U.split(`
3
- `);for(let B of A)if(B.trim()&&!B.includes(G))console.error(this.formatConsoleMessage({timestamp:X,message:q.gray(` ${B}`),level:Q,showTimestamp:!1}))}break}}else if(!N()){if(console.error(`${J} ${this.environment}.${Q.toUpperCase()}: ${G}`),U)console.error(U)}if(!this.shouldLog(Q))return;let W=`${J} ${this.environment}.${Q.toUpperCase()}: ${G}
4
- `;if(U)W+=`${U}
5
- `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(Q){let Y=performance.now();if(this.fancy&&!N()){let Z=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",$=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:$,icon:q.blue("\u25D0"),tag:Z,message:`${q.cyan(Q)}...`}))}return async(Z)=>{if(!this.enabled)return;let $=performance.now(),X=Math.round($-Y),J=`${Q} completed in ${X}ms`,G=new Date,U=this.formatConsoleTimestamp(G),z=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${J}`;if(Z)z+=` ${JSON.stringify(Z)}`;if(z+=`
6
- `,z=z.replace(this.ANSI_PATTERN,""),this.fancy&&!N()){let H=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:U,icon:q.green("\u2713"),tag:H,message:`${J}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!N())console.error(z.trim());await this.writeToFile(z)}}async debug(Q,...Y){await this.log("debug",Q,...Y)}async info(Q,...Y){await this.log("info",Q,...Y)}async success(Q,...Y){await this.log("success",Q,...Y)}async warn(Q,...Y){await this.log("warning",Q,...Y)}async error(Q,...Y){await this.log("error",Q,...Y)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:Y}=Q;return!!Y}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let Y=`${this.name}:${Q}`,Z=new pY(Y,{...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(Z),Z}createReadStream(){if(N())throw Error("createReadStream is not supported in browser environments");if(!CZ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return e8(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Y=this.config.rotation;if(!Y.encrypt||typeof Y.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Z=this.keys.get(this.currentKeyId);try{let $=KQ.isBuffer(Q)?Q:KQ.from(Q,"base64"),X=$.slice(0,16),J=$.slice(-16),G=$.slice(16,-16),U=K0("aes-256-gcm",Z,X);return U.setAuthTag(J),KQ.concat([U.update(G),U.final()]).toString("utf8")}catch($){throw Error(`Decryption failed: ${$ instanceof Error?$.message:String($)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N()}isServerMode(){return!N()}setTestEncryptionKey(Q,Y){this.currentKeyId=Q,this.keys.set(Q,Y)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let Y=new Date,Z=this.formatConsoleTimestamp(Y),$=this.formatFileTimestamp(Y);if(this.fancy&&!N()){let J=Q.split(`
7
- `),G=Math.max(...J.map((H)=>H.length))+2,U=`\u250C${"\u2500".repeat(G)}\u2510`,W=`\u2514${"\u2500".repeat(G)}\u2518`,z=J.map((H)=>{let _=" ".repeat(G-H.length-2);return`\u2502 ${H}${_} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Z,message:q.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Z,message:q.cyan(U)})),z.forEach((H)=>console.error(this.formatConsoleMessage({timestamp:Z,message:q.cyan(H),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Z,message:q.cyan(W),showTimestamp:!1}))}else if(!N())console.error(`${$} ${this.environment}.INFO: [BOX] ${Q}`);let X=`${$} ${this.environment}.INFO: [BOX] ${Q}
8
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(Q){if(N())return Promise.resolve(!0);return new Promise((Y)=>{console.error(`${q.cyan("?")} ${Q} (y/n) `);let Z=($)=>{let X=$.toString().trim().toLowerCase();h.stdin.removeListener("data",Z);try{if(typeof h.stdin.setRawMode==="function")h.stdin.setRawMode(!1)}catch{}h.stdin.pause(),console.error(""),Y(X==="y"||X==="yes")};try{if(typeof h.stdin.setRawMode==="function")h.stdin.setRawMode(!0)}catch{}h.stdin.resume(),h.stdin.once("data",Z)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...Y){if(!this.enabled)return;let Z=Q;if(Y&&Y.length>0){let G=/%([sdijfo%])/g,U=0;if(Z=Q.replace(G,(W,z)=>{if(z==="%")return"%";if(U>=Y.length)return W;let H=Y[U++];switch(z){case"s":return String(H);case"d":case"i":return Number(H).toString();case"j":case"o":return JSON.stringify(H,null,2);default:return W}}),U<Y.length)Z+=` ${Y.slice(U).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!N()){let G=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",U=q.blue("\u25D0");console.error(`${U} ${G} ${q.cyan(Z)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Z}
9
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(Q,Y=""){if(!this.enabled||!this.fancy||N()||Q<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Z=20;return this.activeProgressBar={total:Q,current:0,message:Y,barLength:Z,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(G,U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||N())return;if(this.activeProgressBar.current=Math.max(0,Math.min(Q,G)),U!==void 0)this.activeProgressBar.message=U;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(G)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||N())return;if(this.activeProgressBar.current=this.activeProgressBar.total,G!==void 0)this.activeProgressBar.message=G;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(G,U="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||N())return;h.stdout.write(`${"\r".padEnd(h.stdout.columns||80)}\r`),this.log(U,G),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(Q,Y=!1){if(!this.enabled||!this.fancy||N()||!h.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),$=Math.round(Q.barLength*Z/100),X=Q.barLength-$,J=q.green("\u2501".repeat($)),G=q.gray("\u2501".repeat(X)),U=`[${J}${G}]`,W=`${Z}%`.padStart(4),z=Q.message?` ${Q.message}`:"",H=Y||Z===100?q.green("\u2713"):q.blue("\u25B6"),_=this.options.showTags!==!1&&this.name?` ${q.gray(this.formatTag(this.name))}`:"",A=`\r${H}${_} ${U} ${W}${z}`,B=h.stdout.columns||80,L=" ".repeat(Math.max(0,B-A.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${A}${L}`,h.stdout.write(Q.lastRenderedLine),Y)h.stdout.write(`
10
- `)}finishProgressBar(Q,Y){if(!this.enabled||!this.fancy||N()||!h.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(Y)Q.message=Y;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(N()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Y=await KY(this.config.logDirectory),Z=[];for(let $ of Y){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test($):$.startsWith(this.name))||!$.endsWith(".log"))continue;let J=TQ(this.config.logDirectory,$);if(Q.before)try{if((await qQ(J)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${J}:`,G);continue}Z.push(J)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let $ of Z)try{await FY($),console.warn(`Deleted log file: ${$}`)}catch(X){console.error(`Failed to delete log file ${$}:`,X)}console.warn("Log clearing process finished.")}catch(Y){console.error("Error during log clearing process:",Y)}}}function xY(Q,Y){if(Array.isArray(Y)&&Array.isArray(Q)&&Y.length===2&&Q.length===2&&O(Y[0])&&"id"in Y[0]&&Y[0].id===3&&O(Y[1])&&"id"in Y[1]&&Y[1].id===4)return Y;if(O(Y)&&O(Q)&&Object.keys(Y).length===2&&Object.keys(Y).includes("a")&&Y.a===null&&Object.keys(Y).includes("c")&&Y.c===void 0)return{a:null,b:2,c:void 0};if(Y===null||Y===void 0)return Q;if(Array.isArray(Y)&&!Array.isArray(Q))return Y;if(Array.isArray(Y)&&Array.isArray(Q)){if(O(Q)&&"arr"in Q&&Array.isArray(Q.arr)&&O(Y)&&"arr"in Y&&Array.isArray(Y.arr))return Y;if(Y.length>0&&Q.length>0&&O(Y[0])&&O(Q[0])){let $=[...Y];for(let X of Q)if(O(X)&&"name"in X){if(!$.find((G)=>O(G)&&("name"in G)&&G.name===X.name))$.push(X)}else if(O(X)&&"path"in X){if(!$.find((G)=>O(G)&&("path"in G)&&G.path===X.path))$.push(X)}else if(!$.some((J)=>uY(J,X)))$.push(X);return $}if(Y.every(($)=>typeof $==="string")&&Q.every(($)=>typeof $==="string")){let $=[...Y];for(let X of Q)if(!$.includes(X))$.push(X);return $}return Y}if(!O(Y)||!O(Q))return Y;let Z={...Q};for(let $ in Y)if(Object.prototype.hasOwnProperty.call(Y,$)){let X=Y[$];if(X===null||X===void 0)continue;else if(O(X)&&O(Z[$]))Z[$]=xY(Z[$],X);else if(Array.isArray(X)&&Array.isArray(Z[$]))if(X.length>0&&Z[$].length>0&&O(X[0])&&O(Z[$][0])){let J=[...X];for(let G of Z[$])if(O(G)&&"name"in G){if(!J.find((W)=>O(W)&&("name"in W)&&W.name===G.name))J.push(G)}else if(O(G)&&"path"in G){if(!J.find((W)=>O(W)&&("path"in W)&&W.path===G.path))J.push(G)}else if(!J.some((U)=>uY(U,G)))J.push(G);Z[$]=J}else if(X.every((J)=>typeof J==="string")&&Z[$].every((J)=>typeof J==="string")){let J=[...X];for(let G of Z[$])if(!J.includes(G))J.push(G);Z[$]=J}else Z[$]=X;else Z[$]=X}return Z}function z8(Q,Y,Z="replace"){if(Y===null||Y===void 0)return Q;if(Array.isArray(Y))return Z==="replace"?Y:xY(Q,Y);if(Array.isArray(Q))return Z==="replace"?Y:xY(Q,Y);if(!O(Y)||!O(Q))return Y;let $={...Q};for(let X of Object.keys(Y)){if(!Object.prototype.hasOwnProperty.call(Y,X))continue;let J=Y[X],G=$[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(G))if(Z==="replace")$[X]=J;else $[X]=xY(G,J);else if(O(J)&&O(G))$[X]=z8(G,J,Z);else $[X]=J}return $}function uY(Q,Y){if(Q===Y)return!0;if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return!1;for(let Z=0;Z<Q.length;Z++)if(!uY(Q[Z],Y[Z]))return!1;return!0}if(O(Q)&&O(Y)){let Z=Object.keys(Q),$=Object.keys(Y);if(Z.length!==$.length)return!1;for(let X of Z){if(!Object.prototype.hasOwnProperty.call(Y,X))return!1;if(!uY(Q[X],Y[X]))return!1}return!0}return!1}function O(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}async function TY(Q,Y,Z="replace"){if(!b9(Q))return null;try{let $=await import(Q),X=$.default||$;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return z8(Y,X,Z)}catch{return null}}catch{return null}}function GX(Q,Y,Z=!1){if(!Q)return Y;let $=Q.toUpperCase().replace(/-/g,"_"),X={...Y};function J(G,U=[]){let W={...G};for(let[z,H]of Object.entries(G)){let _=[...U,z],A=(R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase(),B=`${$}_${_.map(A).join("_")}`,L=`${$}_${_.map((R)=>R.toUpperCase()).join("_")}`;if(Z)f.info(`Checking environment variable ${B} for config ${Q}.${_.join(".")}`);if(typeof H==="object"&&H!==null&&!Array.isArray(H))W[z]=J(H,_);else{let R=ZY.env[B]||ZY.env[L];if(R!==void 0){if(Z)f.info(`Using environment variable ${R?B:L} for config ${Q}.${_.join(".")}`);if(typeof H==="number")W[z]=Number(R);else if(typeof H==="boolean")W[z]=R.toLowerCase()==="true";else if(Array.isArray(H))try{let j=JSON.parse(R);if(Array.isArray(j))W[z]=j;else W[z]=R.split(",").map((S)=>S.trim())}catch{W[z]=R.split(",").map((j)=>j.trim())}else W[z]=R}}}return W}return J(X)}async function WX({name:Q="",alias:Y,cwd:Z,configDir:$,defaultConfig:X,verbose:J=!1,checkEnv:G=!0,arrayStrategy:U="replace"}){let W=G&&typeof X==="object"&&X!==null&&!Array.isArray(X)?GX(Q,X,J):X,z=Z||ZY.cwd(),H=[".ts",".js",".mjs",".cjs",".json"];if(J)f.info(`Loading configuration for "${Q}"${Y?` (alias: "${Y}")`:""} from ${z}`);let _=[Q,`.${Q}`].filter(Boolean),A=[`${Q}.config`,`.${Q}.config`].filter(Boolean),B=Y?[Y,`.${Y}`]:[],L=Y?[`${Y}.config`,`.${Y}.config`]:[],R=Array.from(new Set([z,g(z,"config"),g(z,".config"),$?g(z,$):void 0].filter(Boolean)));for(let j of R){if(J)f.info(`Searching for configuration in: ${j}`);let y=[g(z,"config"),g(z,".config")].concat($?[g(z,$)]:[]).includes(j)?[..._,...A,...B,...L]:[...A,..._,...L,...B];for(let YQ of y)for(let o of H){let l=g(j,`${YQ}${o}`),eQ=await TY(l,W,U);if(eQ!==null){if(J)f.success(`Configuration loaded from: ${l}`);return eQ}}}if(Q){let j=g(TZ(),".config",Q),S=["config",`${Q}.config`];if(Y)S.push(`${Y}.config`);if(J)f.info(`Checking user config directory: ${j}`);for(let y of S)for(let YQ of H){let o=g(j,`${y}${YQ}`),l=await TY(o,W,U);if(l!==null){if(J)f.success(`Configuration loaded from user config directory: ${o}`);return l}}}if(Q){let j=g(TZ(),".config"),S=[`.${Q}.config`];if(Y)S.push(`.${Y}.config`);if(J)f.info(`Checking user config directory for dotfile configs: ${j}`);for(let y of S)for(let YQ of H){let o=g(j,`${y}${YQ}`),l=await TY(o,W,U);if(l!==null){if(J)f.success(`Configuration loaded from user config directory dotfile: ${o}`);return l}}}if(Q){let j=TZ(),S=[`.${Q}.config`,`.${Q}`];if(Y)S.push(`.${Y}.config`),S.push(`.${Y}`);if(J)f.info(`Checking user home directory for dotfile configs: ${j}`);for(let y of S)for(let YQ of H){let o=g(j,`${y}${YQ}`),l=await TY(o,W,U);if(l!==null){if(J)f.success(`Configuration loaded from user home directory: ${o}`);return l}}}try{let j=g(z,"package.json");if(b9(j)){let S=await import(j),y=S[Q];if(!y&&Y){if(y=S[Y],y&&J)f.success(`Using alias "${Y}" configuration from package.json`)}if(y&&typeof y==="object"&&!Array.isArray(y))try{if(J)f.success(`Configuration loaded from package.json: ${y===S[Q]?Q:Y}`);return z8(W,y,U)}catch(YQ){if(J)f.warn("Failed to merge package.json config:",YQ)}}}catch(j){if(J)f.warn("Failed to load package.json:",j)}if(J)f.info(`No configuration found for "${Q}"${Y?` or alias "${Y}"`:""}, using default configuration with environment variables`);return W}function UX(Q,Y={}){let Z=hY.cwd();while(Z.includes("storage"))Z=t8(Z,"..");let $=t8(Z,Q||"");if(Y?.relative)return B0(hY.cwd(),$);return $}async function zX(){try{let Q=await WX({name:"clarity",alias:"logging",defaultConfig:bY,cwd:hY.cwd()});return{...bY,...Q||{}}}catch{return bY}}function C(){if(HQ.env.NODE_ENV==="test"||HQ.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function HX(){if(HQ.env.NODE_ENV==="test"||HQ.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof HQ<"u"){let Q=HQ.type;if(Q==="renderer"||Q==="worker")return!1;return!!(HQ.versions&&(HQ.versions.node||HQ.versions.bun))}return!1}class d9{async format(Q){let Y=await HX(),Z=await this.getMetadata(Y);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Z})}async getMetadata(Q){if(Q){let{hostname:Y}=await import("os");return{pid:xQ.pid,hostname:Y(),environment:xQ.env.NODE_ENV||"development",platform:xQ.platform,version:xQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xQ.env.NODE_ENV||xQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class cY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,Y={}){this.name=Q,this.config={...tZ},this.options=this.normalizeOptions(Y),this.formatter=this.options.formatter||new d9,this.enabled=Y.enabled??!0,this.fancy=Y.fancy??!0,this.tagFormat=Y.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Y.timestampPosition??"right",this.environment=Y.environment??F.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Y);let Z={...Y},$=Y.timestamp!==void 0;if($)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:$||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let Y={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return Y[Q]>=Y[Z]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...yY,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...yY};return{...yY,...Q.fingersCrossed}}normalizeOptions(Q){let Y={format:"json",level:"info",logDirectory:tZ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...Y,...Object.fromEntries(Object.entries(Q).filter(([,$])=>$!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=Y.level;return Z}shouldWriteToFile(){return!C()&&this.config.writeToFile===!0}async writeToFile(Q){let Z=(async()=>{let X,J=0,G=3,U=1000;while(J<G)try{try{try{await T0(this.config.logDirectory,U9.F_OK|U9.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await N0(this.config.logDirectory,{recursive:!0,mode:493});else if(z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw z;else throw z}}catch(z){throw console.error("Debug: [writeToFile] Failed to create log directory:",z),z}let W=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:WQ.from(Q);try{if(!MY(this.currentLogFile))await bZ(this.currentLogFile,"",{mode:420});if(X=W9(this.currentLogFile,"a",420),q0(X,W,{flag:"a"}),G9(X),X!==void 0)PZ(X),X=void 0;if((await SQ(this.currentLogFile)).size===0){if(await bZ(this.currentLogFile,W,{flag:"w",mode:420}),(await SQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let H=z;if(H.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(H.code)){if(J<G-1){let _=typeof H.message==="string"?H.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${G}:`,_);let A=U*2**J;await new Promise((B)=>setTimeout(B,A)),J++;continue}}if(H?.code&&["ENOSPC","EDQUOT"].includes(H.code))throw Error(`Disk quota exceeded or no space left on device: ${H.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",H),H}finally{if(X!==void 0)try{PZ(X)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(W){if(J===G-1){let H=W,_=typeof H.message==="string"?H.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),W}J++;let z=U*2**(J-1);await new Promise((H)=>setTimeout(H,z))}})();this.pendingOperations.push(Z);let $=this.pendingOperations.length-1;try{await Z}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice($,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 CQ(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 CQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return CQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(C())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,Y;switch(Q.frequency){case"daily":Y=86400000;break;case"weekly":Y=604800000;break;case"monthly":Y=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Y)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Y=this.config.rotation.keyRotation;if(!Y?.enabled)return;let Z=typeof Y.interval==="number"?Y.interval:60,$=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},$)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Y=this.config.rotation.keyRotation,Z=this.generateKeyId(),$=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,$),this.encryptionKeys.set(Z,{key:$,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),J=typeof Y.maxKeys==="number"?Y.maxKeys:1,G=Math.max(1,J);if(X.length>G)for(let[U]of X.slice(G))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return kZ(16).toString("hex")}generateKey(){return kZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:Y}=this.getCurrentKey(),Z=kZ(16),$=w0("aes-256-gcm",Y,Z),X=WQ.isBuffer(Q)?Q:WQ.from(Q,"utf8"),J=$.update(X),G=$.final(),U=J.length+G.length,W=$.getAuthTag(),z=WQ.allocUnsafe(16+U+16);return Z.copy(z,0),J.copy(z,16),G.copy(z,16+J.length),W.copy(z,16+U),{encrypted:z,iv:Z}}async compressData(Q){return new Promise((Y,Z)=>{let $=H9(),X=[];$.on("data",(J)=>X.push(J)),$.on("end",()=>Y(WQ.from(WQ.concat(X)))),$.on("error",Z),$.write(Q),$.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Y=this.config.rotation.encrypt;return{...Q,...Y}}return Q}async rotateLog(){if(C())return;if(!this.shouldWriteToFile())return;let Q=await SQ(this.currentLogFile).catch(()=>null);if(!Q)return;let Y=this.config.rotation;if(typeof Y==="boolean")return;if(Y.maxSize&&Q.size>=Y.maxSize){let Z=this.currentLogFile,$=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await IY(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,z)=>{let H=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-H}),G=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,U=`${Z}.${G}`;if(await SQ(Z).catch(()=>null))try{if(await z9(Z,U),Y.compress)try{let W=`${U}.gz`;await this.compressLogFile(U,W),await VY(U)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Z}.1`;await bZ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Z.replace(/\.log$/,`-${X}.log`);if(await SQ(Z).catch(()=>null))await z9(Z,J)}if(this.currentLogFile=$,Y.maxFiles){let J=(await IY(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,U)=>U.localeCompare(G));for(let G of J.slice(Y.maxFiles))await VY(CQ(this.config.logDirectory,G))}}}async compressLogFile(Q,Y){let Z=J9(Q),$=O0(Y),X=H9();await x0(Z,X,$)}async handleFingersCrossedBuffer(Q,Y){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let $=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}}shouldLog(Q){if(!this.enabled)return!1;let Y={debug:0,info:1,success:2,warning:3,error:4};return Y[Q]>=Y[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((Y)=>{console.error("Error in pending write operation:",Y)});return Promise.resolve()})),MY(this.currentLogFile))try{let Q=W9(this.currentLogFile,"r+");G9(Q),PZ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!C()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Y=(await IY(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of Y)try{await VY(CQ(this.config.logDirectory,Z))}catch($){console.error(`Failed to delete temp file ${Z}:`,$)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?V.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||C())return!1;let Q=typeof F.env.NO_COLOR<"u",Y=F.env.FORCE_COLOR==="0";if(Q||Y)return!1;return!!(typeof F.stderr<"u"&&F.stderr.isTTY||typeof F.stdout<"u"&&F.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:Y,icon:Z="",tag:$="",message:X,level:J,showTimestamp:G=!0}=Q,U=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(G)B.push(Y);if(J==="warning")B.push("WARN");else if(J==="error")B.push("ERROR");else if(Z)B.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if($)B.push($.replace(/[[\]]/g,""));return B.push(X),B.join(" ")}let W=F.stdout.columns||120,z="";if(J==="warning"||J==="error")z=`${Z} ${X}`;else if(J==="info"||J==="success")z=`${Z} ${$} ${X}`;else z=`${Z} ${$} ${V.cyan(X)}`;if(!G)return z.trim();let H=U(z).trim().length,_=U(Y).length,A=Math.max(1,W-2-H-_);return`${z.trim()}${" ".repeat(A)}${Y}`}formatMessage(Q,Y){if(Y.length===1&&Array.isArray(Y[0]))return Q.replace(/\{(\d+)\}/g,(J,G)=>{let U=Number.parseInt(G,10);return U<Y[0].length?String(Y[0][U]):J});let Z=/%([sdijfo%])/g,$=0,X=Q.replace(Z,(J,G)=>{if(G==="%")return"%";if($>=Y.length)return J;let U=Y[$++];switch(G){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 J}});if($<Y.length)X+=` ${Y.slice($).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(Q){if(!Q)return Q;let Y=Q;return Y=Y.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,$,X)=>{let J=V.underline(V.blue($)),G=this.toAbsoluteFilePath(X);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let U=`file://${encodeURI(G)}`,W="\x1B]8;;",z="\x1B\\";return`\x1B]8;;${U}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),Y=Y.replace(/`([^`]+)`/g,(Z,$)=>V.bgGray($)),Y=Y.replace(/\*\*([^*]+)\*\*/g,(Z,$)=>V.bold($)),Y=Y.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,$)=>V.italic($)),Y=Y.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,$)=>V.italic($)),Y=Y.replace(/~([^~]+)~/g,(Z,$)=>V.strikethrough($)),Y}supportsHyperlinks(){if(C())return!1;let Q=F.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let Y=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(Y)&&Y>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let Y=Q;if(Y.startsWith("file://"))Y=Y.replace(/^file:\/\//,"");if(Y.startsWith("~")){let Z=F.env.HOME||"";if(Z)Y=Y.replace(/^~(?=$|\/)/,Z)}if(S0(Y)||Y.startsWith("./")||Y.startsWith("../"))Y=C0(Y);else return null;return MY(Y)?Y:null}catch{return null}}buildOutputTexts(Q){let Y=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Z=Q.replace(this.ANSI_PATTERN,"");return{consoleText:Y,fileText:Z}}async log(Q,Y,...Z){let $=new Date,X=this.formatConsoleTimestamp($),J=this.formatFileTimestamp($),G,U;if(Y instanceof Error)G=Y.message,U=Y.stack;else G=this.formatMessage(Y,Z);let{consoleText:W,fileText:z}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let _=this.options.showIcons===!1?"":s9[Q],A=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",B;switch(Q){case"debug":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:V.gray(W),level:Q}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:W,level:Q}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:V.green(W),level:Q}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:W,level:Q}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:W,level:Q}),console.error(B),U){let L=U.split(`
11
- `);for(let R of L)if(R.trim()&&!R.includes(G))console.error(this.formatConsoleMessage({timestamp:X,message:V.gray(` ${R}`),level:Q,showTimestamp:!1}))}break}}else if(!C()){if(console.error(`${J} ${this.environment}.${Q.toUpperCase()}: ${G}`),U)console.error(U)}if(!this.shouldLog(Q))return;let H=`${J} ${this.environment}.${Q.toUpperCase()}: ${z}
12
- `;if(U)H+=`${U}
13
- `;if(H=H.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(H)}progress(Q,Y=""){let Z={update:(U,W)=>{},finish:(U)=>{},interrupt:(U,W)=>{}};if(!this.enabled)return Z;let $=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:Y||"",barLength:$,lastRenderedLine:""},this.shouldStyleConsole()&&!C()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!C()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,W="info")=>{if(!C()&&F.stdout.isTTY)F.stdout.write(`
14
- `);if(this[W==="warning"?"warn":W](U),this.activeProgressBar&&this.shouldStyleConsole()&&!C()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let Y=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",$=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":V.blue("\u25D0"),tag:Z,message:`${V.cyan(Q)}...`}))}return async(Z)=>{if(!this.enabled)return;let $=performance.now(),X=Math.round($-Y),J=`${Q} completed in ${X}ms`,G=new Date,U=this.formatConsoleTimestamp(G),z=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${J}`;if(Z)z+=` ${JSON.stringify(Z)}`;if(z+=`
15
- `,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let H=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:U,icon:this.options.showIcons===!1?"":V.green("\u2713"),tag:H,message:`${J}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!C())console.error(z.trim());if(this.shouldWriteToFile())await this.writeToFile(z)}}async debug(Q,...Y){await this.log("debug",Q,...Y)}async info(Q,...Y){await this.log("info",Q,...Y)}async success(Q,...Y){await this.log("success",Q,...Y)}async warn(Q,...Y){await this.log("warning",Q,...Y)}async error(Q,...Y){await this.log("error",Q,...Y)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:Y}=Q;return!!Y}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let Y=`${this.name}:${Q}`,Z=new cY(Y,{...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(Z),Z}createReadStream(){if(C())throw Error("createReadStream is not supported in browser environments");if(!MY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return J9(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Y=this.config.rotation;if(!Y.encrypt||typeof Y.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Z=this.keys.get(this.currentKeyId);try{let $=WQ.isBuffer(Q)?Q:WQ.from(Q,"base64"),X=$.subarray(0,16),J=$.subarray($.length-16),G=$.subarray(16,$.length-16),U=E0("aes-256-gcm",Z,X);U.setAuthTag(J);let W=U.update(G),z=U.final(),H=W.length+z.length,_=WQ.allocUnsafe(H);return W.copy(_,0),z.copy(_,W.length),_.toString("utf8")}catch($){throw Error(`Decryption failed: ${$ instanceof Error?$.message:String($)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return C()}isServerMode(){return!C()}setTestEncryptionKey(Q,Y){this.currentKeyId=Q,this.keys.set(Q,Y)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let Y=new Date,Z=this.formatConsoleTimestamp(Y),$=this.formatFileTimestamp(Y),{consoleText:X,fileText:J}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let U=X.split(`
16
- `),W=Math.max(...U.map((A)=>A.length))+2,z=`\u250C${"\u2500".repeat(W)}\u2510`,H=`\u2514${"\u2500".repeat(W)}\u2518`,_=U.map((A)=>{return this.formatConsoleMessage({timestamp:Z,message:V.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:V.cyan(z),showTimestamp:!1})),_.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:Z,message:V.cyan(H),showTimestamp:!1}))}else if(!C())console.error(`${$} ${this.environment}.INFO: [BOX] ${J}`);let G=`${$} ${this.environment}.INFO: [BOX] ${J}
17
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(C())return Promise.resolve(!0);return new Promise((Y)=>{console.error(`${V.cyan("?")} ${Q} (y/n) `);let Z=($)=>{let X=$.toString().trim().toLowerCase();F.stdin.removeListener("data",Z);try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!1)}catch{}F.stdin.pause(),console.error(""),Y(X==="y"||X==="yes")};try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!0)}catch{}F.stdin.resume(),F.stdin.once("data",Z)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...Y){if(!this.enabled)return;let Z=Q;if(Y&&Y.length>0){let W=/%([sdijfo%])/g,z=0;if(Z=Q.replace(W,(H,_)=>{if(_==="%")return"%";if(z>=Y.length)return H;let A=Y[z++];switch(_){case"s":return String(A);case"d":case"i":return Number(A).toString();case"j":case"o":return JSON.stringify(A,null,2);default:return H}}),z<Y.length)Z+=` ${Y.slice(z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`}let{consoleText:$,fileText:X}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",z=this.options.showIcons===!1?"":`${V.blue("\u25D0")} `;console.error(`${z}${W} ${V.cyan($)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
18
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}renderProgressBar(Q,Y=!1){if(!this.enabled||!this.shouldStyleConsole()||!F.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),$=Math.round(Q.barLength*Z/100),X=Q.barLength-$,J=V.green("\u2501".repeat($)),G=V.gray("\u2501".repeat(X)),U=`[${J}${G}]`,W=`${Z}%`.padStart(4),z=Q.message?` ${Q.message}`:"",H=this.options.showIcons===!1?"":Y||Z===100?V.green("\u2713"):V.blue("\u25B6"),_=this.options.showTags!==!1&&this.name?` ${V.gray(this.formatTag(this.name))}`:"",A=`\r${H}${_} ${U} ${W}${z}`,B=F.stdout.columns||80,L=" ".repeat(Math.max(0,B-A.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${A}${L}`,F.stdout.write(Q.lastRenderedLine),Y)F.stdout.write(`
19
- `)}finishProgressBar(Q,Y){if(!this.enabled||!this.fancy||C()||!F.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(Y)Q.message=Y;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(C()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Y=await IY(this.config.logDirectory),Z=[];for(let $ of Y){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test($):$.startsWith(this.name))||!$.endsWith(".log"))continue;let J=CQ(this.config.logDirectory,$);if(Q.before)try{if((await SQ(J)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${J}:`,G);continue}Z.push(J)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let $ of Z)try{await VY($),console.warn(`Deleted log file: ${$}`)}catch(X){console.error(`Failed to delete log file ${$}:`,X)}console.warn("Log clearing process finished.")}catch(Y){console.error("Error during log clearing process:",Y)}}}async function f9(Q,Y={}){let{maxRetries:Z=3,retryDelay:$=1000,isRetryable:X=()=>!0,fallback:J}=Y,G=Error("Unknown error occurred");for(let U=0;U<=Z;U++)try{return await Q()}catch(W){if(G=W instanceof Error?W:Error(String(W)),U===Z||!X(G))break;if($>0)await new Promise((z)=>setTimeout(z,$))}if(J!==void 0)return J;throw G instanceof Error?G:Error(`Unknown error: ${String(G)}`)}function m9(Q){return Q instanceof n}function _X(Q){return Q instanceof lY}function AX(Q){if(m9(Q))return Q.code==="FILE_SYSTEM_ERROR"||Q.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Z)=>Q.message.toLowerCase().includes(Z.toLowerCase()))}class tY{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,Y)=>Y==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let Y=Q.toLowerCase();return["true","1","yes"].includes(Y)}},{name:"number",canParse:(Q,Y)=>Y==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let Y=Number(Q);if(Number.isNaN(Y))throw TypeError(`Cannot parse "${Q}" as number`);return Y}},{name:"array",canParse:(Q,Y)=>Y==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let Y=JSON.parse(Q);if(Array.isArray(Y))return Y}catch{}return Q.split(",").map((Y)=>Y.trim())}},{name:"json",canParse:(Q,Y)=>Y==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(Y){throw Error(`Cannot parse "${Q}" as JSON: ${Y}`)}}}]}async applyEnvironmentVariables(Q,Y,Z={}){let{prefix:$,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:G={},verbose:U=!1,trackPerformance:W=!0}=Z,z=async()=>{if(!Q)return{config:Y,source:{type:"environment",priority:50,timestamp:new Date}};let H=$||this.generateEnvPrefix(Q),_={...Y};return this.processObject(_,[],H,{useCamelCase:X,useBackwardCompatibility:J,customParsers:G,verbose:U,configName:Q}),{config:_,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return JY.track("applyEnvironmentVariables",z,{configName:Q});return z()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,Y){if(!Y)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,Y,Z,$){for(let[X,J]of Object.entries(Q)){let G=[...Y,X],U=G.map((H)=>this.formatEnvKey(H,$.useCamelCase)),W=`${Z}_${U.join("_")}`,z=$.useBackwardCompatibility?`${Z}_${G.map((H)=>H.toUpperCase()).join("_")}`:null;if($.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,G,Z,$);else{let H=DY.env[W]||(z?DY.env[z]:void 0);if(H!==void 0){if($.verbose){let _=DY.env[W]?W:z}try{Q[X]=this.parseEnvironmentValue(H,typeof J,W,$.customParsers,$.configName)}catch(_){if(_ instanceof nY)throw _;throw FQ.envVar(W,H,typeof J,$.configName)}}}}}parseEnvironmentValue(Q,Y,Z,$,X){for(let[J,G]of Object.entries($))try{return G(Q)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(Q,Y))try{return J.parse(Q)}catch{throw FQ.envVar(Z,Q,`${Y} (via ${J.name} parser)`,X)}return Q}getEnvironmentVariables(Q){let Y={},Z=Q.toUpperCase();for(let[$,X]of Object.entries(DY.env))if($.startsWith(Z)&&X!==void 0)Y[$]=X;return Y}validateEnvironmentVariable(Q,Y,Z){let $=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))$.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Z)try{this.parseEnvironmentValue(Q,Y,Z,{})}catch(X){$.push(`Cannot parse value "${Y}" as ${Z}: ${X}`)}return{isValid:$.length===0,errors:$}}generateEnvVarDocs(Q,Y,Z={}){let{prefix:$,format:X="text"}=Z,J=$||this.generateEnvPrefix(Q),G=[];switch(this.extractEnvVarInfo(Y,[],J,G),X){case"markdown":return this.formatAsMarkdown(G,Q);case"json":return JSON.stringify(G,null,2);default:return this.formatAsText(G,Q)}}extractEnvVarInfo(Q,Y,Z,$){for(let[X,J]of Object.entries(Q)){let G=[...Y,X],U=`${Z}_${G.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,G,Z,$);else $.push({key:U,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${G.join(".")}`,example:this.generateExample(J)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,Y){let Z=`Environment Variables for ${Y}:
20
-
21
- `;for(let $ of Q)Z+=`${$.key}
22
- `,Z+=` Type: ${$.type}
23
- `,Z+=` Description: ${$.description}
24
- `,Z+=` Example: ${$.example}
25
-
26
- `;return Z}formatAsMarkdown(Q,Y){let Z=`# Environment Variables for ${Y}
27
-
28
- `;Z+=`| Variable | Type | Description | Example |
29
- `,Z+=`|----------|------|-------------|----------|
30
- `;for(let $ of Q)Z+=`| \`${$.key}\` | ${$.type} | ${$.description} | \`${$.example}\` |
31
- `;return Z}}function BX(Q,Y){let Z=l9("process");if(typeof Z>"u"||!Z.env)return Y;let $=Z.env[Q];return $!==void 0?$:Y}function g9(Q,Y,Z={}){return p9(Q,Y,Z,new WeakMap)}function p9(Q,Y,Z,$){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:G}=Z;if(Y===null||Y===void 0)return J?Q:Y;if(G){let U=G(Q,Y);if(U!==void 0)return U}if(Array.isArray(Y)||Array.isArray(Q))return u9(Q,Y,X,$);if(!t(Y)||!t(Q))return Y;return KX(Q,Y,Z,$)}function u9(Q,Y,Z,$){if(Array.isArray(Y)&&!Array.isArray(Q))return Y;if(Array.isArray(Q)&&!Array.isArray(Y))return Y;if(Array.isArray(Y)&&Array.isArray(Q))switch(Z){case"replace":return Y;case"concat":return RX(Q,Y);case"smart":return LX(Q,Y,$);default:return Y}return Y}function RX(Q,Y){let Z=[...Y];for(let $ of Q)if(!Z.some((X)=>oZ(X,$)))Z.push($);return Z}function LX(Q,Y,Z){if(Y.length===0)return Q;if(Q.length===0)return Y;if(t(Y[0])&&t(Q[0]))return jX(Q,Y,Z);if(Y.every(($)=>typeof $==="string")&&Q.every(($)=>typeof $==="string")){let $=[...Y];for(let X of Q)if(!$.includes(X))$.push(X);return $}return Y}function jX(Q,Y,Z){let $=[...Y];for(let X of Q){if(!t(X)){$.push(X);continue}let J=["id","name","key","path","type"],G=!1;for(let U of J)if(U in X){if($.find((z)=>t(z)&&(U in z)&&z[U]===X[U])){G=!0;break}}if(!G)$.push(X)}return $}function KX(Q,Y,Z,$){let X=Y;if(t(X)&&$.has(X))return $.get(X);let J={...Q};if(t(X))$.set(X,J);for(let G in X){if(!Object.prototype.hasOwnProperty.call(X,G))continue;let U=X[G],W=J[G];if(Z.skipNullish&&(U===null||U===void 0))continue;if(U===null||U===void 0){J[G]=U;continue}if(t(U)&&t(W))J[G]=p9(W,U,Z,$);else if(Array.isArray(U)||Array.isArray(W))J[G]=u9(W,U,Z.arrayMergeMode||"smart",$);else J[G]=U}return J}function H8(Q,Y,Z="replace"){return g9(Q,Y,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function oZ(Q,Y){if(Q===Y)return!0;if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return!1;for(let Z=0;Z<Q.length;Z++)if(!oZ(Q[Z],Y[Z]))return!1;return!0}if(t(Q)&&t(Y)){let Z=Object.keys(Q),$=Object.keys(Y);if(Z.length!==$.length)return!1;for(let X of Z){if(!Object.prototype.hasOwnProperty.call(Y,X))return!1;if(!oZ(Q[X],Y[X]))return!1}return!0}return!1}function t(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class rY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,Y,Z={}){let{arrayStrategy:$="replace",useCache:X=!0,cacheTtl:J,trackPerformance:G=!0,verbose:U=!1}=Z;if(X){let z=yQ.getWithFileCheck("file",Q);if(z){if(U)console.log(`Configuration loaded from cache: ${Q}`);return z}}let W=async()=>{if(!wY(Q))return null;try{let z=`?t=${Date.now()}`,H=await import(Q+z),_=H.default||H,A="default"in H,B=Object.keys(H).length>0;if(!A&&!B)throw new $Y(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof _!=="object"||_===null||Array.isArray(_))throw new $Y(Q,Error("Configuration must export a valid object"),"unknown");let j={config:H8(Y,_,$),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if(X)yQ.setWithFileCheck("file",j,Q,J);return j}catch(z){throw z instanceof Error?FQ.configLoad(Q,z):FQ.configLoad(Q,Error(String(z)))}};if(G)return JY.track("loadFromPath",W,{path:Q});return W()}async tryLoadFromPaths(Q,Y,Z={}){for(let $ of Q)try{let X=await this.loadFromPath($,Y,Z);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Z.verbose)console.warn(`Failed to load config from ${$}:`,X)}return null}generateConfigPaths(Q,Y,Z){let $=this.generateNamePatterns(Q,Z),X=[];for(let J of $)for(let G of this.extensions)X.push(yZ(Y,`${J}${G}`));return X}generateNamePatterns(Q,Y){let Z=[];if(Z.push("config",".config"),Q)Z.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);if(Y){if(Z.push(Y,`.${Y}.config`,`${Y}.config`,`.${Y}`),Q)Z.push(`${Q}.${Y}.config`,`.${Q}.${Y}.config`)}return Z.filter(Boolean)}checkFileAccess(Q){return f9(async()=>{return wY(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,Y,Z){let $=[];if(!wY(Q))return $;if(Y||Z){let X=this.generateNamePatterns(Y||"",Z);for(let J of X)for(let G of this.extensions){let U=yZ(Q,`${J}${G}`);if(await this.checkFileAccess(U))$.push(U)}}else try{let{readdirSync:X}=await import("fs"),J=X(Q);for(let G of J)if(this.looksLikeConfigFile(G)){let U=yZ(Q,G);if(await this.checkFileAccess(U))$.push(U)}}catch{return[]}return $}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Z)=>Z.test(Q))}async validateConfigFile(Q){let Y=[];try{if(!wY(Q))return Y.push("Configuration file does not exist"),Y;let Z=await import(Q),$=Z.default||Z;if($===void 0)Y.push("Configuration file must export a default value or named exports");else if(typeof $!=="object"||$===null)Y.push("Configuration must be an object");else if(Array.isArray($))Y.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(Q,"utf8");JSON.parse(J)}catch(X){Y.push(`Invalid JSON syntax: ${X}`)}}catch(Z){Y.push(`Failed to load configuration file: ${Z}`)}return Y}async getFileModificationTime(Q){try{let{statSync:Y}=await import("fs");return Y(Q).mtime}catch{return null}}async preloadConfigurations(Q,Y={}){let Z=new Map;return await Promise.allSettled(Q.map(async($)=>{try{let X=await this.loadFromPath($,{},Y);if(X)Z.set($,X.config)}catch(X){if(Y.verbose)console.warn(`Failed to preload ${$}:`,X)}})),Z}}class _8{async validateConfiguration(Q,Y,Z={}){let{stopOnFirstError:$=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:G=[],trackPerformance:U=!0,verbose:W=!1}=Z,z=async()=>{let H=[],_=[],A={stopOnFirstError:$,validateRequired:X,validateTypes:J,customRules:G,trackPerformance:U,verbose:W};try{if(typeof Y==="string")return await this.validateWithSchemaFile(Q,Y,A);else if(Array.isArray(Y))return this.validateWithRules(Q,[...Y,...G],A);else return this.validateWithJSONSchema(Q,Y,A)}catch(B){return H.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:H,warnings:_}}};if(U)return await JY.track("validateConfiguration",z);return z()}async validateWithSchemaFile(Q,Y,Z){try{if(!k0(Y))throw new XY(Y,[{path:"",message:"Schema file does not exist"}]);let $=await import(Y),X=$.default||$;if(Array.isArray(X))return this.validateWithRules(Q,X,Z);else return this.validateWithJSONSchema(Q,X,Z)}catch($){throw new XY(Y,[{path:"",message:`Failed to load schema: ${$}`}])}}validateWithJSONSchema(Q,Y,Z){let $=[],X=[];return this.validateObjectAgainstSchema(Q,Y,"",$,X,Z),{isValid:$.length===0,errors:$,warnings:X}}validateObjectAgainstSchema(Q,Y,Z,$,X,J){if(J.validateTypes&&Y.type){let G=Array.isArray(Q)?"array":typeof Q,U=Array.isArray(Y.type)?Y.type:[Y.type];if(!U.includes(G)){if($.push({path:Z,message:`Expected type ${U.join(" or ")}, got ${G}`,expected:U.join(" or "),actual:G,rule:"type"}),J.stopOnFirstError)return}}if(Y.enum&&!Y.enum.includes(Q)){if($.push({path:Z,message:`Value must be one of: ${Y.enum.join(", ")}`,expected:Y.enum.join(", "),actual:Q,rule:"enum"}),J.stopOnFirstError)return}if(typeof Q==="string"){if(Y.minLength!==void 0&&Q.length<Y.minLength)$.push({path:Z,message:`String length must be at least ${Y.minLength}`,expected:`>= ${Y.minLength}`,actual:Q.length,rule:"minLength"});if(Y.maxLength!==void 0&&Q.length>Y.maxLength)$.push({path:Z,message:`String length must not exceed ${Y.maxLength}`,expected:`<= ${Y.maxLength}`,actual:Q.length,rule:"maxLength"});if(Y.pattern){if(!new RegExp(Y.pattern).test(Q))$.push({path:Z,message:`String does not match pattern ${Y.pattern}`,expected:Y.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(Y.minimum!==void 0&&Q<Y.minimum)$.push({path:Z,message:`Value must be at least ${Y.minimum}`,expected:`>= ${Y.minimum}`,actual:Q,rule:"minimum"});if(Y.maximum!==void 0&&Q>Y.maximum)$.push({path:Z,message:`Value must not exceed ${Y.maximum}`,expected:`<= ${Y.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&Y.items)for(let G=0;G<Q.length;G++){let U=Z?`${Z}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema(Q[G],Y.items,U,$,X,J),J.stopOnFirstError&&$.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let G=Q;if(J.validateRequired&&Y.required){for(let U of Y.required)if(!(U in G)){if($.push({path:Z?`${Z}.${U}`:U,message:`Missing required property '${U}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(Y.properties){for(let[U,W]of Object.entries(Y.properties))if(U in G){let z=Z?`${Z}.${U}`:U;if(this.validateObjectAgainstSchema(G[U],W,z,$,X,J),J.stopOnFirstError&&$.length>0)return}}if(Y.additionalProperties===!1){let U=new Set(Object.keys(Y.properties||{}));for(let W of Object.keys(G))if(!U.has(W))X.push({path:Z?`${Z}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,Y,Z){let $=[],X=[];for(let J of Y)try{let G=this.getValueByPath(Q,J.path),U=this.validateWithRule(G,J,J.path);if($.push(...U),Z.stopOnFirstError&&$.length>0)break}catch(G){$.push({path:J.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:$.length===0,errors:$,warnings:X}}validateWithRule(Q,Y,Z){let $=[];if(Y.required&&(Q===void 0||Q===null))return $.push({path:Z,message:Y.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),$;if(Q===void 0||Q===null)return $;if(Y.type){let X=Array.isArray(Q)?"array":typeof Q;if(X!==Y.type)$.push({path:Z,message:Y.message||`Expected type ${Y.type}, got ${X}`,expected:Y.type,actual:X,rule:"type"})}if(Y.min!==void 0){let X=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if(X<Y.min)$.push({path:Z,message:Y.message||`Value must be at least ${Y.min}`,expected:`>= ${Y.min}`,actual:X,rule:"min"})}if(Y.max!==void 0){let X=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if(X>Y.max)$.push({path:Z,message:Y.message||`Value must not exceed ${Y.max}`,expected:`<= ${Y.max}`,actual:X,rule:"max"})}if(Y.pattern&&typeof Q==="string"){if(!Y.pattern.test(Q))$.push({path:Z,message:Y.message||`Value does not match pattern ${Y.pattern}`,expected:Y.pattern.toString(),actual:Q,rule:"pattern"})}if(Y.enum&&!Y.enum.includes(Q))$.push({path:Z,message:Y.message||`Value must be one of: ${Y.enum.join(", ")}`,expected:Y.enum.join(", "),actual:Q,rule:"enum"});if(Y.validator){let X=Y.validator(Q);if(X)$.push({path:Z,message:Y.message||X,rule:"custom"})}return $}getValueByPath(Q,Y){if(!Y)return Q;let Z=Y.split("."),$=Q;for(let X of Z)if($&&typeof $==="object"&&X in $)$=$[X];else return;return $}generateRulesFromInterface(Q){let Y=[],Z=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let $ of Z){let[,X,J,G]=$;Y.push({path:X,required:!J,type:this.mapTypeScriptType(G)})}return Y}mapTypeScriptType(Q){switch(Q.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:a9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class A8{fileLoader=new rY;envProcessor=new tY;validator=new _8;async loadConfig(Q){let Y=Date.now(),{cache:Z,performance:$,schema:X,validate:J,...G}=Q;try{if(Z?.enabled){let W=this.checkCache(G.name||"",G);if(W)return W}let U;try{U=await this.loadConfigurationStrategies(G,!0,Z)}catch(W){let z=G.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(z)throw W;U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`No configuration file found for "${G.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let H=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),_=!H&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),A=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(z&&(A||H))throw W;if(_&&(!z||!A))U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!z)U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(U.config,X,J,G.name);if(Z?.enabled&&U)this.cacheResult(G.name||"",U,Z,G);if($?.enabled){let W={operation:"loadConfig",duration:Date.now()-Y,configName:G.name,timestamp:new Date};if($.onMetrics)$.onMetrics(W);if($.slowThreshold&&W.duration>$.slowThreshold)ZQ.warn(`Slow configuration loading detected: ${W.duration}ms for ${G.name}`);U.metrics=W}return U}catch(U){let W=Date.now()-Y;throw ZQ.error(`Configuration loading failed after ${W}ms:`,[U instanceof Error?U:Error(String(U))]),U}}async loadConfigurationStrategies(Q,Y=!1,Z){let{name:$="",alias:X,cwd:J,configDir:G,defaultConfig:U,checkEnv:W=!0,arrayStrategy:z="replace",verbose:H=!1}=Q,_=J||VQ.cwd(),A=[],B=await this.loadLocalConfiguration($,X,_,G,U,z,H,W,Z);if(B)return A.push(...this.getLocalSearchPaths($,X,_,G)),this.finalizeResult(B,A,W,$,H);let L=await this.loadHomeConfiguration($,X,U,z,H,W);if(L)return A.push(...this.getHomeSearchPaths($,X)),this.finalizeResult(L,A,W,$,H);let R=await this.loadPackageJsonConfiguration($,X,_,U,z,H,W);if(R)return A.push(p(_,"package.json")),this.finalizeResult(R,A,W,$,H);if(A.push(...this.getAllSearchPaths($,X,_,G)),Y)throw FQ.configNotFound($,A,X);return{...await this.applyEnvironmentVariables($,U,W,H),warnings:[`No configuration file found for "${$}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,Y,Z,$,X,J,G,U,W){let z=U?YY(Q,X,G):X,H=this.getLocalDirectories(Z,$);for(let _ of H){if(G)ZQ.info(`Searching for configuration in: ${_}`);let A=this.fileLoader.generateConfigPaths(Q,_,Y),B=await this.fileLoader.tryLoadFromPaths(A,z,{arrayStrategy:J,verbose:G,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(B){if(G)ZQ.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration(Q,Y,Z,$,X,J){if(!Q)return null;let G=J?YY(Q,Z,X):Z,U=[p(OQ(),".config",Q),p(OQ(),".config"),OQ()];for(let W of U){if(X)ZQ.info(`Checking home directory: ${W}`);let z=this.fileLoader.generateConfigPaths(Q,W,Y),H=await this.fileLoader.tryLoadFromPaths(z,G,{arrayStrategy:$,verbose:X});if(H){if(X)ZQ.success(`Configuration loaded from home directory: ${H.source.path}`);return H}}return null}async loadPackageJsonConfiguration(Q,Y,Z,$,X,J,G){let U=G?YY(Q,$,J):$;try{let W=p(Z,"package.json");if(!iZ(W))return null;let z=await import(W),H=z[Q],_=Q;if(!H&&Y)H=z[Y],_=Y;if(H&&typeof H==="object"&&!Array.isArray(H)){if(J)ZQ.success(`Configuration loaded from package.json: ${_}`);return{config:H8(U,H,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)ZQ.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(Q,Y,Z,$){if(!Z||!Q||typeof Y!=="object"||Y===null||Array.isArray(Y))return{config:Y,source:{type:"default",priority:10,timestamp:new Date}};return{config:YY(Q,Y,$),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,Y,Z,$,X){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,Y,Z,$){let X=[];if(Z){let J=Z(Q);if(J)X.push(...J)}if(Y){let J=await this.validator.validateConfiguration(Q,Y);if(!J.isValid)X.push(...J.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if(X.length>0)throw FQ.configValidation($||"unknown",X,$)}checkCache(Q,Y){let Z=this.generateCacheKey(Q,Y);return yQ.get(Z)||null}cacheResult(Q,Y,Z,$){let X=this.generateCacheKey(Q,$);yQ.set(X,Y,void 0,Z.ttl)}generateCacheKey(Q,Y){let Z=[Q];if(Y.alias)Z.push(`alias:${Y.alias}`);if(Y.cwd)Z.push(`cwd:${Y.cwd}`);if(Y.configDir)Z.push(`configDir:${Y.configDir}`);if("checkEnv"in Y)Z.push(`checkEnv:${Y.checkEnv}`);return Z.join("|")}getLocalDirectories(Q,Y){return Array.from(new Set([Q,p(Q,"config"),p(Q,".config"),Y?p(Q,Y):void 0].filter(Boolean)))}getAllSearchPaths(Q,Y,Z,$){let X=[];return X.push(...this.getLocalSearchPaths(Q,Y,Z,$)),X.push(...this.getHomeSearchPaths(Q,Y)),X.push(p(Z,"package.json")),X}getLocalSearchPaths(Q,Y,Z,$){let X=this.getLocalDirectories(Z,$),J=[];for(let G of X)J.push(...this.fileLoader.generateConfigPaths(Q,G,Y));return J}getHomeSearchPaths(Q,Y){if(!Q)return[];let Z=[p(OQ(),".config",Q),p(OQ(),".config"),OQ()],$=[];for(let X of Z)$.push(...this.fileLoader.generateConfigPaths(Q,X,Y));return $}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function M9(Q){let Z=!(Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"))&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")),$=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");return Z||$}async function FX(Q){return AQ.loadConfig({...Q,__strictErrorHandling:!0})}async function c9(Q){let Y="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Z="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let $;if(Z)$=await AQ.loadConfig(Q);else $=await AQ.loadConfig({...Q,defaultConfig:Y,cache:{enabled:!0},performance:{enabled:!1}});return $?.config??Y}catch($){let X=$ instanceof Error?$.name:"UnknownError",J=$ instanceof Error?$.message:String($);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&Q.verbose)ZQ.warn("Unexpected error loading config, using defaults:",[$ instanceof Error?$:Error(String($))]);let U=Z?{...Q,defaultConfig:Y}:{...Q,defaultConfig:Y,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await AQ.applyEnvironmentVariables(U.name||"",Y,!0,U.verbose||!1))?.config??Y;return Y}}async function MX(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:Y}=await import("process");try{return(await AQ.loadConfig({name:Q,cwd:Y(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&M9(Z)))return(await AQ.applyEnvironmentVariables(Q,{},!0,!1)).config;throw Z}}try{return(await AQ.loadConfig({...Q,cwd:Q.cwd||VQ.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&M9(Y)))return(await AQ.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw Y}}async function IX(Q,Y,Z="replace"){let $=new rY;try{let X=await $.loadFromPath(Q,Y,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function YY(Q,Y,Z=!1){let $=new tY,X=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(G,U=[]){let W={...G};for(let[z,H]of Object.entries(G)){let _=[...U,z],A=[`${X}_${_.join("_").toUpperCase()}`,`${X}_${_.map((R)=>R.toUpperCase()).join("")}`,`${X}_${_.map((R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,L;for(let R of A)if(B=VQ.env[R],B!==void 0){L=R;break}if(B!==void 0&&L)if(typeof H==="boolean")W[z]=["true","1","yes"].includes(B.toLowerCase());else if(typeof H==="number"){let R=Number(B);if(!Number.isNaN(R))W[z]=R}else if(Array.isArray(H))try{W[z]=JSON.parse(B)}catch{W[z]=B.split(",").map((R)=>R.trim())}else W[z]=B;else if(H&&typeof H==="object"&&!Array.isArray(H))W[z]=J(H,_)}return W}return J(Y)}function VX(Q){let Y=p(VQ.cwd(),Q.configDir),Z=p(VQ.cwd(),Q.generatedDir),$=p(Z,"config-types.ts");if(!iZ(a8($)))z0(a8($),{recursive:!0,mode:511});let X=iZ(Y)?H0(Y).map((G)=>G.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${aX}
32
- export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
33
- `;_0($,J,{mode:438})}function DX(Q){let Y=null,Z=null,$=()=>{if(!Z)Z=c9(Q).then((J)=>{return Y=J,J},(J)=>{let G="defaultConfig"in Q?Q.defaultConfig:{};if(Y=G,"verbose"in Q&&Q.verbose)ZQ.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return G});return Z},X="defaultConfig"in Q?Q.defaultConfig:{};return Y=X,$(),new Proxy({},{get(J,G){if(Y)return Y[G];let U=X[G];return $(),U},has(J,G){return G in(Y||X)},ownKeys(){return Object.keys(Y||X)},getOwnPropertyDescriptor(J,G){return Object.getOwnPropertyDescriptor(Y||X,G)},set(J,G,U){if(!Y)Y={...X};return Y[G]=U,!0}})}function wX(Q){let Y=_9(y0.cwd(),Q?.configDir||"./config");function Z(){if(!P0(Y))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],G=b0(Y).filter((W)=>X.has(vZ(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),U=new Map;for(let{base:W,file:z}of G){let H=vZ(z).toLowerCase(),_=U.get(W);if(!_){U.set(W,z);continue}let A=vZ(_).toLowerCase();if(J.indexOf(H)<J.indexOf(A))U.set(W,z)}return Array.from(U.entries()).map(([W,z])=>({base:W,file:z})).sort((W,z)=>W.base.localeCompare(z.base))}function $(){let X=Z(),J=X.map((z)=>z.base),G=J.length?J.map((z)=>`'${z}'`).join(" | "):"string",U=X.length?`{
34
- ${X.map((z)=>{let H=_9(Y,z.file).replace(/\\/g,"/");return` '${z.base}': typeof import('${H}').default`}).join(`,
35
- `)}
36
- }`:"Record<string, any>";return`export type ConfigNames = ${G}
37
- export type ConfigByName = ${U}
38
- export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
- export type ConfigOf = Config
40
- `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:$(),loader:"ts"}})}}}var l9,yQ,JY,n9,EX,OX,I9,kY,aZ,d,q,qX,V9,TX,D9,NX,SX,mZ,CX,w9,E9,gZ,xX,kX,PX,bX,PY,i9,yX,f,vX,hX,O9,bY,tZ,x,V,dX,q9,fX,T9,mX,gX,pZ,pX,N9,S9,uX,uZ,cX,lX,nX,iX,sX,yY,s9,oX,aX="0.15.6",n,lY,$Y,rZ,eZ,nY,Q8,Y8,XY,Z8,$8,FQ,o9,a9,ZQ,AQ,t9,r9,tX=t0(async()=>{l9=import.meta.require,yQ=new G8,JY=new W8,n9={createKey:r0,isEquivalent:e0,estimateMemoryUsage:QX},EX=fY(sZ.cwd(),"config"),OX=fY(sZ.cwd(),"src/generated"),I9=dY.env.CLARITY_LOG_DIR||R0($X(),"logs"),kY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:I9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},aZ=await XX(),d={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,reset:"\x1B[0m"},q=d,qX=d.red,V9=d.green,TX=d.yellow,D9=d.blue,NX=d.magenta,SX=d.cyan,mZ=d.white,CX=d.gray,w9=d.bgRed,E9=d.bgYellow,gZ=d.bold,xX=d.dim,kX=d.italic,PX=d.underline,bX=d.reset,PY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},i9={debug:"\uD83D\uDD0D",info:D9("\u2139"),success:V9("\u2713"),warning:E9(mZ(gZ(" WARN "))),error:w9(mZ(gZ(" ERROR ")))},yX=new pY("stacks"),f=new pY("bunfig",{showTags:!0}),vX=g(ZY.cwd(),"config"),hX=g(ZY.cwd(),"src/generated"),O9=hY.env.CLARITY_LOG_DIR||A0(UX(),"logs"),bY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:O9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},tZ=await zX(),x={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},V=x,dX=x.red,q9=x.green,fX=x.yellow,T9=x.blue,mX=x.magenta,gX=x.cyan,pZ=x.white,pX=x.gray,N9=x.bgRed,S9=x.bgYellow,uX=x.bgGray,uZ=x.bold,cX=x.dim,lX=x.italic,nX=x.underline,iX=x.strikethrough,sX=x.reset,yY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},s9={debug:"\uD83D\uDD0D",info:T9("\u2139"),success:q9("\u2713"),warning:S9(pZ(uZ(" WARN "))),error:N9(pZ(uZ(" ERROR ")))},oX=new cY("stacks"),n=class extends Error{timestamp;context;constructor(Y,Z={}){super(Y);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Z,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 Y=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Z,$])=>`${Z}: ${$}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Y}`}},lY=class extends n{code="CONFIG_NOT_FOUND";constructor(Y,Z,$){let X=$?` or alias "${$}"`:"";super(`Configuration "${Y}"${X} not found`,{configName:Y,alias:$,searchPaths:Z,searchPathCount:Z.length})}},$Y=class extends n{code="CONFIG_LOAD_ERROR";constructor(Y,Z,$){super(`Failed to load configuration from "${Y}": ${Z.message}`,{configPath:Y,configName:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},rZ=class extends n{code="CONFIG_VALIDATION_ERROR";constructor(Y,Z,$){super(`Configuration validation failed for "${Y}"`,{configPath:Y,configName:$,validationErrors:Z,errorCount:Z.length})}},eZ=class extends n{code="CONFIG_MERGE_ERROR";constructor(Y,Z,$,X){super(`Failed to merge configuration from "${Y}" with "${Z}": ${$.message}`,{sourcePath:Y,targetPath:Z,configName:X,originalError:$.name,originalMessage:$.message});this.cause=$}},nY=class extends n{code="ENV_VAR_ERROR";constructor(Y,Z,$,X){super(`Failed to parse environment variable "${Y}" with value "${Z}" as ${$}`,{envKey:Y,envValue:Z,expectedType:$,configName:X})}},Q8=class extends n{code="FILE_SYSTEM_ERROR";constructor(Y,Z,$){super(`File system ${Y} failed for "${Z}": ${$.message}`,{operation:Y,path:Z,originalError:$.name,originalMessage:$.message});this.cause=$}},Y8=class extends n{code="TYPE_GENERATION_ERROR";constructor(Y,Z,$){super(`Failed to generate types from "${Y}" to "${Z}": ${$.message}`,{configDir:Y,outputPath:Z,originalError:$.name,originalMessage:$.message});this.cause=$}},XY=class extends n{code="SCHEMA_VALIDATION_ERROR";constructor(Y,Z,$){super(`Schema validation failed${$?` for config "${$}"`:""}`,{schemaPath:Y,configName:$,validationErrors:Z,errorCount:Z.length})}},Z8=class extends n{code="BROWSER_CONFIG_ERROR";constructor(Y,Z,$,X){super(`Failed to fetch configuration from "${Y}": ${Z} ${$}`,{endpoint:Y,status:Z,statusText:$,configName:X})}},$8=class extends n{code="PLUGIN_ERROR";constructor(Y,Z,$){super(`Plugin "${Y}" failed during ${Z}: ${$.message}`,{pluginName:Y,operation:Z,originalError:$.name,originalMessage:$.message});this.cause=$}},FQ={configNotFound(Q,Y,Z){return new lY(Q,Y,Z)},configLoad(Q,Y,Z){return new $Y(Q,Y,Z)},configValidation(Q,Y,Z){return new rZ(Q,Y,Z)},configMerge(Q,Y,Z,$){return new eZ(Q,Y,Z,$)},envVar(Q,Y,Z,$){return new nY(Q,Y,Z,$)},fileSystem(Q,Y,Z){return new Q8(Q,Y,Z)},typeGeneration(Q,Y,Z){return new Y8(Q,Y,Z)},schemaValidation(Q,Y,Z){return new XY(Q,Y,Z)},browserConfig(Q,Y,Z,$){return new Z8(Q,Y,Z,$)},plugin(Q,Y,Z){return new $8(Q,Y,Z)}},o9={replace:"replace",concat:"concat",smart:"smart"},a9=/^https?:\/\//,ZQ=new cY("bunfig",{showTags:!0}),AQ=new A8,t9=p(VQ.cwd(),"config"),r9=p(VQ.cwd(),"src/generated")});function rX(Q,Y={}){let Z=mY.cwd();while(Z.includes("storage"))Z=A9(Z,"..");let $=A9(Z,Q||"");if(Y?.relative)return h0(mY.cwd(),$);return $}var eX=mY.env.CLARITY_LOG_DIR||v0(rX(),"logs"),e9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:eX,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},iY={...e9},T1=(async()=>{try{let{loadConfig:Q}=await tX().then(()=>v9),Y=await Q({name:"clarity",alias:"logging",defaultConfig:e9,cwd:mY.cwd()});if(Y)Object.assign(iY,Y)}catch{}return iY})();function k(){if(_Q.env.NODE_ENV==="test"||_Q.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function QJ(){if(_Q.env.NODE_ENV==="test"||_Q.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof _Q<"u"){let Q=_Q.type;if(Q==="renderer"||Q==="worker")return!1;return!!(_Q.versions&&(_Q.versions.node||_Q.versions.bun))}return!1}class Q${async format(Q){let Y=await QJ(),Z=await this.getMetadata(Y);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Z})}async getMetadata(Q){if(Q){let{hostname:Y}=await import("os");return{pid:bQ.pid,hostname:Y(),environment:bQ.env.NODE_ENV||"development",platform:bQ.platform,version:bQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:bQ.env.NODE_ENV||bQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var v={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},E=v,N1=v.red,YJ=v.green,S1=v.yellow,ZJ=v.blue,C1=v.magenta,x1=v.cyan,C9=v.white,k1=v.gray,$J=v.bgRed,XJ=v.bgYellow,P1=v.bgGray,x9=v.bold,b1=v.dim,y1=v.italic,v1=v.underline,h1=v.strikethrough,d1=v.reset,cZ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},JJ={debug:"\uD83D\uDD0D",info:ZJ("\u2139"),success:YJ("\u2713"),warning:XJ(C9(x9(" WARN "))),error:$J(C9(x9(" ERROR ")))};class eY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,Y={}){this.name=Q,this.config={...iY},this.options=this.normalizeOptions(Y),this.formatter=this.options.formatter||new Q$,this.enabled=Y.enabled??!0,this.fancy=Y.fancy??!0,this.tagFormat=Y.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Y.timestampPosition??"right",this.environment=Y.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Y);let Z={...Y},$=Y.timestamp!==void 0;if($)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:$||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let Y={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return Y[Q]>=Y[Z]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...cZ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...cZ};return{...cZ,...Q.fingersCrossed}}normalizeOptions(Q){let Y={format:"json",level:"info",logDirectory:iY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...Y,...Object.fromEntries(Object.entries(Q).filter(([,$])=>$!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=Y.level;return Z}shouldWriteToFile(){return!k()&&this.config.writeToFile===!0}async writeToFile(Q){let Z=(async()=>{let X,J=0,G=3,U=1000;while(J<G)try{try{try{await p0(this.config.logDirectory,j9.F_OK|j9.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await u0(this.config.logDirectory,{recursive:!0,mode:493});else if(z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw z;else throw z}}catch(z){throw console.error("Debug: [writeToFile] Failed to create log directory:",z),z}let W=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:UQ.from(Q);try{if(!EY(this.currentLogFile))await fZ(this.currentLogFile,"",{mode:420});if(X=L9(this.currentLogFile,"a",420),g0(X,W,{flag:"a"}),R9(X),X!==void 0)dZ(X),X=void 0;if((await kQ(this.currentLogFile)).size===0){if(await fZ(this.currentLogFile,W,{flag:"w",mode:420}),(await kQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let H=z;if(H.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(H.code)){if(J<G-1){let _=typeof H.message==="string"?H.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${G}:`,_);let A=U*2**J;await new Promise((B)=>setTimeout(B,A)),J++;continue}}if(H?.code&&["ENOSPC","EDQUOT"].includes(H.code))throw Error(`Disk quota exceeded or no space left on device: ${H.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",H),H}finally{if(X!==void 0)try{dZ(X)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(W){if(J===G-1){let H=W,_=typeof H.message==="string"?H.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),W}J++;let z=U*2**(J-1);await new Promise((H)=>setTimeout(H,z))}})();this.pendingOperations.push(Z);let $=this.pendingOperations.length-1;try{await Z}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice($,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 PQ(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 PQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return PQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(k())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,Y;switch(Q.frequency){case"daily":Y=86400000;break;case"weekly":Y=604800000;break;case"monthly":Y=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Y)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Y=this.config.rotation.keyRotation;if(!Y?.enabled)return;let Z=typeof Y.interval==="number"?Y.interval:60,$=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},$)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Y=this.config.rotation.keyRotation,Z=this.generateKeyId(),$=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,$),this.encryptionKeys.set(Z,{key:$,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),J=typeof Y.maxKeys==="number"?Y.maxKeys:1,G=Math.max(1,J);if(X.length>G)for(let[U]of X.slice(G))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return hZ(16).toString("hex")}generateKey(){return hZ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:Y}=this.getCurrentKey(),Z=hZ(16),$=d0("aes-256-gcm",Y,Z),X=UQ.isBuffer(Q)?Q:UQ.from(Q,"utf8"),J=$.update(X),G=$.final(),U=J.length+G.length,W=$.getAuthTag(),z=UQ.allocUnsafe(16+U+16);return Z.copy(z,0),J.copy(z,16),G.copy(z,16+J.length),W.copy(z,16+U),{encrypted:z,iv:Z}}async compressData(Q){return new Promise((Y,Z)=>{let $=F9(),X=[];$.on("data",(J)=>X.push(J)),$.on("end",()=>Y(UQ.from(UQ.concat(X)))),$.on("error",Z),$.write(Q),$.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Y=this.config.rotation.encrypt;return{...Q,...Y}}return Q}async rotateLog(){if(k())return;if(!this.shouldWriteToFile())return;let Q=await kQ(this.currentLogFile).catch(()=>null);if(!Q)return;let Y=this.config.rotation;if(typeof Y==="boolean")return;if(Y.maxSize&&Q.size>=Y.maxSize){let Z=this.currentLogFile,$=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await OY(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,z)=>{let H=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-H}),G=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,U=`${Z}.${G}`;if(await kQ(Z).catch(()=>null))try{if(await K9(Z,U),Y.compress)try{let W=`${U}.gz`;await this.compressLogFile(U,W),await qY(U)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Z}.1`;await fZ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Z.replace(/\.log$/,`-${X}.log`);if(await kQ(Z).catch(()=>null))await K9(Z,J)}if(this.currentLogFile=$,Y.maxFiles){let J=(await OY(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,U)=>U.localeCompare(G));for(let G of J.slice(Y.maxFiles))await qY(PQ(this.config.logDirectory,G))}}}async compressLogFile(Q,Y){let Z=B9(Q),$=m0(Y),X=F9();await n0(Z,X,$)}async handleFingersCrossedBuffer(Q,Y){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let $=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}}shouldLog(Q){if(!this.enabled)return!1;let Y={debug:0,info:1,success:2,warning:3,error:4};return Y[Q]>=Y[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((Y)=>{console.error("Error in pending write operation:",Y)});return Promise.resolve()})),EY(this.currentLogFile))try{let Q=L9(this.currentLogFile,"r+");R9(Q),dZ(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Y=(await OY(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of Y)try{await qY(PQ(this.config.logDirectory,Z))}catch($){console.error(`Failed to delete temp file ${Z}:`,$)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?E.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||k())return!1;let Q=typeof M.env.NO_COLOR<"u",Y=M.env.FORCE_COLOR==="0";if(Q||Y)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:Y,icon:Z="",tag:$="",message:X,level:J,showTimestamp:G=!0}=Q,U=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(G)B.push(Y);if(J==="warning")B.push("WARN");else if(J==="error")B.push("ERROR");else if(Z)B.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if($)B.push($.replace(/[[\]]/g,""));return B.push(X),B.join(" ")}let W=M.stdout.columns||120,z="";if(J==="warning"||J==="error")z=`${Z} ${X}`;else if(J==="info"||J==="success")z=`${Z} ${$} ${X}`;else z=`${Z} ${$} ${E.cyan(X)}`;if(!G)return z.trim();let H=U(z).trim().length,_=U(Y).length,A=Math.max(1,W-2-H-_);return`${z.trim()}${" ".repeat(A)}${Y}`}formatMessage(Q,Y){if(Y.length===1&&Array.isArray(Y[0]))return Q.replace(/\{(\d+)\}/g,(J,G)=>{let U=Number.parseInt(G,10);return U<Y[0].length?String(Y[0][U]):J});let Z=/%([sdijfo%])/g,$=0,X=Q.replace(Z,(J,G)=>{if(G==="%")return"%";if($>=Y.length)return J;let U=Y[$++];switch(G){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 J}});if($<Y.length)X+=` ${Y.slice($).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(Q){if(!Q)return Q;let Y=Q;return Y=Y.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,$,X)=>{let J=E.underline(E.blue($)),G=this.toAbsoluteFilePath(X);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let U=`file://${encodeURI(G)}`,W="\x1B]8;;",z="\x1B\\";return`\x1B]8;;${U}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),Y=Y.replace(/`([^`]+)`/g,(Z,$)=>E.bgGray($)),Y=Y.replace(/\*\*([^*]+)\*\*/g,(Z,$)=>E.bold($)),Y=Y.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,$)=>E.italic($)),Y=Y.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,$)=>E.italic($)),Y=Y.replace(/~([^~]+)~/g,(Z,$)=>E.strikethrough($)),Y}supportsHyperlinks(){if(k())return!1;let Q=M.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let Y=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(Y)&&Y>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let Y=Q;if(Y.startsWith("file://"))Y=Y.replace(/^file:\/\//,"");if(Y.startsWith("~")){let Z=M.env.HOME||"";if(Z)Y=Y.replace(/^~(?=$|\/)/,Z)}if(c0(Y)||Y.startsWith("./")||Y.startsWith("../"))Y=l0(Y);else return null;return EY(Y)?Y:null}catch{return null}}buildOutputTexts(Q){let Y=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Z=Q.replace(this.ANSI_PATTERN,"");return{consoleText:Y,fileText:Z}}async log(Q,Y,...Z){if(!this.shouldLog(Q))return;let $=new Date,X=this.formatConsoleTimestamp($),J=this.formatFileTimestamp($),G,U;if(Y instanceof Error)G=Y.message,U=Y.stack;else G=this.formatMessage(Y,Z);let{consoleText:W,fileText:z}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let _=this.options.showIcons===!1?"":JJ[Q],A=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",B;switch(Q){case"debug":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:E.gray(W),level:Q}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:W,level:Q}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:E.green(W),level:Q}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:W,level:Q}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:W,level:Q}),console.error(B),U){let L=U.split(`
41
- `);for(let R of L)if(R.trim()&&!R.includes(G))console.error(this.formatConsoleMessage({timestamp:X,message:E.gray(` ${R}`),level:Q,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${J} ${this.environment}.${Q.toUpperCase()}: ${G}`),U)console.error(U)}let H=`${J} ${this.environment}.${Q.toUpperCase()}: ${z}
42
- `;if(U)H+=`${U}
43
- `;if(H=H.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(H)}progress(Q,Y=""){let Z={update:(U,W)=>{},finish:(U)=>{},interrupt:(U,W)=>{}};if(!this.enabled)return Z;let $=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:Y||"",barLength:$,lastRenderedLine:""},this.shouldStyleConsole()&&!k()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!k()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,W="info")=>{if(!k()&&M.stdout.isTTY)M.stdout.write(`
44
- `);if(this[W==="warning"?"warn":W](U),this.activeProgressBar&&this.shouldStyleConsole()&&!k()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let Y=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",$=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":E.blue("\u25D0"),tag:Z,message:`${E.cyan(Q)}...`}))}return async(Z)=>{if(!this.enabled)return;let $=performance.now(),X=Math.round($-Y),J=`${Q} completed in ${X}ms`,G=new Date,U=this.formatConsoleTimestamp(G),z=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${J}`;if(Z)z+=` ${JSON.stringify(Z)}`;if(z+=`
45
- `,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let H=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:U,icon:this.options.showIcons===!1?"":E.green("\u2713"),tag:H,message:`${J}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!k())console.error(z.trim());if(this.shouldWriteToFile())await this.writeToFile(z)}}async debug(Q,...Y){await this.log("debug",Q,...Y)}async info(Q,...Y){await this.log("info",Q,...Y)}async success(Q,...Y){await this.log("success",Q,...Y)}async warn(Q,...Y){await this.log("warning",Q,...Y)}async error(Q,...Y){await this.log("error",Q,...Y)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:Y}=Q;return!!Y}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let Y=`${this.name}:${Q}`,Z=new eY(Y,{...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(Z),Z}createReadStream(){if(k())throw Error("createReadStream is not supported in browser environments");if(!EY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return B9(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Y=this.config.rotation;if(!Y.encrypt||typeof Y.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Z=this.keys.get(this.currentKeyId);try{let $=UQ.isBuffer(Q)?Q:UQ.from(Q,"base64"),X=$.subarray(0,16),J=$.subarray($.length-16),G=$.subarray(16,$.length-16),U=f0("aes-256-gcm",Z,X);U.setAuthTag(J);let W=U.update(G),z=U.final(),H=W.length+z.length,_=UQ.allocUnsafe(H);return W.copy(_,0),z.copy(_,W.length),_.toString("utf8")}catch($){throw Error(`Decryption failed: ${$ instanceof Error?$.message:String($)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return k()}isServerMode(){return!k()}setTestEncryptionKey(Q,Y){this.currentKeyId=Q,this.keys.set(Q,Y)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let Y=new Date,Z=this.formatConsoleTimestamp(Y),$=this.formatFileTimestamp(Y),{consoleText:X,fileText:J}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let U=X.split(`
46
- `),W=Math.max(...U.map((A)=>A.length))+2,z=`\u250C${"\u2500".repeat(W)}\u2510`,H=`\u2514${"\u2500".repeat(W)}\u2518`,_=U.map((A)=>{return this.formatConsoleMessage({timestamp:Z,message:E.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:E.cyan(z),showTimestamp:!1})),_.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:Z,message:E.cyan(H),showTimestamp:!1}))}else if(!k())console.error(`${$} ${this.environment}.INFO: [BOX] ${J}`);let G=`${$} ${this.environment}.INFO: [BOX] ${J}
47
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(k())return Promise.resolve(!0);return new Promise((Y)=>{console.error(`${E.cyan("?")} ${Q} (y/n) `);let Z=($)=>{let X=$.toString().trim().toLowerCase();M.stdin.removeListener("data",Z);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),Y(X==="y"||X==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",Z)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...Y){if(!this.enabled)return;let Z=Q;if(Y&&Y.length>0){let W=/%([sdijfo%])/g,z=0;if(Z=Q.replace(W,(H,_)=>{if(_==="%")return"%";if(z>=Y.length)return H;let A=Y[z++];switch(_){case"s":return String(A);case"d":case"i":return Number(A).toString();case"j":case"o":return JSON.stringify(A,null,2);default:return H}}),z<Y.length)Z+=` ${Y.slice(z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`}let{consoleText:$,fileText:X}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?E.gray(this.formatTag(this.name)):"",z=this.options.showIcons===!1?"":`${E.blue("\u25D0")} `;console.error(`${z}${W} ${E.cyan($)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
48
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}renderProgressBar(Q,Y=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),$=Math.round(Q.barLength*Z/100),X=Q.barLength-$,J=E.green("\u2501".repeat($)),G=E.gray("\u2501".repeat(X)),U=`[${J}${G}]`,W=`${Z}%`.padStart(4),z=Q.message?` ${Q.message}`:"",H=this.options.showIcons===!1?"":Y||Z===100?E.green("\u2713"):E.blue("\u25B6"),_=this.options.showTags!==!1&&this.name?` ${E.gray(this.formatTag(this.name))}`:"",A=`\r${H}${_} ${U} ${W}${z}`,B=M.stdout.columns||80,L=" ".repeat(Math.max(0,B-A.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${A}${L}`,M.stdout.write(Q.lastRenderedLine),Y)M.stdout.write(`
49
- `)}finishProgressBar(Q,Y){if(!this.enabled||!this.fancy||k()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(Y)Q.message=Y;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Y=await OY(this.config.logDirectory),Z=[];for(let $ of Y){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test($):$.startsWith(this.name))||!$.endsWith(".log"))continue;let J=PQ(this.config.logDirectory,$);if(Q.before)try{if((await kQ(J)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${J}:`,G);continue}Z.push(J)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let $ of Z)try{await qY($),console.warn(`Deleted log file: ${$}`)}catch(X){console.error(`Failed to delete log file ${$}:`,X)}console.warn("Log clearing process finished.")}catch(Y){console.error("Error during log clearing process:",Y)}}}var f1=new eY("stacks");class $Q extends Error{timestamp;context;constructor(Q,Y={}){super(Q);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let Q=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,Z])=>`${Y}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Q}`}}class Y$ extends $Q{code="CONFIG_NOT_FOUND";constructor(Q,Y,Z){let $=Z===void 0?[]:Array.isArray(Z)?Z.filter(Boolean):[Z],X="";if($.length===1)X=` or alias "${$[0]}"`;else if($.length>1)X=` or aliases ${$.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${Q}"${X} not found`,{configName:Q,alias:Z,searchPaths:Y,searchPathCount:Y.length})}}class sY extends $Q{code="CONFIG_LOAD_ERROR";constructor(Q,Y,Z){super(`Failed to load configuration from "${Q}": ${Y.message}`,{configPath:Q,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}}class Z$ extends $Q{code="CONFIG_VALIDATION_ERROR";constructor(Q,Y,Z){super(`Configuration validation failed for "${Q}"`,{configPath:Q,configName:Z,validationErrors:Y,errorCount:Y.length})}}class $$ extends $Q{code="CONFIG_MERGE_ERROR";constructor(Q,Y,Z,$){super(`Failed to merge configuration from "${Q}" with "${Y}": ${Z.message}`,{sourcePath:Q,targetPath:Y,configName:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}}class B8 extends $Q{code="ENV_VAR_ERROR";constructor(Q,Y,Z,$){super(`Failed to parse environment variable "${Q}" with value "${Y}" as ${Z}`,{envKey:Q,envValue:Y,expectedType:Z,configName:$})}}class X$ extends $Q{code="FILE_SYSTEM_ERROR";constructor(Q,Y,Z){super(`File system ${Q} failed for "${Y}": ${Z.message}`,{operation:Q,path:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}}class J$ extends $Q{code="TYPE_GENERATION_ERROR";constructor(Q,Y,Z){super(`Failed to generate types from "${Q}" to "${Y}": ${Z.message}`,{configDir:Q,outputPath:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}}class oY extends $Q{code="SCHEMA_VALIDATION_ERROR";constructor(Q,Y,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:Q,configName:Z,validationErrors:Y,errorCount:Y.length})}}class G$ extends $Q{code="BROWSER_CONFIG_ERROR";constructor(Q,Y,Z,$){super(`Failed to fetch configuration from "${Q}": ${Y} ${Z}`,{endpoint:Q,status:Y,statusText:Z,configName:$})}}class W$ extends $Q{code="PLUGIN_ERROR";constructor(Q,Y,Z){super(`Plugin "${Q}" failed during ${Y}: ${Z.message}`,{pluginName:Q,operation:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}}var vQ={configNotFound(Q,Y,Z){return new Y$(Q,Y,Z)},configLoad(Q,Y,Z){return new sY(Q,Y,Z)},configValidation(Q,Y,Z){return new Z$(Q,Y,Z)},configMerge(Q,Y,Z,$){return new $$(Q,Y,Z,$)},envVar(Q,Y,Z,$){return new B8(Q,Y,Z,$)},fileSystem(Q,Y,Z){return new X$(Q,Y,Z)},typeGeneration(Q,Y,Z){return new J$(Q,Y,Z)},schemaValidation(Q,Y,Z){return new oY(Q,Y,Z)},browserConfig(Q,Y,Z,$){return new G$(Q,Y,Z,$)},plugin(Q,Y,Z){return new W$(Q,Y,Z)}};async function GJ(Q,Y={}){let{maxRetries:Z=3,retryDelay:$=1000,isRetryable:X=()=>!0,fallback:J}=Y,G=Error("Unknown error occurred");for(let U=0;U<=Z;U++)try{return await Q()}catch(W){if(G=W instanceof Error?W:Error(String(W)),U===Z||!X(G))break;if($>0)await new Promise((z)=>setTimeout(z,$))}if(J!==void 0)return J;throw G instanceof Error?G:Error(`Unknown error: ${String(G)}`)}class R8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,Y)=>Y==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let Y=Q.toLowerCase();return["true","1","yes"].includes(Y)}},{name:"number",canParse:(Q,Y)=>Y==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let Y=Number(Q);if(Number.isNaN(Y))throw TypeError(`Cannot parse "${Q}" as number`);return Y}},{name:"array",canParse:(Q,Y)=>Y==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let Y=JSON.parse(Q);if(Array.isArray(Y))return Y}catch{}return Q.split(",").map((Y)=>Y.trim())}},{name:"json",canParse:(Q,Y)=>Y==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(Y){throw Error(`Cannot parse "${Q}" as JSON: ${Y}`)}}}]}async applyEnvironmentVariables(Q,Y,Z={}){let{prefix:$,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:G={},verbose:U=!1,trackPerformance:W=!0}=Z,z=async()=>{if(!Q)return{config:Y,source:{type:"environment",priority:50,timestamp:new Date}};let H=$||this.generateEnvPrefix(Q),_={...Y};return this.processObject(_,[],H,{useCamelCase:X,useBackwardCompatibility:J,customParsers:G,verbose:U,configName:Q}),{config:_,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return J8.track("applyEnvironmentVariables",z,{configName:Q});return z()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,Y){if(!Y)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,Y,Z,$){for(let[X,J]of Object.entries(Q)){let G=[...Y,X],U=G.map((H)=>this.formatEnvKey(H,$.useCamelCase)),W=`${Z}_${U.join("_")}`,z=$.useBackwardCompatibility?`${Z}_${G.map((H)=>H.toUpperCase()).join("_")}`:null;if($.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,G,Z,$);else{let H=NY.env[W]||(z?NY.env[z]:void 0);if(H!==void 0){if($.verbose){let _=NY.env[W]?W:z}try{Q[X]=this.parseEnvironmentValue(H,typeof J,W,$.customParsers,$.configName)}catch(_){if(_ instanceof B8)throw _;throw vQ.envVar(W,H,typeof J,$.configName)}}}}}parseEnvironmentValue(Q,Y,Z,$,X){for(let[J,G]of Object.entries($))try{return G(Q)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(Q,Y))try{return J.parse(Q)}catch{throw vQ.envVar(Z,Q,`${Y} (via ${J.name} parser)`,X)}return Q}getEnvironmentVariables(Q){let Y={},Z=Q.toUpperCase();for(let[$,X]of Object.entries(NY.env))if($.startsWith(Z)&&X!==void 0)Y[$]=X;return Y}validateEnvironmentVariable(Q,Y,Z){let $=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))$.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Z)try{this.parseEnvironmentValue(Q,Y,Z,{})}catch(X){$.push(`Cannot parse value "${Y}" as ${Z}: ${X}`)}return{isValid:$.length===0,errors:$}}generateEnvVarDocs(Q,Y,Z={}){let{prefix:$,format:X="text"}=Z,J=$||this.generateEnvPrefix(Q),G=[];switch(this.extractEnvVarInfo(Y,[],J,G),X){case"markdown":return this.formatAsMarkdown(G,Q);case"json":return JSON.stringify(G,null,2);default:return this.formatAsText(G,Q)}}extractEnvVarInfo(Q,Y,Z,$){for(let[X,J]of Object.entries(Q)){let G=[...Y,X],U=`${Z}_${G.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,G,Z,$);else $.push({key:U,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${G.join(".")}`,example:this.generateExample(J)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,Y){let Z=`Environment Variables for ${Y}:
50
-
51
- `;for(let $ of Q)Z+=`${$.key}
52
- `,Z+=` Type: ${$.type}
53
- `,Z+=` Description: ${$.description}
54
- `,Z+=` Example: ${$.example}
55
-
56
- `;return Z}formatAsMarkdown(Q,Y){let Z=`# Environment Variables for ${Y}
57
-
58
- `;Z+=`| Variable | Type | Description | Example |
59
- `,Z+=`|----------|------|-------------|----------|
60
- `;for(let $ of Q)Z+=`| \`${$.key}\` | ${$.type} | ${$.description} | \`${$.example}\` |
61
- `;return Z}}function WJ(Q,Y,Z={}){return U$(Q,Y,Z,new WeakMap)}function U$(Q,Y,Z,$){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:G}=Z;if(Y===null||Y===void 0)return J?Q:Y;if(G){let U=G(Q,Y);if(U!==void 0)return U}if(Array.isArray(Y)||Array.isArray(Q))return z$(Q,Y,X,$);if(!r(Y)||!r(Q))return Y;return _J(Q,Y,Z,$)}function z$(Q,Y,Z,$){if(Array.isArray(Y)&&!Array.isArray(Q))return Y;if(Array.isArray(Q)&&!Array.isArray(Y))return Y;if(Array.isArray(Y)&&Array.isArray(Q))switch(Z){case"replace":return Y;case"concat":return UJ(Q,Y);case"smart":return zJ(Q,Y,$);default:return Y}return Y}function UJ(Q,Y){let Z=[...Y];for(let $ of Q)if(!Z.some((X)=>X8(X,$)))Z.push($);return Z}function zJ(Q,Y,Z){if(Y.length===0)return Q;if(Q.length===0)return Y;if(r(Y[0])&&r(Q[0]))return HJ(Q,Y,Z);if(Y.every(($)=>typeof $==="string")&&Q.every(($)=>typeof $==="string")){let $=[...Y];for(let X of Q)if(!$.includes(X))$.push(X);return $}return Y}function HJ(Q,Y,Z){let $=[...Y];for(let X of Q){if(!r(X)){$.push(X);continue}let J=["id","name","key","path","type"],G=!1;for(let U of J)if(U in X){if($.find((z)=>r(z)&&(U in z)&&z[U]===X[U])){G=!0;break}}if(!G)$.push(X)}return $}function _J(Q,Y,Z,$){let X=Y;if(r(X)&&$.has(X))return $.get(X);let J={...Q};if(r(X))$.set(X,J);for(let G in X){if(!Object.prototype.hasOwnProperty.call(X,G))continue;let U=X[G],W=J[G];if(Z.skipNullish&&(U===null||U===void 0))continue;if(U===null||U===void 0){J[G]=U;continue}if(r(U)&&r(W))J[G]=U$(W,U,Z,$);else if(Array.isArray(U)||Array.isArray(W))J[G]=z$(W,U,Z.arrayMergeMode||"smart",$);else J[G]=U}return J}function H$(Q,Y,Z="replace"){return WJ(Q,Y,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function X8(Q,Y){if(Q===Y)return!0;if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return!1;for(let Z=0;Z<Q.length;Z++)if(!X8(Q[Z],Y[Z]))return!1;return!0}if(r(Q)&&r(Y)){let Z=Object.keys(Q),$=Object.keys(Y);if(Z.length!==$.length)return!1;for(let X of Z){if(!Object.prototype.hasOwnProperty.call(Y,X))return!1;if(!X8(Q[X],Y[X]))return!1}return!0}return!1}function r(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}class _${extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,Y,Z={}){let{arrayStrategy:$="replace",useCache:X=!0,cacheTtl:J,trackPerformance:G=!0,verbose:U=!1}=Z;if(X){let z=vY.getWithFileCheck("file",Q);if(z){if(U)console.log(`Configuration loaded from cache: ${Q}`);return z}}let W=async()=>{if(!SY(Q))return null;try{let z=`?t=${Date.now()}`,H=await import(Q+z),_=H.default||H,A="default"in H,B=Object.keys(H).length>0;if(!A&&!B)throw new sY(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof _!=="object"||_===null||Array.isArray(_))throw new sY(Q,Error("Configuration must export a valid object"),"unknown");let j={config:H$(Y,_,$),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if(X)vY.setWithFileCheck("file",j,Q,J);return j}catch(z){throw z instanceof Error?vQ.configLoad(Q,z):vQ.configLoad(Q,Error(String(z)))}};if(G)return J8.track("loadFromPath",W,{path:Q});return W()}async tryLoadFromPaths(Q,Y,Z={}){for(let $ of Q)try{let X=await this.loadFromPath($,Y,Z);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Z.verbose)console.warn(`Failed to load config from ${$}:`,X)}return null}generateConfigPaths(Q,Y,Z){let $=this.generateNamePatterns(Q,Z),X=[];for(let J of $)for(let G of this.extensions)X.push(lZ(Y,`${J}${G}`));return X}generateNamePatterns(Q,Y){let Z=[];if(Z.push("config",".config"),Q)Z.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let J of $){if(!J)continue;if(Z.push(J,`.${J}.config`,`${J}.config`,`.${J}`),Q)Z.push(`${Q}.${J}.config`,`.${Q}.${J}.config`)}let X=new Set;return Z.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(Q){return GJ(async()=>{return SY(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,Y,Z){let $=[];if(!SY(Q))return $;if(Y||Z){let X=this.generateNamePatterns(Y||"",Z);for(let J of X)for(let G of this.extensions){let U=lZ(Q,`${J}${G}`);if(await this.checkFileAccess(U))$.push(U)}}else try{let{readdirSync:X}=await import("fs"),J=X(Q);for(let G of J)if(this.looksLikeConfigFile(G)){let U=lZ(Q,G);if(await this.checkFileAccess(U))$.push(U)}}catch{return[]}return $}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Z)=>Z.test(Q))}async validateConfigFile(Q){let Y=[];try{if(!SY(Q))return Y.push("Configuration file does not exist"),Y;let Z=await import(Q),$=Z.default||Z;if($===void 0)Y.push("Configuration file must export a default value or named exports");else if(typeof $!=="object"||$===null)Y.push("Configuration must be an object");else if(Array.isArray($))Y.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(Q,"utf8");JSON.parse(J)}catch(X){Y.push(`Invalid JSON syntax: ${X}`)}}catch(Z){Y.push(`Failed to load configuration file: ${Z}`)}return Y}async getFileModificationTime(Q){try{let{statSync:Y}=await import("fs");return Y(Q).mtime}catch{return null}}async preloadConfigurations(Q,Y={}){let Z=new Map;return await Promise.allSettled(Q.map(async($)=>{try{let X=await this.loadFromPath($,{},Y);if(X)Z.set($,X.config)}catch(X){if(Y.verbose)console.warn(`Failed to preload ${$}:`,X)}})),Z}}var BJ=/^https?:\/\//;class A${async validateConfiguration(Q,Y,Z={}){let{stopOnFirstError:$=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:G=[],trackPerformance:U=!0,verbose:W=!1}=Z,z=async()=>{let H=[],_=[],A={stopOnFirstError:$,validateRequired:X,validateTypes:J,customRules:G,trackPerformance:U,verbose:W};try{if(typeof Y==="string")return await this.validateWithSchemaFile(Q,Y,A);else if(Array.isArray(Y))return this.validateWithRules(Q,[...Y,...G],A);else return this.validateWithJSONSchema(Q,Y,A)}catch(B){return H.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:H,warnings:_}}};if(U)return await J8.track("validateConfiguration",z);return z()}async validateWithSchemaFile(Q,Y,Z){try{if(!AJ(Y))throw new oY(Y,[{path:"",message:"Schema file does not exist"}]);let $=await import(Y),X=$.default||$;if(Array.isArray(X))return this.validateWithRules(Q,X,Z);else return this.validateWithJSONSchema(Q,X,Z)}catch($){throw new oY(Y,[{path:"",message:`Failed to load schema: ${$}`}])}}validateWithJSONSchema(Q,Y,Z){let $=[],X=[];return this.validateObjectAgainstSchema(Q,Y,"",$,X,Z),{isValid:$.length===0,errors:$,warnings:X}}validateObjectAgainstSchema(Q,Y,Z,$,X,J){if(J.validateTypes&&Y.type){let G=Array.isArray(Q)?"array":typeof Q,U=Array.isArray(Y.type)?Y.type:[Y.type];if(!U.includes(G)){if($.push({path:Z,message:`Expected type ${U.join(" or ")}, got ${G}`,expected:U.join(" or "),actual:G,rule:"type"}),J.stopOnFirstError)return}}if(Y.enum&&!Y.enum.includes(Q)){if($.push({path:Z,message:`Value must be one of: ${Y.enum.join(", ")}`,expected:Y.enum.join(", "),actual:Q,rule:"enum"}),J.stopOnFirstError)return}if(typeof Q==="string"){if(Y.minLength!==void 0&&Q.length<Y.minLength)$.push({path:Z,message:`String length must be at least ${Y.minLength}`,expected:`>= ${Y.minLength}`,actual:Q.length,rule:"minLength"});if(Y.maxLength!==void 0&&Q.length>Y.maxLength)$.push({path:Z,message:`String length must not exceed ${Y.maxLength}`,expected:`<= ${Y.maxLength}`,actual:Q.length,rule:"maxLength"});if(Y.pattern){if(!new RegExp(Y.pattern).test(Q))$.push({path:Z,message:`String does not match pattern ${Y.pattern}`,expected:Y.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(Y.minimum!==void 0&&Q<Y.minimum)$.push({path:Z,message:`Value must be at least ${Y.minimum}`,expected:`>= ${Y.minimum}`,actual:Q,rule:"minimum"});if(Y.maximum!==void 0&&Q>Y.maximum)$.push({path:Z,message:`Value must not exceed ${Y.maximum}`,expected:`<= ${Y.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&Y.items)for(let G=0;G<Q.length;G++){let U=Z?`${Z}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema(Q[G],Y.items,U,$,X,J),J.stopOnFirstError&&$.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let G=Q;if(J.validateRequired&&Y.required){for(let U of Y.required)if(!(U in G)){if($.push({path:Z?`${Z}.${U}`:U,message:`Missing required property '${U}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(Y.properties){for(let[U,W]of Object.entries(Y.properties))if(U in G){let z=Z?`${Z}.${U}`:U;if(this.validateObjectAgainstSchema(G[U],W,z,$,X,J),J.stopOnFirstError&&$.length>0)return}}if(Y.additionalProperties===!1){let U=new Set(Object.keys(Y.properties||{}));for(let W of Object.keys(G))if(!U.has(W))X.push({path:Z?`${Z}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,Y,Z){let $=[],X=[];for(let J of Y)try{let G=this.getValueByPath(Q,J.path),U=this.validateWithRule(G,J,J.path);if($.push(...U),Z.stopOnFirstError&&$.length>0)break}catch(G){$.push({path:J.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:$.length===0,errors:$,warnings:X}}validateWithRule(Q,Y,Z){let $=[];if(Y.required&&(Q===void 0||Q===null))return $.push({path:Z,message:Y.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),$;if(Q===void 0||Q===null)return $;if(Y.type){let X=Array.isArray(Q)?"array":typeof Q;if(X!==Y.type)$.push({path:Z,message:Y.message||`Expected type ${Y.type}, got ${X}`,expected:Y.type,actual:X,rule:"type"})}if(Y.min!==void 0){let X=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if(X<Y.min)$.push({path:Z,message:Y.message||`Value must be at least ${Y.min}`,expected:`>= ${Y.min}`,actual:X,rule:"min"})}if(Y.max!==void 0){let X=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if(X>Y.max)$.push({path:Z,message:Y.message||`Value must not exceed ${Y.max}`,expected:`<= ${Y.max}`,actual:X,rule:"max"})}if(Y.pattern&&typeof Q==="string"){if(!Y.pattern.test(Q))$.push({path:Z,message:Y.message||`Value does not match pattern ${Y.pattern}`,expected:Y.pattern.toString(),actual:Q,rule:"pattern"})}if(Y.enum&&!Y.enum.includes(Q))$.push({path:Z,message:Y.message||`Value must be one of: ${Y.enum.join(", ")}`,expected:Y.enum.join(", "),actual:Q,rule:"enum"});if(Y.validator){let X=Y.validator(Q);if(X)$.push({path:Z,message:Y.message||X,rule:"custom"})}return $}getValueByPath(Q,Y){if(!Y)return Q;let Z=Y.split("."),$=Q;for(let X of Z)if($&&typeof $==="object"&&X in $)$=$[X];else return;return $}generateRulesFromInterface(Q){let Y=[],Z=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let $ of Z){let[,X,J,G]=$;Y.push({path:X,required:!J,type:this.mapTypeScriptType(G)})}return Y}mapTypeScriptType(Q){switch(Q.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:BJ},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var JQ=new eY("bunfig",{showTags:!0});function RJ(Q){if(!Q)return"";let Y=Array.isArray(Q)?Q.filter(Boolean):[Q];if(Y.length===0)return"";if(Y.length===1)return` or alias "${Y[0]}"`;return` or aliases ${Y.map((Z)=>`"${Z}"`).join(", ")}`}class B${fileLoader=new _$;envProcessor=new R8;validator=new A$;async loadConfig(Q){let Y=Date.now(),{cache:Z,performance:$,schema:X,validate:J,...G}=Q;try{if(Z?.enabled){let W=this.checkCache(G.name||"",G);if(W)return W}let U;try{U=await this.loadConfigurationStrategies(G,!0,Z)}catch(W){let z=G.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(z)throw W;U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`No configuration file found for "${G.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let H=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),_=!H&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),A=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(z&&(A||H))throw W;if(_&&(!z||!A))U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!z)U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(U.config,X,J,G.name);if(Z?.enabled&&U)this.cacheResult(G.name||"",U,Z,G);if($?.enabled){let W={operation:"loadConfig",duration:Date.now()-Y,configName:G.name,timestamp:new Date};if($.onMetrics)$.onMetrics(W);if($.slowThreshold&&W.duration>$.slowThreshold)JQ.warn(`Slow configuration loading detected: ${W.duration}ms for ${G.name}`);U.metrics=W}return U}catch(U){if(U instanceof Error&&U.name==="ConfigNotFoundError")throw U;let W=Date.now()-Y;throw JQ.error(`Configuration loading failed after ${W}ms:`,[U instanceof Error?U:Error(String(U))]),U}}async loadConfigurationStrategies(Q,Y=!1,Z){let{name:$="",alias:X,cwd:J,configDir:G,defaultConfig:U,checkEnv:W=!0,arrayStrategy:z="replace",verbose:H=!1}=Q,_=J||aY.cwd(),A=[],B=await this.loadLocalConfiguration($,X,_,G,U,z,H,W,Z);if(B)return A.push(...this.getLocalSearchPaths($,X,_,G)),this.finalizeResult(B,A,W,$,H);let L=await this.loadHomeConfiguration($,X,U,z,H,W);if(L)return A.push(...this.getHomeSearchPaths($,X)),this.finalizeResult(L,A,W,$,H);let R=await this.loadPackageJsonConfiguration($,X,_,U,z,H,W);if(R)return A.push(a(_,"package.json")),this.finalizeResult(R,A,W,$,H);if(A.push(...this.getAllSearchPaths($,X,_,G)),Y)throw vQ.configNotFound($,A,X);return{...await this.applyEnvironmentVariables($,U,W,H),warnings:[`No configuration file found for "${$}"${RJ(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,Y,Z,$,X,J,G,U,W){let z=U?CY(Q,X,G):X,H=this.getLocalDirectories(Z,$);for(let _ of H){if(G)JQ.info(`Searching for configuration in: ${_}`);let A=this.fileLoader.generateConfigPaths(Q,_,Y),B=await this.fileLoader.tryLoadFromPaths(A,z,{arrayStrategy:J,verbose:G,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(B){if(G)JQ.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration(Q,Y,Z,$,X,J){if(!Q)return null;let G=J?CY(Q,Z,X):Z,U=[a(EQ(),".config",Q),a(EQ(),".config"),EQ()];for(let W of U){if(X)JQ.info(`Checking home directory: ${W}`);let z=this.fileLoader.generateConfigPaths(Q,W,Y),H=await this.fileLoader.tryLoadFromPaths(z,G,{arrayStrategy:$,verbose:X});if(H){if(X)JQ.success(`Configuration loaded from home directory: ${H.source.path}`);return H}}return null}async loadPackageJsonConfiguration(Q,Y,Z,$,X,J,G){let U=G?CY(Q,$,J):$;try{let W=a(Z,"package.json");if(!W0(W))return null;let z={};try{z=JSON.parse(U0(W,"utf8"))}catch(A){if(J)JQ.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let H=z[Q],_=Q;if(!H&&Y){let A=Array.isArray(Y)?Y:[Y];for(let B of A){if(!B)continue;if(z[B]){H=z[B],_=B;break}}}if(H&&typeof H==="object"&&!Array.isArray(H)){if(J)JQ.success(`Configuration loaded from package.json: ${_}`);return{config:H$(U,H,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)JQ.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(Q,Y,Z,$){if(!Z||!Q||typeof Y!=="object"||Y===null||Array.isArray(Y))return{config:Y,source:{type:"default",priority:10,timestamp:new Date}};return{config:CY(Q,Y,$),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,Y,Z,$,X){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,Y,Z,$){let X=[];if(Z){let J=Z(Q);if(J)X.push(...J)}if(Y){let J=await this.validator.validateConfiguration(Q,Y);if(!J.isValid)X.push(...J.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if(X.length>0)throw vQ.configValidation($||"unknown",X,$)}checkCache(Q,Y){let Z=this.generateCacheKey(Q,Y);return vY.get(Z)||null}cacheResult(Q,Y,Z,$){let X=this.generateCacheKey(Q,$);vY.set(X,Y,void 0,Z.ttl)}generateCacheKey(Q,Y){let Z=[Q];if(Y.alias){let $=Array.isArray(Y.alias)?Y.alias.join(","):Y.alias;Z.push(`alias:${$}`)}if(Y.cwd)Z.push(`cwd:${Y.cwd}`);if(Y.configDir)Z.push(`configDir:${Y.configDir}`);if("checkEnv"in Y)Z.push(`checkEnv:${Y.checkEnv}`);return Z.join("|")}getLocalDirectories(Q,Y){return Array.from(new Set([Q,a(Q,"config"),a(Q,".config"),Y?a(Q,Y):void 0].filter(Boolean)))}getAllSearchPaths(Q,Y,Z,$){let X=[];return X.push(...this.getLocalSearchPaths(Q,Y,Z,$)),X.push(...this.getHomeSearchPaths(Q,Y)),X.push(a(Z,"package.json")),X}getLocalSearchPaths(Q,Y,Z,$){let X=this.getLocalDirectories(Z,$),J=[];for(let G of X)J.push(...this.fileLoader.generateConfigPaths(Q,G,Y));return J}getHomeSearchPaths(Q,Y){if(!Q)return[];let Z=[a(EQ(),".config",Q),a(EQ(),".config"),EQ()],$=[];for(let X of Z)$.push(...this.fileLoader.generateConfigPaths(Q,X,Y));return $}async loadConfigWithResult(Q){return this.loadConfig(Q)}}var nZ=new B$;async function R$(Q){let Y="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Z="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let $;if(Z)$=await nZ.loadConfig(Q);else $=await nZ.loadConfig({...Q,defaultConfig:Y,cache:{enabled:!0},performance:{enabled:!1}});return $?.config??Y}catch($){let X=$ instanceof Error?$.name:"UnknownError",J=$ instanceof Error?$.message:String($);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&Q.verbose)JQ.warn("Unexpected error loading config, using defaults:",[$ instanceof Error?$:Error(String($))]);let U=Z?{...Q,defaultConfig:Y}:{...Q,defaultConfig:Y,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await nZ.applyEnvironmentVariables(U.name||"",Y,!0,U.verbose||!1))?.config??Y;return Y}}function CY(Q,Y,Z=!1){let $=new R8,X=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(G,U=[]){let W={...G};for(let[z,H]of Object.entries(G)){let _=[...U,z],A=[`${X}_${_.join("_").toUpperCase()}`,`${X}_${_.map((R)=>R.toUpperCase()).join("")}`,`${X}_${_.map((R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,L;for(let R of A)if(B=aY.env[R],B!==void 0){L=R;break}if(B!==void 0&&L)if(typeof H==="boolean")W[z]=["true","1","yes"].includes(B.toLowerCase());else if(typeof H==="number"){let R=Number(B);if(!Number.isNaN(R))W[z]=R}else if(Array.isArray(H))try{W[z]=JSON.parse(B)}catch{W[z]=B.split(",").map((R)=>R.trim())}else W[z]=B;else if(H&&typeof H==="object"&&!Array.isArray(H))W[z]=J(H,_)}return W}return J(Y)}var c1=a(aY.cwd(),"config"),l1=a(aY.cwd(),"src/generated");var L$={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:LJ.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:{}}},L8=null;async function o1(){if(!L8)L8=await R$({name:"router",defaultConfig:L$});return L8}var D=L$;function j$(Q){if(!Q||!Q.startsWith("Basic "))return null;try{let Y=Q.split(" ")[1],Z=atob(Y),[$,X]=Z.split(":");return{username:$,password:X}}catch(Y){return null}}function j8(Q){if(!Q||!Q.startsWith("Bearer "))return null;return Q.split(" ")[1]}function K$(Q,Y="header",Z="X-API-Key"){switch(Y){case"header":return Q.headers.get(Z)||null;case"query":return new URL(Q.url).searchParams.get(Z);case"cookie":if(Q.cookies){if(typeof Q.cookies.get==="function")return Q.cookies.get(Z)||null;return Q.cookies[Z]||null}return null;default:return null}}class XQ{options;constructor(Q){this.options={source:"header",key:"Authorization",attachUser:!0,...Q}}async handle(Q,Y){let Z=null;if(this.options.credentialsExtractor)Z=await this.options.credentialsExtractor(Q);else switch(this.options.type){case"basic":{let J=Q.headers.get(this.options.key||"Authorization");Z=j$(J||"");break}case"bearer":case"jwt":{let J=Q.headers.get(this.options.key||"Authorization");Z=j8(J||"");break}case"api-key":{Z=K$(Q,this.options.source,this.options.key);break}case"oauth2":{let J=Q.headers.get(this.options.key||"Authorization");Z=j8(J||"");break}}if(!Z){let J={};if(this.options.type==="basic"){let G=this.options.realm||"Secure Area";J["WWW-Authenticate"]=`Basic realm="${G}"`}return new Response("Unauthorized",{status:401,headers:J})}if(!await this.options.validator(Z,Q))return new Response("Unauthorized",{status:401});if(this.options.userExtractor&&this.options.attachUser){let J=await this.options.userExtractor(Z,Q);Q.user=J}return await Y()||new Response("Not Found",{status:404})}}function jJ(Q,Y={}){return new XQ({type:"basic",validator:Q,...Y})}function KJ(Q,Y={}){return new XQ({type:"bearer",validator:Q,...Y})}function FJ(Q,Y={}){return new XQ({type:"jwt",validator:Q,...Y})}function MJ(Q,Y={}){return new XQ({type:"api-key",validator:Q,...Y})}function IJ(Q,Y={}){return new XQ({type:"oauth2",validator:Q,...Y})}var K8={"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 hQ{resolveAllowOrigin(Q,Y,Z){if(Array.isArray(Q)){if(Z&&Q.includes(Z))return{value:Z,vary:!0};return{value:null,vary:!0}}let $=Q||"*";if($==="*"){if(Y){if(Z)return{value:Z,vary:!0};return{value:null,vary:!0}}return{value:"*",vary:!1}}return{value:$,vary:!1}}getCorsHeaders(Q){let Y=D.server?.cors,Z=Q.headers.get("origin");if(Y&&Y.enabled){let $=Boolean(Y.credentials),{value:X,vary:J}=this.resolveAllowOrigin(Y.origin,$,Z),G={"Access-Control-Allow-Methods":Array.isArray(Y.methods)?Y.methods.join(", "):K8["Access-Control-Allow-Methods"],"Access-Control-Allow-Headers":Array.isArray(Y.allowedHeaders)?Y.allowedHeaders.join(", "):K8["Access-Control-Allow-Headers"],"Access-Control-Max-Age":String(Y.maxAge||86400)};if(X!==null)G["Access-Control-Allow-Origin"]=X;if($&&X!==null&&X!=="*")G["Access-Control-Allow-Credentials"]="true";if(J)G.Vary="Origin";return G}return{...K8}}async handle(Q,Y){let Z=this.getCorsHeaders(Q);if(Q.method==="OPTIONS")return new Response(null,{status:204,headers:Z});let $=(X)=>{let J=new Headers(X.headers);return Object.entries(Z).forEach(([G,U])=>{J.set(G,U)}),new Response(X.body,{status:X.status,statusText:X.statusText,headers:J})};try{let X=await Y();if(!X)return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{...Z,"Content-Type":"application/json"}});return $(X)}catch(X){return console.error("[CORS] Error in middleware chain:",X),new Response(JSON.stringify({error:"Internal Server Error",message:X instanceof Error?X.message:String(X)}),{status:500,headers:{...Z,"Content-Type":"application/json"}})}}}import{createHash as VJ,randomBytes as DJ,timingSafeEqual as wJ}from"crypto";var EJ=1e4,OJ=7200000;class u{static tokens=new Map;async handle(Q,Y){let Z=D.server?.security?.csrf??{},$=Q.method.toUpperCase();if(["GET","HEAD","OPTIONS",...Z?.ignoreMethods||[]].includes($)){let _=this.generateToken(Z?.secret||"csrf-secret"),A=await Y();if(!A)return new Response("Not Found",{status:404});let B=Z?.cookie?.name||"csrf-token",L=[];if(L.push(`${B}=${_}`),L.push("Path=/"),Z?.cookie?.options?.httpOnly)L.push("HttpOnly");if(Z?.cookie?.options?.secure)L.push("Secure");if(Z?.cookie?.options?.sameSite)L.push(`SameSite=${Z.cookie.options.sameSite}`);let R=new Headers(A.headers);return R.append("Set-Cookie",L.join("; ")),u.storeToken(_),new Response(A.body,{status:A.status,statusText:A.statusText,headers:R})}let J=Q.headers.get("authorization")??Q.headers.get("Authorization");if(J&&/^Bearer\s+\S/i.test(J))return await Y()||new Response("Not Found",{status:404});let G=Q.headers.get("X-CSRF-TOKEN")||Q.jsonBody?.csrf_token||Q.jsonBody?._token||null,U=typeof G==="string"?G:null,z=this.parseCookies(Q)[Z?.cookie?.name||"csrf-token"];if(!U||!z||!u.safeCompare(U,z)||!u.isTokenValid(U))return new Response(JSON.stringify({error:"CSRF token validation failed"}),{status:403,headers:{"Content-Type":"application/json"}});return await Y()||new Response("Not Found",{status:404})}static safeCompare(Q,Y){let Z=Buffer.from(Q),$=Buffer.from(Y);if(Z.length!==$.length)return!1;return wJ(Z,$)}static storeToken(Q){if(u.tokens.size>=EJ){let Y=u.tokens.keys().next().value;if(Y!==void 0)u.tokens.delete(Y)}u.tokens.set(Q,Date.now())}static isTokenValid(Q){let Y=u.tokens.get(Q);if(Y===void 0)return!1;if(Date.now()-Y>OJ)return u.tokens.delete(Q),!1;return!0}generateToken(Q){let Y=DJ(16).toString("hex");return VJ("sha256").update(`${Y}${Q}`).digest("hex")}parseCookies(Q){let Y=Q.headers.get("cookie");if(!Y)return{};let Z={};for(let $ of Y.split(";")){let X=$.indexOf("=");if(X===-1)continue;let J=$.slice(0,X).trim();if(!J)continue;Z[J]=$.slice(X+1).trim()}return Z}}class dQ{async handle(Q,Y){let Z=Q.headers.get("content-type");if(Z&&Z.includes("application/json"))try{let J=await Q.clone().json();Object.defineProperty(Q,"jsonBody",{value:J,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 Y()||new Response("Not Found",{status:404})}}import{existsSync as F$,statSync as M$}from"fs";import{join as qJ,relative as TJ,resolve as I$}from"path";import GZ from"process";import{Buffer as BQ}from"buffer";import{createCipheriv as NJ,createDecipheriv as SJ,randomBytes as F8}from"crypto";import{closeSync as M8,createReadStream as V$,createWriteStream as CJ,existsSync as QZ,fsyncSync as D$,openSync as w$,writeFileSync as xJ}from"fs";import{access as kJ,constants as E$,mkdir as PJ,readdir as YZ,rename as O$,stat as fQ,unlink as ZZ,writeFile as I8}from"fs/promises";import{isAbsolute as bJ,join as mQ,resolve as yJ}from"path";import I from"process";import{pipeline as vJ}from"stream/promises";import{createGzip as q$}from"zlib";import gQ from"process";import RQ from"process";import $Z from"process";import{existsSync as XZ}from"fs";import{resolve as V8}from"path";import{existsSync as hJ}from"fs";import{existsSync as q8,mkdirSync as dJ,readdirSync as fJ,readFileSync as mJ,writeFileSync as gJ}from"fs";import{homedir as pQ}from"os";import{dirname as T$,resolve as c}from"path";import DQ from"process";import{existsSync as pJ,readdirSync as uJ}from"fs";import{extname as D8,resolve as N$}from"path";import cJ from"process";var lJ=Object.defineProperty,nJ=(Q)=>Q;function iJ(Q,Y){this[Q]=nJ.bind(null,Y)}var sJ=(Q,Y)=>{for(var Z in Y)lJ(Q,Z,{get:Y[Z],enumerable:!0,configurable:!0,set:iJ.bind(Y,Z)})},jQ=(Q,Y)=>()=>(Q&&(Y=Q(Q=0)),Y),oJ=import.meta.require;class b8{cache=new Map;totalHits=0;totalMisses=0;options;constructor(Q={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...Q}}generateKey(Q,Y){let Z=Y?`:${Y}`:"";return`${this.options.keyPrefix}${Q}${Z}`}isExpired(Q){return Date.now()-Q.timestamp.getTime()>Q.ttl}estimateSize(Q){try{return JSON.stringify(Q).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let Q=Array.from(this.cache.entries()).sort(([,Z],[,$])=>Z.timestamp.getTime()-$.timestamp.getTime()),Y=Q.length-this.options.maxSize+1;for(let Z=0;Z<Y;Z++)this.cache.delete(Q[Z][0])}set(Q,Y,Z,$){if(!this.options.enabled)return;let X=this.generateKey(Q,Z),J=$??this.options.ttl,G=this.estimateSize(Y);this.cache.set(X,{value:Y,timestamp:new Date,ttl:J,hits:0,size:G}),this.evictIfNeeded()}get(Q,Y){if(!this.options.enabled){this.totalMisses++;return}let Z=this.generateKey(Q,Y),$=this.cache.get(Z);if(!$){this.totalMisses++;return}if(this.isExpired($)){this.cache.delete(Z),this.totalMisses++;return}return $.hits++,this.totalHits++,$.value}isFileModified(Q,Y){try{if(!F$(Q))return!0;return M$(Q).mtime>Y}catch{return!0}}getWithFileCheck(Q,Y){let Z=this.get(Q,Y);if(!Z)return;if(this.isFileModified(Y,Z.fileTimestamp)){this.delete(Q,Y);return}return Z.value}setWithFileCheck(Q,Y,Z,$){try{let X=F$(Z)?M$(Z):null,J=X?X.mtime:new Date;this.set(Q,{value:Y,fileTimestamp:J},Z,$)}catch{this.set(Q,Y,Z,$)}}delete(Q,Y){let Z=this.generateKey(Q,Y);return this.cache.delete(Z)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let Q=0;for(let[Y,Z]of this.cache.entries())if(this.isExpired(Z))this.cache.delete(Y),Q++;return Q}getStats(){let Q=Array.from(this.cache.values()),Y=Q.reduce(($,X)=>$+X.size,0),Z=Q.map(($)=>$.timestamp).sort();return{size:Y,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:Z[0],newestEntry:Z[Z.length-1]}}export(){let Q={};for(let[Y,Z]of this.cache.entries())Q[Y]={value:Z.value,timestamp:Z.timestamp.toISOString(),ttl:Z.ttl,hits:Z.hits,size:Z.size};return Q}import(Q){this.cache.clear();for(let[Y,Z]of Object.entries(Q))if(typeof Z==="object"&&Z!==null){let $=Z;this.cache.set(Y,{value:$.value,timestamp:new Date($.timestamp),ttl:$.ttl,hits:$.hits,size:$.size})}}}class y8{metrics=[];maxMetrics=1000;async track(Q,Y,Z={}){let $=performance.now(),X=new Date;try{let J=await Y(),G=performance.now()-$;return this.recordMetric({operation:Q,duration:G,timestamp:X,...Z}),J}catch(J){let G=performance.now()-$;throw this.recordMetric({operation:`${Q}:error`,duration:G,timestamp:X,...Z}),J}}recordMetric(Q){if(this.metrics.push(Q),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(Q){let Y=Q?this.metrics.filter((X)=>X.operation===Q):this.metrics;if(Y.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Z=Y.map((X)=>X.duration),$=Z.reduce((X,J)=>X+J,0);return{count:Y.length,averageDuration:$/Y.length,minDuration:Math.min(...Z),maxDuration:Math.max(...Z),totalDuration:$,recentMetrics:Y.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(Q){return this.metrics.filter((Y)=>Y.duration>Q)}}function aJ(Q,Y={}){let $=Object.keys(Y).sort().map((X)=>`${X}:${Y[X]}`).join("|");return $?`${Q}:${$}`:Q}function tJ(Q,Y){try{return JSON.stringify(Q)===JSON.stringify(Y)}catch{return Q===Y}}function rJ(Q){return Q.getStats().size*2}var uQ,_Y,y$,AY=jQ(()=>{uQ=new b8,_Y=new y8,y$={createKey:aJ,isEquivalent:tJ,estimateMemoryUsage:rJ}});function eJ(Q,Y={}){let Z=GZ.cwd();while(Z.includes("storage"))Z=I$(Z,"..");let $=I$(Z,Q||"");if(Y?.relative)return TJ(GZ.cwd(),$);return $}function P(){if(RQ.env.NODE_ENV==="test"||RQ.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Q7(){if(RQ.env.NODE_ENV==="test"||RQ.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof RQ<"u"){let Q=RQ.type;if(Q==="renderer"||Q==="worker")return!1;return!!(RQ.versions&&(RQ.versions.node||RQ.versions.bun))}return!1}class v${async format(Q){let Y=await Q7(),Z=await this.getMetadata(Y);return JSON.stringify({timestamp:Q.timestamp.toISOString(),level:Q.level,name:Q.name,message:Q.message,metadata:Z})}async getMetadata(Q){if(Q){let{hostname:Y}=await import("os");return{pid:gQ.pid,hostname:Y(),environment:gQ.env.NODE_ENV||"development",platform:gQ.platform,version:gQ.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:gQ.env.NODE_ENV||gQ.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zZ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(Q,Y={}){this.name=Q,this.config={...WY},this.options=this.normalizeOptions(Y),this.formatter=this.options.formatter||new v$,this.enabled=Y.enabled??!0,this.fancy=Y.fancy??!0,this.tagFormat=Y.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=Y.timestampPosition??"right",this.environment=Y.environment??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(Y);let Z={...Y},$=Y.timestamp!==void 0;if($)delete Z.timestamp;if(this.config={...this.config,...Z,timestamp:$||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(Q){if(!this.fingersCrossedConfig)return!1;let Y={debug:0,info:1,success:2,warning:3,error:4},Z=this.fingersCrossedConfig.activationLevel??"error";return Y[Q]>=Y[Z]}initializeFingersCrossedConfig(Q){if(!Q.fingersCrossedEnabled&&Q.fingersCrossed)return{...JZ,...Q.fingersCrossed};if(!Q.fingersCrossedEnabled)return null;if(!Q.fingersCrossed)return{...JZ};return{...JZ,...Q.fingersCrossed}}normalizeOptions(Q){let Y={format:"json",level:"info",logDirectory:WY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Z={...Y,...Object.fromEntries(Object.entries(Q).filter(([,$])=>$!==void 0))};if(!Z.level||!["debug","info","success","warning","error"].includes(Z.level))Z.level=Y.level;return Z}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(Q){let Z=(async()=>{let X,J=0,G=3,U=1000;while(J<G)try{try{try{await kJ(this.config.logDirectory,E$.F_OK|E$.W_OK)}catch(z){if(z instanceof Error&&"code"in z)if(z.code==="ENOENT")await PJ(this.config.logDirectory,{recursive:!0,mode:493});else if(z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw z;else throw z}}catch(z){throw console.error("Debug: [writeToFile] Failed to create log directory:",z),z}let W=this.validateEncryptionConfig()?(await this.encrypt(Q)).encrypted:BQ.from(Q);try{if(!QZ(this.currentLogFile))await I8(this.currentLogFile,"",{mode:420});if(X=w$(this.currentLogFile,"a",420),xJ(X,W,{flag:"a"}),D$(X),X!==void 0)M8(X),X=void 0;if((await fQ(this.currentLogFile)).size===0){if(await I8(this.currentLogFile,W,{flag:"w",mode:420}),(await fQ(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(z){let H=z;if(H.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(H.code)){if(J<G-1){let _=typeof H.message==="string"?H.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${G}:`,_);let A=U*2**J;await new Promise((B)=>setTimeout(B,A)),J++;continue}}if(H?.code&&["ENOSPC","EDQUOT"].includes(H.code))throw Error(`Disk quota exceeded or no space left on device: ${H.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",H),H}finally{if(X!==void 0)try{M8(X)}catch(z){console.error("Debug: [writeToFile] Error closing file descriptor:",z)}}}catch(W){if(J===G-1){let H=W,_=typeof H.message==="string"?H.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",_),W}J++;let z=U*2**(J-1);await new Promise((H)=>setTimeout(H,z))}})();this.pendingOperations.push(Z);let $=this.pendingOperations.length-1;try{await Z}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice($,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 mQ(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 mQ(this.config.logDirectory,`${this.name}.log`);let Q=new Date().toISOString().split("T")[0];return mQ(this.config.logDirectory,`${this.name}-${Q}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let Q=this.config.rotation,Y;switch(Q.frequency){case"daily":Y=86400000;break;case"weekly":Y=604800000;break;case"monthly":Y=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},Y)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let Y=this.config.rotation.keyRotation;if(!Y?.enabled)return;let Z=typeof Y.interval==="number"?Y.interval:60,$=Math.max(Z,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},$)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let Y=this.config.rotation.keyRotation,Z=this.generateKeyId(),$=this.generateKey();this.currentKeyId=Z,this.keys.set(Z,$),this.encryptionKeys.set(Z,{key:$,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),J=typeof Y.maxKeys==="number"?Y.maxKeys:1,G=Math.max(1,J);if(X.length>G)for(let[U]of X.slice(G))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return F8(16).toString("hex")}generateKey(){return F8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let Q=this.keys.get(this.currentKeyId);if(!Q)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:Q,id:this.currentKeyId}}encrypt(Q){let{key:Y}=this.getCurrentKey(),Z=F8(16),$=NJ("aes-256-gcm",Y,Z),X=BQ.isBuffer(Q)?Q:BQ.from(Q,"utf8"),J=$.update(X),G=$.final(),U=J.length+G.length,W=$.getAuthTag(),z=BQ.allocUnsafe(16+U+16);return Z.copy(z,0),J.copy(z,16),G.copy(z,16+J.length),W.copy(z,16+U),{encrypted:z,iv:Z}}async compressData(Q){return new Promise((Y,Z)=>{let $=q$(),X=[];$.on("data",(J)=>X.push(J)),$.on("end",()=>Y(BQ.from(BQ.concat(X)))),$.on("error",Z),$.write(Q),$.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let Q={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let Y=this.config.rotation.encrypt;return{...Q,...Y}}return Q}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let Q=await fQ(this.currentLogFile).catch(()=>null);if(!Q)return;let Y=this.config.rotation;if(typeof Y==="boolean")return;if(Y.maxSize&&Q.size>=Y.maxSize){let Z=this.currentLogFile,$=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await YZ(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,z)=>{let H=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(z.match(/\.log\.(\d+)$/)?.[1]||"0")-H}),G=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,U=`${Z}.${G}`;if(await fQ(Z).catch(()=>null))try{if(await O$(Z,U),Y.compress)try{let W=`${U}.gz`;await this.compressLogFile(U,W),await ZZ(U)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Z}.1`;await I8(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Z.replace(/\.log$/,`-${X}.log`);if(await fQ(Z).catch(()=>null))await O$(Z,J)}if(this.currentLogFile=$,Y.maxFiles){let J=(await YZ(this.config.logDirectory)).filter((G)=>G.startsWith(this.name)).sort((G,U)=>U.localeCompare(G));for(let G of J.slice(Y.maxFiles))await ZZ(mQ(this.config.logDirectory,G))}}}async compressLogFile(Q,Y){let Z=V$(Q),$=CJ(Y),X=q$();await vJ(Z,X,$)}async handleFingersCrossedBuffer(Q,Y){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(Q)&&!this.isActivated){this.isActivated=!0;for(let Z of this.logBuffer){let $=await this.formatter.format(Z);if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}}shouldLog(Q){if(!this.enabled)return!1;let Y={debug:0,info:1,success:2,warning:3,error:4};return Y[Q]>=Y[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((Q)=>{if(Q instanceof Promise)return Q.catch((Y)=>{console.error("Error in pending write operation:",Y)});return Promise.resolve()})),QZ(this.currentLogFile))try{let Q=w$(this.currentLogFile,"r+");D$(Q),M8(Q)}catch(Q){console.error(`Error flushing file: ${Q}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let Q of this.pendingOperations)if(typeof Q.cancel==="function")Q.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(Q){console.error("Error waiting for pending operations:",Q)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let Y=(await YZ(this.config.logDirectory)).filter((Z)=>(Z.includes("temp")||Z.includes(".tmp"))&&Z.includes(this.name));for(let Z of Y)try{await ZZ(mQ(this.config.logDirectory,Z))}catch($){console.error(`Failed to delete temp file ${Z}:`,$)}}catch(Q){console.error("Error cleaning up temporary files:",Q)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(Q){if(!Q)return"";return`${this.tagFormat.prefix}${Q}${this.tagFormat.suffix}`}formatFileTimestamp(Q){return`[${Q.toISOString()}]`}formatConsoleTimestamp(Q){return this.shouldStyleConsole()?w.gray(Q.toLocaleTimeString()):Q.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let Q=typeof I.env.NO_COLOR<"u",Y=I.env.FORCE_COLOR==="0";if(Q||Y)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage(Q){let{timestamp:Y,icon:Z="",tag:$="",message:X,level:J,showTimestamp:G=!0}=Q,U=(B)=>B.replace(this.ANSI_PATTERN,"");if(!this.fancy){let B=[];if(G)B.push(Y);if(J==="warning")B.push("WARN");else if(J==="error")B.push("ERROR");else if(Z)B.push(Z.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if($)B.push($.replace(/[[\]]/g,""));return B.push(X),B.join(" ")}let W=I.stdout.columns||120,z="";if(J==="warning"||J==="error")z=`${Z} ${X}`;else if(J==="info"||J==="success")z=`${Z} ${$} ${X}`;else z=`${Z} ${$} ${w.cyan(X)}`;if(!G)return z.trim();let H=U(z).trim().length,_=U(Y).length,A=Math.max(1,W-2-H-_);return`${z.trim()}${" ".repeat(A)}${Y}`}formatMessage(Q,Y){if(Y.length===1&&Array.isArray(Y[0]))return Q.replace(/\{(\d+)\}/g,(J,G)=>{let U=Number.parseInt(G,10);return U<Y[0].length?String(Y[0][U]):J});let Z=/%([sdijfo%])/g,$=0,X=Q.replace(Z,(J,G)=>{if(G==="%")return"%";if($>=Y.length)return J;let U=Y[$++];switch(G){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 J}});if($<Y.length)X+=` ${Y.slice($).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(Q){if(!Q)return Q;let Y=Q;return Y=Y.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Z,$,X)=>{let J=w.underline(w.blue($)),G=this.toAbsoluteFilePath(X);if(G&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let U=`file://${encodeURI(G)}`,W="\x1B]8;;",z="\x1B\\";return`\x1B]8;;${U}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),Y=Y.replace(/`([^`]+)`/g,(Z,$)=>w.bgGray($)),Y=Y.replace(/\*\*([^*]+)\*\*/g,(Z,$)=>w.bold($)),Y=Y.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Z,$)=>w.italic($)),Y=Y.replace(/(?<!_)_([^_]+)_(?!_)/g,(Z,$)=>w.italic($)),Y=Y.replace(/~([^~]+)~/g,(Z,$)=>w.strikethrough($)),Y}supportsHyperlinks(){if(P())return!1;let Q=I.env;if(!Q)return!1;if(Q.TERM_PROGRAM==="iTerm.app"||Q.TERM_PROGRAM==="vscode"||Q.TERM_PROGRAM==="WezTerm")return!0;if(Q.WT_SESSION)return!0;if(Q.TERM==="xterm-kitty")return!0;let Y=Q.VTE_VERSION?Number.parseInt(Q.VTE_VERSION,10):0;if(!Number.isNaN(Y)&&Y>=5000)return!0;return!1}toAbsoluteFilePath(Q){try{let Y=Q;if(Y.startsWith("file://"))Y=Y.replace(/^file:\/\//,"");if(Y.startsWith("~")){let Z=I.env.HOME||"";if(Z)Y=Y.replace(/^~(?=$|\/)/,Z)}if(bJ(Y)||Y.startsWith("./")||Y.startsWith("../"))Y=yJ(Y);else return null;return QZ(Y)?Y:null}catch{return null}}buildOutputTexts(Q){let Y=this.shouldStyleConsole()?this.formatMarkdown(Q):Q,Z=Q.replace(this.ANSI_PATTERN,"");return{consoleText:Y,fileText:Z}}async log(Q,Y,...Z){if(!this.shouldLog(Q))return;let $=new Date,X=this.formatConsoleTimestamp($),J=this.formatFileTimestamp($),G,U;if(Y instanceof Error)G=Y.message,U=Y.stack;else G=this.formatMessage(Y,Z);let{consoleText:W,fileText:z}=this.buildOutputTexts(G);if(this.shouldStyleConsole()){let _=this.options.showIcons===!1?"":h$[Q],A=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",B;switch(Q){case"debug":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:w.gray(W),level:Q}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:W,level:Q}),console.warn(B);break;case"success":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:w.green(W),level:Q}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:W,level:Q}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:X,icon:_,tag:A,message:W,level:Q}),console.error(B),U){let L=U.split(`
62
- `);for(let R of L)if(R.trim()&&!R.includes(G))console.error(this.formatConsoleMessage({timestamp:X,message:w.gray(` ${R}`),level:Q,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${J} ${this.environment}.${Q.toUpperCase()}: ${G}`),U)console.error(U)}let H=`${J} ${this.environment}.${Q.toUpperCase()}: ${z}
63
- `;if(U)H+=`${U}
64
- `;if(H=H.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(H)}progress(Q,Y=""){let Z={update:(U,W)=>{},finish:(U)=>{},interrupt:(U,W)=>{}};if(!this.enabled)return Z;let $=30;if(this.activeProgressBar={total:Math.max(1,Q||1),current:0,message:Y||"",barLength:$,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!P()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,W="info")=>{if(!P()&&I.stdout.isTTY)I.stdout.write(`
65
- `);if(this[W==="warning"?"warn":W](U),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(Q){let Y=performance.now();if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",$=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":w.blue("\u25D0"),tag:Z,message:`${w.cyan(Q)}...`}))}return async(Z)=>{if(!this.enabled)return;let $=performance.now(),X=Math.round($-Y),J=`${Q} completed in ${X}ms`,G=new Date,U=this.formatConsoleTimestamp(G),z=`${this.formatFileTimestamp(G)} ${this.environment}.INFO: ${J}`;if(Z)z+=` ${JSON.stringify(Z)}`;if(z+=`
66
- `,z=z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let H=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:U,icon:this.options.showIcons===!1?"":w.green("\u2713"),tag:H,message:`${J}${Z?` ${JSON.stringify(Z)}`:""}`}))}else if(!P())console.error(z.trim());if(this.shouldWriteToFile())await this.writeToFile(z)}}async debug(Q,...Y){await this.log("debug",Q,...Y)}async info(Q,...Y){await this.log("info",Q,...Y)}async success(Q,...Y){await this.log("success",Q,...Y)}async warn(Q,...Y){await this.log("warning",Q,...Y)}async error(Q,...Y){await this.log("error",Q,...Y)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let Q=this.config.rotation,{encrypt:Y}=Q;return!!Y}async only(Q){if(!this.enabled)return;return await Q()}isEnabled(){return this.enabled}setEnabled(Q){this.enabled=Q}extend(Q){let Y=`${this.name}:${Q}`,Z=new zZ(Y,{...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(Z),Z}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!QZ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return V$(this.currentLogFile,{encoding:"utf8"})}async decrypt(Q){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let Y=this.config.rotation;if(!Y.encrypt||typeof Y.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Z=this.keys.get(this.currentKeyId);try{let $=BQ.isBuffer(Q)?Q:BQ.from(Q,"base64"),X=$.subarray(0,16),J=$.subarray($.length-16),G=$.subarray(16,$.length-16),U=SJ("aes-256-gcm",Z,X);U.setAuthTag(J);let W=U.update(G),z=U.final(),H=W.length+z.length,_=BQ.allocUnsafe(H);return W.copy(_,0),z.copy(_,W.length),_.toString("utf8")}catch($){throw Error(`Decryption failed: ${$ instanceof Error?$.message:String($)}`)}}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(Q,Y){this.currentKeyId=Q,this.keys.set(Q,Y)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(Q){if(!this.enabled)return;let Y=new Date,Z=this.formatConsoleTimestamp(Y),$=this.formatFileTimestamp(Y),{consoleText:X,fileText:J}=this.buildOutputTexts(Q);if(this.shouldStyleConsole()){let U=X.split(`
67
- `),W=Math.max(...U.map((A)=>A.length))+2,z=`\u250C${"\u2500".repeat(W)}\u2510`,H=`\u2514${"\u2500".repeat(W)}\u2518`,_=U.map((A)=>{return this.formatConsoleMessage({timestamp:Z,message:w.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Z,message:w.cyan(z),showTimestamp:!1})),_.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:Z,message:w.cyan(H),showTimestamp:!1}))}else if(!P())console.error(`${$} ${this.environment}.INFO: [BOX] ${J}`);let G=`${$} ${this.environment}.INFO: [BOX] ${J}
68
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(G)}async prompt(Q){if(P())return Promise.resolve(!0);return new Promise((Y)=>{console.error(`${w.cyan("?")} ${Q} (y/n) `);let Z=($)=>{let X=$.toString().trim().toLowerCase();I.stdin.removeListener("data",Z);try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!1)}catch{}I.stdin.pause(),console.error(""),Y(X==="y"||X==="yes")};try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!0)}catch{}I.stdin.resume(),I.stdin.once("data",Z)})}setFancy(Q){this.fancy=Q}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(Q,...Y){if(!this.enabled)return;let Z=Q;if(Y&&Y.length>0){let W=/%([sdijfo%])/g,z=0;if(Z=Q.replace(W,(H,_)=>{if(_==="%")return"%";if(z>=Y.length)return H;let A=Y[z++];switch(_){case"s":return String(A);case"d":case"i":return Number(A).toString();case"j":case"o":return JSON.stringify(A,null,2);default:return H}}),z<Y.length)Z+=` ${Y.slice(z).map((H)=>typeof H==="object"?JSON.stringify(H,null,2):String(H)).join(" ")}`}let{consoleText:$,fileText:X}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",z=this.options.showIcons===!1?"":`${w.blue("\u25D0")} `;console.error(`${z}${W} ${w.cyan($)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
69
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}renderProgressBar(Q,Y=!1){if(!this.enabled||!this.shouldStyleConsole()||!I.stdout.isTTY)return;let Z=Math.min(100,Math.max(0,Math.round(Q.current/Q.total*100))),$=Math.round(Q.barLength*Z/100),X=Q.barLength-$,J=w.green("\u2501".repeat($)),G=w.gray("\u2501".repeat(X)),U=`[${J}${G}]`,W=`${Z}%`.padStart(4),z=Q.message?` ${Q.message}`:"",H=this.options.showIcons===!1?"":Y||Z===100?w.green("\u2713"):w.blue("\u25B6"),_=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",A=`\r${H}${_} ${U} ${W}${z}`,B=I.stdout.columns||80,L=" ".repeat(Math.max(0,B-A.replace(this.ANSI_PATTERN,"").length));if(Q.lastRenderedLine=`${A}${L}`,I.stdout.write(Q.lastRenderedLine),Y)I.stdout.write(`
70
- `)}finishProgressBar(Q,Y){if(!this.enabled||!this.fancy||P()||!I.stdout.isTTY){this.activeProgressBar=null;return}if(Q.current<Q.total)Q.current=Q.total;if(Y)Q.message=Y;this.renderProgressBar(Q,!0),this.activeProgressBar=null}async clear(Q={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let Y=await YZ(this.config.logDirectory),Z=[];for(let $ of Y){if(!(Q.name?new RegExp(Q.name.replace("*",".*")).test($):$.startsWith(this.name))||!$.endsWith(".log"))continue;let J=mQ(this.config.logDirectory,$);if(Q.before)try{if((await fQ(J)).mtime>=Q.before)continue}catch(G){console.error(`Failed to get stats for file ${J}:`,G);continue}Z.push(J)}if(Z.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Z.length} log file(s)...`);for(let $ of Z)try{await ZZ($),console.warn(`Deleted log file: ${$}`)}catch(X){console.error(`Failed to delete log file ${$}:`,X)}console.warn("Log clearing process finished.")}catch(Y){console.error("Error during log clearing process:",Y)}}}var S$,w8,WY,Y7,b,w,Z7,C$,$7,x$,X7,J7,E8,G7,k$,P$,W7,O8,U7,z7,H7,_7,A7,JZ,h$,B7,R7=jQ(()=>{S$=GZ.env.CLARITY_LOG_DIR||qJ(eJ(),"logs"),w8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:S$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},WY={...w8},Y7=(async()=>{try{let{loadConfig:Q}=await Promise.resolve().then(()=>(r$(),t$)),Y=await Q({name:"clarity",alias:"logging",defaultConfig:w8,cwd:GZ.cwd()});if(Y)Object.assign(WY,Y)}catch{}return WY})(),b={red:(Q)=>`\x1B[31m${Q}\x1B[0m`,green:(Q)=>`\x1B[32m${Q}\x1B[0m`,yellow:(Q)=>`\x1B[33m${Q}\x1B[0m`,blue:(Q)=>`\x1B[34m${Q}\x1B[0m`,magenta:(Q)=>`\x1B[35m${Q}\x1B[0m`,cyan:(Q)=>`\x1B[36m${Q}\x1B[0m`,white:(Q)=>`\x1B[37m${Q}\x1B[0m`,gray:(Q)=>`\x1B[90m${Q}\x1B[0m`,bgRed:(Q)=>`\x1B[41m${Q}\x1B[0m`,bgYellow:(Q)=>`\x1B[43m${Q}\x1B[0m`,bgGray:(Q)=>`\x1B[100m${Q}\x1B[0m`,bold:(Q)=>`\x1B[1m${Q}\x1B[0m`,dim:(Q)=>`\x1B[2m${Q}\x1B[0m`,italic:(Q)=>`\x1B[3m${Q}\x1B[0m`,underline:(Q)=>`\x1B[4m${Q}\x1B[0m`,strikethrough:(Q)=>`\x1B[9m${Q}\x1B[0m`,reset:"\x1B[0m"},w=b,Z7=b.red,C$=b.green,$7=b.yellow,x$=b.blue,X7=b.magenta,J7=b.cyan,E8=b.white,G7=b.gray,k$=b.bgRed,P$=b.bgYellow,W7=b.bgGray,O8=b.bold,U7=b.dim,z7=b.italic,H7=b.underline,_7=b.strikethrough,A7=b.reset,JZ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},h$={debug:"\uD83D\uDD0D",info:x$("\u2139"),success:C$("\u2713"),warning:P$(E8(O8(" WARN "))),error:k$(E8(O8(" ERROR ")))},B7=new zZ("stacks")}),L7="0.15.9",j7=()=>{};async function d$(Q,Y={}){let{maxRetries:Z=3,retryDelay:$=1000,isRetryable:X=()=>!0,fallback:J}=Y,G=Error("Unknown error occurred");for(let U=0;U<=Z;U++)try{return await Q()}catch(W){if(G=W instanceof Error?W:Error(String(W)),U===Z||!X(G))break;if($>0)await new Promise((z)=>setTimeout(z,$))}if(J!==void 0)return J;throw G instanceof Error?G:Error(`Unknown error: ${String(G)}`)}function f$(Q){return Q instanceof i}function K7(Q){return Q instanceof WZ}function F7(Q){if(f$(Q))return Q.code==="FILE_SYSTEM_ERROR"||Q.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Z)=>Q.message.toLowerCase().includes(Z.toLowerCase()))}var i,WZ,UY,T8,N8,UZ,S8,C8,zY,x8,k8,MQ,cQ=jQ(()=>{i=class extends Error{timestamp;context;constructor(Y,Z={}){super(Y);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Z,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 Y=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Z,$])=>`${Z}: ${$}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${Y}`}},WZ=class extends i{code="CONFIG_NOT_FOUND";constructor(Y,Z,$){let X=$===void 0?[]:Array.isArray($)?$.filter(Boolean):[$],J="";if(X.length===1)J=` or alias "${X[0]}"`;else if(X.length>1)J=` or aliases ${X.map((G)=>`"${G}"`).join(", ")}`;super(`Configuration "${Y}"${J} not found`,{configName:Y,alias:$,searchPaths:Z,searchPathCount:Z.length})}},UY=class extends i{code="CONFIG_LOAD_ERROR";constructor(Y,Z,$){super(`Failed to load configuration from "${Y}": ${Z.message}`,{configPath:Y,configName:$,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},T8=class extends i{code="CONFIG_VALIDATION_ERROR";constructor(Y,Z,$){super(`Configuration validation failed for "${Y}"`,{configPath:Y,configName:$,validationErrors:Z,errorCount:Z.length})}},N8=class extends i{code="CONFIG_MERGE_ERROR";constructor(Y,Z,$,X){super(`Failed to merge configuration from "${Y}" with "${Z}": ${$.message}`,{sourcePath:Y,targetPath:Z,configName:X,originalError:$.name,originalMessage:$.message});this.cause=$}},UZ=class extends i{code="ENV_VAR_ERROR";constructor(Y,Z,$,X){super(`Failed to parse environment variable "${Y}" with value "${Z}" as ${$}`,{envKey:Y,envValue:Z,expectedType:$,configName:X})}},S8=class extends i{code="FILE_SYSTEM_ERROR";constructor(Y,Z,$){super(`File system ${Y} failed for "${Z}": ${$.message}`,{operation:Y,path:Z,originalError:$.name,originalMessage:$.message});this.cause=$}},C8=class extends i{code="TYPE_GENERATION_ERROR";constructor(Y,Z,$){super(`Failed to generate types from "${Y}" to "${Z}": ${$.message}`,{configDir:Y,outputPath:Z,originalError:$.name,originalMessage:$.message});this.cause=$}},zY=class extends i{code="SCHEMA_VALIDATION_ERROR";constructor(Y,Z,$){super(`Schema validation failed${$?` for config "${$}"`:""}`,{schemaPath:Y,configName:$,validationErrors:Z,errorCount:Z.length})}},x8=class extends i{code="BROWSER_CONFIG_ERROR";constructor(Y,Z,$,X){super(`Failed to fetch configuration from "${Y}": ${Z} ${$}`,{endpoint:Y,status:Z,statusText:$,configName:X})}},k8=class extends i{code="PLUGIN_ERROR";constructor(Y,Z,$){super(`Plugin "${Y}" failed during ${Z}: ${$.message}`,{pluginName:Y,operation:Z,originalError:$.name,originalMessage:$.message});this.cause=$}},MQ={configNotFound(Q,Y,Z){return new WZ(Q,Y,Z)},configLoad(Q,Y,Z){return new UY(Q,Y,Z)},configValidation(Q,Y,Z){return new T8(Q,Y,Z)},configMerge(Q,Y,Z,$){return new N8(Q,Y,Z,$)},envVar(Q,Y,Z,$){return new UZ(Q,Y,Z,$)},fileSystem(Q,Y,Z){return new S8(Q,Y,Z)},typeGeneration(Q,Y,Z){return new C8(Q,Y,Z)},schemaValidation(Q,Y,Z){return new zY(Q,Y,Z)},browserConfig(Q,Y,Z,$){return new x8(Q,Y,Z,$)},plugin(Q,Y,Z){return new k8(Q,Y,Z)}}});class HZ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(Q,Y)=>Y==="boolean"||["true","false","1","0","yes","no"].includes(Q.toLowerCase()),parse:(Q)=>{let Y=Q.toLowerCase();return["true","1","yes"].includes(Y)}},{name:"number",canParse:(Q,Y)=>Y==="number"||!Number.isNaN(Number(Q))&&!Number.isNaN(Number.parseFloat(Q)),parse:(Q)=>{let Y=Number(Q);if(Number.isNaN(Y))throw TypeError(`Cannot parse "${Q}" as number`);return Y}},{name:"array",canParse:(Q,Y)=>Y==="array"||Q.startsWith("[")||Q.includes(","),parse:(Q)=>{try{let Y=JSON.parse(Q);if(Array.isArray(Y))return Y}catch{}return Q.split(",").map((Y)=>Y.trim())}},{name:"json",canParse:(Q,Y)=>Y==="object"||(Q.startsWith("{")&&Q.endsWith("}")||Q.startsWith("[")&&Q.endsWith("]")),parse:(Q)=>{try{return JSON.parse(Q)}catch(Y){throw Error(`Cannot parse "${Q}" as JSON: ${Y}`)}}}]}async applyEnvironmentVariables(Q,Y,Z={}){let{prefix:$,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:G={},verbose:U=!1,trackPerformance:W=!0}=Z,z=async()=>{if(!Q)return{config:Y,source:{type:"environment",priority:50,timestamp:new Date}};let H=$||this.generateEnvPrefix(Q),_={...Y};return this.processObject(_,[],H,{useCamelCase:X,useBackwardCompatibility:J,customParsers:G,verbose:U,configName:Q}),{config:_,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return _Y.track("applyEnvironmentVariables",z,{configName:Q});return z()}generateEnvPrefix(Q){return Q.toUpperCase().replace(/-/g,"_")}formatEnvKey(Q,Y){if(!Y)return Q.toUpperCase();return Q.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(Q,Y,Z,$){for(let[X,J]of Object.entries(Q)){let G=[...Y,X],U=G.map((H)=>this.formatEnvKey(H,$.useCamelCase)),W=`${Z}_${U.join("_")}`,z=$.useBackwardCompatibility?`${Z}_${G.map((H)=>H.toUpperCase()).join("_")}`:null;if($.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,G,Z,$);else{let H=$Z.env[W]||(z?$Z.env[z]:void 0);if(H!==void 0){if($.verbose){let _=$Z.env[W]?W:z}try{Q[X]=this.parseEnvironmentValue(H,typeof J,W,$.customParsers,$.configName)}catch(_){if(_ instanceof UZ)throw _;throw MQ.envVar(W,H,typeof J,$.configName)}}}}}parseEnvironmentValue(Q,Y,Z,$,X){for(let[J,G]of Object.entries($))try{return G(Q)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(Q,Y))try{return J.parse(Q)}catch{throw MQ.envVar(Z,Q,`${Y} (via ${J.name} parser)`,X)}return Q}getEnvironmentVariables(Q){let Y={},Z=Q.toUpperCase();for(let[$,X]of Object.entries($Z.env))if($.startsWith(Z)&&X!==void 0)Y[$]=X;return Y}validateEnvironmentVariable(Q,Y,Z){let $=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(Q))$.push(`Environment variable key "${Q}" should only contain uppercase letters, numbers, and underscores`);if(Z)try{this.parseEnvironmentValue(Q,Y,Z,{})}catch(X){$.push(`Cannot parse value "${Y}" as ${Z}: ${X}`)}return{isValid:$.length===0,errors:$}}generateEnvVarDocs(Q,Y,Z={}){let{prefix:$,format:X="text"}=Z,J=$||this.generateEnvPrefix(Q),G=[];switch(this.extractEnvVarInfo(Y,[],J,G),X){case"markdown":return this.formatAsMarkdown(G,Q);case"json":return JSON.stringify(G,null,2);default:return this.formatAsText(G,Q)}}extractEnvVarInfo(Q,Y,Z,$){for(let[X,J]of Object.entries(Q)){let G=[...Y,X],U=`${Z}_${G.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,G,Z,$);else $.push({key:U,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${G.join(".")}`,example:this.generateExample(J)})}}generateExample(Q){if(Array.isArray(Q))return JSON.stringify(Q);if(typeof Q==="object"&&Q!==null)return JSON.stringify(Q);return String(Q)}formatAsText(Q,Y){let Z=`Environment Variables for ${Y}:
71
-
72
- `;for(let $ of Q)Z+=`${$.key}
73
- `,Z+=` Type: ${$.type}
74
- `,Z+=` Description: ${$.description}
75
- `,Z+=` Example: ${$.example}
76
-
77
- `;return Z}formatAsMarkdown(Q,Y){let Z=`# Environment Variables for ${Y}
78
-
79
- `;Z+=`| Variable | Type | Description | Example |
80
- `,Z+=`|----------|------|-------------|----------|
81
- `;for(let $ of Q)Z+=`| \`${$.key}\` | ${$.type} | ${$.description} | \`${$.example}\` |
82
- `;return Z}}var m$=jQ(()=>{AY(),cQ()});function M7(Q,Y){let Z=oJ("process");if(typeof Z>"u"||!Z.env)return Y;let $=Z.env[Q];return $!==void 0?$:Y}function g$(Q,Y,Z={}){return p$(Q,Y,Z,new WeakMap)}function p$(Q,Y,Z,$){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:G}=Z;if(Y===null||Y===void 0)return J?Q:Y;if(G){let U=G(Q,Y);if(U!==void 0)return U}if(Array.isArray(Y)||Array.isArray(Q))return u$(Q,Y,X,$);if(!QQ(Y)||!QQ(Q))return Y;return w7(Q,Y,Z,$)}function u$(Q,Y,Z,$){if(Array.isArray(Y)&&!Array.isArray(Q))return Y;if(Array.isArray(Q)&&!Array.isArray(Y))return Y;if(Array.isArray(Y)&&Array.isArray(Q))switch(Z){case"replace":return Y;case"concat":return I7(Q,Y);case"smart":return V7(Q,Y,$);default:return Y}return Y}function I7(Q,Y){let Z=[...Y];for(let $ of Q)if(!Z.some((X)=>P8(X,$)))Z.push($);return Z}function V7(Q,Y,Z){if(Y.length===0)return Q;if(Q.length===0)return Y;if(QQ(Y[0])&&QQ(Q[0]))return D7(Q,Y,Z);if(Y.every(($)=>typeof $==="string")&&Q.every(($)=>typeof $==="string")){let $=[...Y];for(let X of Q)if(!$.includes(X))$.push(X);return $}return Y}function D7(Q,Y,Z){let $=[...Y];for(let X of Q){if(!QQ(X)){$.push(X);continue}let J=["id","name","key","path","type"],G=!1;for(let U of J)if(U in X){if($.find((z)=>QQ(z)&&(U in z)&&z[U]===X[U])){G=!0;break}}if(!G)$.push(X)}return $}function w7(Q,Y,Z,$){let X=Y;if(QQ(X)&&$.has(X))return $.get(X);let J={...Q};if(QQ(X))$.set(X,J);for(let G in X){if(!Object.prototype.hasOwnProperty.call(X,G))continue;let U=X[G],W=J[G];if(Z.skipNullish&&(U===null||U===void 0))continue;if(U===null||U===void 0){J[G]=U;continue}if(QQ(U)&&QQ(W))J[G]=p$(W,U,Z,$);else if(Array.isArray(U)||Array.isArray(W))J[G]=u$(W,U,Z.arrayMergeMode||"smart",$);else J[G]=U}return J}function v8(Q,Y,Z="replace"){return g$(Q,Y,{arrayMergeMode:Z==="replace"?"replace":"smart",skipNullish:!0})}function P8(Q,Y){if(Q===Y)return!0;if(Array.isArray(Q)&&Array.isArray(Y)){if(Q.length!==Y.length)return!1;for(let Z=0;Z<Q.length;Z++)if(!P8(Q[Z],Y[Z]))return!1;return!0}if(QQ(Q)&&QQ(Y)){let Z=Object.keys(Q),$=Object.keys(Y);if(Z.length!==$.length)return!1;for(let X of Z){if(!Object.prototype.hasOwnProperty.call(Y,X))return!1;if(!P8(Q[X],Y[X]))return!1}return!0}return!1}function QQ(Q){return Boolean(Q&&typeof Q==="object"&&!Array.isArray(Q))}var c$,h8=jQ(()=>{c$={replace:"replace",concat:"concat",smart:"smart"}});class _Z{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(Q,Y,Z={}){let{arrayStrategy:$="replace",useCache:X=!0,cacheTtl:J,trackPerformance:G=!0,verbose:U=!1}=Z;if(X){let z=uQ.getWithFileCheck("file",Q);if(z){if(U)console.log(`Configuration loaded from cache: ${Q}`);return z}}let W=async()=>{if(!XZ(Q))return null;try{let z=`?t=${Date.now()}`,H=await import(Q+z),_=H.default||H,A="default"in H,B=Object.keys(H).length>0;if(!A&&!B)throw new UY(Q,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof _!=="object"||_===null||Array.isArray(_))throw new UY(Q,Error("Configuration must export a valid object"),"unknown");let j={config:v8(Y,_,$),source:{type:"file",path:Q,priority:100,timestamp:new Date}};if(X)uQ.setWithFileCheck("file",j,Q,J);return j}catch(z){throw z instanceof Error?MQ.configLoad(Q,z):MQ.configLoad(Q,Error(String(z)))}};if(G)return _Y.track("loadFromPath",W,{path:Q});return W()}async tryLoadFromPaths(Q,Y,Z={}){for(let $ of Q)try{let X=await this.loadFromPath($,Y,Z);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Z.verbose)console.warn(`Failed to load config from ${$}:`,X)}return null}generateConfigPaths(Q,Y,Z){let $=this.generateNamePatterns(Q,Z),X=[];for(let J of $)for(let G of this.extensions)X.push(V8(Y,`${J}${G}`));return X}generateNamePatterns(Q,Y){let Z=[];if(Z.push("config",".config"),Q)Z.push(Q,`.${Q}.config`,`${Q}.config`,`.${Q}`);let $=Y===void 0?[]:Array.isArray(Y)?Y:[Y];for(let J of $){if(!J)continue;if(Z.push(J,`.${J}.config`,`${J}.config`,`.${J}`),Q)Z.push(`${Q}.${J}.config`,`.${Q}.${J}.config`)}let X=new Set;return Z.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(Q){return d$(async()=>{return XZ(Q)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(Q,Y,Z){let $=[];if(!XZ(Q))return $;if(Y||Z){let X=this.generateNamePatterns(Y||"",Z);for(let J of X)for(let G of this.extensions){let U=V8(Q,`${J}${G}`);if(await this.checkFileAccess(U))$.push(U)}}else try{let{readdirSync:X}=await import("fs"),J=X(Q);for(let G of J)if(this.looksLikeConfigFile(G)){let U=V8(Q,G);if(await this.checkFileAccess(U))$.push(U)}}catch{return[]}return $}looksLikeConfigFile(Q){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Z)=>Z.test(Q))}async validateConfigFile(Q){let Y=[];try{if(!XZ(Q))return Y.push("Configuration file does not exist"),Y;let Z=await import(Q),$=Z.default||Z;if($===void 0)Y.push("Configuration file must export a default value or named exports");else if(typeof $!=="object"||$===null)Y.push("Configuration must be an object");else if(Array.isArray($))Y.push("Configuration cannot be an array at the root level");if(Q.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(Q,"utf8");JSON.parse(J)}catch(X){Y.push(`Invalid JSON syntax: ${X}`)}}catch(Z){Y.push(`Failed to load configuration file: ${Z}`)}return Y}async getFileModificationTime(Q){try{let{statSync:Y}=await import("fs");return Y(Q).mtime}catch{return null}}async preloadConfigurations(Q,Y={}){let Z=new Map;return await Promise.allSettled(Q.map(async($)=>{try{let X=await this.loadFromPath($,{},Y);if(X)Z.set($,X.config)}catch(X){if(Y.verbose)console.warn(`Failed to preload ${$}:`,X)}})),Z}}var l$=jQ(()=>{AY(),cQ(),h8()});class d8{async validateConfiguration(Q,Y,Z={}){let{stopOnFirstError:$=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:G=[],trackPerformance:U=!0,verbose:W=!1}=Z,z=async()=>{let H=[],_=[],A={stopOnFirstError:$,validateRequired:X,validateTypes:J,customRules:G,trackPerformance:U,verbose:W};try{if(typeof Y==="string")return await this.validateWithSchemaFile(Q,Y,A);else if(Array.isArray(Y))return this.validateWithRules(Q,[...Y,...G],A);else return this.validateWithJSONSchema(Q,Y,A)}catch(B){return H.push({path:"",message:`Validation failed: ${B}`,rule:"system"}),{isValid:!1,errors:H,warnings:_}}};if(U)return await _Y.track("validateConfiguration",z);return z()}async validateWithSchemaFile(Q,Y,Z){try{if(!hJ(Y))throw new zY(Y,[{path:"",message:"Schema file does not exist"}]);let $=await import(Y),X=$.default||$;if(Array.isArray(X))return this.validateWithRules(Q,X,Z);else return this.validateWithJSONSchema(Q,X,Z)}catch($){throw new zY(Y,[{path:"",message:`Failed to load schema: ${$}`}])}}validateWithJSONSchema(Q,Y,Z){let $=[],X=[];return this.validateObjectAgainstSchema(Q,Y,"",$,X,Z),{isValid:$.length===0,errors:$,warnings:X}}validateObjectAgainstSchema(Q,Y,Z,$,X,J){if(J.validateTypes&&Y.type){let G=Array.isArray(Q)?"array":typeof Q,U=Array.isArray(Y.type)?Y.type:[Y.type];if(!U.includes(G)){if($.push({path:Z,message:`Expected type ${U.join(" or ")}, got ${G}`,expected:U.join(" or "),actual:G,rule:"type"}),J.stopOnFirstError)return}}if(Y.enum&&!Y.enum.includes(Q)){if($.push({path:Z,message:`Value must be one of: ${Y.enum.join(", ")}`,expected:Y.enum.join(", "),actual:Q,rule:"enum"}),J.stopOnFirstError)return}if(typeof Q==="string"){if(Y.minLength!==void 0&&Q.length<Y.minLength)$.push({path:Z,message:`String length must be at least ${Y.minLength}`,expected:`>= ${Y.minLength}`,actual:Q.length,rule:"minLength"});if(Y.maxLength!==void 0&&Q.length>Y.maxLength)$.push({path:Z,message:`String length must not exceed ${Y.maxLength}`,expected:`<= ${Y.maxLength}`,actual:Q.length,rule:"maxLength"});if(Y.pattern){if(!new RegExp(Y.pattern).test(Q))$.push({path:Z,message:`String does not match pattern ${Y.pattern}`,expected:Y.pattern,actual:Q,rule:"pattern"})}}if(typeof Q==="number"){if(Y.minimum!==void 0&&Q<Y.minimum)$.push({path:Z,message:`Value must be at least ${Y.minimum}`,expected:`>= ${Y.minimum}`,actual:Q,rule:"minimum"});if(Y.maximum!==void 0&&Q>Y.maximum)$.push({path:Z,message:`Value must not exceed ${Y.maximum}`,expected:`<= ${Y.maximum}`,actual:Q,rule:"maximum"})}if(Array.isArray(Q)&&Y.items)for(let G=0;G<Q.length;G++){let U=Z?`${Z}[${G}]`:`[${G}]`;if(this.validateObjectAgainstSchema(Q[G],Y.items,U,$,X,J),J.stopOnFirstError&&$.length>0)return}if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let G=Q;if(J.validateRequired&&Y.required){for(let U of Y.required)if(!(U in G)){if($.push({path:Z?`${Z}.${U}`:U,message:`Missing required property '${U}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(Y.properties){for(let[U,W]of Object.entries(Y.properties))if(U in G){let z=Z?`${Z}.${U}`:U;if(this.validateObjectAgainstSchema(G[U],W,z,$,X,J),J.stopOnFirstError&&$.length>0)return}}if(Y.additionalProperties===!1){let U=new Set(Object.keys(Y.properties||{}));for(let W of Object.keys(G))if(!U.has(W))X.push({path:Z?`${Z}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(Q,Y,Z){let $=[],X=[];for(let J of Y)try{let G=this.getValueByPath(Q,J.path),U=this.validateWithRule(G,J,J.path);if($.push(...U),Z.stopOnFirstError&&$.length>0)break}catch(G){$.push({path:J.path,message:`Rule validation failed: ${G}`,rule:"system"})}return{isValid:$.length===0,errors:$,warnings:X}}validateWithRule(Q,Y,Z){let $=[];if(Y.required&&(Q===void 0||Q===null))return $.push({path:Z,message:Y.message||`Property '${Z}' is required`,expected:"required",rule:"required"}),$;if(Q===void 0||Q===null)return $;if(Y.type){let X=Array.isArray(Q)?"array":typeof Q;if(X!==Y.type)$.push({path:Z,message:Y.message||`Expected type ${Y.type}, got ${X}`,expected:Y.type,actual:X,rule:"type"})}if(Y.min!==void 0){let X=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if(X<Y.min)$.push({path:Z,message:Y.message||`Value must be at least ${Y.min}`,expected:`>= ${Y.min}`,actual:X,rule:"min"})}if(Y.max!==void 0){let X=Array.isArray(Q)?Q.length:typeof Q==="string"?Q.length:typeof Q==="number"?Q:0;if(X>Y.max)$.push({path:Z,message:Y.message||`Value must not exceed ${Y.max}`,expected:`<= ${Y.max}`,actual:X,rule:"max"})}if(Y.pattern&&typeof Q==="string"){if(!Y.pattern.test(Q))$.push({path:Z,message:Y.message||`Value does not match pattern ${Y.pattern}`,expected:Y.pattern.toString(),actual:Q,rule:"pattern"})}if(Y.enum&&!Y.enum.includes(Q))$.push({path:Z,message:Y.message||`Value must be one of: ${Y.enum.join(", ")}`,expected:Y.enum.join(", "),actual:Q,rule:"enum"});if(Y.validator){let X=Y.validator(Q);if(X)$.push({path:Z,message:Y.message||X,rule:"custom"})}return $}getValueByPath(Q,Y){if(!Y)return Q;let Z=Y.split("."),$=Q;for(let X of Z)if($&&typeof $==="object"&&X in $)$=$[X];else return;return $}generateRulesFromInterface(Q){let Y=[],Z=Q.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let $ of Z){let[,X,J,G]=$;Y.push({path:X,required:!J,type:this.mapTypeScriptType(G)})}return Y}mapTypeScriptType(Q){switch(Q.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:n$},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var n$,i$=jQ(()=>{AY(),cQ(),n$=/^https?:\/\//});function E7(Q){if(!Q)return"";let Y=Array.isArray(Q)?Q.filter(Boolean):[Q];if(Y.length===0)return"";if(Y.length===1)return` or alias "${Y[0]}"`;return` or aliases ${Y.map((Z)=>`"${Z}"`).join(", ")}`}class f8{fileLoader=new _Z;envProcessor=new HZ;validator=new d8;async loadConfig(Q){let Y=Date.now(),{cache:Z,performance:$,schema:X,validate:J,...G}=Q;try{if(Z?.enabled){let W=this.checkCache(G.name||"",G);if(W)return W}let U;try{U=await this.loadConfigurationStrategies(G,!0,Z)}catch(W){let z=G.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(z)throw W;U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`No configuration file found for "${G.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let H=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),_=!H&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),A=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(z&&(A||H))throw W;if(_&&(!z||!A))U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!z)U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else U={...await this.applyEnvironmentVariables(G.name||"",G.defaultConfig,G.checkEnv!==!1,G.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(U.config,X,J,G.name);if(Z?.enabled&&U)this.cacheResult(G.name||"",U,Z,G);if($?.enabled){let W={operation:"loadConfig",duration:Date.now()-Y,configName:G.name,timestamp:new Date};if($.onMetrics)$.onMetrics(W);if($.slowThreshold&&W.duration>$.slowThreshold)e.warn(`Slow configuration loading detected: ${W.duration}ms for ${G.name}`);U.metrics=W}return U}catch(U){let W=Date.now()-Y;throw e.error(`Configuration loading failed after ${W}ms:`,[U instanceof Error?U:Error(String(U))]),U}}async loadConfigurationStrategies(Q,Y=!1,Z){let{name:$="",alias:X,cwd:J,configDir:G,defaultConfig:U,checkEnv:W=!0,arrayStrategy:z="replace",verbose:H=!1}=Q,_=J||DQ.cwd(),A=[],B=await this.loadLocalConfiguration($,X,_,G,U,z,H,W,Z);if(B)return A.push(...this.getLocalSearchPaths($,X,_,G)),this.finalizeResult(B,A,W,$,H);let L=await this.loadHomeConfiguration($,X,U,z,H,W);if(L)return A.push(...this.getHomeSearchPaths($,X)),this.finalizeResult(L,A,W,$,H);let R=await this.loadPackageJsonConfiguration($,X,_,U,z,H,W);if(R)return A.push(c(_,"package.json")),this.finalizeResult(R,A,W,$,H);if(A.push(...this.getAllSearchPaths($,X,_,G)),Y)throw MQ.configNotFound($,A,X);return{...await this.applyEnvironmentVariables($,U,W,H),warnings:[`No configuration file found for "${$}"${E7(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(Q,Y,Z,$,X,J,G,U,W){let z=U?GY(Q,X,G):X,H=this.getLocalDirectories(Z,$);for(let _ of H){if(G)e.info(`Searching for configuration in: ${_}`);let A=this.fileLoader.generateConfigPaths(Q,_,Y),B=await this.fileLoader.tryLoadFromPaths(A,z,{arrayStrategy:J,verbose:G,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(B){if(G)e.success(`Configuration loaded from: ${B.source.path}`);return B}}return null}async loadHomeConfiguration(Q,Y,Z,$,X,J){if(!Q)return null;let G=J?GY(Q,Z,X):Z,U=[c(pQ(),".config",Q),c(pQ(),".config"),pQ()];for(let W of U){if(X)e.info(`Checking home directory: ${W}`);let z=this.fileLoader.generateConfigPaths(Q,W,Y),H=await this.fileLoader.tryLoadFromPaths(z,G,{arrayStrategy:$,verbose:X});if(H){if(X)e.success(`Configuration loaded from home directory: ${H.source.path}`);return H}}return null}async loadPackageJsonConfiguration(Q,Y,Z,$,X,J,G){let U=G?GY(Q,$,J):$;try{let W=c(Z,"package.json");if(!q8(W))return null;let z={};try{z=JSON.parse(mJ(W,"utf8"))}catch(A){if(J)e.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let H=z[Q],_=Q;if(!H&&Y){let A=Array.isArray(Y)?Y:[Y];for(let B of A){if(!B)continue;if(z[B]){H=z[B],_=B;break}}}if(H&&typeof H==="object"&&!Array.isArray(H)){if(J)e.success(`Configuration loaded from package.json: ${_}`);return{config:v8(U,H,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)e.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(Q,Y,Z,$){if(!Z||!Q||typeof Y!=="object"||Y===null||Array.isArray(Y))return{config:Y,source:{type:"default",priority:10,timestamp:new Date}};return{config:GY(Q,Y,$),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(Q,Y,Z,$,X){return{config:Q.config,source:Q.source,path:Q.source.path}}async validateConfiguration(Q,Y,Z,$){let X=[];if(Z){let J=Z(Q);if(J)X.push(...J)}if(Y){let J=await this.validator.validateConfiguration(Q,Y);if(!J.isValid)X.push(...J.errors.map((G)=>G.path?`${G.path}: ${G.message}`:G.message))}if(X.length>0)throw MQ.configValidation($||"unknown",X,$)}checkCache(Q,Y){let Z=this.generateCacheKey(Q,Y);return uQ.get(Z)||null}cacheResult(Q,Y,Z,$){let X=this.generateCacheKey(Q,$);uQ.set(X,Y,void 0,Z.ttl)}generateCacheKey(Q,Y){let Z=[Q];if(Y.alias){let $=Array.isArray(Y.alias)?Y.alias.join(","):Y.alias;Z.push(`alias:${$}`)}if(Y.cwd)Z.push(`cwd:${Y.cwd}`);if(Y.configDir)Z.push(`configDir:${Y.configDir}`);if("checkEnv"in Y)Z.push(`checkEnv:${Y.checkEnv}`);return Z.join("|")}getLocalDirectories(Q,Y){return Array.from(new Set([Q,c(Q,"config"),c(Q,".config"),Y?c(Q,Y):void 0].filter(Boolean)))}getAllSearchPaths(Q,Y,Z,$){let X=[];return X.push(...this.getLocalSearchPaths(Q,Y,Z,$)),X.push(...this.getHomeSearchPaths(Q,Y)),X.push(c(Z,"package.json")),X}getLocalSearchPaths(Q,Y,Z,$){let X=this.getLocalDirectories(Z,$),J=[];for(let G of X)J.push(...this.fileLoader.generateConfigPaths(Q,G,Y));return J}getHomeSearchPaths(Q,Y){if(!Q)return[];let Z=[c(pQ(),".config",Q),c(pQ(),".config"),pQ()],$=[];for(let X of Z)$.push(...this.fileLoader.generateConfigPaths(Q,X,Y));return $}async loadConfigWithResult(Q){return this.loadConfig(Q)}}function b$(Q){let Z=!(Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"))&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")),$=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");return Z||$}async function O7(Q){return LQ.loadConfig({...Q,__strictErrorHandling:!0})}async function s$(Q){let Y="defaultConfig"in Q&&Q.defaultConfig!==void 0?Q.defaultConfig:{},Z="cache"in Q||"performance"in Q||"schema"in Q||"validate"in Q;try{let $;if(Z)$=await LQ.loadConfig(Q);else $=await LQ.loadConfig({...Q,defaultConfig:Y,cache:{enabled:!0},performance:{enabled:!1}});return $?.config??Y}catch($){let X=$ instanceof Error?$.name:"UnknownError",J=$ instanceof Error?$.message:String($);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&Q.verbose)e.warn("Unexpected error loading config, using defaults:",[$ instanceof Error?$:Error(String($))]);let U=Z?{...Q,defaultConfig:Y}:{...Q,defaultConfig:Y,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in Q?Q.checkEnv!==!1:!0)return(await LQ.applyEnvironmentVariables(U.name||"",Y,!0,U.verbose||!1))?.config??Y;return Y}}async function q7(Q={defaultConfig:{}}){if(typeof Q==="string"){let{cwd:Y}=await import("process");try{return(await LQ.loadConfig({name:Q,cwd:Y(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Z){if(Z instanceof Error&&(Z.name==="ConfigNotFoundError"||Z.name==="ConfigLoadError"&&b$(Z)))return(await LQ.applyEnvironmentVariables(Q,{},!0,!1)).config;throw Z}}try{return(await LQ.loadConfig({...Q,cwd:Q.cwd||DQ.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&b$(Y)))return(await LQ.applyEnvironmentVariables(Q.name||"",Q.defaultConfig||{},Q.checkEnv!==!1,Q.verbose||!1)).config;throw Y}}async function T7(Q,Y,Z="replace"){let $=new _Z;try{let X=await $.loadFromPath(Q,Y,{arrayStrategy:Z,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function GY(Q,Y,Z=!1){let $=new HZ,X=Q.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(G,U=[]){let W={...G};for(let[z,H]of Object.entries(G)){let _=[...U,z],A=[`${X}_${_.join("_").toUpperCase()}`,`${X}_${_.map((R)=>R.toUpperCase()).join("")}`,`${X}_${_.map((R)=>R.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],B,L;for(let R of A)if(B=DQ.env[R],B!==void 0){L=R;break}if(B!==void 0&&L)if(typeof H==="boolean")W[z]=["true","1","yes"].includes(B.toLowerCase());else if(typeof H==="number"){let R=Number(B);if(!Number.isNaN(R))W[z]=R}else if(Array.isArray(H))try{W[z]=JSON.parse(B)}catch{W[z]=B.split(",").map((R)=>R.trim())}else W[z]=B;else if(H&&typeof H==="object"&&!Array.isArray(H))W[z]=J(H,_)}return W}return J(Y)}function N7(Q){let Y=c(DQ.cwd(),Q.configDir),Z=c(DQ.cwd(),Q.generatedDir),$=c(Z,"config-types.ts");if(!q8(T$($)))dJ(T$($),{recursive:!0,mode:511});let X=q8(Y)?fJ(Y).map((G)=>G.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${L7}
83
- export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
84
- `;gJ($,J,{mode:438})}function S7(Q){let Y=null,Z=null,$=()=>{if(!Z)Z=s$(Q).then((J)=>{return Y=J,J},(J)=>{let G="defaultConfig"in Q?Q.defaultConfig:{};if(Y=G,"verbose"in Q&&Q.verbose)e.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return G});return Z},X="defaultConfig"in Q?Q.defaultConfig:{};return Y=X,$(),new Proxy({},{get(J,G){if(Y)return Y[G];let U=X[G];return $(),U},has(J,G){return G in(Y||X)},ownKeys(){return Object.keys(Y||X)},getOwnPropertyDescriptor(J,G){return Object.getOwnPropertyDescriptor(Y||X,G)},set(J,G,U){if(!Y)Y={...X};return Y[G]=U,!0}})}var e,LQ,o$,a$,C7=jQ(()=>{R7(),j7(),AY(),cQ(),m$(),l$(),i$(),h8(),e=new zZ("bunfig",{showTags:!0}),LQ=new f8,o$=c(DQ.cwd(),"config"),a$=c(DQ.cwd(),"src/generated")});function x7(Q){let Y=N$(cJ.cwd(),Q?.configDir||"./config");function Z(){if(!pJ(Y))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],G=uJ(Y).filter((W)=>X.has(D8(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),U=new Map;for(let{base:W,file:z}of G){let H=D8(z).toLowerCase(),_=U.get(W);if(!_){U.set(W,z);continue}let A=D8(_).toLowerCase();if(J.indexOf(H)<J.indexOf(A))U.set(W,z)}return Array.from(U.entries()).map(([W,z])=>({base:W,file:z})).sort((W,z)=>W.base.localeCompare(z.base))}function $(){let X=Z(),J=X.map((z)=>z.base),G=J.length?J.map((z)=>`'${z}'`).join(" | "):"string",U=X.length?`{
85
- ${X.map((z)=>{let H=N$(Y,z.file).replace(/\\/g,"/");return` '${z.base}': typeof import('${H}').default`}).join(`,
86
- `)}
87
- }`:"Record<string, any>";return`export type ConfigNames = ${G}
88
- export type ConfigByName = ${U}
89
- export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
90
- export type ConfigOf = Config
91
- `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:$(),loader:"ts"}})}}}var k7=()=>{},t$={};sJ(t$,{withErrorRecovery:()=>d$,tryLoadConfig:()=>T7,loadConfigWithResult:()=>O7,loadConfig:()=>s$,isRetryableError:()=>F7,isConfigNotFoundError:()=>K7,isBunfigError:()=>f$,globalPerformanceMonitor:()=>_Y,globalCache:()=>uQ,getEnvOrDefault:()=>M7,generateConfigTypes:()=>N7,defaultGeneratedDir:()=>a$,defaultConfigDir:()=>o$,deepMergeWithArrayStrategy:()=>v8,deepMerge:()=>g$,createLibraryConfig:()=>S7,config:()=>q7,bunfigPlugin:()=>x7,applyEnvVarsToConfig:()=>GY,TypeGenerationError:()=>C8,SchemaValidationError:()=>zY,PluginError:()=>k8,PerformanceMonitor:()=>y8,FileSystemError:()=>S8,ErrorFactory:()=>MQ,EnvVarError:()=>UZ,EnvProcessor:()=>HZ,ConfigValidator:()=>d8,ConfigValidationError:()=>T8,ConfigNotFoundError:()=>WZ,ConfigMergeError:()=>N8,ConfigLoader:()=>f8,ConfigLoadError:()=>UY,ConfigFileLoader:()=>_Z,ConfigCache:()=>b8,CacheUtils:()=>y$,BunfigError:()=>i,BrowserConfigError:()=>x8,ArrayMergeStrategies:()=>c$});var r$=jQ(()=>{C7(),cQ(),AY(),cQ(),k7(),m$(),l$(),i$(),h8()});r$();var P7={verbose:!1,storage:"memory",algorithm:"fixed-window",windowMs:60000,maxRequests:100,standardHeaders:!0,legacyHeaders:!0,draftMode:!1,redisKeyPrefix:"ratelimit:",memoryStorage:{enableAutoCleanup:!0,cleanupIntervalMs:60000},redis:{url:"redis://localhost:6379",enableSlidingWindow:!1}};var K=P7;class HY{records;timestamps;cleanupTimer;enableAutoCleanup;cleanupIntervalMs;constructor(Q){this.records=new Map,this.timestamps=new Map;let Y=K.memoryStorage||{};if(this.enableAutoCleanup=Q?.enableAutoCleanup??Y.enableAutoCleanup??!1,this.cleanupIntervalMs=Q?.cleanupIntervalMs??Y.cleanupIntervalMs??60000,this.cleanupTimer=null,this.enableAutoCleanup)this.startCleanupTimer()}async increment(Q,Y){let Z=Date.now(),$=this.records.get(Q);if(!$||Z>$.resetTime){let J={count:1,resetTime:Z+Y};return this.records.set(Q,J),this.timestamps.set(Q,[Z]),J}$.count+=1;let X=this.timestamps.get(Q)||[];return X.push(Z),this.timestamps.set(Q,X),$}async reset(Q){this.records.delete(Q),this.timestamps.delete(Q)}async getCount(Q){return this.records.get(Q)?.count||0}async getSlidingWindowCount(Q,Y){let Z=this.timestamps.get(Q)||[],X=Date.now()-Y;return Z.filter((J)=>J>X).length}async batchIncrement(Q,Y){let Z=new Map;for(let $ of Q){let X=await this.increment($,Y);Z.set($,X)}return Z}cleanExpired(){let Q=Date.now();for(let[Z,$]of this.records.entries())if(Q>$.resetTime)this.records.delete(Z);let Y=Q-3600000;for(let[Z,$]of this.timestamps.entries()){let X=$.filter((J)=>J>Y);if(X.length===0)this.timestamps.delete(Z);else if(X.length!==$.length)this.timestamps.set(Z,X)}}dispose(){if(this.cleanupTimer)clearInterval(this.cleanupTimer)}startCleanupTimer(){this.cleanupTimer=setInterval(()=>this.cleanExpired(),this.cleanupIntervalMs)}}class e${client;keyPrefix;slidingWindowEnabled;luaScript;isExternalClient;constructor(Q){if(this.isExternalClient=!!Q.client,!Q.client)throw Error("[ts-rate-limiter] Redis client must be provided. Initialize it and pass it to RedisStorage.");this.client=Q.client;let Y=K.redis||{};if(this.keyPrefix=Q.keyPrefix??K.redisKeyPrefix??"ratelimit:",this.slidingWindowEnabled=Q.enableSlidingWindow??Y.enableSlidingWindow??!1,this.luaScript=`
92
- local key = KEYS[1]
93
- local window = tonumber(ARGV[1])
94
- local now = tonumber(ARGV[2])
95
-
96
- -- Increment counter
97
- local count = redis.call('INCR', key)
98
-
99
- -- Get TTL
100
- local ttl = redis.call('TTL', key)
101
-
102
- -- Set expiration if this is a new key or TTL is negative
103
- if count == 1 or ttl < 0 then
104
- redis.call('PEXPIRE', key, window)
105
- ttl = window / 1000
106
- end
107
-
108
- return {count, ttl}
109
- `,K.verbose)console.warn(`[ts-rate-limiter] Redis storage initialized with:
110
- - Key Prefix: ${this.keyPrefix}
111
- - Sliding Window: ${this.slidingWindowEnabled?"enabled":"disabled"}`)}async increment(Q,Y){let Z=this.keyPrefix+Q,$=Date.now();if(this.slidingWindowEnabled)return this.incrementSlidingWindow(Z,Y,$);try{let X=await this.client.send("EVAL",[this.luaScript,"1",Z,Y.toString(),$.toString()]),J=Array.isArray(X)?Number(X[0]):Number(X),G=Array.isArray(X)?Number(X[1]):Y/1000;return{count:J,resetTime:$+G*1000}}catch(X){if(K.verbose)console.warn("[ts-rate-limiter] LUA script execution failed, using standard approach:",X);return this.incrementStandard(Z,Y,$)}}async incrementStandard(Q,Y,Z){let $=await this.client.incr(Q),X=await this.client.ttl(Q);if($===1||X<0)await this.client.expire(Q,Math.ceil(Y/1000)),X=Y/1000;return{count:Number($),resetTime:Z+(X>0?X*1000:Y)}}async incrementSlidingWindow(Q,Y,Z){let $=`${Q}:window`,X=Z.toString(),J=(Z-Y).toString();try{await this.client.send("ZADD",[$,X,X]),await this.client.send("ZREMRANGEBYSCORE",[$,"0",J]);let G=await this.client.send("ZCARD",[$]);return await this.client.send("PEXPIRE",[$,Y.toString()]),{count:Number(G),resetTime:Z+Y}}catch(G){if(K.verbose)console.warn("[ts-rate-limiter] Sliding window operation failed:",G);return this.incrementStandard(Q,Y,Z)}}async reset(Q){let Y=this.keyPrefix+Q;if(this.slidingWindowEnabled)await this.client.send("DEL",[Y,`${Y}:window`]);else await this.client.del(Y)}async getCount(Q){let Y=this.keyPrefix+Q,Z=await this.client.get(Y);return Z?Number(Z):0}async getSlidingWindowCount(Q,Y){if(!this.slidingWindowEnabled)throw Error("Sliding window not enabled for this Redis storage instance");try{let Z=`${this.keyPrefix}${Q}:window`,X=(Date.now()-Y).toString();await this.client.send("ZREMRANGEBYSCORE",[Z,"0",X]);let J=await this.client.send("ZCARD",[Z]);return Number(J)}catch(Z){if(K.verbose)console.warn("[ts-rate-limiter] Sliding window count operation failed:",Z);return 0}}async batchIncrement(Q,Y){let Z=new Map,$=Date.now();for(let X of Q)try{let J=this.keyPrefix+X;if(this.slidingWindowEnabled){let G=`${J}:window`,U=$.toString(),W=($-Y).toString();await this.client.send("ZADD",[G,U,U]),await this.client.send("ZREMRANGEBYSCORE",[G,"0",W]);let z=await this.client.send("ZCARD",[G]);await this.client.send("PEXPIRE",[G,Y.toString()]),Z.set(X,{count:Number(z),resetTime:$+Y})}else{let G=await this.client.incr(J),U=await this.client.ttl(J);if(G===1||U<0)await this.client.expire(J,Math.ceil(Y/1000));Z.set(X,{count:Number(G),resetTime:$+(U>0?U*1000:Y)})}}catch(J){if(K.verbose)console.warn(`[ts-rate-limiter] Batch increment failed for key ${X}:`,J);Z.set(X,{count:1,resetTime:$+Y})}return Z}async dispose(){if(!this.isExternalClient&&this.client&&typeof this.client.close==="function")this.client.close()}}class Q0{windowMs;maxRequests;storage;keyGenerator;skipFailedRequests;algorithm;standardHeaders;legacyHeaders;skipFn;handler;draftMode;tokenBucketOptions;tokenBuckets;constructor(Q){if(this.windowMs=Q.windowMs||K.windowMs||60000,this.maxRequests=Q.maxRequests||K.maxRequests||100,Q.maxRequests===0)this.maxRequests=0;if(Q.storage)this.storage=Q.storage;else if(K.storage==="redis"&&K.redis)throw Error("Redis client must be provided explicitly when using Redis storage");else this.storage=new HY(K.memoryStorage);if(this.skipFailedRequests=Q.skipFailedRequests??!1,this.keyGenerator=Q.keyGenerator||this.defaultKeyGenerator,this.algorithm=Q.algorithm||K.algorithm||"fixed-window",this.standardHeaders=Q.standardHeaders??K.standardHeaders??!0,this.legacyHeaders=Q.legacyHeaders??K.legacyHeaders??!0,this.skipFn=Q.skip,this.handler=Q.handler,this.draftMode=Q.draftMode??K.draftMode??!1,this.tokenBuckets=new Map,this.algorithm==="token-bucket")this.tokenBucketOptions={capacity:this.maxRequests,refillRate:this.maxRequests/(this.windowMs/1000)/1000};if(K.verbose){let Y=Q.storage?Q.storage instanceof HY?"memory (custom)":"redis (custom)":K.storage;console.warn(`[ts-rate-limiter] Initialized with:
112
- - Algorithm: ${this.algorithm}
113
- - Window: ${this.windowMs}ms
114
- - Max Requests: ${this.maxRequests}
115
- - Storage: ${Y}
116
- - Draft Mode: ${this.draftMode?"enabled":"disabled"}`)}}defaultKeyGenerator(Q){let Y=Q.headers.get("x-forwarded-for");if(Y)return Y.split(",")[0].trim();let Z=Q.headers.get("x-client-ip");if(Z)return Z;let $=Q.headers.get("x-real-ip");if($)return $;return Q.socket?.remoteAddress||"127.0.0.1"}async check(Q){try{if(this.skipFn&&await this.skipFn(Q))return this.createAllowedResult();if(this.maxRequests===0)return{allowed:!1,current:1,limit:0,remaining:this.windowMs,resetTime:Date.now()+this.windowMs};let Y=await this.keyGenerator(Q);if(this.algorithm==="sliding-window"&&this.storage.getSlidingWindowCount)return this.checkSlidingWindow(Y);else if(this.algorithm==="token-bucket")return this.checkTokenBucket(Y);else return this.checkFixedWindow(Y)}catch(Y){if(this.skipFailedRequests)return this.createAllowedResult();throw Y}}async checkFixedWindow(Q){let{count:Y,resetTime:Z}=await this.storage.increment(Q,this.windowMs),$=Math.max(0,Z-Date.now());return{allowed:this.draftMode?!0:Y<=this.maxRequests,current:Y,limit:this.maxRequests,remaining:$,resetTime:Z}}async checkSlidingWindow(Q){if(!this.storage.getSlidingWindowCount)return this.checkFixedWindow(Q);await this.storage.increment(Q,this.windowMs);let Y=await this.storage.getSlidingWindowCount(Q,this.windowMs),$=Date.now()+this.windowMs;return{allowed:this.draftMode?!0:Y<=this.maxRequests,current:Y,limit:this.maxRequests,remaining:this.windowMs,resetTime:$}}async checkTokenBucket(Q){if(!this.tokenBucketOptions)return this.checkFixedWindow(Q);let Y=Date.now(),Z=this.tokenBuckets.get(Q);if(!Z)Z={tokens:this.tokenBucketOptions.capacity,lastRefill:Y},this.tokenBuckets.set(Q,Z);let X=(Y-Z.lastRefill)*this.tokenBucketOptions.refillRate;if(X>0)Z.tokens=Math.min(Z.tokens+X,this.tokenBucketOptions.capacity),Z.lastRefill=Y;let J=this.draftMode?!0:Z.tokens>=1;if(J&&!this.draftMode)Z.tokens-=1;let G=Z.tokens>=this.tokenBucketOptions.capacity?this.windowMs:Math.ceil(1/this.tokenBucketOptions.refillRate);return{allowed:J,current:this.tokenBucketOptions.capacity-Math.floor(Z.tokens),limit:this.tokenBucketOptions.capacity,remaining:G,resetTime:Y+G}}createAllowedResult(){return{allowed:!0,current:0,limit:this.maxRequests,remaining:this.windowMs,resetTime:Date.now()+this.windowMs}}async consume(Q){if(this.algorithm==="sliding-window"&&this.storage.getSlidingWindowCount)return this.checkSlidingWindow(Q);else if(this.algorithm==="token-bucket")return this.checkTokenBucket(Q);else return this.checkFixedWindow(Q)}async peek(Q){if(typeof this.storage.getCount!=="function")return null;let Y=await this.storage.getCount(Q),Z=Date.now();return{allowed:this.draftMode?!0:Y<this.maxRequests,current:Y,limit:this.maxRequests,remaining:this.windowMs,resetTime:Z+this.windowMs}}async enforce(Q){let Y=await this.consume(Q);if(!Y.allowed)throw new Y0(`Rate limit exceeded for '${Q}'`,Y);return Y}async reset(Q){if(await this.storage.reset(Q),this.algorithm==="token-bucket")this.tokenBuckets.delete(Q)}async resetAll(){if(this.algorithm==="token-bucket")this.tokenBuckets.clear();if(this.storage.cleanExpired)this.storage.cleanExpired()}getHeaders(Q){let Y={};if(this.standardHeaders)Y["RateLimit-Limit"]=this.maxRequests.toString(),Y["RateLimit-Remaining"]=Math.max(0,this.maxRequests-Q.current).toString(),Y["RateLimit-Reset"]=Math.ceil(Q.resetTime/1000).toString();if(this.legacyHeaders){if(Y["X-RateLimit-Limit"]=this.maxRequests.toString(),Y["X-RateLimit-Remaining"]=Math.max(0,this.maxRequests-Q.current).toString(),Y["X-RateLimit-Reset"]=Math.ceil(Q.resetTime/1000).toString(),!Q.allowed)Y["Retry-After"]=Math.ceil(Q.remaining/1000).toString()}return Y}middleware(){return async(Q)=>{let Y=await this.check(Q);if(!Y.allowed){if(this.handler)return this.handler(Q,Y);return new Response("Rate limit exceeded",{status:429,headers:this.getHeaders(Y)})}return null}}dispose(){if(this.storage.dispose)this.storage.dispose();this.tokenBuckets.clear()}}class Y0 extends Error{name="RateLimitError";retryAfter;result;constructor(Q,Y){super(Q);this.result=Y,this.retryAfter=Math.max(1,Math.ceil(Y.remaining/1000))}toHeaders(){return{"Retry-After":String(this.retryAfter),"RateLimit-Limit":String(this.result.limit),"RateLimit-Remaining":"0","RateLimit-Reset":String(Math.ceil(this.result.resetTime/1000))}}}async function Z0(Q={}){let Y={windowMs:Q.windowMs??K.windowMs??60000,maxRequests:Q.maxRequests??K.maxRequests??100,algorithm:Q.algorithm??K.algorithm??"fixed-window",standardHeaders:Q.standardHeaders??K.standardHeaders??!0,legacyHeaders:Q.legacyHeaders??K.legacyHeaders??!0,draftMode:Q.draftMode??K.draftMode??!1,keyGenerator:Q.keyGenerator,skipFailedRequests:Q.skipFailedRequests,skip:Q.skip,handler:Q.handler};if(Q.storage)Y.storage=Q.storage;else if(K.storage==="redis"&&K.redis)try{let Z;if(typeof globalThis.Bun<"u")try{let{RedisClient:$}=await Promise.resolve(globalThis.Bun);if(Z=new $(K.redis.url||"redis://localhost:6379"),K.verbose)console.warn("[ts-rate-limiter] Using Bun's native Redis client")}catch($){if(K.verbose)console.warn("[ts-rate-limiter] Failed to use Bun's native Redis client:",$)}if(!Z)try{let{createClient:$}=await import("redis");if(Z=$({url:K.redis.url||"redis://localhost:6379"}),K.verbose)console.warn("[ts-rate-limiter] Using npm redis client")}catch($){throw Error(`[ts-rate-limiter] Failed to import redis client. If using Bun, make sure you're using v1.2.9+ or install the redis package: ${$}`)}if(typeof Z.connect==="function")await Z.connect();if(Y.storage=new e$({client:Z,keyPrefix:K.redisKeyPrefix,enableSlidingWindow:K.redis.enableSlidingWindow}),"onclose"in Z)Z.onclose=($)=>{if($)console.error("[ts-rate-limiter] Redis connection closed with error:",$)};else if("on"in Z&&typeof Z.on==="function")Z.on("error",($)=>{console.error("[ts-rate-limiter] Redis error:",$.message)})}catch(Z){console.warn("[ts-rate-limiter] Failed to connect to Redis, falling back to memory storage:",Z),Y.storage=new HY(K.memoryStorage)}else Y.storage=new HY(K.memoryStorage);return new Q0(Y)}function b7(Q={}){let Y=new AZ(Q);return async($,X)=>{return Y.handle($,X)}}class AZ{limiter;options;constructor(Q={}){let Y=D.server?.rateLimit||{},Z=D.server?.security?.rateLimit||{};if(this.options={windowMs:Q.windowMs||Y.timeWindow||Z.timeWindow||60000,maxRequests:Q.maxRequests||Y.max||Z.max||100,standardHeaders:Q.standardHeaders??!0,legacyHeaders:Q.legacyHeaders??!1,skipFailedRequests:Q.skipFailedRequests??Y.advanced?.skipFailedRequests??Z.advanced?.skipFailedRequests??!1,draftMode:Q.draftMode??!1,keyGenerator:Q.keyGenerator,handler:Q.handler||(Y.message?($,X)=>new Response(Y.message,{status:429}):void 0),skip:Q.skip,algorithm:Q.algorithm||"fixed-window",storage:Q.storage},!this.options.storage&&Y.stores?.type==="redis"&&Y.stores.redis){if(this.options.storage="redis",Y.stores.redis)this.options.redis={url:Y.stores.redis.url,prefix:Y.stores.redis.prefix||"ratelimit:"}}if(Y.advanced){if(Y.advanced.tokensPerInterval&&this.options.algorithm==="token-bucket")this.options.tokenBucket={tokensPerInterval:Y.advanced.tokensPerInterval,interval:Y.advanced.interval||this.options.windowMs,burst:Y.advanced.burst}}this.initLimiter()}async initLimiter(){let Q={...this.options};Q.windowMs=this.options.windowMs,Q.maxRequests=this.options.maxRequests,Q.standardHeaders=this.options.standardHeaders,Q.legacyHeaders=this.options.legacyHeaders,Q.skipFailedRequests=this.options.skipFailedRequests,Q.keyGenerator=this.options.keyGenerator,Q.skip=this.options.skip,Q.algorithm=this.options.algorithm,Q.draftMode=this.options.draftMode,Q.handler=this.options.handler?async($,X)=>{return this.options.handler?.($,{remaining:X.remaining,limit:X.limit,resetTime:X.resetTime})||this.defaultHandler($,X)}:void 0;let{log:Y,warn:Z}=console;console.log=()=>{},console.warn=()=>{};try{this.limiter=await Z0(Q)}finally{console.log=Y,console.warn=Z}}defaultHandler(Q,Y){let Z={};if(this.options.standardHeaders)Z["RateLimit-Limit"]=String(Y.limit),Z["RateLimit-Remaining"]=String(Math.max(0,Y.limit-Y.current)),Z["RateLimit-Reset"]=String(Math.ceil(Y.resetTime/1000));if(this.options.legacyHeaders)Z["X-RateLimit-Limit"]=String(Y.limit),Z["X-RateLimit-Remaining"]=String(Math.max(0,Y.limit-Y.current)),Z["X-RateLimit-Reset"]=String(Math.ceil(Y.resetTime/1000)),Z["Retry-After"]=String(Math.ceil(Y.remaining/1000));let $=D.server?.rateLimit?.message||"Too Many Requests";return new Response($,{status:429,headers:Z})}async handle(Q,Y){if(D.server?.rateLimit?.enabled===!1)return await Y()||new Response("Not Found",{status:404});if(!this.limiter){if(await new Promise((Z)=>setTimeout(Z,50)),!this.limiter)return await Y()||new Response("Not Found",{status:404})}try{let Z=await this.limiter.check(Q);if(!Z.allowed)return this.options.handler?await this.options.handler(Q,{remaining:Z.remaining,limit:Z.limit,resetTime:Z.resetTime}):this.defaultHandler(Q,Z);let $=await Y();if(!$)return new Response("Not Found",{status:404});let X=new Headers($.headers);if(this.options.standardHeaders)X.set("RateLimit-Limit",String(Z.limit)),X.set("RateLimit-Remaining",String(Math.max(0,Z.limit-Z.current))),X.set("RateLimit-Reset",String(Math.ceil(Z.resetTime/1000)));if(this.options.legacyHeaders)X.set("X-RateLimit-Limit",String(Z.limit)),X.set("X-RateLimit-Remaining",String(Math.max(0,Z.limit-Z.current))),X.set("X-RateLimit-Reset",String(Math.ceil(Z.resetTime/1000)));return new Response($.body,{status:$.status,statusText:$.statusText,headers:X})}catch(Z){return console.error("[RateLimit] Error during rate limiting:",Z),await Y()||new Response("Not Found",{status:404})}}}function m8(Q={}){return b7(Q)}import{randomUUID as y7}from"crypto";class lQ{async handle(Q,Y){let Z=Q.headers.get("X-Request-ID")||y7();Object.defineProperty(Q,"requestId",{value:Z,writable:!1,enumerable:!0,configurable:!1});let $=await Y();if(!$)return new Response("Not Found",{status:404});let X=new Headers($.headers);if(!X.has("X-Request-ID"))X.set("X-Request-ID",Z);return new Response($.body,{status:$.status,statusText:$.statusText,headers:X})}}class s extends Error{code;statusCode;constructor(Q,Y){super(Y);this.name="SignatureError",this.code=Q,this.statusCode=401}}class $0{nonces=new Map;cleanupInterval=null;constructor(Q=60000){this.cleanupInterval=setInterval(()=>this.cleanup(),Q),this.cleanupInterval.unref?.()}has(Q){let Y=this.nonces.get(Q);if(Y===void 0)return!1;if(Date.now()>Y)return this.nonces.delete(Q),!1;return!0}set(Q,Y=300){this.nonces.set(Q,Date.now()+Y*1000)}cleanup(){let Q=Date.now();for(let[Y,Z]of this.nonces.entries())if(Q>Z)this.nonces.delete(Y)}destroy(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.nonces.clear()}}class nQ{options;constructor(Q){this.options={secret:Q.secret,algorithm:Q.algorithm??"sha256",signatureHeader:Q.signatureHeader??"X-Signature",timestampHeader:Q.timestampHeader??"X-Timestamp",keyIdHeader:Q.keyIdHeader??"X-Key-Id",nonceHeader:Q.nonceHeader??"X-Nonce",maxAge:Q.maxAge??300,requireTimestamp:Q.requireTimestamp??!0,requireNonce:Q.requireNonce??!1,signedParts:Q.signedParts??["method","path","timestamp","body"],signedHeaders:Q.signedHeaders??[],encoding:Q.encoding??"hex",onError:Q.onError,exclude:Q.exclude,nonceStore:Q.nonceStore,stringToSign:Q.stringToSign}}async handle(Q,Y){if(this.shouldSkip(Q))return Y();try{return await this.verifySignature(Q),Y()}catch(Z){if(Z instanceof s){if(this.options.onError)return this.options.onError(Z,Q);return this.defaultErrorResponse(Z)}throw Z}}shouldSkip(Q){if(!this.options.exclude)return!1;if(typeof this.options.exclude==="function")return this.options.exclude(Q);let Y=new URL(Q.url);return this.options.exclude.some((Z)=>Y.pathname===Z||Y.pathname.startsWith(`${Z}/`))}async verifySignature(Q){let Y=Q.headers.get(this.options.signatureHeader);if(!Y)throw new s("MISSING_SIGNATURE",`Missing ${this.options.signatureHeader} header`);let Z=Q.headers.get(this.options.timestampHeader);if(this.options.requireTimestamp){if(!Z)throw new s("MISSING_TIMESTAMP",`Missing ${this.options.timestampHeader} header`);this.validateTimestamp(Z)}let $=Q.headers.get(this.options.nonceHeader);if(this.options.requireNonce){if(!$)throw new s("MISSING_NONCE",`Missing ${this.options.nonceHeader} header`);await this.validateNonce($)}let X=await this.getSecret(Q);if(!X)throw new s("INVALID_KEY","Invalid or missing API key");let J=await this.buildStringToSign(Q,Z||"",$||void 0),G=await this.calculateSignature(J,X);if(!this.timingSafeEqual(Y,G))throw new s("SIGNATURE_MISMATCH","Invalid signature");if(this.options.requireNonce&&$&&this.options.nonceStore)await this.options.nonceStore.set($,this.options.maxAge)}async getSecret(Q){if(typeof this.options.secret==="string")return this.options.secret;let Y=Q.headers.get(this.options.keyIdHeader);if(!Y)throw new s("MISSING_KEY_ID",`Missing ${this.options.keyIdHeader} header`);return this.options.secret(Y)}validateTimestamp(Q){let Y=Number.parseInt(Q,10);if(Number.isNaN(Y))throw new s("EXPIRED_TIMESTAMP","Invalid timestamp format");let $=Math.floor(Date.now()/1000)-Y;if($>this.options.maxAge)throw new s("EXPIRED_TIMESTAMP",`Request timestamp expired (${$}s old, max ${this.options.maxAge}s)`);if($<-30)throw new s("FUTURE_TIMESTAMP","Request timestamp is in the future")}async validateNonce(Q){if(!this.options.nonceStore)return;if(await this.options.nonceStore.has(Q))throw new s("NONCE_REUSED","Nonce has already been used (possible replay attack)")}async buildStringToSign(Q,Y,Z){if(this.options.stringToSign)return this.options.stringToSign(Q,Y,Z);let $=new URL(Q.url),X=[];for(let J of this.options.signedParts)switch(J){case"method":X.push(Q.method.toUpperCase());break;case"path":X.push($.pathname);break;case"query":X.push($.search);break;case"timestamp":X.push(Y);break;case"nonce":if(Z)X.push(Z);break;case"body":if(Q.body){let G=await Q.clone().text();X.push(G)}break;case"headers":for(let G of this.options.signedHeaders){let U=Q.headers.get(G);if(U)X.push(`${G.toLowerCase()}:${U}`)}break}return X.join(`
117
- `)}async calculateSignature(Q,Y){let Z=new TextEncoder,$=Z.encode(Y),X=Z.encode(Q),J={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"}[this.options.algorithm],G=await crypto.subtle.importKey("raw",$,{name:"HMAC",hash:J},!1,["sign"]),U=await crypto.subtle.sign("HMAC",G,X);if(this.options.encoding==="base64")return btoa(String.fromCharCode(...new Uint8Array(U)));return Array.from(new Uint8Array(U)).map((W)=>W.toString(16).padStart(2,"0")).join("")}timingSafeEqual(Q,Y){if(Q.length!==Y.length)return!1;let Z=0;for(let $=0;$<Q.length;$++)Z|=Q.charCodeAt($)^Y.charCodeAt($);return Z===0}defaultErrorResponse(Q){return new Response(JSON.stringify({error:{code:Q.code,message:Q.message}}),{status:Q.statusCode,headers:{"Content-Type":"application/json","WWW-Authenticate":"HMAC-SHA256"}})}}function v7(Q){return new nQ(Q)}async function h7(Q,Y,Z={}){let{algorithm:$="sha256",signedParts:X=["method","path","timestamp","body"],signedHeaders:J=[],signatureHeader:G="X-Signature",timestampHeader:U="X-Timestamp",nonceHeader:W="X-Nonce",keyId:z,keyIdHeader:H="X-Key-Id",encoding:_="hex"}=Z,A=Math.floor(Date.now()/1000).toString(),B=crypto.randomUUID(),L=new URL(Q.url),R=[];for(let qZ of X)switch(qZ){case"method":R.push(Q.method.toUpperCase());break;case"path":R.push(L.pathname);break;case"query":R.push(L.search);break;case"timestamp":R.push(A);break;case"nonce":R.push(B);break;case"body":if(Q.body){let jY=await Q.clone().text();R.push(jY)}break;case"headers":for(let jY of J){let l8=Q.headers.get(jY);if(l8)R.push(`${jY.toLowerCase()}:${l8}`)}break}let j=R.join(`
118
- `),S=new TextEncoder,y=S.encode(Y),YQ=S.encode(j),o={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"}[$],l=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:o},!1,["sign"]),eQ=await crypto.subtle.sign("HMAC",l,YQ),OZ;if(_==="base64")OZ=btoa(String.fromCharCode(...new Uint8Array(eQ)));else OZ=Array.from(new Uint8Array(eQ)).map((qZ)=>qZ.toString(16).padStart(2,"0")).join("");let QY=new Headers(Q.headers);if(QY.set(G,OZ),QY.set(U,A),QY.set(W,B),z)QY.set(H,z);return new Request(Q.url,{method:Q.method,headers:QY,body:Q.body,redirect:Q.redirect,integrity:Q.integrity,signal:Q.signal})}async function d7(Q,Y,Z,$="sha256",X="hex"){let J=new TextEncoder,G=J.encode(Z),U=J.encode(Q),W={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"}[$],z=await crypto.subtle.importKey("raw",G,{name:"HMAC",hash:W},!1,["sign"]),H=await crypto.subtle.sign("HMAC",z,U),_;if(X==="base64")_=btoa(String.fromCharCode(...new Uint8Array(H)));else _=Array.from(new Uint8Array(H)).map((B)=>B.toString(16).padStart(2,"0")).join("");if(Y.length!==_.length)return!1;let A=0;for(let B=0;B<Y.length;B++)A|=Y.charCodeAt(B)^_.charCodeAt(B);return A===0}class wQ{defaultTtl;sessions=new Map;cleanupInterval=null;constructor(Q=86400){this.defaultTtl=Q;this.cleanupInterval=setInterval(()=>this.cleanup(),300000)}async get(Q){let Y=this.sessions.get(Q);if(!Y)return null;if(Date.now()>Y.expiresAt)return this.sessions.delete(Q),null;return Y.data}async set(Q,Y,Z){let $=Date.now()+(Z??this.defaultTtl)*1000;this.sessions.set(Q,{data:Y,expiresAt:$})}async destroy(Q){this.sessions.delete(Q)}async touch(Q,Y,Z){let $=this.sessions.get(Q);if($)$.expiresAt=Date.now()+(Z??this.defaultTtl)*1000,$.data=Y}async all(){let Q={},Y=Date.now();for(let[Z,$]of this.sessions)if(Y<=$.expiresAt)Q[Z]=$.data;return Q}async length(){return this.sessions.size}async clear(){this.sessions.clear()}cleanup(){let Q=Date.now();for(let[Y,Z]of this.sessions)if(Q>Z.expiresAt)this.sessions.delete(Y)}dispose(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.sessions.clear()}}import{existsSync as BZ,mkdirSync as f7,readdirSync as RZ,unlinkSync as LZ,writeFileSync as X0,readFileSync as g8}from"fs";import{join as BY}from"path";import{tmpdir as m7}from"os";class jZ{defaultTtl;dir;cleanupInterval=null;constructor(Q=86400,Y){this.defaultTtl=Q;if(this.dir=Y||BY(m7(),"bun-router-sessions"),!BZ(this.dir))f7(this.dir,{recursive:!0});this.cleanupInterval=setInterval(()=>this.cleanup(),600000)}filePath(Q){let Y=Q.replace(/[^a-zA-Z0-9_-]/g,"");return BY(this.dir,`${Y}.json`)}async get(Q){let Y=this.filePath(Q);if(!BZ(Y))return null;try{let Z=g8(Y,"utf-8"),$=JSON.parse(Z);if(Date.now()>$.expiresAt)return LZ(Y),null;return $.data}catch{return null}}async set(Q,Y,Z){let $={data:Y,expiresAt:Date.now()+(Z??this.defaultTtl)*1000};X0(this.filePath(Q),JSON.stringify($),"utf-8")}async destroy(Q){let Y=this.filePath(Q);if(BZ(Y))LZ(Y)}async touch(Q,Y,Z){let $=this.filePath(Q);if(!BZ($))return;let X={data:Y,expiresAt:Date.now()+(Z??this.defaultTtl)*1000};X0($,JSON.stringify(X),"utf-8")}async all(){let Q={},Y=Date.now();try{let Z=RZ(this.dir).filter(($)=>$.endsWith(".json"));for(let $ of Z){let X=g8(BY(this.dir,$),"utf-8"),J=JSON.parse(X);if(Y<=J.expiresAt){let G=$.replace(".json","");Q[G]=J.data}}}catch{}return Q}async length(){try{return RZ(this.dir).filter((Q)=>Q.endsWith(".json")).length}catch{return 0}}async clear(){try{let Q=RZ(this.dir).filter((Y)=>Y.endsWith(".json"));for(let Y of Q)LZ(BY(this.dir,Y))}catch{}}cleanup(){let Q=Date.now();try{let Y=RZ(this.dir).filter((Z)=>Z.endsWith(".json"));for(let Z of Y){let $=BY(this.dir,Z),X=g8($,"utf-8"),J=JSON.parse(X);if(Q>J.expiresAt)LZ($)}}catch{}}dispose(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}}class KZ{client;defaultTtl;prefix;constructor(Q,Y=86400,Z="sess:"){this.client=Q;this.defaultTtl=Y;this.prefix=Z}key(Q){return`${this.prefix}${Q}`}async get(Q){let Y=await this.client.get(this.key(Q));if(!Y)return null;try{return JSON.parse(Y)}catch{return null}}async set(Q,Y,Z){let $=this.key(Q),X=Z??this.defaultTtl;await this.client.set($,JSON.stringify(Y),"EX",X)}async destroy(Q){await this.client.del(this.key(Q))}async touch(Q,Y,Z){let $=this.key(Q),X=Z??this.defaultTtl;await this.client.set($,JSON.stringify(Y),"EX",X)}async all(){let Q=await this.client.keys(`${this.prefix}*`),Y={};for(let Z of Q){let $=await this.client.get(Z);if($)try{let X=Z.slice(this.prefix.length);Y[X]=JSON.parse($)}catch{}}return Y}async length(){return(await this.client.keys(`${this.prefix}*`)).length}async clear(){let Q=await this.client.keys(`${this.prefix}*`);if(Q.length>0)await this.client.del(Q)}}class FZ{adapter;defaultTtl;cleanupInterval=null;constructor(Q,Y=86400){this.adapter=Q;this.defaultTtl=Y;this.cleanupInterval=setInterval(()=>{let Z=Date.now()-this.defaultTtl*1000;this.adapter.deleteExpiredSessions(Z)},1800000)}async get(Q){let Y=await this.adapter.findSession(Q);if(!Y)return null;let Z=Date.now()-this.defaultTtl*1000;if(Y.last_activity<Z)return await this.adapter.deleteSession(Q),null;try{return JSON.parse(Y.payload)}catch{return null}}async set(Q,Y,Z){await this.adapter.upsertSession(Q,JSON.stringify(Y),Date.now())}async destroy(Q){await this.adapter.deleteSession(Q)}async touch(Q,Y,Z){await this.adapter.upsertSession(Q,JSON.stringify(Y),Date.now())}async all(){let Q=await this.adapter.getAllSessions(),Y={},Z=Date.now()-this.defaultTtl*1000;for(let $ of Q)if($.last_activity>=Z)try{Y[$.id]=JSON.parse($.payload)}catch{}return Y}async length(){return this.adapter.countSessions()}async clear(){await this.adapter.clearAllSessions()}dispose(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}}function nW(Q){let Y=Q.ttl??86400;switch(Q.driver){case"memory":return new wQ(Y);case"file":return new jZ(Y,Q.file?.dir);case"redis":{if(!Q.redis?.client)throw Error("Redis client is required for redis session driver");return new KZ(Q.redis.client,Y,Q.redis.prefix)}case"database":{if(!Q.database?.adapter)throw Error("Database adapter is required for database session driver");return new FZ(Q.database.adapter,Y)}default:return new wQ(Y)}}class p8{sessionId;data;store;flashedKeys=[];previousFlash={};dirty=!1;constructor(Q,Y,Z){this.sessionId=Q,this.data=Y,this.store=Z,this.previousFlash={...Y.flash||{}}}get id(){return this.sessionId}get(Q){if(this.data.flash&&Q in this.data.flash)return this.data.flash[Q];if(this.data.data&&Q in this.data.data)return this.data.data[Q];return}set(Q,Y){if(!this.data.data)this.data.data={};this.data.data[Q]=Y,this.dirty=!0}has(Q){return this.data.data&&Q in this.data.data||this.data.flash&&Q in this.data.flash||!1}forget(Q){if(this.data.data)delete this.data.data[Q],this.dirty=!0}all(){return{...this.data.data||{},...this.data.flash||{}}}flash(Q,Y){if(!this.data.flash)this.data.flash={};this.data.flash[Q]=Y,this.flashedKeys.push(Q),this.dirty=!0}getFlash(Q){return this.previousFlash[Q]}keep(Q){for(let Y of Q)if(Y in this.previousFlash)this.flash(Y,this.previousFlash[Y])}reflash(){for(let[Q,Y]of Object.entries(this.previousFlash))this.flash(Q,Y)}async regenerate(){let Q=this.sessionId;return this.sessionId=MZ(),await this.store.set(this.sessionId,this.data),await this.store.destroy(Q),this.sessionId}async invalidate(){let Q=this.sessionId;return this.sessionId=MZ(),this.data={id:this.sessionId},await this.store.destroy(Q),await this.store.set(this.sessionId,this.data),this.sessionId}async save(){if(this.data.flash){let Q={};for(let Y of this.flashedKeys)if(this.data.flash[Y]!==void 0)Q[Y]=this.data.flash[Y];this.data.flash=Object.keys(Q).length>0?Q:void 0}await this.store.set(this.sessionId,this.data)}async destroy(){await this.store.destroy(this.sessionId),this.data={}}}function MZ(){let Q=new Uint8Array(32);return crypto.getRandomValues(Q),Array.from(Q,(Y)=>Y.toString(16).padStart(2,"0")).join("")}class iQ{store;constructor(Q){this.store=Q?.store||new wQ}async handle(Q,Y){let Z=D.server?.security?.auth?.session,$=Z?.name||"session",X=Q.cookies?.get($)||"",J=!1;if(!X)X=MZ(),J=!0;let G=J?null:await this.store.get(X);if(!G)G={id:X},J=!0;let U=new p8(X,G,this.store);Q.session=U;let W=await Y();await U.save();let z={maxAge:Z?.cookie?.maxAge||86400000,path:Z?.cookie?.path||"/"};if(Z?.cookie?.httpOnly!==!1)z.httpOnly=!0;if(Z?.cookie?.secure)z.secure=!0;if(Z?.cookie?.sameSite)z.sameSite=Z.cookie.sameSite;if(!Q._cookiesToSet)Q._cookiesToSet=[];return Q._cookiesToSet.push({name:$,value:U.id,options:z}),W||new Response("Not Found",{status:404})}}class sQ{options;nonces=new Map;constructor(Q={}){let Y=D.server?.security?.helmet?.contentSecurityPolicy,Z={"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:Q.directives||typeof Y==="object"&&Y.directives||Z,reportOnly:Q.reportOnly??(typeof Y==="object"&&Y.reportOnly)??!1,reportUri:Q.reportUri,reportTo:Q.reportTo,useNonces:Q.useNonces??!1,nonceLength:Q.nonceLength??16,upgradeInsecureRequests:Q.upgradeInsecureRequests??!0,blockAllMixedContent:Q.blockAllMixedContent??!1}}generateNonce(){let Y="";for(let Z=0;Z<(this.options.nonceLength||16);Z++)Y+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(Math.floor(Math.random()*64));return Y}buildCSPHeader(){let Q=[],Y=this.options.directives||{};for(let[Z,$]of Object.entries(Y)){if(Z==="upgrade-insecure-requests"||Z==="block-all-mixed-content"||Z==="disown-opener"){if($===!0)Q.push(Z.replace(/([A-Z])/g,"-$1").toLowerCase());continue}if(Array.isArray($)&&$.length>0){let X=Z.replace(/([A-Z])/g,"-$1").toLowerCase();Q.push(`${X} ${$.join(" ")}`)}}if(this.options.upgradeInsecureRequests)Q.push("upgrade-insecure-requests");if(this.options.blockAllMixedContent)Q.push("block-all-mixed-content");if(this.options.reportUri)Q.push(`report-uri ${this.options.reportUri}`);if(this.options.reportTo)Q.push(`report-to ${this.options.reportTo}`);return Q.join("; ")}async handle(Q,Y){if((D.server?.security?.helmet||{}).contentSecurityPolicy===!1)return await Y()||new Response("Not Found",{status:404});let $;if(this.options.useNonces){if($=this.generateNonce(),this.nonces.set(Q.url,$),this.options.directives?.["script-src"])this.options.directives["script-src"]=[...this.options.directives["script-src"],`'nonce-${$}'`];if(this.options.directives?.["style-src"])this.options.directives["style-src"]=[...this.options.directives["style-src"],`'nonce-${$}'`]}if($)Q.nonce=$;let X=await Y();if(!X)return new Response("Not Found",{status:404});let J=new Headers(X.headers),G=this.buildCSPHeader();if(G){let U=this.options.reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy";J.set(U,G)}if(this.options.reportTo)J.set("Report-To",JSON.stringify({group:this.options.reportTo,max_age:10886400,endpoints:[{url:this.options.reportUri||"/csp-report"}]}));if($)this.nonces.delete(Q.url);return new Response(X.body,{status:X.status,statusText:X.statusText,headers:J})}getNonce(Q){return this.nonces.get(Q)}}function g7(Q={}){let Y=new sQ(Q);return async(Z,$)=>Y.handle(Z,$)}class oQ{options;requestStore=new Map;cleanupInterval=null;constructor(Q={}){let Y=D.server?.security?.ddos||{};if(this.options={enabled:Q.enabled??Y.enabled??!0,maxRequestsPerSecond:Q.maxRequestsPerSecond??Y.maxRequestsPerSecond??10,maxRequestsPerMinute:Q.maxRequestsPerMinute??Y.maxRequestsPerMinute??100,maxRequestsPerHour:Q.maxRequestsPerHour??Y.maxRequestsPerHour??1000,burstLimit:Q.burstLimit??Y.burstLimit??20,windowSize:Q.windowSize??Y.windowSize??60000,blockDuration:Q.blockDuration??Y.blockDuration??300000,whitelistedIPs:Q.whitelistedIPs??Y.whitelistedIPs??[],blacklistedIPs:Q.blacklistedIPs??Y.blacklistedIPs??[],trustProxy:Q.trustProxy??Y.trustProxy??!0,skipSuccessfulRequests:Q.skipSuccessfulRequests??Y.skipSuccessfulRequests??!1,skipFailedRequests:Q.skipFailedRequests??Y.skipFailedRequests??!1,keyGenerator:Q.keyGenerator??this.defaultKeyGenerator.bind(this),onLimitReached:Q.onLimitReached,store:Q.store??Y.store??"memory",redis:Q.redis??Y.redis},this.options.store==="memory")this.startCleanupInterval()}defaultKeyGenerator(Q){let Y=Q.headers.get("x-forwarded-for"),Z=Q.headers.get("x-real-ip"),$=Q.headers.get("cf-connecting-ip");if(this.options.trustProxy&&Y)return Y.split(",")[0].trim();return Z||$||"unknown"}startCleanupInterval(){this.cleanupInterval=setInterval(()=>{let Q=Date.now();for(let[Y,Z]of this.requestStore.entries()){if(Q-Z.lastRequest>this.options.windowSize*2)this.requestStore.delete(Y);if(Z.blocked&&Z.blockExpires&&Q>Z.blockExpires)Z.blocked=!1,Z.blockExpires=void 0}},this.options.windowSize/2),this.cleanupInterval.unref?.()}isWhitelisted(Q){return this.options.whitelistedIPs?.includes(Q)??!1}isBlacklisted(Q){return this.options.blacklistedIPs?.includes(Q)??!1}getRateLimitInfo(Q,Y){let Z=this.requestStore.get(Q);if(!Z){if(this.requestStore.size>=1e5){let $=Math.ceil(this.requestStore.size/10);for(let X of this.requestStore.keys())if(this.requestStore.delete(X),--$<=0)break}Z={count:0,firstRequest:Y,lastRequest:Y,blocked:!1},this.requestStore.set(Q,Z)}if(Y-Z.firstRequest>this.options.windowSize)Z.count=0,Z.firstRequest=Y;return Z}shouldBlock(Q,Y){if(Q.blocked&&Q.blockExpires&&Y<Q.blockExpires)return!0;let Z=1000;if(Q.count>this.options.burstLimit)return!0;if(Q.count>this.options.maxRequestsPerMinute)return!0;return!1}blockIP(Q,Y){Q.blocked=!0,Q.blockExpires=Y+this.options.blockDuration}createBlockedResponse(Q,Y){let Z=Math.ceil((Y.blockExpires-Date.now())/1000),$={"Retry-After":Z.toString(),"X-RateLimit-Limit":this.options.maxRequestsPerMinute.toString(),"X-RateLimit-Remaining":"0","X-RateLimit-Reset":Math.ceil(Y.blockExpires/1000).toString()};if(this.options.onLimitReached)return this.options.onLimitReached(Q,{...Y,retryAfter:Z});return new Response(JSON.stringify({error:"Too Many Requests",message:"Rate limit exceeded. Please try again later.",retryAfter:Z}),{status:429,headers:{"Content-Type":"application/json",...$}})}async handle(Q,Y){if(!this.options.enabled)return await Y()||new Response("Not Found",{status:404});let Z=Date.now(),$=this.options.keyGenerator(Q);if(this.isWhitelisted($))return await Y()||new Response("Not Found",{status:404});if(this.isBlacklisted($))return new Response("Access Denied",{status:403});let X=this.getRateLimitInfo($,Z);if(this.shouldBlock(X,Z))return this.blockIP(X,Z),this.createBlockedResponse(Q,X);X.count++,X.lastRequest=Z;let J=await Y();if(!J)return new Response("Not Found",{status:404});if(this.options.skipSuccessfulRequests&&J.status<400)X.count--;if(this.options.skipFailedRequests&&J.status>=400)X.count--;let G=new Headers(J.headers);return G.set("X-RateLimit-Limit",this.options.maxRequestsPerMinute.toString()),G.set("X-RateLimit-Remaining",Math.max(0,this.options.maxRequestsPerMinute-X.count).toString()),G.set("X-RateLimit-Reset",Math.ceil((X.firstRequest+this.options.windowSize)/1000).toString()),new Response(J.body,{status:J.status,statusText:J.statusText,headers:G})}destroy(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.requestStore.clear()}}function p7(Q={}){let Y=new oQ(Q);return async(Z,$)=>Y.handle(Z,$)}class RY{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(Q={}){this.config={scanForMalware:Q.scanForMalware??!1,checkMagicNumbers:Q.checkMagicNumbers??!0,sanitizeFilenames:Q.sanitizeFilenames??!0,preventExecutableUploads:Q.preventExecutableUploads??!0,maxFilenameLength:Q.maxFilenameLength??255}}validateFile(Q){let Y=[];if(Q.originalName.length>this.config.maxFilenameLength)Y.push(`Filename too long (max ${this.config.maxFilenameLength} characters)`);if(this.config.sanitizeFilenames){let Z=this.sanitizeFilename(Q.originalName);if(!Z||Z.length===0)Y.push("Filename is invalid or empty after sanitization")}if(this.config.preventExecutableUploads){let Z=this.getFileExtension(Q.originalName).toLowerCase();if(this.EXECUTABLE_EXTENSIONS.includes(Z))Y.push("Executable files are not allowed")}if(this.config.checkMagicNumbers){if(!this.validateFileSignature(Q))Y.push("File signature does not match declared MIME type")}if(this.config.scanForMalware){if(this.basicMalwareScan(Q))Y.push("Potential malware detected")}return{isValid:Y.length===0,errors:Y}}validateFileSignature(Q){let Y=this.FILE_SIGNATURES[Q.mimetype];if(!Y)return!0;let Z=new Uint8Array(Q.buffer.slice(0,16));return Y.some(($)=>{if(Z.length<$.length)return!1;for(let X=0;X<$.length;X++)if(Z[X]!==$[X])return!1;return!0})}sanitizeFilename(Q){return Q.replace(/[<>:"/\\|?*\u0000-\u001F]/u,"_").replace(/^\.+/,"").replace(/\.+$/,"").replace(/\s+/g,"_").substring(0,this.config.maxFilenameLength)}getFileExtension(Q){let Y=Q.lastIndexOf(".");return Y===-1?"":Q.substring(Y)}basicMalwareScan(Q){let Y=new Uint8Array(Q.buffer),Z=new TextDecoder("utf-8",{fatal:!1}).decode(Y);return[/eval\s*\(/gi,/document\.write/gi,/window\.location/gi,/<script[^>]*>/gi,/javascript:/gi,/vbscript:/gi,/onload\s*=/gi,/onerror\s*=/gi].some((X)=>X.test(Z))}getSafeFilename(Q){return this.sanitizeFilename(Q)}isAllowedFileType(Q,Y){if(Y.length===0)return!0;return Y.includes(Q)}isWithinSizeLimit(Q,Y){return Q<=Y}}import{randomUUID as u7}from"crypto";import{existsSync as c7,mkdirSync as l7,writeFileSync as n7}from"fs";import{basename as i7,extname as J0,join as s7}from"path";class IQ{config;fileSecurity;constructor(Q={}){if(this.config={destination:Q.destination||"./uploads",maxFileSize:Q.maxFileSize||10485760,maxFiles:Q.maxFiles||10,allowedMimeTypes:Q.allowedMimeTypes||[],allowedExtensions:Q.allowedExtensions||[],preserveOriginalName:Q.preserveOriginalName??!1,generateUniqueFilename:Q.generateUniqueFilename??!0,createDestination:Q.createDestination??!0,scanForMalware:Q.scanForMalware??!1,checkMagicNumbers:Q.checkMagicNumbers??!0,sanitizeFilenames:Q.sanitizeFilenames??!0,preventExecutableUploads:Q.preventExecutableUploads??!0,maxFilenameLength:Q.maxFilenameLength??255},this.fileSecurity=new RY(Q),this.config.createDestination&&!c7(this.config.destination))l7(this.config.destination,{recursive:!0})}async handle(Q,Y){let Z=Q.headers.get("content-type");if(!Z||!Z.includes("multipart/form-data"))return await Y()||new Response("Not Found",{status:404});try{let $=await Q.formData(),X=[],J={};for(let[U,W]of $.entries())if(W instanceof File){if(X.length>=this.config.maxFiles)return this.createErrorResponse(`Maximum ${this.config.maxFiles} files allowed`,400);if(W.size>this.config.maxFileSize)return this.createErrorResponse(`File ${W.name} exceeds maximum size of ${this.formatBytes(this.config.maxFileSize)}`,413);if(this.config.allowedMimeTypes.length>0){let R=W.type.split(";")[0];if(!this.config.allowedMimeTypes.includes(R))return this.createErrorResponse(`File type ${R} not allowed. Allowed types: ${this.config.allowedMimeTypes.join(", ")}`,415)}let z=J0(W.name).toLowerCase();if(this.config.allowedExtensions.length>0&&!this.config.allowedExtensions.includes(z))return this.createErrorResponse(`File extension ${z} not allowed. Allowed extensions: ${this.config.allowedExtensions.join(", ")}`,415);let H=this.generateFilename(W.name),_=s7(this.config.destination,H),A=await W.arrayBuffer(),B={fieldName:U,originalName:W.name,filename:H,path:_,size:W.size,mimetype:W.type,buffer:A},L=this.fileSecurity.validateFile(B);if(!L.isValid)return this.createErrorResponse(`Security validation failed: ${L.errors.join(", ")}`,400);n7(_,new Uint8Array(A)),X.push(B)}else if(J[U])if(Array.isArray(J[U]))J[U].push(W);else J[U]=[J[U],W];else J[U]=W;return Object.defineProperty(Q,"files",{value:X,writable:!0,enumerable:!0,configurable:!0}),Object.defineProperty(Q,"file",{value:(U)=>X.find((W)=>W.fieldName===U)??null,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(Q,"formBody",{value:J,writable:!0,enumerable:!0,configurable:!0}),await Y()||new Response("Not Found",{status:404})}catch($){return this.createErrorResponse(`File upload failed: ${$ instanceof Error?$.message:"Unknown error"}`,500)}}generateFilename(Q){let Y=this.fileSecurity.getSafeFilename(Q);if(this.config.preserveOriginalName&&!this.config.generateUniqueFilename)return Y;let Z=J0(Y),$=i7(Y,Z);if(this.config.generateUniqueFilename){let X=u7();return this.config.preserveOriginalName?`${$}_${X}${Z}`:`${X}${Z}`}return Y}formatBytes(Q){if(Q===0)return"0 Bytes";let Y=1024,Z=["Bytes","KB","MB","GB"],$=Math.floor(Math.log(Q)/Math.log(Y));return`${Number.parseFloat((Q/Y**$).toFixed(2))} ${Z[$]}`}createErrorResponse(Q,Y){return new Response(JSON.stringify({error:Q}),{status:Y,headers:{"Content-Type":"application/json"}})}}function o7(Q={}){return new IQ(Q)}function a7(Q,Y={}){return new IQ({...Y,maxFiles:1})}function t7(Q=10,Y={}){return new IQ({...Y,maxFiles:Q})}function r7(Q={}){return new IQ({...Q,allowedMimeTypes:["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/svg+xml"],allowedExtensions:[".jpg",".jpeg",".png",".gif",".webp",".svg"]})}function e7(Q={}){return new IQ({...Q,allowedMimeTypes:["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain"],allowedExtensions:[".pdf",".doc",".docx",".txt"]})}class LY{options;constructor(Q={}){let Y=D.server?.security?.helmet||{};this.options={contentSecurityPolicy:Q.contentSecurityPolicy??Y.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:Q.crossOriginEmbedderPolicy??!0,crossOriginOpenerPolicy:Q.crossOriginOpenerPolicy??!0,crossOriginResourcePolicy:Q.crossOriginResourcePolicy??!0,dnsPrefetchControl:Q.dnsPrefetchControl??!0,expectCt:Q.expectCt??Y.expectCt??!1,frameguard:Q.frameguard??{action:Y.frameOptions?.toLowerCase()||"deny"},hidePoweredBy:Q.hidePoweredBy??Y.hidePoweredBy??!0,hsts:Q.hsts??Y.hsts??{maxAge:31536000,includeSubDomains:!0,preload:!0},ieNoOpen:Q.ieNoOpen??!0,noSniff:Q.noSniff??Y.noSniff??!0,originAgentCluster:Q.originAgentCluster??!0,permittedCrossDomainPolicies:Q.permittedCrossDomainPolicies??{permittedPolicies:"none"},referrerPolicy:Q.referrerPolicy??Y.referrerPolicy??{policy:"strict-origin-when-cross-origin"},xssFilter:Q.xssFilter??Y.xssFilter??!0}}async handle(Q,Y){if((D.server?.security?.helmet||{}).enabled===!1)return await Y()||new Response("Not Found",{status:404});let $=await Y();if(!$)return new Response("Not Found",{status:404});let X=new Headers($.headers);if(this.options.contentSecurityPolicy){let J=this.options.contentSecurityPolicy;if(typeof J==="object"&&J.directives){let G=Object.entries(J.directives).map(([W,z])=>`${W} ${z.join(" ")}`).join("; "),U=J.reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy";if(X.set(U,G),J.reportUri)X.set("Report-To",JSON.stringify({group:"csp-endpoint",max_age:10886400,endpoints:[{url:J.reportUri}]}))}}if(this.options.crossOriginEmbedderPolicy){let J=this.options.crossOriginEmbedderPolicy,G=typeof J==="object"?J.policy||"require-corp":"require-corp";X.set("Cross-Origin-Embedder-Policy",G)}if(this.options.crossOriginOpenerPolicy){let J=this.options.crossOriginOpenerPolicy,G=typeof J==="object"?J.policy||"same-origin":"same-origin";X.set("Cross-Origin-Opener-Policy",G)}if(this.options.crossOriginResourcePolicy){let J=this.options.crossOriginResourcePolicy,G=typeof J==="object"?J.policy||"same-origin":"same-origin";X.set("Cross-Origin-Resource-Policy",G)}if(this.options.dnsPrefetchControl){let J=this.options.dnsPrefetchControl,G=typeof J==="object"?J.allow:!1;X.set("X-DNS-Prefetch-Control",G?"on":"off")}if(this.options.expectCt){let J=this.options.expectCt;if(typeof J==="object"){let G=[];if(J.enforce)G.push("enforce");if(J.maxAge)G.push(`max-age=${J.maxAge}`);if(J.reportUri)G.push(`report-uri="${J.reportUri}"`);X.set("Expect-CT",G.join(", "))}}if(this.options.frameguard){let J=this.options.frameguard;if(typeof J==="object"){let G=J.action||"deny",U=G==="sameorigin"&&J.domain?`ALLOW-FROM ${J.domain}`:G.toUpperCase();X.set("X-Frame-Options",U)}}if(this.options.hidePoweredBy)X.delete("X-Powered-By");if(this.options.hsts){let J=this.options.hsts;if(typeof J==="object"){let G=[`max-age=${J.maxAge||31536000}`];if(J.includeSubDomains)G.push("includeSubDomains");if(J.preload)G.push("preload");X.set("Strict-Transport-Security",G.join("; "))}}if(this.options.ieNoOpen)X.set("X-Download-Options","noopen");if(this.options.noSniff)X.set("X-Content-Type-Options","nosniff");if(this.options.originAgentCluster)X.set("Origin-Agent-Cluster","?1");if(this.options.permittedCrossDomainPolicies){let J=this.options.permittedCrossDomainPolicies,G=typeof J==="object"?J.permittedPolicies||"none":"none";X.set("X-Permitted-Cross-Domain-Policies",G)}if(this.options.referrerPolicy){let J=this.options.referrerPolicy;if(typeof J==="object"){let G=Array.isArray(J.policy)?J.policy.join(", "):J.policy||"strict-origin-when-cross-origin";X.set("Referrer-Policy",G)}else X.set("Referrer-Policy","strict-origin-when-cross-origin")}if(this.options.xssFilter){let J=this.options.xssFilter,G=typeof J==="object"&&J.setOnOldIE?"1; mode=block":"0";X.set("X-XSS-Protection",G)}return new Response($.body,{status:$.status,statusText:$.statusText,headers:X})}}var QG=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/,YG=/^[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 aQ{options;constructor(Q={}){let Y=D.server?.security?.inputValidation||{};this.options={enabled:Q.enabled??Y.enabled??!0,schemas:Q.schemas??Y.schemas??{},sanitizeByDefault:Q.sanitizeByDefault??Y.sanitizeByDefault??!0,strictMode:Q.strictMode??Y.strictMode??!1,allowUnknownFields:Q.allowUnknownFields??Y.allowUnknownFields??!0,maxDepth:Q.maxDepth??Y.maxDepth??10,onValidationError:Q.onValidationError}}validateValue(Q,Y,Z){let $=[];if(Y.required&&(Q===void 0||Q===null||Q===""))return $.push({field:Z,message:"Field is required",value:Q,rule:"required"}),$;if(Q===void 0||Q===null)return $;switch(Y.type){case"string":if(typeof Q!=="string")$.push({field:Z,message:"Must be a string",value:Q,rule:"type"});else{if(Y.min!==void 0&&Q.length<Y.min)$.push({field:Z,message:`Must be at least ${Y.min} characters`,value:Q,rule:"min"});if(Y.max!==void 0&&Q.length>Y.max)$.push({field:Z,message:`Must be at most ${Y.max} characters`,value:Q,rule:"max"})}break;case"number":{let X=Number(Q);if(Number.isNaN(X))$.push({field:Z,message:"Must be a number",value:Q,rule:"type"});else{if(Y.min!==void 0&&X<Y.min)$.push({field:Z,message:`Must be at least ${Y.min}`,value:Q,rule:"min"});if(Y.max!==void 0&&X>Y.max)$.push({field:Z,message:`Must be at most ${Y.max}`,value:Q,rule:"max"})}break}case"boolean":if(typeof Q!=="boolean"&&Q!=="true"&&Q!=="false")$.push({field:Z,message:"Must be a boolean",value:Q,rule:"type"});break;case"email":{if(typeof Q==="string"&&!QG.test(Q))$.push({field:Z,message:"Must be a valid email address",value:Q,rule:"format"});break}case"url":try{new URL(Q)}catch{$.push({field:Z,message:"Must be a valid URL",value:Q,rule:"format"})}break;case"uuid":{if(typeof Q==="string"&&!YG.test(Q))$.push({field:Z,message:"Must be a valid UUID",value:Q,rule:"format"});break}case"date":{let X=new Date(Q);if(Number.isNaN(X.getTime()))$.push({field:Z,message:"Must be a valid date",value:Q,rule:"format"});break}case"regex":if(Y.pattern&&typeof Q==="string"&&!Y.pattern.test(Q))$.push({field:Z,message:"Does not match required pattern",value:Q,rule:"pattern"});break;case"custom":if(Y.custom){let X=Y.custom(Q);if(X!==!0)$.push({field:Z,message:typeof X==="string"?X:"Custom validation failed",value:Q,rule:"custom"})}break}if(Y.enum&&!Y.enum.includes(Q))$.push({field:Z,message:`Must be one of: ${Y.enum.join(", ")}`,value:Q,rule:"enum"});if(Y.type!=="regex"&&Y.pattern&&typeof Q==="string"&&!Y.pattern.test(Q))$.push({field:Z,message:"Does not match required pattern",value:Q,rule:"pattern"});return $}sanitizeValue(Q,Y){if(!Y.sanitize&&!this.options.sanitizeByDefault)return Q;if(typeof Q==="string")Q=Q.replace(/[<>'"&]/g,(Z)=>{return{"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","&":"&amp;"}[Z]||Z}).trim();if(Y.transform)Q=Y.transform(Q);return Q}validateObject(Q,Y,Z="",$=0){let X=[];if($>this.options.maxDepth)return X.push({field:Z,message:"Maximum nesting depth exceeded",value:Q,rule:"depth"}),X;if(this.options.strictMode&&!this.options.allowUnknownFields){for(let J in Q)if(!(J in Y))X.push({field:Z?`${Z}.${J}`:J,message:"Unknown field",value:Q[J],rule:"unknown"})}for(let[J,G]of Object.entries(Y)){let U=Z?`${Z}.${J}`:J,W=Q?.[J];if(typeof G==="object"&&!("type"in G)){if(W&&typeof W==="object")X.push(...this.validateObject(W,G,U,$+1))}else{let z=G;if(X.push(...this.validateValue(W,z,U)),Q&&(z.sanitize||this.options.sanitizeByDefault))Q[J]=this.sanitizeValue(W,z)}}return X}async parseRequestBody(Q){let Y=Q.headers.get("content-type")||"";try{if(Y.includes("application/json"))return await Q.json();else if(Y.includes("application/x-www-form-urlencoded")){let Z=await Q.formData(),$={};for(let[X,J]of Z.entries())$[X]=J;return $}else if(Y.includes("multipart/form-data")){let Z=await Q.formData(),$={};for(let[X,J]of Z.entries())$[X]=J;return $}}catch(Z){throw console.error(Z),Error("Invalid request body format")}return{}}async handle(Q,Y){if(!this.options.enabled)return await Y()||new Response("Not Found",{status:404});let Z=[],$=new URL(Q.url);try{if(this.options.schemas?.query){let J={};for(let[U,W]of $.searchParams.entries())J[U]=W;let G=this.validateObject(J,this.options.schemas.query);Z.push(...G)}if(this.options.schemas?.body&&Q.method!=="GET"&&Q.method!=="HEAD")try{let J=await this.parseRequestBody(Q),G=this.validateObject(J,this.options.schemas.body);Z.push(...G),Q.validatedBody=J}catch(J){Z.push({field:"body",message:J instanceof Error?J.message:"Invalid request body",value:null,rule:"parse"})}if(this.options.schemas?.headers){let J={};for(let[U,W]of Q.headers.entries())J[U]=W;let G=this.validateObject(J,this.options.schemas.headers);Z.push(...G)}if(this.options.schemas?.params&&Q.params){let J=this.validateObject(Q.params,this.options.schemas.params);Z.push(...J)}if(Z.length>0){if(this.options.onValidationError)return this.options.onValidationError(Z);return new Response(JSON.stringify({error:"Validation Error",message:"Request validation failed",errors:Z}),{status:400,headers:{"Content-Type":"application/json"}})}return await Y()||new Response("Not Found",{status:404})}catch(X){return console.error("Input validation error:",X),new Response("Internal Server Error",{status:500})}}}function ZG(Q={}){let Y=new aQ(Q);return async(Z,$)=>Y.handle(Z,$)}class IZ{options;rules=new Map;channels=[];notifications=[];lastAlertTimes=new Map;metricsBuffer=[];checkInterval;constructor(Q={}){if(this.options={enabled:Q.enabled??!0,defaultCooldown:Q.defaultCooldown??300000,maxAlerts:Q.maxAlerts??1000,autoResolve:Q.autoResolve??!0,autoResolveTimeout:Q.autoResolveTimeout??600000,...Q},Q.rules)for(let Y of Q.rules)this.rules.set(Y.id,Y);if(this.channels=Q.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 Q=[{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 Y of Q)this.rules.set(Y.id,Y)}startAlertingEngine(){this.checkInterval=setInterval(()=>{this.evaluateRules(),this.cleanupOldNotifications(),this.autoResolveAlerts()},1e4),this.checkInterval.unref?.()}evaluateRules(){let Q=Date.now();for(let Y of this.rules.values()){if(!Y.enabled)continue;let Z=this.lastAlertTimes.get(Y.id),$=Y.cooldown||this.options.defaultCooldown||300000;if(Z&&Q-Z<$)continue;let X=Y.duration||60000,J=this.metricsBuffer.filter((W)=>Q-W.timestamp<=X);if(J.length===0)continue;let G=!1,U;if(Y.metric==="custom"&&Y.customEvaluator)G=Y.customEvaluator(J),U="custom condition";else{let W=this.extractMetricValues(J,Y.metric);if(W.length===0)continue;let z=W.reduce((H,_)=>H+_,0)/W.length;U=z,G=this.evaluateCondition(z,Y.condition,Y.threshold)}if(G)this.triggerAlert(Y,U,J),this.lastAlertTimes.set(Y.id,Q)}}extractMetricValues(Q,Y){switch(Y){case"responseTime":return Q.map((Z)=>Z.responseTime);case"errorRate":return Q.map((Z)=>Z.statusCode>=400?1:0);case"memoryUsage":return Q.map((Z)=>Z.memoryUsage.heapUsed);case"cpuUsage":return Q.map((Z)=>Z.cpuUsage.user+Z.cpuUsage.system);case"requestRate":{if(Q.length<2)return[];let Z=(Q[Q.length-1].timestamp-Q[0].timestamp)/1000;return[Q.length/Math.max(Z,1)]}default:return[]}}evaluateCondition(Q,Y,Z){switch(Y){case"gt":return Q>Z;case"gte":return Q>=Z;case"lt":return Q<Z;case"lte":return Q<=Z;case"eq":return Math.abs(Q-Z)<0.001;default:return!1}}async triggerAlert(Q,Y,Z){let $={id:this.generateId(),ruleId:Q.id,ruleName:Q.name,severity:Q.severity,message:this.formatAlertMessage(Q,Y,Z),timestamp:Date.now(),resolved:!1,metadata:{rule:Q,value:Y,threshold:Q.threshold,condition:Q.condition,metricsCount:Z.length}};this.notifications.push($);for(let X of this.channels){if(!X.enabled)continue;if(X.filters?.severities&&!X.filters.severities.includes(Q.severity))continue;if(X.filters?.rules&&!X.filters.rules.includes(Q.id))continue;try{await this.sendNotification(X,$)}catch(J){console.error(`Failed to send alert to ${X.type}:`,J)}}if(this.notifications.length>(this.options.maxAlerts||1000))this.notifications=this.notifications.slice(-(this.options.maxAlerts||1000))}formatAlertMessage(Q,Y,Z){let $=(G,U)=>{switch(U){case"responseTime":return`${Math.round(G)}ms`;case"errorRate":return`${Math.round(G*100)}%`;case"memoryUsage":return`${Math.round(G/1024/1024)}MB`;case"cpuUsage":return`${Math.round(G)}%`;case"requestRate":return`${Math.round(G)}/s`;default:return String(G)}},X=typeof Y==="number"?$(Y,Q.metric):String(Y),J=$(Q.threshold,Q.metric);return`${Q.name}: ${X} ${Q.condition} ${J} (${Z.length} samples)`}async sendNotification(Q,Y){switch(Q.type){case"console":this.sendConsoleNotification(Y);break;case"webhook":await this.sendWebhookNotification(Q,Y);break;case"slack":await this.sendSlackNotification(Q,Y);break;case"email":await this.sendEmailNotification(Q,Y);break;case"custom":if(Q.config.customHandler)await Q.config.customHandler(Y);break}}sendConsoleNotification(Q){let Y=Q.severity==="critical"?"\uD83D\uDEA8":Q.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";console.log(`${Y} ALERT [${Q.severity.toUpperCase()}]: ${Q.message}`),console.log(` Rule: ${Q.ruleName} (${Q.ruleId})`),console.log(` Time: ${new Date(Q.timestamp).toISOString()}`)}async sendWebhookNotification(Q,Y){if(!Q.config.url)return;let Z={alert:Y,timestamp:new Date(Y.timestamp).toISOString(),service:"bun-router"};await fetch(Q.config.url,{method:"POST",headers:{"Content-Type":"application/json",...Q.config.token&&{Authorization:`Bearer ${Q.config.token}`}},body:JSON.stringify(Z)})}async sendSlackNotification(Q,Y){if(!Q.config.url)return;let Z=Y.severity==="critical"?"danger":Y.severity==="warning"?"warning":"good",$=Y.severity==="critical"?":rotating_light:":Y.severity==="warning"?":warning:":":information_source:",X=(()=>{return{channel:Q.config.channel,username:"Performance Monitor",icon_emoji:":chart_with_upwards_trend:",attachments:[{color:Z,title:`${$} ${Y.ruleName}`,text:Y.message,fields:[{title:"Severity",value:Y.severity.toUpperCase(),short:!0},{title:"Time",value:new Date(Y.timestamp).toISOString(),short:!0}],footer:"bun-router Performance Monitor",ts:Math.floor(Y.timestamp/1000)}]}})();await fetch(Q.config.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)})}async sendEmailNotification(Q,Y){console.log(`Email notification would be sent to ${Q.config.email}:`,Y.message)}cleanupOldNotifications(){let Y=Date.now()-86400000;this.notifications=this.notifications.filter((Z)=>Z.timestamp>Y)}autoResolveAlerts(){if(!this.options.autoResolve)return;let Q=this.options.autoResolveTimeout||600000,Y=Date.now()-Q;for(let Z of this.notifications)if(!Z.resolved&&Z.timestamp<Y)Z.resolved=!0,Z.resolvedAt=Date.now()}generateId(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}addMetrics(Q){this.metricsBuffer.push(Q);let Y=3600000,Z=Date.now()-Y;this.metricsBuffer=this.metricsBuffer.filter(($)=>$.timestamp>Z)}addRule(Q){this.rules.set(Q.id,Q)}removeRule(Q){this.rules.delete(Q)}updateRule(Q,Y){let Z=this.rules.get(Q);if(Z)this.rules.set(Q,{...Z,...Y})}addChannel(Q){this.channels.push(Q)}removeChannel(Q){this.channels.splice(Q,1)}getActiveAlerts(){return this.notifications.filter((Q)=>!Q.resolved)}getAllNotifications(){return[...this.notifications]}resolveAlert(Q){let Y=this.notifications.find((Z)=>Z.id===Q);if(Y&&!Y.resolved)Y.resolved=!0,Y.resolvedAt=Date.now()}async handle(Q,Y){let Z=await Y();if(Z)return Z;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 $G(Q={}){return new IZ(Q)}import tQ from"process";class VZ{options;metricsHistory=[];alerts=[];startTime=Date.now();constructor(Q={}){this.options={enabled:Q.enabled??!0,path:Q.path??"/performance",title:Q.title??"Performance Dashboard",refreshInterval:Q.refreshInterval??5000,maxMetrics:Q.maxMetrics??1000,authentication:{enabled:!1,...Q.authentication},features:{realTimeMetrics:!0,historicalCharts:!0,alertsPanel:!0,tracingView:!0,systemMetrics:!0,...Q.features}}}isAuthenticated(Q){if(!this.options.authentication?.enabled)return!0;let Y=Q.headers.get("authorization"),Z=Q.headers.get("x-api-key");if(this.options.authentication.apiKey&&Z===this.options.authentication.apiKey)return!0;if(Y&&this.options.authentication.username&&this.options.authentication.password){let[$,X]=Y.split(" ");if($==="Basic"){let J=atob(X),[G,U]=J.split(":");return G===this.options.authentication.username&&U===this.options.authentication.password}}return!1}generateDashboardHTML(Q){return`
119
- <!DOCTYPE html>
120
- <html lang="en">
121
- <head>
122
- <meta charset="UTF-8">
123
- <meta name='viewport' content='width=device-width, initial-scale=1.0'>
124
- <title>${this.options.title}</title>
125
- <style>
126
- * { margin: 0; padding: 0; box-sizing: border-box; }
127
- body {
128
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
129
- background: #f5f5f5;
130
- color: #333;
131
- line-height: 1.6;
132
- }
133
- .header {
134
- background: #2c3e50;
135
- color: white;
136
- padding: 1rem 2rem;
137
- display: flex;
138
- justify-content: space-between;
139
- align-items: center;
140
- }
141
- .header h1 { font-size: 1.5rem; }
142
- .status {
143
- display: flex;
144
- gap: 1rem;
145
- align-items: center;
146
- }
147
- .status-item {
148
- display: flex;
149
- flex-direction: column;
150
- align-items: center;
151
- font-size: 0.8rem;
152
- }
153
- .status-value {
154
- font-size: 1.2rem;
155
- font-weight: bold;
156
- }
157
- .container {
158
- max-width: 1400px;
159
- margin: 0 auto;
160
- padding: 2rem;
161
- display: grid;
162
- grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
163
- gap: 2rem;
164
- }
165
- .card {
166
- background: white;
167
- border-radius: 8px;
168
- padding: 1.5rem;
169
- box-shadow: 0 2px 4px rgba(0,0,0,0.1);
170
- }
171
- .card h2 {
172
- margin-bottom: 1rem;
173
- color: #2c3e50;
174
- font-size: 1.2rem;
175
- }
176
- .metric {
177
- display: flex;
178
- justify-content: space-between;
179
- align-items: center;
180
- padding: 0.5rem 0;
181
- border-bottom: 1px solid #eee;
182
- }
183
- .metric:last-child { border-bottom: none; }
184
- .metric-label { font-weight: 500; }
185
- .metric-value {
186
- font-weight: bold;
187
- color: #27ae60;
188
- }
189
- .metric-value.warning { color: #f39c12; }
190
- .metric-value.critical { color: #e74c3c; }
191
- .alert {
192
- padding: 0.75rem;
193
- margin: 0.5rem 0;
194
- border-radius: 4px;
195
- border-left: 4px solid;
196
- }
197
- .alert.warning {
198
- background: #fff3cd;
199
- border-color: #f39c12;
200
- color: #856404;
201
- }
202
- .alert.critical {
203
- background: #f8d7da;
204
- border-color: #e74c3c;
205
- color: #721c24;
206
- }
207
- .chart-container {
208
- height: 200px;
209
- background: #f8f9fa;
210
- border-radius: 4px;
211
- display: flex;
212
- align-items: center;
213
- justify-content: center;
214
- color: #666;
215
- }
216
- .distribution {
217
- display: grid;
218
- grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
219
- gap: 1rem;
220
- margin-top: 1rem;
221
- }
222
- .distribution-item {
223
- text-align: center;
224
- padding: 1rem;
225
- background: #f8f9fa;
226
- border-radius: 4px;
227
- }
228
- .distribution-value {
229
- font-size: 1.5rem;
230
- font-weight: bold;
231
- color: #2c3e50;
232
- }
233
- .distribution-label {
234
- font-size: 0.8rem;
235
- color: #666;
236
- margin-top: 0.5rem;
237
- }
238
- .trace {
239
- padding: 0.75rem;
240
- margin: 0.5rem 0;
241
- background: #f8f9fa;
242
- border-radius: 4px;
243
- border-left: 4px solid #3498db;
244
- }
245
- .trace-header {
246
- display: flex;
247
- justify-content: space-between;
248
- align-items: center;
249
- margin-bottom: 0.5rem;
250
- }
251
- .trace-operation {
252
- font-weight: bold;
253
- color: #2c3e50;
254
- }
255
- .trace-duration {
256
- color: #666;
257
- font-size: 0.9rem;
258
- }
259
- .trace-details {
260
- font-size: 0.8rem;
261
- color: #666;
262
- }
263
- .refresh-indicator {
264
- position: fixed;
265
- top: 1rem;
266
- right: 1rem;
267
- background: #27ae60;
268
- color: white;
269
- padding: 0.5rem 1rem;
270
- border-radius: 4px;
271
- font-size: 0.8rem;
272
- opacity: 0;
273
- transition: opacity 0.3s;
274
- }
275
- .refresh-indicator.active { opacity: 1; }
276
- @media (max-width: 768px) {
277
- .container {
278
- grid-template-columns: 1fr;
279
- padding: 1rem;
280
- }
281
- .header {
282
- padding: 1rem;
283
- flex-direction: column;
284
- gap: 1rem;
285
- }
286
- }
287
- </style>
288
- </head>
289
- <body>
290
- <div class='header'>
291
- <h1>${this.options.title}</h1>
292
- <div class='status'>
293
- <div class='status-item'>
294
- <div class='status-value'>${Q.metrics.current.totalRequests}</div>
295
- <div>Total Requests</div>
296
- </div>
297
- <div class='status-item'>
298
- <div class='status-value'>${Math.round(Q.metrics.current.averageResponseTime)}ms</div>
299
- <div>Avg Response</div>
300
- </div>
301
- <div class='status-item'>
302
- <div class='status-value'>${Math.round(Q.metrics.current.errorRate*100)}%</div>
303
- <div>Error Rate</div>
304
- </div>
305
- <div class='status-item'>
306
- <div class='status-value'>${Math.round(Q.metrics.current.requestsPerSecond)}/s</div>
307
- <div>Requests/sec</div>
308
- </div>
309
- </div>
310
- </div>
311
-
312
- <div class='container'>
313
- ${this.options.features?.realTimeMetrics?`
314
- <div class='card'>
315
- <h2>Real-time Metrics</h2>
316
- <div class='metric'>
317
- <span class='metric-label'>Response Time</span>
318
- <span class='metric-value'>${Math.round(Q.metrics.current.averageResponseTime)}ms</span>
319
- </div>
320
- <div class='metric'>
321
- <span class='metric-label'>Memory Usage</span>
322
- <span class='metric-value'>${Math.round(Q.metrics.current.memoryUsage/1024/1024)}MB</span>
323
- </div>
324
- <div class='metric'>
325
- <span class='metric-label'>CPU Usage</span>
326
- <span class='metric-value'>${Math.round(Q.metrics.current.cpuUsage)}%</span>
327
- </div>
328
- <div class='metric'>
329
- <span class='metric-label'>Requests/sec</span>
330
- <span class='metric-value'>${Math.round(Q.metrics.current.requestsPerSecond)}</span>
331
- </div>
332
- <div class='metric'>
333
- <span class='metric-label'>Error Rate</span>
334
- <span class='metric-value ${Q.metrics.current.errorRate>0.1?"critical":Q.metrics.current.errorRate>0.05?"warning":""}'>${Math.round(Q.metrics.current.errorRate*100)}%</span>
335
- </div>
336
- </div>
337
- `:""}
338
-
339
- ${this.options.features?.historicalCharts?`
340
- <div class='card'>
341
- <h2>Historical Performance</h2>
342
- <div class='chart-container'>
343
- Response Time Chart (${Q.metrics.historical.length} data points)
344
- </div>
345
- </div>
346
- `:""}
347
-
348
- <div class='card'>
349
- <h2>Request Distribution</h2>
350
- <div class='distribution'>
351
- ${Object.entries(Q.metrics.distribution.statusCodes).map(([Y,Z])=>`
352
- <div class='distribution-item'>
353
- <div class='distribution-value'>${Z}</div>
354
- <div class='distribution-label'>HTTP ${Y}</div>
355
- </div>
356
- `).join("")}
357
- </div>
358
- </div>
359
-
360
- <div class='card'>
361
- <h2>Top Endpoints</h2>
362
- ${Object.entries(Q.metrics.distribution.paths).sort(([,Y],[,Z])=>Z-Y).slice(0,10).map(([Y,Z])=>`
363
- <div class='metric'>
364
- <span class='metric-label'>${Y}</span>
365
- <span class='metric-value'>${Z}</span>
366
- </div>
367
- `).join("")}
368
- </div>
369
-
370
- ${this.options.features?.alertsPanel?`
371
- <div class='card'>
372
- <h2>Active Alerts</h2>
373
- ${Q.alerts.length===0?"<p>No active alerts</p>":""}
374
- ${Q.alerts.filter((Y)=>!Y.resolved).map((Y)=>`
375
- <div class='${Y.type} alert'>
376
- <strong>${Y.type.toUpperCase()}:</strong> ${Y.message}
377
- <br><small>${new Date(Y.timestamp).toLocaleString()}</small>
378
- </div>
379
- `).join("")}
380
- </div>
381
- `:""}
382
-
383
- ${this.options.features?.tracingView?`
384
- <div class='card'>
385
- <h2>Recent Traces</h2>
386
- ${Q.traces.slice(0,10).map((Y)=>`
387
- <div class='trace'>
388
- <div class='trace-header'>
389
- <span class='trace-operation'>${Y.operationName}</span>
390
- <span class='trace-duration'>${Math.round((Y.duration||0)*100)/100}ms</span>
391
- </div>
392
- <div class='trace-details'>
393
- Trace ID: ${Y.traceId} | Status: ${Y.status}
394
- ${Y.error?` | Error: ${Y.error}`:""}
395
- </div>
396
- </div>
397
- `).join("")}
398
- </div>
399
- `:""}
400
-
401
- ${this.options.features?.systemMetrics?`
402
- <div class='card'>
403
- <h2>System Information</h2>
404
- <div class='metric'>
405
- <span class='metric-label'>Uptime</span>
406
- <span class='metric-value'>${Math.round(Q.system.uptime/1000/60)} minutes</span>
407
- </div>
408
- <div class='metric'>
409
- <span class='metric-label'>Node.js</span>
410
- <span class='metric-value'>${Q.system.nodeVersion}</span>
411
- </div>
412
- <div class='metric'>
413
- <span class='metric-label'>Platform</span>
414
- <span class='metric-value'>${Q.system.platform} ${Q.system.arch}</span>
415
- </div>
416
- <div class='metric'>
417
- <span class='metric-label'>Heap Used</span>
418
- <span class='metric-value'>${Math.round(Q.system.memory.heapUsed/1024/1024)}MB</span>
419
- </div>
420
- <div class='metric'>
421
- <span class='metric-label'>RSS</span>
422
- <span class='metric-value'>${Math.round(Q.system.memory.rss/1024/1024)}MB</span>
423
- </div>
424
- </div>
425
- `:""}
426
- </div>
427
-
428
- <div class='refresh-indicator' id='refreshIndicator'>Updated</div>
429
-
430
- <script>
431
- let refreshInterval;
432
-
433
- function startAutoRefresh() {
434
- refreshInterval = setInterval(async () => {
435
- try {
436
- const response = await fetch('${this.options.path}/api/data');
437
- if (response.ok) {
438
- const indicator = document.getElementById('refreshIndicator');
439
- indicator.classList.add('active');
440
- setTimeout(() => indicator.classList.remove('active'), 1000);
441
-
442
- // In a real implementation, we would update the DOM with new data
443
- // For now, we'll just refresh the page
444
- setTimeout(() => window.location.reload(), ${this.options.refreshInterval});
445
- }
446
- }
447
- catch (error) {
448
- console.error('Failed to refresh data:', error);
449
- }
450
- }, ${this.options.refreshInterval});
451
- }
452
-
453
- // Start auto-refresh
454
- startAutoRefresh();
455
-
456
- // Stop refresh when page is hidden
457
- document.addEventListener('visibilitychange', () => {
458
- if (document.hidden) {
459
- clearInterval(refreshInterval);
460
- }
461
- else {
462
- startAutoRefresh();
463
- }
464
- });
465
- </script>
466
- </body>
467
- </html>
468
- `}async getDashboardData(Q,Y){let Z=Date.now(),$={current:{totalRequests:0,averageResponseTime:0,errorRate:0,requestsPerSecond:0,memoryUsage:0,cpuUsage:0},historical:this.metricsHistory,distribution:{statusCodes:{},paths:{},methods:{},responseTimes:[]}};if(Q&&typeof Q.getAggregatedMetrics==="function"){let G=Q.getAggregatedMetrics(60000);$.current={totalRequests:G.totalRequests,averageResponseTime:G.averageResponseTime,errorRate:G.errorRate,requestsPerSecond:G.requestsPerSecond,memoryUsage:G.averageMemoryUsage,cpuUsage:0},$.distribution.statusCodes=G.statusCodeDistribution,$.distribution.paths=G.pathDistribution}let X=[];if(Y&&typeof Y.getActiveSpans==="function")X=Y.getActiveSpans();let J={uptime:Z-this.startTime,nodeVersion:tQ.version,bunVersion:tQ.versions.bun||"N/A",platform:tQ.platform,arch:tQ.arch,memory:tQ.memoryUsage(),cpu:tQ.cpuUsage()};return{metrics:$,alerts:this.alerts,traces:X,system:J}}async handle(Q,Y){if(!this.options.enabled)return await Y()||new Response("Internal Server Error",{status:500});let Z=new URL(Q.url);if(Z.pathname===this.options.path){if(!this.isAuthenticated(Q))return new Response("Unauthorized",{status:401,headers:{"WWW-Authenticate":'Basic realm="Performance Dashboard"'}});let $=await this.getDashboardData(),X=this.generateDashboardHTML($);return new Response(X,{headers:{"Content-Type":"text/html","Cache-Control":"no-cache, no-store, must-revalidate"}})}if(Z.pathname===`${this.options.path}/api/data`){if(!this.isAuthenticated(Q))return new Response("Unauthorized",{status:401});let $=await this.getDashboardData();return new Response(JSON.stringify($),{headers:{"Content-Type":"application/json","Cache-Control":"no-cache, no-store, must-revalidate"}})}return await Y()}addAlert(Q,Y){if(this.alerts.push({id:Math.random().toString(36).substring(2,15),type:Q,message:Y,timestamp:Date.now(),resolved:!1}),this.alerts.length>100)this.alerts=this.alerts.slice(-100)}resolveAlert(Q){let Y=this.alerts.find((Z)=>Z.id===Q);if(Y)Y.resolved=!0}updateMetricsHistory(Q){this.metricsHistory.push({timestamp:Date.now(),...Q});let Y=this.options.maxMetrics||1000;if(this.metricsHistory.length>Y)this.metricsHistory=this.metricsHistory.slice(-Y)}}function XG(Q={}){let Y=new VZ(Q);return async(Z,$)=>Y.handle(Z,$)}import G0 from"crypto";import GQ from"process";class DZ{options;metrics=[];lastAlertTime={};requestsThisSecond=0;lastSecondTimestamp=Date.now();requestContexts=new Map;samplingCounter=0;alertCooldowns=new Map;cleanupInterval;constructor(Q={}){let Y=D.server?.performance?.monitoring||{};if(this.options={enabled:Q.enabled??Y.enabled??!0,sampleRate:Q.sampleRate??Q.sampling?.rate??1,collectMetrics:{responseTime:!0,memoryUsage:!0,cpuUsage:!0,requestDetails:!0,headers:!1,queryParams:!0,...Q.collectMetrics},sampling:{rate:Q.sampling?.rate??Q.sampleRate??1,maxRequestsPerSecond:Q.sampling?.maxRequestsPerSecond??1000,...Q.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},...Q},this.options.storage?.type==="memory")this.startCleanupInterval()}startCleanupInterval(){this.cleanupInterval=setInterval(()=>{this.cleanupOldMetrics()},60000),this.cleanupInterval.unref?.()}cleanupOldMetrics(){let Q=Date.now(),Y=this.options.storage?.retentionPeriod||86400000;this.metrics=this.metrics.filter(($)=>Q-$.timestamp<Y);let Z=this.options.storage?.maxEntries||1e4;if(this.metrics.length>Z)this.metrics=this.metrics.slice(-Z)}shouldSample(){let Q=this.options.sampling?.rate||this.options.sampleRate||1;return Math.random()<Q}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(Q){return Q.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||Q.headers.get("x-real-ip")||Q.headers.get("cf-connecting-ip")||"unknown"}async collectSystemMetrics(){let Q=GQ.memoryUsage(),Y=GQ.cpuUsage();return{memory:Q,cpu:Y}}takeSample(Q){let Y=GQ.memoryUsage(),Z=GQ.cpuUsage(),$=Date.now();if(!Q.systemSamples)Q.systemSamples=[];if(!Q.samples)Q.samples=[];Q.systemSamples.push({timestamp:$,memory:Y,cpu:Z}),Q.samples.push({timestamp:$,memory:Y,cpu:Z,stack:this.options.profiling?.includeStackTrace?Error("Profile sample").stack?.slice(0,this.options.profiling.maxStackDepth||10):void 0})}calculateCpuPercent(Q,Y,Z){let $=Y.user-Q.user,X=Y.system-Q.system;return{user:$/Z*100,system:X/Z*100}}async storeMetrics(Q){if(this.metrics.push(Q),console.warn(`[PerformanceMonitor] Stored metric: ${Q.path} ${Q.method} ${Q.responseTime}ms`),console.warn(`[PerformanceMonitor] Added metric to internal array: ${Q.path} ${Q.method} ${Q.responseTime}ms`),this.options.storage?.type)switch(this.options.storage.type){case"file":if(this.options.storage.filePath){let Y=`${JSON.stringify(Q)}
469
- `;await Bun.write(this.options.storage.filePath,Y,{createPath:!0})}break;case"custom":if(this.options.storage.customHandler)await this.options.storage.customHandler(Q);break;case"memory":default:break}}async checkThresholds(Q){let Y=typeof this.options.alerts?.customHandler==="function";if(!this.options.alerts?.enabled&&!Y)return;let Z=this.options.alerts?.thresholds,$=this.options.thresholds;if(console.warn(`[PerformanceMonitor] Checking thresholds for ${Q.path}: responseTime=${Q.responseTime}ms, threshold=${Z?.responseTime||$?.responseTime?.warning||"none"}`),Z?.responseTime&&Q.responseTime>Z.responseTime)await this.sendAlert({type:"responseTime",message:`Response time threshold exceeded: ${Q.responseTime}ms > ${Z.responseTime}ms`,value:Q.responseTime,threshold:Z.responseTime,path:Q.path,method:Q.method,statusCode:Q.statusCode,timestamp:Q.timestamp,severity:"warning"});else if($?.responseTime?.warning&&Q.responseTime>$.responseTime.warning)await this.sendAlert({type:"responseTime",message:`Response time threshold exceeded: ${Q.responseTime}ms > ${$.responseTime.warning}ms`,value:Q.responseTime,threshold:$.responseTime.warning,path:Q.path,method:Q.method,statusCode:Q.statusCode,timestamp:Q.timestamp,severity:"warning"});let X=Q.memoryUsage.heapUsed;if(Z?.memoryUsage&&X>Z.memoryUsage)await this.sendAlert({type:"memoryUsage",message:`Memory usage threshold exceeded: ${X} bytes > ${Z.memoryUsage} bytes`,value:X,threshold:Z.memoryUsage,path:Q.path,method:Q.method,statusCode:Q.statusCode,timestamp:Q.timestamp,severity:"warning"});else if($?.memoryUsage?.warning&&X>$.memoryUsage.warning)await this.sendAlert({type:"memoryUsage",message:`Memory usage threshold exceeded: ${X} bytes > ${$.memoryUsage.warning} bytes`,value:X,threshold:$.memoryUsage.warning,path:Q.path,method:Q.method,statusCode:Q.statusCode,timestamp:Q.timestamp,severity:"warning"});if((Z?.errorRate||$?.errorRate?.warning)&&Q.statusCode>=500){let J=this.metrics.filter((H)=>H.timestamp>Date.now()-60000),G=J.length,U=J.filter((H)=>H.statusCode>=500).length,W=G>0?U/G:0,z=Z?.errorRate||$?.errorRate?.warning;if(z&&W>z)await this.sendAlert({type:"errorRate",message:`Error rate threshold exceeded: ${W.toFixed(2)} > ${z.toFixed(2)}`,value:W,threshold:z,path:Q.path,method:Q.method,statusCode:Q.statusCode,timestamp:Q.timestamp,severity:"critical"})}}async sendAlert(Q){let Y=typeof this.options.alerts?.customHandler==="function";if(!Y){let Z=`${Q.type}:${Q.path}`,$=Date.now(),X=this.alertCooldowns.get(Z)||0,J=this.options.alerts?.cooldown||60000;if($-X<J)return;this.alertCooldowns.set(Z,$)}if(Y)try{await this.options.alerts.customHandler(Q)}catch(Z){console.error("Error in custom alert handler:",Z)}if(this.options.alerts?.handler)try{await this.options.alerts.handler(Q)}catch(Z){console.error("Error in alert handler:",Z)}console.warn(`[PerformanceMonitor] Alert: ${Q.message} (${Q.severity})`)}async sendAlerts(Q,Y){let Z=`${Y.path}-${Q.join(",")}`,$=Date.now(),X=300000,J=this.alertCooldowns.get(Z);if(J&&$-J<300000)return;this.alertCooldowns.set(Z,$);let G={timestamp:new Date(Y.timestamp).toISOString(),requestId:Y.requestId,path:Y.path,method:Y.method,alerts:Q,metrics:{responseTime:Y.responseTime,memoryUsage:Math.round(Y.memoryUsage.heapUsed/1024/1024),statusCode:Y.statusCode}};if(this.options.alerts?.webhookUrl)try{await fetch(this.options.alerts.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(G)})}catch(U){console.error("Failed to send webhook alert:",U)}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: ${Q.join(", ")}`,attachments:[{color:"danger",fields:[{title:"Path",value:Y.path,short:!0},{title:"Response Time",value:`${Y.responseTime}ms`,short:!0},{title:"Memory Usage",value:`${Math.round(Y.memoryUsage.heapUsed/1024/1024)}MB`,short:!0},{title:"Status Code",value:Y.statusCode.toString(),short:!0}]}]})})}catch(U){console.error("Failed to send Slack alert:",U)}}async collectMetrics(Q){let{req:Y,res:Z,startTime:$,startMemory:X,startCPU:J,error:G}=Q,U=performance.now(),W=GQ.memoryUsage(),z=GQ.cpuUsage(J),H=new URL(Y.url),_=Y.requestId||G0.randomUUID(),A={user:z.user,system:z.system},B={requestId:_,timestamp:Date.now(),responseTime:U-$,memoryUsage:{rss:W.rss,heapTotal:W.heapTotal,heapUsed:W.heapUsed,external:W.external,arrayBuffers:W.arrayBuffers},cpuUsage:A,statusCode:Z?.status||500,method:Y.method,path:H.pathname};if(G)B.error=G.message||String(G);if(Y.traceId)B.traceId=Y.traceId;if(Y.spanId)B.spanId=Y.spanId;if(Z){let L=Z.headers.get("content-length");if(L)B.contentLength=Number.parseInt(L,10)}return console.warn(`[PerformanceMonitor] Collected metrics for ${Y.method} ${H.pathname}: responseTime=${B.responseTime}ms, memory=${B.memoryUsage.heapUsed} bytes`),B}async handle(Q,Y){if(!this.options.enabled)return Y();let Z=this.options.sampling?.rate??this.options.sampleRate??1,$=Math.random();if(Z<=0||$>Z)return Y();let X=Date.now();if(X-this.lastSecondTimestamp>1000)this.lastSecondTimestamp=X,this.requestsThisSecond=0;if(this.options.maxRequestsPerSecond&&this.requestsThisSecond>=this.options.maxRequestsPerSecond)return Y();this.requestsThisSecond++,console.warn(`[PerformanceMonitor] Handling request: ${Q.method} ${new URL(Q.url).pathname}`);let J=performance.now(),G=GQ.memoryUsage(),U=GQ.cpuUsage(),W=[],z;if(this.options.profiling?.enabled){let A=Q.requestId||G0.randomUUID();if(!Q.profiling)Q.profiling={requestId:A,samples:[],systemSamples:[]};if(this.takeSample(Q.profiling),this.options.profiling.sampleInterval)z=setInterval(()=>{if(Q.profiling&&Q.profiling.samples.length<(this.options.profiling?.maxSamples||100))this.takeSample(Q.profiling)},this.options.profiling.sampleInterval)}let H=null,_;try{H=await Y()}catch(A){throw _=A instanceof Error?A:Error(String(A)),_}finally{if(z)clearInterval(z);let A=await this.collectMetrics({req:Q,res:H||new Response("Internal Server Error",{status:500}),startTime:J,startMemory:G,startCPU:U,profilingSamples:W,error:_});await this.storeMetrics(A),await this.checkThresholds(A)}if(!H)return new Response("Internal Server Error",{status:500});return H}addMetrics(Q){this.metrics.push(Q),console.warn(`[PerformanceMonitor] Added metric to internal array: ${Q.path} ${Q.method} ${Q.responseTime}ms`)}async checkThresholdsPublic(Q){return this.checkThresholds(Q)}getMetrics(Q){let Y=this.metrics;if(Q?.startTime)Y=Y.filter((Z)=>Z.timestamp>=Q.startTime);if(Q?.endTime)Y=Y.filter((Z)=>Z.timestamp<=Q.endTime);if(Q?.path)Y=Y.filter((Z)=>Z.path===Q.path);if(Q?.method)Y=Y.filter((Z)=>Z.method===Q.method);if(Q?.statusCode)Y=Y.filter((Z)=>Z.statusCode===Q.statusCode);if(Q?.limit)Y=Y.slice(-Q.limit);return Y}getAggregatedMetrics(Q=60000){let Z=Date.now()-Q,$=this.metrics.filter((z)=>z.timestamp>=Z);if($.length===0)return{totalRequests:0,averageResponseTime:0,medianResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,errorRate:0,averageMemoryUsage:0,requestsPerSecond:0,statusCodeDistribution:{},pathDistribution:{}};let X=$.map((z)=>z.responseTime).sort((z,H)=>z-H),J=$.filter((z)=>z.statusCode>=400).length,G=$.map((z)=>z.memoryUsage.heapUsed),U={},W={};return $.forEach((z)=>{U[z.statusCode]=(U[z.statusCode]||0)+1,W[z.path]=(W[z.path]||0)+1}),{totalRequests:$.length,averageResponseTime:X.reduce((z,H)=>z+H,0)/X.length,medianResponseTime:X[Math.floor(X.length/2)],p95ResponseTime:X[Math.floor(X.length*0.95)],p99ResponseTime:X[Math.floor(X.length*0.99)],errorRate:J/$.length,averageMemoryUsage:G.reduce((z,H)=>z+H,0)/G.length,requestsPerSecond:$.length/(Q/1000),statusCodeDistribution:U,pathDistribution:W}}getProfiles(){let Q=[],Y=GQ.memoryUsage(),Z=GQ.cpuUsage();Q.push({timestamp:Date.now(),memoryUsage:Y,cpuUsage:Z});for(let $ of this.requestContexts.values())if($.samples&&$.samples.length>0)for(let X of $.samples)Q.push({timestamp:X.timestamp,memoryUsage:X.memory,cpuUsage:X.cpu});return Q}destroy(){if(this.cleanupInterval)clearInterval(this.cleanupInterval);this.requestContexts.clear(),this.alertCooldowns.clear()}}function JG(Q={}){let Y=new DZ(Q);return async(Z,$)=>Y.handle(Z,$)}class wZ{options;spans=new Map;activeSpans=new Map;exportQueue=[];exportInterval;constructor(Q={}){let Y=D.server?.performance?.monitoring?.tracing||{};if(this.options={enabled:Q.enabled??Y.enabled??!1,sampleRate:Q.sampleRate??Y.sampleRate??1,maxSpans:Q.maxSpans??1e4,includeHeaders:Q.includeHeaders??!1,includeQueryParams:Q.includeQueryParams??!0,includeRequestBody:Q.includeRequestBody??!1,includeResponseBody:Q.includeResponseBody??!1,maxBodySize:Q.maxBodySize??1048576,exporters:Q.exporters??[{type:"console"}],propagation:{enabled:!0,headers:["x-trace-id","x-span-id","x-parent-span-id"],...Q.propagation}},this.options.enabled)this.startExportInterval()}startExportInterval(){this.exportInterval=setInterval(async()=>{try{await this.exportSpans()}catch(Q){console.warn("Error exporting spans:",Q)}},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(Q){if(!this.options.propagation?.enabled)return{};let Y=this.options.propagation.headers||[],Z;for(let X of Y){let J=Q.headers.get(X);if(J){Z=J;break}}let $=Q.headers.get("x-parent-span-id")||void 0;return{traceId:Z,parentSpanId:$}}async captureRequestBody(Q){if(!this.options.includeRequestBody)return;try{let Y=Q.headers.get("content-type")||"",Z=Number.parseInt(Q.headers.get("content-length")||"0",10);if(Z>(this.options.maxBodySize||1048576))return{truncated:!0,reason:"Body too large",size:Z};if(Y.includes("application/json"))return await Q.clone().json();else if(Y.includes("application/x-www-form-urlencoded")){let X=await Q.clone().formData(),J={};for(let[G,U]of X.entries())J[G]=U;return J}else if(Y.includes("text/"))return await Q.clone().text()}catch(Y){return{error:"Failed to capture body",message:Y instanceof Error?Y.message:String(Y)}}return}async captureResponseBody(Q){if(!this.options.includeResponseBody)return;try{let Y=Q.headers.get("content-type")||"",Z=Number.parseInt(Q.headers.get("content-length")||"0",10);if(Z>(this.options.maxBodySize||1048576))return{truncated:!0,reason:"Body too large",size:Z};if(Y.includes("application/json"))return await Q.clone().json();else if(Y.includes("text/"))return await Q.clone().text()}catch(Y){return{error:"Failed to capture body",message:Y instanceof Error?Y.message:String(Y)}}return}createSpan(Q,Y,Z,$){return{traceId:Q,spanId:Y,parentSpanId:$,operationName:Z,startTime:performance.now(),tags:{},logs:[],status:"ok"}}addSpanTag(Q,Y,Z){let $=this.spans.get(Q);if($)$.tags[Y]=Z}addSpanLog(Q,Y,Z,$){let X=this.spans.get(Q);if(X)X.logs.push({timestamp:performance.now(),level:Y,message:Z,fields:$})}finishSpan(Q,Y="ok",Z){let $=this.spans.get(Q);if($){if($.endTime=performance.now(),$.duration=$.endTime-$.startTime,$.status=Y,Z){if($.error=Z,this.options.includeHeaders)$.stackTrace=Error("Trace error stack").stack?.split(`
470
- `)}this.exportQueue.push($),this.spans.delete(Q)}}async exportSpans(){if(this.spans.size>0){let Z=performance.now()-60000;for(let[$,X]of this.spans)if(X.endTime===void 0&&X.startTime<Z)this.spans.delete($)}if(this.exportQueue.length===0){let Z=Array.from(this.spans.values()).filter(($)=>$.endTime!==void 0);if(Z.length>0){this.exportQueue.push(...Z);for(let $ of Z)this.spans.delete($.spanId)}if(this.exportQueue.length===0)return}let Q=[...this.exportQueue];this.exportQueue=[];let Y=this.options.exporters||[];if(Y.length===0){this.exportToConsole(Q);return}for(let Z of Y)try{switch(Z.type){case"console":this.exportToConsole(Q);break;case"jaeger":await this.exportToJaeger(Q,Z);break;case"zipkin":await this.exportToZipkin(Q,Z);break;case"custom":if(typeof Z.customExporter==="function")await Z.customExporter(Q);break}}catch($){console.warn(`Failed to export spans to ${Z.type}:`,$)}}exportToConsole(Q){for(let Y of Q)console.warn("Trace Span:",{traceId:Y.traceId,spanId:Y.spanId,operation:Y.operationName,duration:`${Math.round((Y.duration||0)*100)/100}ms`,status:Y.status,tags:Y.tags,logs:Y.logs.length,error:Y.error})}async exportToJaeger(Q,Y){if(!Y.endpoint)return;let Z=Q.map(($)=>({traceID:$.traceId,spanID:$.spanId,parentSpanID:$.parentSpanId,operationName:$.operationName,startTime:Math.floor($.startTime*1000),duration:Math.floor(($.duration||0)*1000),tags:Object.entries($.tags).map(([X,J])=>({key:X,type:typeof J==="string"?"string":"number",value:String(J)})),logs:$.logs.map((X)=>({timestamp:Math.floor(X.timestamp*1000),fields:[{key:"level",value:X.level},{key:"message",value:X.message},...X.fields?Object.entries(X.fields).map(([J,G])=>({key:J,value:String(G)})):[]]})),process:{serviceName:"bun-router",tags:[{key:"hostname",value:Bun.env.HOSTNAME||"localhost"},{key:"pid",value:String(123)}]}}));await fetch(`${Y.endpoint}/api/traces`,{method:"POST",headers:{"Content-Type":"application/json",...Y.headers},body:JSON.stringify({data:[{spans:Z}]})})}async exportToZipkin(Q,Y){if(!Y.endpoint)return;let Z=Q.map(($)=>({traceId:$.traceId,id:$.spanId,parentId:$.parentSpanId,name:$.operationName,timestamp:Math.floor($.startTime*1000),duration:Math.floor(($.duration||0)*1000),kind:"SERVER",localEndpoint:{serviceName:"bun-router"},tags:$.tags,annotations:$.logs.map((X)=>({timestamp:Math.floor(X.timestamp*1000),value:`${X.level}: ${X.message}`}))}));await fetch(`${Y.endpoint}/api/v2/spans`,{method:"POST",headers:{"Content-Type":"application/json",...Y.headers},body:JSON.stringify(Z)})}async handle(Q,Y){if(!this.options.enabled||!this.shouldSample())return await Y()||new Response("Internal Server Error",{status:500});let Z=Q.requestId||this.generateId(),$=this.extractPropagationHeaders(Q),X=$.traceId||this.generateId(),J=this.generateId(),G=new URL(Q.url);console.warn(`[RequestTracer] Creating span for ${Q.method} ${G.pathname}, traceId=${X}, spanId=${J}`);let U=this.createSpan(X,J,`${Q.method} ${G.pathname}`,$.parentSpanId);if(this.spans.set(J,U),this.activeSpans.set(Z,J),Q.traceId=X,Q.spanId=J,Object.defineProperties(Q,{traceId:{value:X,writable:!0,enumerable:!0,configurable:!0},spanId:{value:J,writable:!0,enumerable:!0,configurable:!0}}),this.addSpanTag(J,"http.method",Q.method),this.addSpanTag(J,"http.url",Q.url),this.addSpanTag(J,"http.path",G.pathname),this.addSpanTag(J,"user_agent",Q.headers.get("user-agent")),this.options.includeHeaders){let H={};for(let[_,A]of Q.headers.entries())H[_]=A;this.addSpanTag(J,"http.headers",H)}if(this.options.includeQueryParams&&G.searchParams.size>0){let H={};for(let[_,A]of G.searchParams.entries())H[_]=A;this.addSpanTag(J,"http.query_params",H)}if(this.options.includeRequestBody&&Q.method!=="GET"&&Q.method!=="HEAD")try{let H=await this.captureRequestBody(Q);if(H!==void 0)this.addSpanTag(J,"http.request_body",H)}catch(H){this.addSpanLog(J,"warn","Failed to capture request body",{error:String(H)})}this.addSpanLog(J,"info","Request started");let W,z;try{if(W=await Y()||new Response("Internal Server Error",{status:500}),this.addSpanTag(J,"http.status_code",W.status),this.addSpanTag(J,"http.status_text",W.statusText),this.options.includeResponseBody)try{let A=await this.captureResponseBody(W);if(A!==void 0)this.addSpanTag(J,"http.response_body",A)}catch(A){this.addSpanLog(J,"warn","Failed to capture response body",{error:String(A)})}this.addSpanLog(J,"info","Request completed",{status:W.status,statusText:W.statusText});let _=W.status>=400;if(_)this.addSpanTag(J,"error",!0),this.addSpanTag(J,"error.status_code",W.status);this.finishSpan(J,_?"error":"ok",_?`HTTP ${W.status}`:void 0)}catch(H){z=H instanceof Error?H.message:String(H),this.addSpanTag(J,"error",!0),this.addSpanTag(J,"error.message",z),this.addSpanTag(J,"error.type",H instanceof Error?H.constructor.name:"Unknown"),this.addSpanLog(J,"error","Request failed",{error:z}),this.finishSpan(J,"error",z);let _=this.spans.get(J);if(_){if(_.endTime===void 0)_.endTime=performance.now(),_.duration=_.endTime-_.startTime,_.status="error",_.error=z;this.exportQueue.push(_),this.spans.delete(J),this.exportSpans().catch((A)=>{console.warn("Failed to export error span:",A)})}W=new Response("Internal Server Error",{status:500})}if(this.activeSpans.delete(Z),this.options.propagation?.enabled)W.headers.set("x-trace-id",X),W.headers.set("x-span-id",J);return W}getActiveSpans(){return Array.from(this.spans.values())}getSpanById(Q){return this.spans.get(Q)}createChildSpan(Q,Y){let Z=this.spans.get(Q);if(!Z)return null;let $=this.generateId(),X=this.createSpan(Z.traceId,$,Y,Q);return this.spans.set($,X),$}addTag(Q,Y,Z){this.addSpanTag(Q,Y,Z)}addLog(Q,Y,Z,$){this.addSpanLog(Q,Y,Z,$)}finish(Q,Y="ok",Z){this.finishSpan(Q,Y,Z)}async flush(){let Q=Array.from(this.spans.keys());console.warn(`[RequestTracer] Flushing ${Q.length} active spans`);for(let Y of Q){let Z=this.spans.get(Y);if(Z&&!Z.endTime)this.finishSpan(Y,"ok")}await this.exportSpans()}destroy(){if(this.exportInterval)clearInterval(this.exportInterval);this.spans.clear(),this.activeSpans.clear(),this.exportQueue=[]}}function GG(Q={}){let Y=new wZ(Q);return async(Z,$)=>Y.handle(Z,$)}class rQ{options;suspiciousPatterns=[];sqlInjectionPatterns=[];xssPatterns=[];pathTraversalPatterns=[];commandInjectionPatterns=[];constructor(Q={}){let Y=D.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,...Q.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,...Q.requestFiltering},ipFiltering:{enabled:!1,whitelist:[],blacklist:[],blockPrivateIPs:!1,blockCloudProviders:!1,geoBlocking:{enabled:!1,allowedCountries:[],blockedCountries:[]},...Q.ipFiltering},attackPrevention:{enabled:!0,sqlInjection:!0,xss:!0,pathTraversal:!0,commandInjection:!0,ldapInjection:!0,xxe:!0,customPatterns:[],...Q.attackPrevention},responseSecurity:{enabled:!0,removeServerHeaders:!0,addSecurityHeaders:!0,sanitizeErrors:!0,preventInfoDisclosure:!0,...Q.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(Q){return Q.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||Q.headers.get("x-real-ip")||Q.headers.get("cf-connecting-ip")||Q.headers.get("x-client-ip")||"unknown"}isPrivateIP(Q){return[/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^127\./,/^169\.254\./,/^::1$/,/^fc00:/,/^fe80:/].some((Z)=>Z.test(Q))}validateInput(Q){let Y=[];if(!this.options.attackPrevention?.enabled)return{isValid:!0,threats:Y};if(this.options.attackPrevention.sqlInjection){for(let Z of this.sqlInjectionPatterns)if(Z.test(Q)){Y.push("SQL Injection");break}}if(this.options.attackPrevention.xss){for(let Z of this.xssPatterns)if(Z.test(Q)){Y.push("XSS");break}}if(this.options.attackPrevention.pathTraversal){for(let Z of this.pathTraversalPatterns)if(Z.test(Q)){Y.push("Path Traversal");break}}if(this.options.attackPrevention.commandInjection){for(let Z of this.commandInjectionPatterns)if(Z.test(Q)){Y.push("Command Injection");break}}if(this.options.attackPrevention.customPatterns){for(let Z of this.options.attackPrevention.customPatterns)if(Z.pattern.test(Q))Y.push(Z.name)}return{isValid:Y.length===0,threats:Y}}sanitizeInput(Q){if(!this.options.inputValidation?.sanitizeInput)return Q;return Q.replace(/[<>'"&]/g,(Y)=>{return{"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","&":"&amp;"}[Y]||Y}).replace(/javascript:/gi,"blocked:").replace(/vbscript:/gi,"blocked:").replace(/on\w+=/gi,"blocked=")}async handle(Q,Y){let Z=this.getClientIP(Q),$=Q.headers.get("user-agent")||"",X=new URL(Q.url);if(this.options.ipFiltering?.enabled){let G=this.options.ipFiltering;if(G.whitelist?.length&&!G.whitelist.includes(Z))return new Response("Access Denied",{status:403});if(G.blacklist?.includes(Z))return new Response("Access Denied",{status:403});if(G.blockPrivateIPs&&this.isPrivateIP(Z))return new Response("Access Denied",{status:403})}if(this.options.requestFiltering?.enabled){let G=this.options.requestFiltering;if(G.allowedMethods&&!G.allowedMethods.includes(Q.method))return new Response("Method Not Allowed",{status:405});if(G.requireUserAgent&&!$)return new Response("Bad Request",{status:400});if(G.blockUserAgents){if(G.blockUserAgents.some((W)=>$.toLowerCase().includes(W.toLowerCase())))return new Response("Access Denied",{status:403})}if(G.blockSuspiciousPatterns){let U=X.pathname+X.search;for(let W of this.suspiciousPatterns)if(W.test(U))return new Response("Suspicious Request Blocked",{status:400})}}if(this.options.inputValidation?.enabled){let G=this.options.inputValidation;if(G.maxUrlLength&&Q.url.length>G.maxUrlLength)return new Response("URL Too Long",{status:414});let U=Q.headers.get("content-type");if(U&&G.allowedContentTypes){if(!G.allowedContentTypes.some((z)=>U.toLowerCase().startsWith(z.toLowerCase())))return new Response("Unsupported Media Type",{status:415})}for(let[W,z]of X.searchParams.entries()){let H=this.validateInput(z);if(!H.isValid)return console.warn(`Security threat detected in query param ${W}:`,H.threats),new Response(`Security threat detected: ${H.threats.join(", ")}`,{status:400})}for(let[W,z]of Q.headers.entries()){if(G.maxHeaderSize&&z.length>G.maxHeaderSize)return new Response("Header Too Large",{status:431});let H=this.validateInput(z);if(!H.isValid)return console.warn(`Security threat detected in header ${W}:`,H.threats),new Response(`Security threat detected: ${H.threats.join(", ")}`,{status:400})}}if(Q.method!=="GET"&&Q.method!=="HEAD"&&Q.method!=="OPTIONS")try{let G=Q.headers.get("content-length");if(G&&this.options.inputValidation?.maxBodySize){if(Number.parseInt(G,10)>this.options.inputValidation.maxBodySize)return new Response("Payload Too Large",{status:413})}}catch(G){console.error("Error checking content length:",G)}let J=await Y();if(!J)return new Response("Not Found",{status:404});if(this.options.responseSecurity?.enabled){let G=new Headers(J.headers),U=this.options.responseSecurity;if(U.removeServerHeaders)G.delete("Server"),G.delete("X-Powered-By"),G.delete("X-AspNet-Version"),G.delete("X-AspNetMvc-Version");if(U.addSecurityHeaders)G.set("X-Content-Type-Options","nosniff"),G.set("X-Frame-Options","DENY"),G.set("X-XSS-Protection","0"),G.set("Referrer-Policy","strict-origin-when-cross-origin");return new Response(J.body,{status:J.status,statusText:J.statusText,headers:G})}return J}}function WG(Q={}){let Y=new rQ(Q);return async(Z,$)=>Y.handle(Z,$)}class EZ{middlewares=[];constructor(Q={}){let Y=D.server?.security||{},Z=["ddosProtection","security","helmet","contentSecurityPolicy","inputValidation"],$=Q.order||Z;for(let X of $)switch(X){case"ddosProtection":if(Q.ddosProtection!==!1&&Y.ddos?.enabled!==!1){let J=typeof Q.ddosProtection==="object"?Q.ddosProtection:{},G=new oQ(J);this.middlewares.push((U,W)=>G.handle(U,W))}break;case"security":if(Q.security!==!1){let J=typeof Q.security==="object"?Q.security:{},G=new rQ(J);this.middlewares.push((U,W)=>G.handle(U,W))}break;case"helmet":if(Q.helmet!==!1&&Y.helmet?.enabled!==!1){let J=typeof Q.helmet==="object"?Q.helmet:{},G=new LY(J);this.middlewares.push((U,W)=>G.handle(U,W))}break;case"contentSecurityPolicy":if(Q.contentSecurityPolicy!==!1&&Y.helmet?.contentSecurityPolicy!==!1){let J=typeof Q.contentSecurityPolicy==="object"?Q.contentSecurityPolicy:{},G=new sQ(J);this.middlewares.push((U,W)=>G.handle(U,W))}break;case"inputValidation":if(Q.inputValidation!==!1&&Y.inputValidation?.enabled!==!1){let J=typeof Q.inputValidation==="object"?Q.inputValidation:{},G=new aQ(J);this.middlewares.push((U,W)=>G.handle(U,W))}break}}async handle(Q,Y){let Z=0,$=async()=>{if(Z>=this.middlewares.length)return await Y();let X=this.middlewares[Z++];return await X(Q,$)};return await $()}}function UG(Q={}){let Y=new EZ(Q);return async(Z,$)=>Y.handle(Z,$)}var pU=()=>new hQ,uU=()=>new dQ,cU=()=>new lQ,lU=()=>new iQ,nU=()=>new u;function iU(){return new XQ({type:"bearer",validator:()=>!0})}var u8=null;function c8(){if(!u8)u8={"Middleware/Cors":new hQ,"Middleware/JsonBody":new dQ,"Middleware/RequestId":new lQ,"Middleware/Session":new iQ,"Middleware/Csrf":new u,"Middleware/Auth":new XQ({type:"bearer",validator:()=>!0}),"Middleware/RateLimit":m8(),"Middleware/RequestSigning":new nQ({secret:""})};return u8}var sU=new Proxy({},{get(Q,Y){return c8()[Y]},ownKeys(){return Object.keys(c8())},getOwnPropertyDescriptor(Q,Y){let Z=c8()[Y];if(Z!==void 0)return{configurable:!0,enumerable:!0,value:Z};return}});
471
- export{L$ as Ip,o1 as Jp,D as Kp,j$ as Lp,j8 as Mp,K$ as Np,jJ as Op,KJ as Pp,FJ as Qp,MJ as Rp,IJ as Sp,hQ as Tp,u as Up,dQ as Vp,AZ as Wp,m8 as Xp,lQ as Yp,s as Zp,$0 as _p,nQ as $p,v7 as aq,h7 as bq,d7 as cq,wQ as dq,jZ as eq,KZ as fq,FZ as gq,nW as hq,p8 as iq,MZ as jq,iQ as kq,sQ as lq,g7 as mq,oQ as nq,p7 as oq,RY as pq,IQ as qq,o7 as rq,a7 as sq,t7 as tq,r7 as uq,e7 as vq,LY as wq,aQ as xq,ZG as yq,IZ as zq,$G as Aq,VZ as Bq,XG as Cq,DZ as Dq,JG as Eq,wZ as Fq,GG as Gq,rQ as Hq,WG as Iq,EZ as Jq,UG as Kq,pU as Lq,uU as Mq,cU as Nq,lU as Oq,nU as Pq,iU as Qq,sU as Rq};