@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
@@ -0,0 +1,412 @@
1
+ // @bun
2
+ import{Jq as St}from"./chunk-p0qhpnqh.js";import{Zu as z}from"./chunk-nf3kv7kv.js";import wr from"process";var xt={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:wr.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:{}}},He=null;async function fn(){if(!He)He=await St({name:"router",defaultConfig:xt});return He}var y=xt;function Rt(e){if(!e||!e.startsWith("Basic "))return null;try{let t=e.split(" ")[1],r=atob(t),[s,n]=r.split(":");return{username:s,password:n}}catch(t){return null}}function _e(e){if(!e||!e.startsWith("Bearer "))return null;return e.split(" ")[1]}function kt(e,t="header",r="X-API-Key"){switch(t){case"header":return e.headers.get(r)||null;case"query":return new URL(e.url).searchParams.get(r);case"cookie":if(e.cookies){if(typeof e.cookies.get==="function")return e.cookies.get(r)||null;return e.cookies[r]||null}return null;default:return null}}class P{options;constructor(e){this.options={source:"header",key:"Authorization",attachUser:!0,...e}}async handle(e,t){let r=null;if(this.options.credentialsExtractor)r=await this.options.credentialsExtractor(e);else switch(this.options.type){case"basic":{let i=e.headers.get(this.options.key||"Authorization");r=Rt(i||"");break}case"bearer":case"jwt":{let i=e.headers.get(this.options.key||"Authorization");r=_e(i||"");break}case"api-key":{r=kt(e,this.options.source,this.options.key);break}case"oauth2":{let i=e.headers.get(this.options.key||"Authorization");r=_e(i||"");break}}if(!r){let i={};if(this.options.type==="basic"){let o=this.options.realm||"Secure Area";i["WWW-Authenticate"]=`Basic realm="${o}"`}return new Response("Unauthorized",{status:401,headers:i})}if(!await this.options.validator(r,e))return new Response("Unauthorized",{status:401});if(this.options.userExtractor&&this.options.attachUser){let i=await this.options.userExtractor(r,e);e.user=i}return await t()||new Response("Not Found",{status:404})}}function br(e,t={}){return new P({type:"basic",validator:e,...t})}function vr(e,t={}){return new P({type:"bearer",validator:e,...t})}function Sr(e,t={}){return new P({type:"jwt",validator:e,...t})}function xr(e,t={}){return new P({type:"api-key",validator:e,...t})}function Rr(e,t={}){return new P({type:"oauth2",validator:e,...t})}var Ve={"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 L{resolveAllowOrigin(e,t,r){if(Array.isArray(e)){if(r&&e.includes(r))return{value:r,vary:!0};return{value:null,vary:!0}}let s=e||"*";if(s==="*"){if(t){if(r)return{value:r,vary:!0};return{value:null,vary:!0}}return{value:"*",vary:!1}}return{value:s,vary:!1}}getCorsHeaders(e){let t=y.server?.cors,r=e.headers.get("origin");if(t&&t.enabled){let s=Boolean(t.credentials),{value:n,vary:i}=this.resolveAllowOrigin(t.origin,s,r),o={"Access-Control-Allow-Methods":Array.isArray(t.methods)?t.methods.join(", "):Ve["Access-Control-Allow-Methods"],"Access-Control-Allow-Headers":Array.isArray(t.allowedHeaders)?t.allowedHeaders.join(", "):Ve["Access-Control-Allow-Headers"],"Access-Control-Max-Age":String(t.maxAge||86400)};if(n!==null)o["Access-Control-Allow-Origin"]=n;if(s&&n!==null&&n!=="*")o["Access-Control-Allow-Credentials"]="true";if(i)o.Vary="Origin";return o}return{...Ve}}async handle(e,t){let r=this.getCorsHeaders(e);if(e.method==="OPTIONS")return new Response(null,{status:204,headers:r});let s=(n)=>{let i=new Headers(n.headers);return Object.entries(r).forEach(([o,c])=>{i.set(o,c)}),new Response(n.body,{status:n.status,statusText:n.statusText,headers:i})};try{let n=await t();if(!n)return new Response(JSON.stringify({error:"Not Found"}),{status:404,headers:{...r,"Content-Type":"application/json"}});return s(n)}catch(n){return console.error("[CORS] Error in middleware chain:",n),new Response(JSON.stringify({error:"Internal Server Error",message:n instanceof Error?n.message:String(n)}),{status:500,headers:{...r,"Content-Type":"application/json"}})}}}import{createHash as kr,randomBytes as Er,timingSafeEqual as Cr}from"crypto";var Tr=1e4,Pr=7200000;class x{static tokens=new Map;async handle(e,t){let r=y.server?.security?.csrf??{},s=e.method.toUpperCase();if(["GET","HEAD","OPTIONS",...r?.ignoreMethods||[]].includes(s)){let d=this.generateToken(r?.secret||"csrf-secret"),m=await t();if(!m)return new Response("Not Found",{status:404});let p=r?.cookie?.name||"csrf-token",b=[];if(b.push(`${p}=${d}`),b.push("Path=/"),r?.cookie?.options?.httpOnly)b.push("HttpOnly");if(r?.cookie?.options?.secure)b.push("Secure");if(r?.cookie?.options?.sameSite)b.push(`SameSite=${r.cookie.options.sameSite}`);let f=new Headers(m.headers);return f.append("Set-Cookie",b.join("; ")),x.storeToken(d),new Response(m.body,{status:m.status,statusText:m.statusText,headers:f})}let i=e.headers.get("authorization")??e.headers.get("Authorization");if(i&&/^Bearer\s+\S/i.test(i))return await t()||new Response("Not Found",{status:404});let o=e.headers.get("X-CSRF-TOKEN")||e.jsonBody?.csrf_token||e.jsonBody?._token||null,c=typeof o==="string"?o:null,l=this.parseCookies(e)[r?.cookie?.name||"csrf-token"];if(!c||!l||!x.safeCompare(c,l)||!x.isTokenValid(c))return new Response(JSON.stringify({error:"CSRF token validation failed"}),{status:403,headers:{"Content-Type":"application/json"}});return await t()||new Response("Not Found",{status:404})}static safeCompare(e,t){let r=Buffer.from(e),s=Buffer.from(t);if(r.length!==s.length)return!1;return Cr(r,s)}static storeToken(e){if(x.tokens.size>=Tr){let t=x.tokens.keys().next().value;if(t!==void 0)x.tokens.delete(t)}x.tokens.set(e,Date.now())}static isTokenValid(e){let t=x.tokens.get(e);if(t===void 0)return!1;if(Date.now()-t>Pr)return x.tokens.delete(e),!1;return!0}generateToken(e){let t=Er(16).toString("hex");return kr("sha256").update(`${t}${e}`).digest("hex")}parseCookies(e){let t=e.headers.get("cookie");if(!t)return{};let r={};for(let s of t.split(";")){let n=s.indexOf("=");if(n===-1)continue;let i=s.slice(0,n).trim();if(!i)continue;r[i]=s.slice(n+1).trim()}return r}}class j{async handle(e,t){let r=e.headers.get("content-type");if(r&&r.includes("application/json"))try{let i=await e.clone().json();Object.defineProperty(e,"jsonBody",{value:i,writable:!0,enumerable:!0,configurable:!0})}catch{return new Response(JSON.stringify({error:"Invalid JSON payload"}),{status:400,headers:{"Content-Type":"application/json"}})}return await t()||new Response("Not Found",{status:404})}}import{existsSync as Et,statSync as Ct}from"fs";import{join as Ar,relative as Mr,resolve as Tt}from"path";import Se from"process";import{Buffer as M}from"buffer";import{createCipheriv as Ir,createDecipheriv as $r,randomBytes as ze}from"crypto";import{closeSync as We,createReadStream as Pt,createWriteStream as Fr,existsSync as fe,fsyncSync as At,openSync as Mt,writeFileSync as Nr}from"fs";import{access as Dr,constants as It,mkdir as Or,readdir as ge,rename as $t,stat as B,unlink as ye,writeFile as Ke}from"fs/promises";import{isAbsolute as qr,join as H,resolve as Ur}from"path";import g from"process";import{pipeline as Lr}from"stream/promises";import{createGzip as Ft}from"zlib";import _ from"process";import I from"process";import we from"process";import{existsSync as be}from"fs";import{resolve as Je}from"path";import{existsSync as jr}from"fs";import{existsSync as Qe,mkdirSync as Br,readdirSync as Hr,readFileSync as _r,writeFileSync as Vr}from"fs";import{homedir as V}from"os";import{dirname as Nt,resolve as R}from"path";import q from"process";import{existsSync as zr,readdirSync as Wr}from"fs";import{extname as Ge,resolve as Dt}from"path";import Kr from"process";var Jr=Object.defineProperty,Gr=(e)=>e;function Xr(e,t){this[e]=Gr.bind(null,t)}var Yr=(e,t)=>{for(var r in t)Jr(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Xr.bind(t,r)})},N=(e,t)=>()=>(e&&(t=e(e=0)),t),Zr=import.meta.require;class at{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,s])=>r.timestamp.getTime()-s.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,s){if(!this.options.enabled)return;let n=this.generateKey(e,r),i=s??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:i,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),s=this.cache.get(r);if(!s){this.totalMisses++;return}if(this.isExpired(s)){this.cache.delete(r),this.totalMisses++;return}return s.hits++,this.totalHits++,s.value}isFileModified(e,t){try{if(!Et(e))return!0;return Ct(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,s){try{let n=Et(r)?Ct(r):null,i=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:i},r,s)}catch{this.set(e,t,r,s)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((s,n)=>s+n.size,0),r=e.map((s)=>s.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let s=r;this.cache.set(t,{value:s.value,timestamp:new Date(s.timestamp),ttl:s.ttl,hits:s.hits,size:s.size})}}}class ct{metrics=[];maxMetrics=1000;async track(e,t,r={}){let s=performance.now(),n=new Date;try{let i=await t(),o=performance.now()-s;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),i}catch(i){let o=performance.now()-s;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),i}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),s=r.reduce((n,i)=>n+i,0);return{count:t.length,averageDuration:s/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:s,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Qr(e,t={}){let s=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return s?`${e}:${s}`:e}function es(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function ts(e){return e.getStats().size*2}var W,le,Ht,ue=N(()=>{W=new at,le=new ct,Ht={createKey:Qr,isEquivalent:es,estimateMemoryUsage:ts}});function rs(e,t={}){let r=Se.cwd();while(r.includes("storage"))r=Tt(r,"..");let s=Tt(r,e||"");if(t?.relative)return Mr(Se.cwd(),s);return s}function v(){if(I.env.NODE_ENV==="test"||I.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ss(){if(I.env.NODE_ENV==="test"||I.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof I<"u"){let e=I.type;if(e==="renderer"||e==="worker")return!1;return!!(I.versions&&(I.versions.node||I.versions.bun))}return!1}class _t{async format(e){let t=await ss(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:_.pid,hostname:t(),environment:_.env.NODE_ENV||"development",platform:_.platform,version:_.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_.env.NODE_ENV||_.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ke{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...ie},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new _t,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},s=t.timestamp!==void 0;if(s)delete r.timestamp;if(this.config={...this.config,...r,timestamp:s||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),i=this.generateKey();this.currentKeyId=n,this.keys.set(n,i),this.encryptionKeys.set(n,{key:i,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ve,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ve};return{...ve,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ie.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,s])=>s!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!v()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,i=0,o=3,c=1000;while(i<o)try{try{try{await Dr(this.config.logDirectory,It.F_OK|It.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Or(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:M.from(e);try{if(!fe(this.currentLogFile))await Ke(this.currentLogFile,"",{mode:420});if(n=Mt(this.currentLogFile,"a",420),Nr(n,a,{flag:"a"}),At(n),n!==void 0)We(n),n=void 0;if((await B(this.currentLogFile)).size===0){if(await Ke(this.currentLogFile,a,{flag:"w",mode:420}),(await B(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(i<o-1){let d=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${o}:`,d);let m=c*2**i;await new Promise((p)=>setTimeout(p,m)),i++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{We(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(i===o-1){let u=a,d=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",d),a}i++;let l=c*2**(i-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let s=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(s,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return H(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 H(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return H(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(v())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,s=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},s)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),s=this.generateKey();this.currentKeyId=r,this.keys.set(r,s),this.encryptionKeys.set(r,{key:s,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),i=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,i);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ze(16).toString("hex")}generateKey(){return ze(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=ze(16),s=Ir("aes-256-gcm",t,r),n=M.isBuffer(e)?e:M.from(e,"utf8"),i=s.update(n),o=s.final(),c=i.length+o.length,a=s.getAuthTag(),l=M.allocUnsafe(16+c+16);return r.copy(l,0),i.copy(l,16),o.copy(l,16+i.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let s=Ft(),n=[];s.on("data",(i)=>n.push(i)),s.on("end",()=>t(M.from(M.concat(n)))),s.on("error",r),s.write(e),s.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(v())return;if(!this.shouldWriteToFile())return;let e=await B(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,s=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await ge(this.config.logDirectory),i=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=i.length>0?Number.parseInt(i[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await B(r).catch(()=>null))try{if(await $t(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await ye(c)}catch(a){console.error("Error compressing rotated file:",a)}if(i.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Ke(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),i=r.replace(/\.log$/,`-${n}.log`);if(await B(r).catch(()=>null))await $t(r,i)}if(this.currentLogFile=s,t.maxFiles){let i=(await ge(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of i.slice(t.maxFiles))await ye(H(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Pt(e),s=Fr(t),n=Ft();await Lr(r,n,s)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let s=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(s);console.log(s)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),fe(this.currentLogFile))try{let e=Mt(this.currentLogFile,"r+");At(e),We(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!v()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await ge(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ye(H(this.config.logDirectory,r))}catch(s){console.error(`Failed to delete temp file ${r}:`,s)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?w.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||v())return!1;let e=typeof g.env.NO_COLOR<"u",t=g.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:s="",message:n,level:i,showTimestamp:o=!0}=e,c=(p)=>p.replace(this.ANSI_PATTERN,"");if(!this.fancy){let p=[];if(o)p.push(t);if(i==="warning")p.push("WARN");else if(i==="error")p.push("ERROR");else if(r)p.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(s)p.push(s.replace(/[[\]]/g,""));return p.push(n),p.join(" ")}let a=g.stdout.columns||120,l="";if(i==="warning"||i==="error")l=`${r} ${n}`;else if(i==="info"||i==="success")l=`${r} ${s} ${n}`;else l=`${r} ${s} ${w.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,d=c(t).length,m=Math.max(1,a-2-u-d);return`${l.trim()}${" ".repeat(m)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(i,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):i});let r=/%([sdijfo%])/g,s=0,n=e.replace(r,(i,o)=>{if(o==="%")return"%";if(s>=t.length)return i;let c=t[s++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return i}});if(s<t.length)n+=` ${t.slice(s).map((i)=>typeof i==="object"?JSON.stringify(i,null,2):String(i)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,s,n)=>{let i=w.underline(w.blue(s)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${i}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${i}\x1B]8;;\x1B\\`;return i}),t=t.replace(/`([^`]+)`/g,(r,s)=>w.bgGray(s)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,s)=>w.bold(s)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,s)=>w.italic(s)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,s)=>w.italic(s)),t=t.replace(/~([^~]+)~/g,(r,s)=>w.strikethrough(s)),t}supportsHyperlinks(){if(v())return!1;let e=g.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=g.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(qr(t)||t.startsWith("./")||t.startsWith("../"))t=Ur(t);else return null;return fe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let s=new Date,n=this.formatConsoleTimestamp(s),i=this.formatFileTimestamp(s),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let d=this.options.showIcons===!1?"":Vt[e],m=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",p;switch(e){case"debug":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:m,message:w.gray(a),level:e}),console.error(p);break;case"info":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:m,message:a,level:e}),console.warn(p);break;case"success":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:m,message:w.green(a),level:e}),console.error(p);break;case"warning":p=this.formatConsoleMessage({timestamp:n,icon:d,tag:m,message:a,level:e}),console.warn(p);break;case"error":if(p=this.formatConsoleMessage({timestamp:n,icon:d,tag:m,message:a,level:e}),console.error(p),c){let b=c.split(`
3
+ `);for(let f of b)if(f.trim()&&!f.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:w.gray(` ${f}`),level:e,showTimestamp:!1}))}break}}else if(!v()){if(console.error(`${i} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${i} ${this.environment}.${e.toUpperCase()}: ${l}
4
+ `;if(c)u+=`${c}
5
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let s=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:s,lastRenderedLine:""},this.shouldStyleConsole()&&!v()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!v()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!v()&&g.stdout.isTTY)g.stdout.write(`
6
+ `);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!v()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",s=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:s,icon:this.options.showIcons===!1?"":w.blue("\u25D0"),tag:r,message:`${w.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let s=performance.now(),n=Math.round(s-t),i=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${i}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
7
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":w.green("\u2713"),tag:u,message:`${i}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!v())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ke(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(v())throw Error("createReadStream is not supported in browser environments");if(!fe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Pt(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let s=M.isBuffer(e)?e:M.from(e,"base64"),n=s.subarray(0,16),i=s.subarray(s.length-16),o=s.subarray(16,s.length-16),c=$r("aes-256-gcm",r,n);c.setAuthTag(i);let a=c.update(o),l=c.final(),u=a.length+l.length,d=M.allocUnsafe(u);return a.copy(d,0),l.copy(d,a.length),d.toString("utf8")}catch(s){throw Error(`Decryption failed: ${s instanceof Error?s.message:String(s)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return v()}isServerMode(){return!v()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),s=this.formatFileTimestamp(t),{consoleText:n,fileText:i}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
8
+ `),a=Math.max(...c.map((m)=>m.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,u=`\u2514${"\u2500".repeat(a)}\u2518`,d=c.map((m)=>this.formatConsoleMessage({timestamp:r,message:w.cyan(m),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:w.cyan(l),showTimestamp:!1})),d.forEach((m)=>console.error(m)),console.error(this.formatConsoleMessage({timestamp:r,message:w.cyan(u),showTimestamp:!1}))}else if(!v())console.error(`${s} ${this.environment}.INFO: [BOX] ${i}`);let o=`${s} ${this.environment}.INFO: [BOX] ${i}
9
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(v())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${w.cyan("?")} ${e} (y/n) `);let r=(s)=>{let n=s.toString().trim().toLowerCase();g.stdin.removeListener("data",r);try{if(typeof g.stdin.setRawMode==="function")g.stdin.setRawMode(!1)}catch{}g.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof g.stdin.setRawMode==="function")g.stdin.setRawMode(!0)}catch{}g.stdin.resume(),g.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,d)=>{if(d==="%")return"%";if(l>=t.length)return u;let m=t[l++];switch(d){case"s":return String(m);case"d":case"i":return Number(m).toString();case"j":case"o":return JSON.stringify(m,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:s,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?w.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${w.blue("\u25D0")} `;console.error(`${l}${a} ${w.cyan(s)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
10
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!g.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),s=Math.round(e.barLength*r/100),n=e.barLength-s,i=w.green("\u2501".repeat(s)),o=w.gray("\u2501".repeat(n)),c=`[${i}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?w.green("\u2713"):w.blue("\u25B6"),d=this.options.showTags!==!1&&this.name?` ${w.gray(this.formatTag(this.name))}`:"",m=`\r${u}${d} ${c} ${a}${l}`,p=g.stdout.columns||80,b=" ".repeat(Math.max(0,p-m.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${m}${b}`,g.stdout.write(e.lastRenderedLine),t)g.stdout.write(`
11
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||v()||!g.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(v()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ge(this.config.logDirectory),r=[];for(let s of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(s):s.startsWith(this.name))||!s.endsWith(".log"))continue;let i=H(this.config.logDirectory,s);if(e.before)try{if((await B(i)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${i}:`,o);continue}r.push(i)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let s of r)try{await ye(s),console.warn(`Deleted log file: ${s}`)}catch(n){console.error(`Failed to delete log file ${s}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var Ot,Xe,ie,ns,S,w,is,qt,os,Ut,as,cs,Ye,ls,Lt,jt,us,Ze,ds,ms,ps,hs,fs,ve,Vt,gs,ys=N(()=>{Ot=Se.env.CLARITY_LOG_DIR||Ar(rs(),"logs"),Xe={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ot,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ie={...Xe},ns=(async()=>{try{let{loadConfig:e}=await Promise.resolve().then(()=>(ir(),nr)),t=await e({name:"clarity",alias:"logging",defaultConfig:Xe,cwd:Se.cwd()});if(t)Object.assign(ie,t)}catch{}return ie})(),S={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},w=S,is=S.red,qt=S.green,os=S.yellow,Ut=S.blue,as=S.magenta,cs=S.cyan,Ye=S.white,ls=S.gray,Lt=S.bgRed,jt=S.bgYellow,us=S.bgGray,Ze=S.bold,ds=S.dim,ms=S.italic,ps=S.underline,hs=S.strikethrough,fs=S.reset,ve={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Vt={debug:"\uD83D\uDD0D",info:Ut("\u2139"),success:qt("\u2713"),warning:jt(Ye(Ze(" WARN "))),error:Lt(Ye(Ze(" ERROR ")))},gs=new ke("stacks")}),ws="0.15.9",bs=()=>{};async function zt(e,t={}){let{maxRetries:r=3,retryDelay:s=1000,isRetryable:n=()=>!0,fallback:i}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!n(o))break;if(s>0)await new Promise((l)=>setTimeout(l,s))}if(i!==void 0)return i;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Wt(e){return e instanceof k}function vs(e){return e instanceof xe}function Ss(e){if(Wt(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}var k,xe,oe,et,tt,Re,rt,st,ae,nt,it,D,K=N(()=>{k=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,s])=>`${r}: ${s}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},xe=class extends k{code="CONFIG_NOT_FOUND";constructor(t,r,s){let n=s===void 0?[]:Array.isArray(s)?s.filter(Boolean):[s],i="";if(n.length===1)i=` or alias "${n[0]}"`;else if(n.length>1)i=` or aliases ${n.map((o)=>`"${o}"`).join(", ")}`;super(`Configuration "${t}"${i} not found`,{configName:t,alias:s,searchPaths:r,searchPathCount:r.length})}},oe=class extends k{code="CONFIG_LOAD_ERROR";constructor(t,r,s){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:s,originalError:r.name,originalMessage:r.message});this.cause=r}},et=class extends k{code="CONFIG_VALIDATION_ERROR";constructor(t,r,s){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:s,validationErrors:r,errorCount:r.length})}},tt=class extends k{code="CONFIG_MERGE_ERROR";constructor(t,r,s,n){super(`Failed to merge configuration from "${t}" with "${r}": ${s.message}`,{sourcePath:t,targetPath:r,configName:n,originalError:s.name,originalMessage:s.message});this.cause=s}},Re=class extends k{code="ENV_VAR_ERROR";constructor(t,r,s,n){super(`Failed to parse environment variable "${t}" with value "${r}" as ${s}`,{envKey:t,envValue:r,expectedType:s,configName:n})}},rt=class extends k{code="FILE_SYSTEM_ERROR";constructor(t,r,s){super(`File system ${t} failed for "${r}": ${s.message}`,{operation:t,path:r,originalError:s.name,originalMessage:s.message});this.cause=s}},st=class extends k{code="TYPE_GENERATION_ERROR";constructor(t,r,s){super(`Failed to generate types from "${t}" to "${r}": ${s.message}`,{configDir:t,outputPath:r,originalError:s.name,originalMessage:s.message});this.cause=s}},ae=class extends k{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,s){super(`Schema validation failed${s?` for config "${s}"`:""}`,{schemaPath:t,configName:s,validationErrors:r,errorCount:r.length})}},nt=class extends k{code="BROWSER_CONFIG_ERROR";constructor(t,r,s,n){super(`Failed to fetch configuration from "${t}": ${r} ${s}`,{endpoint:t,status:r,statusText:s,configName:n})}},it=class extends k{code="PLUGIN_ERROR";constructor(t,r,s){super(`Plugin "${t}" failed during ${r}: ${s.message}`,{pluginName:t,operation:r,originalError:s.name,originalMessage:s.message});this.cause=s}},D={configNotFound(e,t,r){return new xe(e,t,r)},configLoad(e,t,r){return new oe(e,t,r)},configValidation(e,t,r){return new et(e,t,r)},configMerge(e,t,r,s){return new tt(e,t,r,s)},envVar(e,t,r,s){return new Re(e,t,r,s)},fileSystem(e,t,r){return new rt(e,t,r)},typeGeneration(e,t,r){return new st(e,t,r)},schemaValidation(e,t,r){return new ae(e,t,r)},browserConfig(e,t,r,s){return new nt(e,t,r,s)},plugin(e,t,r){return new it(e,t,r)}}});class Ee{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:s,useCamelCase:n=!0,useBackwardCompatibility:i=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=s||this.generateEnvPrefix(e),d={...t};return this.processObject(d,[],u,{useCamelCase:n,useBackwardCompatibility:i,customParsers:o,verbose:c,configName:e}),{config:d,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return le.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,s){for(let[n,i]of Object.entries(e)){let o=[...t,n],c=o.map((u)=>this.formatEnvKey(u,s.useCamelCase)),a=`${r}_${c.join("_")}`,l=s.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(s.verbose);if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.processObject(i,o,r,s);else{let u=we.env[a]||(l?we.env[l]:void 0);if(u!==void 0){if(s.verbose){let d=we.env[a]?a:l}try{e[n]=this.parseEnvironmentValue(u,typeof i,a,s.customParsers,s.configName)}catch(d){if(d instanceof Re)throw d;throw D.envVar(a,u,typeof i,s.configName)}}}}}parseEnvironmentValue(e,t,r,s,n){for(let[i,o]of Object.entries(s))try{return o(e)}catch{continue}for(let i of this.defaultParsers)if(i.canParse(e,t))try{return i.parse(e)}catch{throw D.envVar(r,e,`${t} (via ${i.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[s,n]of Object.entries(we.env))if(s.startsWith(r)&&n!==void 0)t[s]=n;return t}validateEnvironmentVariable(e,t,r){let s=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))s.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){s.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:s.length===0,errors:s}}generateEnvVarDocs(e,t,r={}){let{prefix:s,format:n="text"}=r,i=s||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],i,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,s){for(let[n,i]of Object.entries(e)){let o=[...t,n],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof i==="object"&&i!==null&&!Array.isArray(i))this.extractEnvVarInfo(i,o,r,s);else s.push({key:c,type:Array.isArray(i)?"array":typeof i,description:`Configuration for ${o.join(".")}`,example:this.generateExample(i)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
12
+
13
+ `;for(let s of e)r+=`${s.key}
14
+ `,r+=` Type: ${s.type}
15
+ `,r+=` Description: ${s.description}
16
+ `,r+=` Example: ${s.example}
17
+
18
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
19
+
20
+ `;r+=`| Variable | Type | Description | Example |
21
+ `,r+=`|----------|------|-------------|----------|
22
+ `;for(let s of e)r+=`| \`${s.key}\` | ${s.type} | ${s.description} | \`${s.example}\` |
23
+ `;return r}}var Kt=N(()=>{ue(),K()});function xs(e,t){let r=Zr("process");if(typeof r>"u"||!r.env)return t;let s=r.env[e];return s!==void 0?s:t}function Jt(e,t,r={}){return Gt(e,t,r,new WeakMap)}function Gt(e,t,r,s){let{arrayMergeMode:n="replace",skipNullish:i=!1,customMerger:o}=r;if(t===null||t===void 0)return i?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Xt(e,t,n,s);if(!T(t)||!T(e))return t;return Cs(e,t,r,s)}function Xt(e,t,r,s){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Rs(e,t);case"smart":return ks(e,t,s);default:return t}return t}function Rs(e,t){let r=[...t];for(let s of e)if(!r.some((n)=>ot(n,s)))r.push(s);return r}function ks(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(T(t[0])&&T(e[0]))return Es(e,t,r);if(t.every((s)=>typeof s==="string")&&e.every((s)=>typeof s==="string")){let s=[...t];for(let n of e)if(!s.includes(n))s.push(n);return s}return t}function Es(e,t,r){let s=[...t];for(let n of e){if(!T(n)){s.push(n);continue}let i=["id","name","key","path","type"],o=!1;for(let c of i)if(c in n){if(s.find((l)=>T(l)&&(c in l)&&l[c]===n[c])){o=!0;break}}if(!o)s.push(n)}return s}function Cs(e,t,r,s){let n=t;if(T(n)&&s.has(n))return s.get(n);let i={...e};if(T(n))s.set(n,i);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=i[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){i[o]=c;continue}if(T(c)&&T(a))i[o]=Gt(a,c,r,s);else if(Array.isArray(c)||Array.isArray(a))i[o]=Xt(a,c,r.arrayMergeMode||"smart",s);else i[o]=c}return i}function lt(e,t,r="replace"){return Jt(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ot(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ot(e[r],t[r]))return!1;return!0}if(T(e)&&T(t)){let r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ot(e[n],t[n]))return!1}return!0}return!1}function T(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}var Yt,ut=N(()=>{Yt={replace:"replace",concat:"concat",smart:"smart"}});class Ce{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:s="replace",useCache:n=!0,cacheTtl:i,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=W.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!be(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),d=u.default||u,m="default"in u,p=Object.keys(u).length>0;if(!m&&!p)throw new oe(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof d!=="object"||d===null||Array.isArray(d))throw new oe(e,Error("Configuration must export a valid object"),"unknown");let re={config:lt(t,d,s),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)W.setWithFileCheck("file",re,e,i);return re}catch(l){throw l instanceof Error?D.configLoad(e,l):D.configLoad(e,Error(String(l)))}};if(o)return le.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let s of e)try{let n=await this.loadFromPath(s,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${s}:`,n)}return null}generateConfigPaths(e,t,r){let s=this.generateNamePatterns(e,r),n=[];for(let i of s)for(let o of this.extensions)n.push(Je(t,`${i}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let s=t===void 0?[]:Array.isArray(t)?t:[t];for(let i of s){if(!i)continue;if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),e)r.push(`${e}.${i}.config`,`.${e}.${i}.config`)}let n=new Set;return r.filter((i)=>{if(!i||n.has(i))return!1;return n.add(i),!0})}checkFileAccess(e){return zt(async()=>be(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let s=[];if(!be(e))return s;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let i of n)for(let o of this.extensions){let c=Je(e,`${i}${o}`);if(await this.checkFileAccess(c))s.push(c)}}else try{let{readdirSync:n}=await import("fs"),i=n(e);for(let o of i)if(this.looksLikeConfigFile(o)){let c=Je(e,o);if(await this.checkFileAccess(c))s.push(c)}}catch{return[]}return s}looksLikeConfigFile(e){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!be(e))return t.push("Configuration file does not exist"),t;let r=await import(e),s=r.default||r;if(s===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof s!=="object"||s===null)t.push("Configuration must be an object");else if(Array.isArray(s))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),i=n(e,"utf8");JSON.parse(i)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(s)=>{try{let n=await this.loadFromPath(s,{},t);if(n)r.set(s,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${s}:`,n)}})),r}}var Zt=N(()=>{ue(),K(),ut()});class dt{async validateConfiguration(e,t,r={}){let{stopOnFirstError:s=!1,validateRequired:n=!0,validateTypes:i=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],d=[],m={stopOnFirstError:s,validateRequired:n,validateTypes:i,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,m);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],m);else return this.validateWithJSONSchema(e,t,m)}catch(p){return u.push({path:"",message:`Validation failed: ${p}`,rule:"system"}),{isValid:!1,errors:u,warnings:d}}};if(c)return await le.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!jr(t))throw new ae(t,[{path:"",message:"Schema file does not exist"}]);let s=await import(t),n=s.default||s;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(s){throw new ae(t,[{path:"",message:`Failed to load schema: ${s}`}])}}validateWithJSONSchema(e,t,r){let s=[],n=[];return this.validateObjectAgainstSchema(e,t,"",s,n,r),{isValid:s.length===0,errors:s,warnings:n}}validateObjectAgainstSchema(e,t,r,s,n,i){if(i.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(s.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),i.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(s.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),i.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)s.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)s.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))s.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)s.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)s.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,s,n,i),i.stopOnFirstError&&s.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(i.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(s.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),i.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,s,n,i),i.stopOnFirstError&&s.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let s=[],n=[];for(let i of t)try{let o=this.getValueByPath(e,i.path),c=this.validateWithRule(o,i,i.path);if(s.push(...c),r.stopOnFirstError&&s.length>0)break}catch(o){s.push({path:i.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:s.length===0,errors:s,warnings:n}}validateWithRule(e,t,r){let s=[];if(t.required&&(e===void 0||e===null))return s.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),s;if(e===void 0||e===null)return s;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)s.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)s.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)s.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))s.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))s.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)s.push({path:r,message:t.message||n,rule:"custom"})}return s}getValueByPath(e,t){if(!t)return e;let r=t.split("."),s=e;for(let n of r)if(s&&typeof s==="object"&&n in s)s=s[n];else return;return s}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let s of r){let[,n,i,o]=s;t.push({path:n,required:!i,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Qt},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Qt,er=N(()=>{ue(),K(),Qt=/^https?:\/\//});function Ts(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class mt{fileLoader=new Ce;envProcessor=new Ee;validator=new dt;async loadConfig(e){let t=Date.now(),{cache:r,performance:s,schema:n,validate:i,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),d=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),m=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(m||u))throw a;if(d&&(!l||!m))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||i)await this.validateConfiguration(c.config,n,i,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(s?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(s.onMetrics)s.onMetrics(a);if(s.slowThreshold&&a.duration>s.slowThreshold)C.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw C.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:s="",alias:n,cwd:i,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,d=i||q.cwd(),m=[],p=await this.loadLocalConfiguration(s,n,d,o,c,l,u,a,r);if(p)return m.push(...this.getLocalSearchPaths(s,n,d,o)),this.finalizeResult(p,m,a,s,u);let b=await this.loadHomeConfiguration(s,n,c,l,u,a);if(b)return m.push(...this.getHomeSearchPaths(s,n)),this.finalizeResult(b,m,a,s,u);let f=await this.loadPackageJsonConfiguration(s,n,d,c,l,u,a);if(f)return m.push(R(d,"package.json")),this.finalizeResult(f,m,a,s,u);if(m.push(...this.getAllSearchPaths(s,n,d,o)),t)throw D.configNotFound(s,m,n);return{...await this.applyEnvironmentVariables(s,c,a,u),warnings:[`No configuration file found for "${s}"${Ts(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,s,n,i,o,c,a){let l=c?ne(e,n,o):n,u=this.getLocalDirectories(r,s);for(let d of u){if(o)C.info(`Searching for configuration in: ${d}`);let m=this.fileLoader.generateConfigPaths(e,d,t),p=await this.fileLoader.tryLoadFromPaths(m,l,{arrayStrategy:i,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(p){if(o)C.success(`Configuration loaded from: ${p.source.path}`);return p}}return null}async loadHomeConfiguration(e,t,r,s,n,i){if(!e)return null;let o=i?ne(e,r,n):r,c=[R(V(),".config",e),R(V(),".config"),V()];for(let a of c){if(n)C.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:s,verbose:n});if(u){if(n)C.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,s,n,i,o){let c=o?ne(e,s,i):s;try{let a=R(r,"package.json");if(!Qe(a))return null;let l={};try{l=JSON.parse(_r(a,"utf8"))}catch(m){if(i)C.warn("Failed to parse package.json:",[m instanceof Error?m:Error(String(m))]);return null}let u=l[e],d=e;if(!u&&t){let m=Array.isArray(t)?t:[t];for(let p of m){if(!p)continue;if(l[p]){u=l[p],d=p;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(i)C.success(`Configuration loaded from package.json: ${d}`);return{config:lt(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(i)C.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,s){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ne(e,t,s),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,s,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,s){let n=[];if(r){let i=r(e);if(i)n.push(...i)}if(t){let i=await this.validator.validateConfiguration(e,t);if(!i.isValid)n.push(...i.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw D.configValidation(s||"unknown",n,s)}checkCache(e,t){let r=this.generateCacheKey(e,t);return W.get(r)||null}cacheResult(e,t,r,s){let n=this.generateCacheKey(e,s);W.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let s=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${s}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,R(e,"config"),R(e,".config"),t?R(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,s){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,s)),n.push(...this.getHomeSearchPaths(e,t)),n.push(R(r,"package.json")),n}getLocalSearchPaths(e,t,r,s){let n=this.getLocalDirectories(r,s),i=[];for(let o of n)i.push(...this.fileLoader.generateConfigPaths(e,o,t));return i}getHomeSearchPaths(e,t){if(!e)return[];let r=[R(V(),".config",e),R(V(),".config"),V()],s=[];for(let n of r)s.push(...this.fileLoader.generateConfigPaths(e,n,t));return s}async loadConfigWithResult(e){return this.loadConfig(e)}}function Bt(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),s=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||s}async function Ps(e){return F.loadConfig({...e,__strictErrorHandling:!0})}async function tr(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let s;if(r)s=await F.loadConfig(e);else s=await F.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return s?.config??t}catch(s){let n=s instanceof Error?s.name:"UnknownError",i=s instanceof Error?s.message:String(s);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||i.includes("config"))&&e.verbose)C.warn("Unexpected error loading config, using defaults:",[s instanceof Error?s:Error(String(s))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await F.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function As(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await F.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Bt(r)))return(await F.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await F.loadConfig({...e,cwd:e.cwd||q.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Bt(t)))return(await F.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Ms(e,t,r="replace"){let s=new Ce;try{let n=await s.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function ne(e,t,r=!1){let s=new Ee,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function i(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let d=[...c,l],m=[`${n}_${d.join("_").toUpperCase()}`,`${n}_${d.map((f)=>f.toUpperCase()).join("")}`,`${n}_${d.map((f)=>f.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],p,b;for(let f of m)if(p=q.env[f],p!==void 0){b=f;break}if(p!==void 0&&b)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(p.toLowerCase());else if(typeof u==="number"){let f=Number(p);if(!Number.isNaN(f))a[l]=f}else if(Array.isArray(u))try{a[l]=JSON.parse(p)}catch{a[l]=p.split(",").map((f)=>f.trim())}else a[l]=p;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=i(u,d)}return a}return i(t)}function Is(e){let t=R(q.cwd(),e.configDir),r=R(q.cwd(),e.generatedDir),s=R(r,"config-types.ts");if(!Qe(Nt(s)))Br(Nt(s),{recursive:!0,mode:511});let n=Qe(t)?Hr(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],i=`// Generated by bunfig v${ws}
24
+ export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
25
+ `;Vr(s,i,{mode:438})}function $s(e){let t=null,r=null,s=()=>{if(!r)r=tr(e).then((i)=>(t=i,i),(i)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)C.warn("Config loading failed, using defaults:",[i instanceof Error?i:Error(String(i))]);return o});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,s(),new Proxy({},{get(i,o){if(t)return t[o];let c=n[o];return s(),c},has(i,o){return o in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(i,o){return Object.getOwnPropertyDescriptor(t||n,o)},set(i,o,c){if(!t)t={...n};return t[o]=c,!0}})}var C,F,rr,sr,Fs=N(()=>{ys(),bs(),ue(),K(),Kt(),Zt(),er(),ut(),C=new ke("bunfig",{showTags:!0}),F=new mt,rr=R(q.cwd(),"config"),sr=R(q.cwd(),"src/generated")});function Ns(e){let t=Dt(Kr.cwd(),e?.configDir||"./config");function r(){if(!zr(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),i=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Wr(t).filter((a)=>n.has(Ge(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=Ge(l).toLowerCase(),d=c.get(a);if(!d){c.set(a,l);continue}let m=Ge(d).toLowerCase();if(i.indexOf(u)<i.indexOf(m))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function s(){let n=r(),i=n.map((l)=>l.base),o=i.length?i.map((l)=>`'${l}'`).join(" | "):"string",c=n.length?`{
26
+ ${n.map((l)=>{let u=Dt(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${u}').default`}).join(`,
27
+ `)}
28
+ }`:"Record<string, any>";return`export type ConfigNames = ${o}
29
+ export type ConfigByName = ${c}
30
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
31
+ export type ConfigOf = Config
32
+ `}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(i)=>({path:i.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:s(),loader:"ts"}))}}}var Ds=()=>{},nr={};Yr(nr,{withErrorRecovery:()=>zt,tryLoadConfig:()=>Ms,loadConfigWithResult:()=>Ps,loadConfig:()=>tr,isRetryableError:()=>Ss,isConfigNotFoundError:()=>vs,isBunfigError:()=>Wt,globalPerformanceMonitor:()=>le,globalCache:()=>W,getEnvOrDefault:()=>xs,generateConfigTypes:()=>Is,defaultGeneratedDir:()=>sr,defaultConfigDir:()=>rr,deepMergeWithArrayStrategy:()=>lt,deepMerge:()=>Jt,createLibraryConfig:()=>$s,config:()=>As,bunfigPlugin:()=>Ns,applyEnvVarsToConfig:()=>ne,TypeGenerationError:()=>st,SchemaValidationError:()=>ae,PluginError:()=>it,PerformanceMonitor:()=>ct,FileSystemError:()=>rt,ErrorFactory:()=>D,EnvVarError:()=>Re,EnvProcessor:()=>Ee,ConfigValidator:()=>dt,ConfigValidationError:()=>et,ConfigNotFoundError:()=>xe,ConfigMergeError:()=>tt,ConfigLoader:()=>mt,ConfigLoadError:()=>oe,ConfigFileLoader:()=>Ce,ConfigCache:()=>at,CacheUtils:()=>Ht,BunfigError:()=>k,BrowserConfigError:()=>nt,ArrayMergeStrategies:()=>Yt});var ir=N(()=>{Fs(),K(),ue(),K(),Ds(),Kt(),Zt(),er(),ut()});ir();var Os={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 h=Os;class ce{records;timestamps;cleanupTimer;enableAutoCleanup;cleanupIntervalMs;constructor(e){this.records=new Map,this.timestamps=new Map;let t=h.memoryStorage||{};if(this.enableAutoCleanup=e?.enableAutoCleanup??t.enableAutoCleanup??!1,this.cleanupIntervalMs=e?.cleanupIntervalMs??t.cleanupIntervalMs??60000,this.cleanupTimer=null,this.enableAutoCleanup)this.startCleanupTimer()}async increment(e,t){let r=Date.now(),s=this.records.get(e);if(!s||r>s.resetTime){let i={count:1,resetTime:r+t};return this.records.set(e,i),this.timestamps.set(e,[r]),i}s.count+=1;let n=this.timestamps.get(e)||[];return n.push(r),this.timestamps.set(e,n),s}async reset(e){this.records.delete(e),this.timestamps.delete(e)}async getCount(e){return this.records.get(e)?.count||0}async getSlidingWindowCount(e,t){let r=this.timestamps.get(e)||[],n=Date.now()-t;return r.filter((i)=>i>n).length}async batchIncrement(e,t){let r=new Map;for(let s of e){let n=await this.increment(s,t);r.set(s,n)}return r}cleanExpired(){let e=Date.now();for(let[r,s]of this.records.entries())if(e>s.resetTime)this.records.delete(r);let t=e-3600000;for(let[r,s]of this.timestamps.entries()){let n=s.filter((i)=>i>t);if(n.length===0)this.timestamps.delete(r);else if(n.length!==s.length)this.timestamps.set(r,n)}}dispose(){if(this.cleanupTimer)clearInterval(this.cleanupTimer)}startCleanupTimer(){this.cleanupTimer=setInterval(()=>this.cleanExpired(),this.cleanupIntervalMs)}}class or{client;keyPrefix;slidingWindowEnabled;luaScript;isExternalClient;constructor(e){if(this.isExternalClient=!!e.client,!e.client)throw Error("[ts-rate-limiter] Redis client must be provided. Initialize it and pass it to RedisStorage.");this.client=e.client;let t=h.redis||{};if(this.keyPrefix=e.keyPrefix??h.redisKeyPrefix??"ratelimit:",this.slidingWindowEnabled=e.enableSlidingWindow??t.enableSlidingWindow??!1,this.luaScript=`
33
+ local key = KEYS[1]
34
+ local window = tonumber(ARGV[1])
35
+ local now = tonumber(ARGV[2])
36
+
37
+ -- Increment counter
38
+ local count = redis.call('INCR', key)
39
+
40
+ -- Get TTL
41
+ local ttl = redis.call('TTL', key)
42
+
43
+ -- Set expiration if this is a new key or TTL is negative
44
+ if count == 1 or ttl < 0 then
45
+ redis.call('PEXPIRE', key, window)
46
+ ttl = window / 1000
47
+ end
48
+
49
+ return {count, ttl}
50
+ `,h.verbose)console.warn(`[ts-rate-limiter] Redis storage initialized with:
51
+ - Key Prefix: ${this.keyPrefix}
52
+ - Sliding Window: ${this.slidingWindowEnabled?"enabled":"disabled"}`)}async increment(e,t){let r=this.keyPrefix+e,s=Date.now();if(this.slidingWindowEnabled)return this.incrementSlidingWindow(r,t,s);try{let n=await this.client.send("EVAL",[this.luaScript,"1",r,t.toString(),s.toString()]),i=Array.isArray(n)?Number(n[0]):Number(n),o=Array.isArray(n)?Number(n[1]):t/1000;return{count:i,resetTime:s+o*1000}}catch(n){if(h.verbose)console.warn("[ts-rate-limiter] LUA script execution failed, using standard approach:",n);return this.incrementStandard(r,t,s)}}async incrementStandard(e,t,r){let s=await this.client.incr(e),n=await this.client.ttl(e);if(s===1||n<0)await this.client.expire(e,Math.ceil(t/1000)),n=t/1000;return{count:Number(s),resetTime:r+(n>0?n*1000:t)}}async incrementSlidingWindow(e,t,r){let s=`${e}:window`,n=r.toString(),i=(r-t).toString();try{await this.client.send("ZADD",[s,n,n]),await this.client.send("ZREMRANGEBYSCORE",[s,"0",i]);let o=await this.client.send("ZCARD",[s]);return await this.client.send("PEXPIRE",[s,t.toString()]),{count:Number(o),resetTime:r+t}}catch(o){if(h.verbose)console.warn("[ts-rate-limiter] Sliding window operation failed:",o);return this.incrementStandard(e,t,r)}}async reset(e){let t=this.keyPrefix+e;if(this.slidingWindowEnabled)await this.client.send("DEL",[t,`${t}:window`]);else await this.client.del(t)}async getCount(e){let t=this.keyPrefix+e,r=await this.client.get(t);return r?Number(r):0}async getSlidingWindowCount(e,t){if(!this.slidingWindowEnabled)throw Error("Sliding window not enabled for this Redis storage instance");try{let r=`${this.keyPrefix}${e}:window`,n=(Date.now()-t).toString();await this.client.send("ZREMRANGEBYSCORE",[r,"0",n]);let i=await this.client.send("ZCARD",[r]);return Number(i)}catch(r){if(h.verbose)console.warn("[ts-rate-limiter] Sliding window count operation failed:",r);return 0}}async batchIncrement(e,t){let r=new Map,s=Date.now();for(let n of e)try{let i=this.keyPrefix+n;if(this.slidingWindowEnabled){let o=`${i}:window`,c=s.toString(),a=(s-t).toString();await this.client.send("ZADD",[o,c,c]),await this.client.send("ZREMRANGEBYSCORE",[o,"0",a]);let l=await this.client.send("ZCARD",[o]);await this.client.send("PEXPIRE",[o,t.toString()]),r.set(n,{count:Number(l),resetTime:s+t})}else{let o=await this.client.incr(i),c=await this.client.ttl(i);if(o===1||c<0)await this.client.expire(i,Math.ceil(t/1000));r.set(n,{count:Number(o),resetTime:s+(c>0?c*1000:t)})}}catch(i){if(h.verbose)console.warn(`[ts-rate-limiter] Batch increment failed for key ${n}:`,i);r.set(n,{count:1,resetTime:s+t})}return r}async dispose(){if(!this.isExternalClient&&this.client&&typeof this.client.close==="function")this.client.close()}}class ar{windowMs;maxRequests;storage;keyGenerator;skipFailedRequests;algorithm;standardHeaders;legacyHeaders;skipFn;handler;draftMode;tokenBucketOptions;tokenBuckets;constructor(e){if(this.windowMs=e.windowMs||h.windowMs||60000,this.maxRequests=e.maxRequests||h.maxRequests||100,e.maxRequests===0)this.maxRequests=0;if(e.storage)this.storage=e.storage;else if(h.storage==="redis"&&h.redis)throw Error("Redis client must be provided explicitly when using Redis storage");else this.storage=new ce(h.memoryStorage);if(this.skipFailedRequests=e.skipFailedRequests??!1,this.keyGenerator=e.keyGenerator||this.defaultKeyGenerator,this.algorithm=e.algorithm||h.algorithm||"fixed-window",this.standardHeaders=e.standardHeaders??h.standardHeaders??!0,this.legacyHeaders=e.legacyHeaders??h.legacyHeaders??!0,this.skipFn=e.skip,this.handler=e.handler,this.draftMode=e.draftMode??h.draftMode??!1,this.tokenBuckets=new Map,this.algorithm==="token-bucket")this.tokenBucketOptions={capacity:this.maxRequests,refillRate:this.maxRequests/(this.windowMs/1000)/1000};if(h.verbose){let t=e.storage?e.storage instanceof ce?"memory (custom)":"redis (custom)":h.storage;console.warn(`[ts-rate-limiter] Initialized with:
53
+ - Algorithm: ${this.algorithm}
54
+ - Window: ${this.windowMs}ms
55
+ - Max Requests: ${this.maxRequests}
56
+ - Storage: ${t}
57
+ - Draft Mode: ${this.draftMode?"enabled":"disabled"}`)}}defaultKeyGenerator(e){let t=e.headers.get("x-forwarded-for");if(t)return t.split(",")[0].trim();let r=e.headers.get("x-client-ip");if(r)return r;let s=e.headers.get("x-real-ip");if(s)return s;return e.socket?.remoteAddress||"127.0.0.1"}async check(e){try{if(this.skipFn&&await this.skipFn(e))return this.createAllowedResult();if(this.maxRequests===0)return{allowed:!1,current:1,limit:0,remaining:this.windowMs,resetTime:Date.now()+this.windowMs};let t=await this.keyGenerator(e);if(this.algorithm==="sliding-window"&&this.storage.getSlidingWindowCount)return this.checkSlidingWindow(t);else if(this.algorithm==="token-bucket")return this.checkTokenBucket(t);else return this.checkFixedWindow(t)}catch(t){if(this.skipFailedRequests)return this.createAllowedResult();throw t}}async checkFixedWindow(e){let{count:t,resetTime:r}=await this.storage.increment(e,this.windowMs),s=Math.max(0,r-Date.now());return{allowed:this.draftMode?!0:t<=this.maxRequests,current:t,limit:this.maxRequests,remaining:s,resetTime:r}}async checkSlidingWindow(e){if(!this.storage.getSlidingWindowCount)return this.checkFixedWindow(e);await this.storage.increment(e,this.windowMs);let t=await this.storage.getSlidingWindowCount(e,this.windowMs),s=Date.now()+this.windowMs;return{allowed:this.draftMode?!0:t<=this.maxRequests,current:t,limit:this.maxRequests,remaining:this.windowMs,resetTime:s}}async checkTokenBucket(e){if(!this.tokenBucketOptions)return this.checkFixedWindow(e);let t=Date.now(),r=this.tokenBuckets.get(e);if(!r)r={tokens:this.tokenBucketOptions.capacity,lastRefill:t},this.tokenBuckets.set(e,r);let n=(t-r.lastRefill)*this.tokenBucketOptions.refillRate;if(n>0)r.tokens=Math.min(r.tokens+n,this.tokenBucketOptions.capacity),r.lastRefill=t;let i=this.draftMode?!0:r.tokens>=1;if(i&&!this.draftMode)r.tokens-=1;let o=r.tokens>=this.tokenBucketOptions.capacity?this.windowMs:Math.ceil(1/this.tokenBucketOptions.refillRate);return{allowed:i,current:this.tokenBucketOptions.capacity-Math.floor(r.tokens),limit:this.tokenBucketOptions.capacity,remaining:o,resetTime:t+o}}createAllowedResult(){return{allowed:!0,current:0,limit:this.maxRequests,remaining:this.windowMs,resetTime:Date.now()+this.windowMs}}async consume(e){if(this.algorithm==="sliding-window"&&this.storage.getSlidingWindowCount)return this.checkSlidingWindow(e);else if(this.algorithm==="token-bucket")return this.checkTokenBucket(e);else return this.checkFixedWindow(e)}async peek(e){if(typeof this.storage.getCount!=="function")return null;let t=await this.storage.getCount(e),r=Date.now();return{allowed:this.draftMode?!0:t<this.maxRequests,current:t,limit:this.maxRequests,remaining:this.windowMs,resetTime:r+this.windowMs}}async enforce(e){let t=await this.consume(e);if(!t.allowed)throw new cr(`Rate limit exceeded for '${e}'`,t);return t}async reset(e){if(await this.storage.reset(e),this.algorithm==="token-bucket")this.tokenBuckets.delete(e)}async resetAll(){if(this.algorithm==="token-bucket")this.tokenBuckets.clear();if(this.storage.cleanExpired)this.storage.cleanExpired()}getHeaders(e){let t={};if(this.standardHeaders)t["RateLimit-Limit"]=this.maxRequests.toString(),t["RateLimit-Remaining"]=Math.max(0,this.maxRequests-e.current).toString(),t["RateLimit-Reset"]=Math.ceil(e.resetTime/1000).toString();if(this.legacyHeaders){if(t["X-RateLimit-Limit"]=this.maxRequests.toString(),t["X-RateLimit-Remaining"]=Math.max(0,this.maxRequests-e.current).toString(),t["X-RateLimit-Reset"]=Math.ceil(e.resetTime/1000).toString(),!e.allowed)t["Retry-After"]=Math.ceil(e.remaining/1000).toString()}return t}middleware(){return async(e)=>{let t=await this.check(e);if(!t.allowed){if(this.handler)return this.handler(e,t);return new Response("Rate limit exceeded",{status:429,headers:this.getHeaders(t)})}return null}}dispose(){if(this.storage.dispose)this.storage.dispose();this.tokenBuckets.clear()}}class cr extends Error{name="RateLimitError";retryAfter;result;constructor(e,t){super(e);this.result=t,this.retryAfter=Math.max(1,Math.ceil(t.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 lr(e={}){let t={windowMs:e.windowMs??h.windowMs??60000,maxRequests:e.maxRequests??h.maxRequests??100,algorithm:e.algorithm??h.algorithm??"fixed-window",standardHeaders:e.standardHeaders??h.standardHeaders??!0,legacyHeaders:e.legacyHeaders??h.legacyHeaders??!0,draftMode:e.draftMode??h.draftMode??!1,keyGenerator:e.keyGenerator,skipFailedRequests:e.skipFailedRequests,skip:e.skip,handler:e.handler};if(e.storage)t.storage=e.storage;else if(h.storage==="redis"&&h.redis)try{let r;if(typeof globalThis.Bun<"u")try{let{RedisClient:s}=await Promise.resolve(globalThis.Bun);if(r=new s(h.redis.url||"redis://localhost:6379"),h.verbose)console.warn("[ts-rate-limiter] Using Bun's native Redis client")}catch(s){if(h.verbose)console.warn("[ts-rate-limiter] Failed to use Bun's native Redis client:",s)}if(!r)try{let{createClient:s}=await import("redis");if(r=s({url:h.redis.url||"redis://localhost:6379"}),h.verbose)console.warn("[ts-rate-limiter] Using npm redis client")}catch(s){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: ${s}`)}if(typeof r.connect==="function")await r.connect();if(t.storage=new or({client:r,keyPrefix:h.redisKeyPrefix,enableSlidingWindow:h.redis.enableSlidingWindow}),"onclose"in r)r.onclose=(s)=>{if(s)console.error("[ts-rate-limiter] Redis connection closed with error:",s)};else if("on"in r&&typeof r.on==="function")r.on("error",(s)=>{console.error("[ts-rate-limiter] Redis error:",s.message)})}catch(r){console.warn("[ts-rate-limiter] Failed to connect to Redis, falling back to memory storage:",r),t.storage=new ce(h.memoryStorage)}else t.storage=new ce(h.memoryStorage);return new ar(t)}function qs(e={}){let t=new Te(e);return async(s,n)=>t.handle(s,n)}class Te{limiter;options;constructor(e={}){let t=y.server?.rateLimit||{},r=y.server?.security?.rateLimit||{};if(this.options={windowMs:e.windowMs||t.timeWindow||r.timeWindow||60000,maxRequests:e.maxRequests||t.max||r.max||100,standardHeaders:e.standardHeaders??!0,legacyHeaders:e.legacyHeaders??!1,skipFailedRequests:e.skipFailedRequests??t.advanced?.skipFailedRequests??r.advanced?.skipFailedRequests??!1,draftMode:e.draftMode??!1,keyGenerator:e.keyGenerator,handler:e.handler||(t.message?(s,n)=>new Response(t.message,{status:429}):void 0),skip:e.skip,algorithm:e.algorithm||"fixed-window",storage:e.storage},!this.options.storage&&t.stores?.type==="redis"&&t.stores.redis){if(this.options.storage="redis",t.stores.redis)this.options.redis={url:t.stores.redis.url,prefix:t.stores.redis.prefix||"ratelimit:"}}if(t.advanced){if(t.advanced.tokensPerInterval&&this.options.algorithm==="token-bucket")this.options.tokenBucket={tokensPerInterval:t.advanced.tokensPerInterval,interval:t.advanced.interval||this.options.windowMs,burst:t.advanced.burst}}this.initLimiter()}async initLimiter(){let e={...this.options};e.windowMs=this.options.windowMs,e.maxRequests=this.options.maxRequests,e.standardHeaders=this.options.standardHeaders,e.legacyHeaders=this.options.legacyHeaders,e.skipFailedRequests=this.options.skipFailedRequests,e.keyGenerator=this.options.keyGenerator,e.skip=this.options.skip,e.algorithm=this.options.algorithm,e.draftMode=this.options.draftMode,e.handler=this.options.handler?async(s,n)=>this.options.handler?.(s,{remaining:n.remaining,limit:n.limit,resetTime:n.resetTime})||this.defaultHandler(s,n):void 0;let{log:t,warn:r}=console;console.log=()=>{},console.warn=()=>{};try{this.limiter=await lr(e)}finally{console.log=t,console.warn=r}}defaultHandler(e,t){let r={};if(this.options.standardHeaders)r["RateLimit-Limit"]=String(t.limit),r["RateLimit-Remaining"]=String(Math.max(0,t.limit-t.current)),r["RateLimit-Reset"]=String(Math.ceil(t.resetTime/1000));if(this.options.legacyHeaders)r["X-RateLimit-Limit"]=String(t.limit),r["X-RateLimit-Remaining"]=String(Math.max(0,t.limit-t.current)),r["X-RateLimit-Reset"]=String(Math.ceil(t.resetTime/1000)),r["Retry-After"]=String(Math.ceil(t.remaining/1000));let s=y.server?.rateLimit?.message||"Too Many Requests";return new Response(s,{status:429,headers:r})}async handle(e,t){if(y.server?.rateLimit?.enabled===!1)return await t()||new Response("Not Found",{status:404});if(!this.limiter){if(await new Promise((r)=>setTimeout(r,50)),!this.limiter)return await t()||new Response("Not Found",{status:404})}try{let r=await this.limiter.check(e);if(!r.allowed)return this.options.handler?await this.options.handler(e,{remaining:r.remaining,limit:r.limit,resetTime:r.resetTime}):this.defaultHandler(e,r);let s=await t();if(!s)return new Response("Not Found",{status:404});let n=new Headers(s.headers);if(this.options.standardHeaders)n.set("RateLimit-Limit",String(r.limit)),n.set("RateLimit-Remaining",String(Math.max(0,r.limit-r.current))),n.set("RateLimit-Reset",String(Math.ceil(r.resetTime/1000)));if(this.options.legacyHeaders)n.set("X-RateLimit-Limit",String(r.limit)),n.set("X-RateLimit-Remaining",String(Math.max(0,r.limit-r.current))),n.set("X-RateLimit-Reset",String(Math.ceil(r.resetTime/1000)));return new Response(s.body,{status:s.status,statusText:s.statusText,headers:n})}catch(r){return console.error("[RateLimit] Error during rate limiting:",r),await t()||new Response("Not Found",{status:404})}}}function pt(e={}){return qs(e)}import{randomUUID as Us}from"crypto";class J{async handle(e,t){let r=e.headers.get("X-Request-ID")||Us();Object.defineProperty(e,"requestId",{value:r,writable:!1,enumerable:!0,configurable:!1});let s=await t();if(!s)return new Response("Not Found",{status:404});let n=new Headers(s.headers);if(!n.has("X-Request-ID"))n.set("X-Request-ID",r);return new Response(s.body,{status:s.status,statusText:s.statusText,headers:n})}}class E extends Error{code;statusCode;constructor(e,t){super(t);this.name="SignatureError",this.code=e,this.statusCode=401}}class ur{nonces=new Map;cleanupInterval=null;constructor(e=60000){this.cleanupInterval=setInterval(()=>this.cleanup(),e),this.cleanupInterval.unref?.()}has(e){let t=this.nonces.get(e);if(t===void 0)return!1;if(Date.now()>t)return this.nonces.delete(e),!1;return!0}set(e,t=300){this.nonces.set(e,Date.now()+t*1000)}cleanup(){let e=Date.now();for(let[t,r]of this.nonces.entries())if(e>r)this.nonces.delete(t)}destroy(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.nonces.clear()}}class G{options;constructor(e){this.options={secret:e.secret,algorithm:e.algorithm??"sha256",signatureHeader:e.signatureHeader??"X-Signature",timestampHeader:e.timestampHeader??"X-Timestamp",keyIdHeader:e.keyIdHeader??"X-Key-Id",nonceHeader:e.nonceHeader??"X-Nonce",maxAge:e.maxAge??300,requireTimestamp:e.requireTimestamp??!0,requireNonce:e.requireNonce??!1,signedParts:e.signedParts??["method","path","timestamp","body"],signedHeaders:e.signedHeaders??[],encoding:e.encoding??"hex",onError:e.onError,exclude:e.exclude,nonceStore:e.nonceStore,stringToSign:e.stringToSign}}async handle(e,t){if(this.shouldSkip(e))return t();try{return await this.verifySignature(e),t()}catch(r){if(r instanceof E){if(this.options.onError)return this.options.onError(r,e);return this.defaultErrorResponse(r)}throw r}}shouldSkip(e){if(!this.options.exclude)return!1;if(typeof this.options.exclude==="function")return this.options.exclude(e);let t=new URL(e.url);return this.options.exclude.some((r)=>t.pathname===r||t.pathname.startsWith(`${r}/`))}async verifySignature(e){let t=e.headers.get(this.options.signatureHeader);if(!t)throw new E("MISSING_SIGNATURE",`Missing ${this.options.signatureHeader} header`);let r=e.headers.get(this.options.timestampHeader);if(this.options.requireTimestamp){if(!r)throw new E("MISSING_TIMESTAMP",`Missing ${this.options.timestampHeader} header`);this.validateTimestamp(r)}let s=e.headers.get(this.options.nonceHeader);if(this.options.requireNonce){if(!s)throw new E("MISSING_NONCE",`Missing ${this.options.nonceHeader} header`);await this.validateNonce(s)}let n=await this.getSecret(e);if(!n)throw new E("INVALID_KEY","Invalid or missing API key");let i=await this.buildStringToSign(e,r||"",s||void 0),o=await this.calculateSignature(i,n);if(!this.timingSafeEqual(t,o))throw new E("SIGNATURE_MISMATCH","Invalid signature");if(this.options.requireNonce&&s&&this.options.nonceStore)await this.options.nonceStore.set(s,this.options.maxAge)}async getSecret(e){if(typeof this.options.secret==="string")return this.options.secret;let t=e.headers.get(this.options.keyIdHeader);if(!t)throw new E("MISSING_KEY_ID",`Missing ${this.options.keyIdHeader} header`);return this.options.secret(t)}validateTimestamp(e){let t=Number.parseInt(e,10);if(Number.isNaN(t))throw new E("EXPIRED_TIMESTAMP","Invalid timestamp format");let s=Math.floor(Date.now()/1000)-t;if(s>this.options.maxAge)throw new E("EXPIRED_TIMESTAMP",`Request timestamp expired (${s}s old, max ${this.options.maxAge}s)`);if(s<-30)throw new E("FUTURE_TIMESTAMP","Request timestamp is in the future")}async validateNonce(e){if(!this.options.nonceStore)return;if(await this.options.nonceStore.has(e))throw new E("NONCE_REUSED","Nonce has already been used (possible replay attack)")}async buildStringToSign(e,t,r){if(this.options.stringToSign)return this.options.stringToSign(e,t,r);let s=new URL(e.url),n=[];for(let i of this.options.signedParts)switch(i){case"method":n.push(e.method.toUpperCase());break;case"path":n.push(s.pathname);break;case"query":n.push(s.search);break;case"timestamp":n.push(t);break;case"nonce":if(r)n.push(r);break;case"body":if(e.body){let o=await e.clone().text();n.push(o)}break;case"headers":for(let o of this.options.signedHeaders){let c=e.headers.get(o);if(c)n.push(`${o.toLowerCase()}:${c}`)}break}return n.join(`
58
+ `)}async calculateSignature(e,t){let r=new TextEncoder,s=r.encode(t),n=r.encode(e),i={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"}[this.options.algorithm],o=await crypto.subtle.importKey("raw",s,{name:"HMAC",hash:i},!1,["sign"]),c=await crypto.subtle.sign("HMAC",o,n);if(this.options.encoding==="base64")return btoa(String.fromCharCode(...new Uint8Array(c)));return Array.from(new Uint8Array(c)).map((a)=>a.toString(16).padStart(2,"0")).join("")}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let s=0;s<e.length;s++)r|=e.charCodeAt(s)^t.charCodeAt(s);return r===0}defaultErrorResponse(e){return new Response(JSON.stringify({error:{code:e.code,message:e.message}}),{status:e.statusCode,headers:{"Content-Type":"application/json","WWW-Authenticate":"HMAC-SHA256"}})}}function Ls(e){return new G(e)}async function js(e,t,r={}){let{algorithm:s="sha256",signedParts:n=["method","path","timestamp","body"],signedHeaders:i=[],signatureHeader:o="X-Signature",timestampHeader:c="X-Timestamp",nonceHeader:a="X-Nonce",keyId:l,keyIdHeader:u="X-Key-Id",encoding:d="hex"}=r,m=Math.floor(Date.now()/1000).toString(),p=crypto.randomUUID(),b=new URL(e.url),f=[];for(let Be of n)switch(Be){case"method":f.push(e.method.toUpperCase());break;case"path":f.push(b.pathname);break;case"query":f.push(b.search);break;case"timestamp":f.push(m);break;case"nonce":f.push(p);break;case"body":if(e.body){let he=await e.clone().text();f.push(he)}break;case"headers":for(let he of i){let vt=e.headers.get(he);if(vt)f.push(`${he.toLowerCase()}:${vt}`)}break}let re=f.join(`
59
+ `),wt=new TextEncoder,hr=wt.encode(t),fr=wt.encode(re),gr={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"}[s],yr=await crypto.subtle.importKey("raw",hr,{name:"HMAC",hash:gr},!1,["sign"]),bt=await crypto.subtle.sign("HMAC",yr,fr),je;if(d==="base64")je=btoa(String.fromCharCode(...new Uint8Array(bt)));else je=Array.from(new Uint8Array(bt)).map((Be)=>Be.toString(16).padStart(2,"0")).join("");let se=new Headers(e.headers);if(se.set(o,je),se.set(c,m),se.set(a,p),l)se.set(u,l);return new Request(e.url,{method:e.method,headers:se,body:e.body,redirect:e.redirect,integrity:e.integrity,signal:e.signal})}async function Bs(e,t,r,s="sha256",n="hex"){let i=new TextEncoder,o=i.encode(r),c=i.encode(e),a={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"}[s],l=await crypto.subtle.importKey("raw",o,{name:"HMAC",hash:a},!1,["sign"]),u=await crypto.subtle.sign("HMAC",l,c),d;if(n==="base64")d=btoa(String.fromCharCode(...new Uint8Array(u)));else d=Array.from(new Uint8Array(u)).map((p)=>p.toString(16).padStart(2,"0")).join("");if(t.length!==d.length)return!1;let m=0;for(let p=0;p<t.length;p++)m|=t.charCodeAt(p)^d.charCodeAt(p);return m===0}class U{defaultTtl;sessions=new Map;cleanupInterval=null;constructor(e=86400){this.defaultTtl=e;this.cleanupInterval=setInterval(()=>this.cleanup(),300000)}async get(e){let t=this.sessions.get(e);if(!t)return null;if(Date.now()>t.expiresAt)return this.sessions.delete(e),null;return t.data}async set(e,t,r){let s=Date.now()+(r??this.defaultTtl)*1000;this.sessions.set(e,{data:t,expiresAt:s})}async destroy(e){this.sessions.delete(e)}async touch(e,t,r){let s=this.sessions.get(e);if(s)s.expiresAt=Date.now()+(r??this.defaultTtl)*1000,s.data=t}async all(){let e={},t=Date.now();for(let[r,s]of this.sessions)if(t<=s.expiresAt)e[r]=s.data;return e}async length(){return this.sessions.size}async clear(){this.sessions.clear()}cleanup(){let e=Date.now();for(let[t,r]of this.sessions)if(e>r.expiresAt)this.sessions.delete(t)}dispose(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.sessions.clear()}}import{existsSync as Pe,mkdirSync as Hs,readdirSync as Ae,unlinkSync as Me,writeFileSync as dr,readFileSync as ht}from"fs";import{join as de}from"path";import{tmpdir as _s}from"os";class Ie{defaultTtl;dir;cleanupInterval=null;constructor(e=86400,t){this.defaultTtl=e;if(this.dir=t||de(_s(),"bun-router-sessions"),!Pe(this.dir))Hs(this.dir,{recursive:!0});this.cleanupInterval=setInterval(()=>this.cleanup(),600000)}filePath(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"");return de(this.dir,`${t}.json`)}async get(e){let t=this.filePath(e);if(!Pe(t))return null;try{let r=ht(t,"utf-8"),s=JSON.parse(r);if(Date.now()>s.expiresAt)return Me(t),null;return s.data}catch{return null}}async set(e,t,r){let s={data:t,expiresAt:Date.now()+(r??this.defaultTtl)*1000};dr(this.filePath(e),JSON.stringify(s),"utf-8")}async destroy(e){let t=this.filePath(e);if(Pe(t))Me(t)}async touch(e,t,r){let s=this.filePath(e);if(!Pe(s))return;let n={data:t,expiresAt:Date.now()+(r??this.defaultTtl)*1000};dr(s,JSON.stringify(n),"utf-8")}async all(){let e={},t=Date.now();try{let r=Ae(this.dir).filter((s)=>s.endsWith(".json"));for(let s of r){let n=ht(de(this.dir,s),"utf-8"),i=JSON.parse(n);if(t<=i.expiresAt){let o=s.replace(".json","");e[o]=i.data}}}catch{}return e}async length(){try{return Ae(this.dir).filter((e)=>e.endsWith(".json")).length}catch{return 0}}async clear(){try{let e=Ae(this.dir).filter((t)=>t.endsWith(".json"));for(let t of e)Me(de(this.dir,t))}catch{}}cleanup(){let e=Date.now();try{let t=Ae(this.dir).filter((r)=>r.endsWith(".json"));for(let r of t){let s=de(this.dir,r),n=ht(s,"utf-8"),i=JSON.parse(n);if(e>i.expiresAt)Me(s)}}catch{}}dispose(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}}class $e{client;defaultTtl;prefix;constructor(e,t=86400,r="sess:"){this.client=e;this.defaultTtl=t;this.prefix=r}key(e){return`${this.prefix}${e}`}async get(e){let t=await this.client.get(this.key(e));if(!t)return null;try{return JSON.parse(t)}catch{return null}}async set(e,t,r){let s=this.key(e),n=r??this.defaultTtl;await this.client.set(s,JSON.stringify(t),"EX",n)}async destroy(e){await this.client.del(this.key(e))}async touch(e,t,r){let s=this.key(e),n=r??this.defaultTtl;await this.client.set(s,JSON.stringify(t),"EX",n)}async all(){let e=await this.client.keys(`${this.prefix}*`),t={};for(let r of e){let s=await this.client.get(r);if(s)try{let n=r.slice(this.prefix.length);t[n]=JSON.parse(s)}catch{}}return t}async length(){return(await this.client.keys(`${this.prefix}*`)).length}async clear(){let e=await this.client.keys(`${this.prefix}*`);if(e.length>0)await this.client.del(e)}}class Fe{adapter;defaultTtl;cleanupInterval=null;constructor(e,t=86400){this.adapter=e;this.defaultTtl=t;this.cleanupInterval=setInterval(()=>{let r=Date.now()-this.defaultTtl*1000;this.adapter.deleteExpiredSessions(r)},1800000)}async get(e){let t=await this.adapter.findSession(e);if(!t)return null;let r=Date.now()-this.defaultTtl*1000;if(t.last_activity<r)return await this.adapter.deleteSession(e),null;try{return JSON.parse(t.payload)}catch{return null}}async set(e,t,r){await this.adapter.upsertSession(e,JSON.stringify(t),Date.now())}async destroy(e){await this.adapter.deleteSession(e)}async touch(e,t,r){await this.adapter.upsertSession(e,JSON.stringify(t),Date.now())}async all(){let e=await this.adapter.getAllSessions(),t={},r=Date.now()-this.defaultTtl*1000;for(let s of e)if(s.last_activity>=r)try{t[s.id]=JSON.parse(s.payload)}catch{}return t}async length(){return this.adapter.countSessions()}async clear(){await this.adapter.clearAllSessions()}dispose(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}}function mi(e){let t=e.ttl??86400;switch(e.driver){case"memory":return new U(t);case"file":return new Ie(t,e.file?.dir);case"redis":{if(!e.redis?.client)throw Error("Redis client is required for redis session driver");return new $e(e.redis.client,t,e.redis.prefix)}case"database":{if(!e.database?.adapter)throw Error("Database adapter is required for database session driver");return new Fe(e.database.adapter,t)}default:return new U(t)}}class ft{sessionId;data;store;flashedKeys=[];previousFlash={};dirty=!1;constructor(e,t,r){this.sessionId=e,this.data=t,this.store=r,this.previousFlash={...t.flash||{}}}get id(){return this.sessionId}get(e){if(this.data.flash&&e in this.data.flash)return this.data.flash[e];if(this.data.data&&e in this.data.data)return this.data.data[e];return}set(e,t){if(!this.data.data)this.data.data={};this.data.data[e]=t,this.dirty=!0}has(e){return this.data.data&&e in this.data.data||this.data.flash&&e in this.data.flash||!1}forget(e){if(this.data.data)delete this.data.data[e],this.dirty=!0}all(){return{...this.data.data||{},...this.data.flash||{}}}flash(e,t){if(!this.data.flash)this.data.flash={};this.data.flash[e]=t,this.flashedKeys.push(e),this.dirty=!0}getFlash(e){return this.previousFlash[e]}keep(e){for(let t of e)if(t in this.previousFlash)this.flash(t,this.previousFlash[t])}reflash(){for(let[e,t]of Object.entries(this.previousFlash))this.flash(e,t)}async regenerate(){let e=this.sessionId;return this.sessionId=Ne(),await this.store.set(this.sessionId,this.data),await this.store.destroy(e),this.sessionId}async invalidate(){let e=this.sessionId;return this.sessionId=Ne(),this.data={id:this.sessionId},await this.store.destroy(e),await this.store.set(this.sessionId,this.data),this.sessionId}async save(){if(this.data.flash){let e={};for(let t of this.flashedKeys)if(this.data.flash[t]!==void 0)e[t]=this.data.flash[t];this.data.flash=Object.keys(e).length>0?e:void 0}await this.store.set(this.sessionId,this.data)}async destroy(){await this.store.destroy(this.sessionId),this.data={}}}function Ne(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e,(t)=>t.toString(16).padStart(2,"0")).join("")}class X{store;constructor(e){this.store=e?.store||new U}async handle(e,t){let r=y.server?.security?.auth?.session,s=r?.name||"session",n=e.cookies?.get(s)||"",i=!1;if(!n)n=Ne(),i=!0;let o=i?null:await this.store.get(n);if(!o)o={id:n},i=!0;let c=new ft(n,o,this.store);e.session=c;let a=await t();await c.save();let l={maxAge:r?.cookie?.maxAge||86400000,path:r?.cookie?.path||"/"};if(r?.cookie?.httpOnly!==!1)l.httpOnly=!0;if(r?.cookie?.secure)l.secure=!0;if(r?.cookie?.sameSite)l.sameSite=r.cookie.sameSite;if(!e._cookiesToSet)e._cookiesToSet=[];return e._cookiesToSet.push({name:s,value:c.id,options:l}),a||new Response("Not Found",{status:404})}}class Y{options;nonces=new Map;constructor(e={}){let t=y.server?.security?.helmet?.contentSecurityPolicy,r={"default-src":["'self'"],"script-src":["'self'"],"style-src":["'self'"],"img-src":["'self'","data:","https:"],"font-src":["'self'"],"connect-src":["'self'"],"media-src":["'self'"],"object-src":["'none'"],"child-src":["'self'"],"worker-src":["'self'"],"frame-ancestors":["'none'"],"form-action":["'self'"],"base-uri":["'self'"],"manifest-src":["'self'"]};this.options={directives:e.directives||typeof t==="object"&&t.directives||r,reportOnly:e.reportOnly??(typeof t==="object"&&t.reportOnly)??!1,reportUri:e.reportUri,reportTo:e.reportTo,useNonces:e.useNonces??!1,nonceLength:e.nonceLength??16,upgradeInsecureRequests:e.upgradeInsecureRequests??!0,blockAllMixedContent:e.blockAllMixedContent??!1}}generateNonce(){let t="";for(let r=0;r<(this.options.nonceLength||16);r++)t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(Math.floor(Math.random()*64));return t}buildCSPHeader(){let e=[],t=this.options.directives||{};for(let[r,s]of Object.entries(t)){if(r==="upgrade-insecure-requests"||r==="block-all-mixed-content"||r==="disown-opener"){if(s===!0)e.push(r.replace(/([A-Z])/g,"-$1").toLowerCase());continue}if(Array.isArray(s)&&s.length>0){let n=r.replace(/([A-Z])/g,"-$1").toLowerCase();e.push(`${n} ${s.join(" ")}`)}}if(this.options.upgradeInsecureRequests)e.push("upgrade-insecure-requests");if(this.options.blockAllMixedContent)e.push("block-all-mixed-content");if(this.options.reportUri)e.push(`report-uri ${this.options.reportUri}`);if(this.options.reportTo)e.push(`report-to ${this.options.reportTo}`);return e.join("; ")}async handle(e,t){if((y.server?.security?.helmet||{}).contentSecurityPolicy===!1)return await t()||new Response("Not Found",{status:404});let s;if(this.options.useNonces){if(s=this.generateNonce(),this.nonces.set(e.url,s),this.options.directives?.["script-src"])this.options.directives["script-src"]=[...this.options.directives["script-src"],`'nonce-${s}'`];if(this.options.directives?.["style-src"])this.options.directives["style-src"]=[...this.options.directives["style-src"],`'nonce-${s}'`]}if(s)e.nonce=s;let n=await t();if(!n)return new Response("Not Found",{status:404});let i=new Headers(n.headers),o=this.buildCSPHeader();if(o){let c=this.options.reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy";i.set(c,o)}if(this.options.reportTo)i.set("Report-To",JSON.stringify({group:this.options.reportTo,max_age:10886400,endpoints:[{url:this.options.reportUri||"/csp-report"}]}));if(s)this.nonces.delete(e.url);return new Response(n.body,{status:n.status,statusText:n.statusText,headers:i})}getNonce(e){return this.nonces.get(e)}}function Vs(e={}){let t=new Y(e);return async(r,s)=>t.handle(r,s)}class Z{options;requestStore=new Map;cleanupInterval=null;constructor(e={}){let t=y.server?.security?.ddos||{};if(this.options={enabled:e.enabled??t.enabled??!0,maxRequestsPerSecond:e.maxRequestsPerSecond??t.maxRequestsPerSecond??10,maxRequestsPerMinute:e.maxRequestsPerMinute??t.maxRequestsPerMinute??100,maxRequestsPerHour:e.maxRequestsPerHour??t.maxRequestsPerHour??1000,burstLimit:e.burstLimit??t.burstLimit??20,windowSize:e.windowSize??t.windowSize??60000,blockDuration:e.blockDuration??t.blockDuration??300000,whitelistedIPs:e.whitelistedIPs??t.whitelistedIPs??[],blacklistedIPs:e.blacklistedIPs??t.blacklistedIPs??[],trustProxy:e.trustProxy??t.trustProxy??!0,skipSuccessfulRequests:e.skipSuccessfulRequests??t.skipSuccessfulRequests??!1,skipFailedRequests:e.skipFailedRequests??t.skipFailedRequests??!1,keyGenerator:e.keyGenerator??this.defaultKeyGenerator.bind(this),onLimitReached:e.onLimitReached,store:e.store??t.store??"memory",redis:e.redis??t.redis},this.options.store==="memory")this.startCleanupInterval()}defaultKeyGenerator(e){let t=e.headers.get("x-forwarded-for"),r=e.headers.get("x-real-ip"),s=e.headers.get("cf-connecting-ip");if(this.options.trustProxy&&t)return t.split(",")[0].trim();return r||s||"unknown"}startCleanupInterval(){this.cleanupInterval=setInterval(()=>{let e=Date.now();for(let[t,r]of this.requestStore.entries()){if(e-r.lastRequest>this.options.windowSize*2)this.requestStore.delete(t);if(r.blocked&&r.blockExpires&&e>r.blockExpires)r.blocked=!1,r.blockExpires=void 0}},this.options.windowSize/2),this.cleanupInterval.unref?.()}isWhitelisted(e){return this.options.whitelistedIPs?.includes(e)??!1}isBlacklisted(e){return this.options.blacklistedIPs?.includes(e)??!1}getRateLimitInfo(e,t){let r=this.requestStore.get(e);if(!r){if(this.requestStore.size>=1e5){let s=Math.ceil(this.requestStore.size/10);for(let n of this.requestStore.keys())if(this.requestStore.delete(n),--s<=0)break}r={count:0,firstRequest:t,lastRequest:t,blocked:!1},this.requestStore.set(e,r)}if(t-r.firstRequest>this.options.windowSize)r.count=0,r.firstRequest=t;return r}shouldBlock(e,t){if(e.blocked&&e.blockExpires&&t<e.blockExpires)return!0;let r=1000;if(e.count>this.options.burstLimit)return!0;if(e.count>this.options.maxRequestsPerMinute)return!0;return!1}blockIP(e,t){e.blocked=!0,e.blockExpires=t+this.options.blockDuration}createBlockedResponse(e,t){let r=Math.ceil((t.blockExpires-Date.now())/1000),s={"Retry-After":r.toString(),"X-RateLimit-Limit":this.options.maxRequestsPerMinute.toString(),"X-RateLimit-Remaining":"0","X-RateLimit-Reset":Math.ceil(t.blockExpires/1000).toString()};if(this.options.onLimitReached)return this.options.onLimitReached(e,{...t,retryAfter:r});return new Response(JSON.stringify({error:"Too Many Requests",message:"Rate limit exceeded. Please try again later.",retryAfter:r}),{status:429,headers:{"Content-Type":"application/json",...s}})}async handle(e,t){if(!this.options.enabled)return await t()||new Response("Not Found",{status:404});let r=Date.now(),s=this.options.keyGenerator(e);if(this.isWhitelisted(s))return await t()||new Response("Not Found",{status:404});if(this.isBlacklisted(s))return new Response("Access Denied",{status:403});let n=this.getRateLimitInfo(s,r);if(this.shouldBlock(n,r))return this.blockIP(n,r),this.createBlockedResponse(e,n);n.count++,n.lastRequest=r;let i=await t();if(!i)return new Response("Not Found",{status:404});if(this.options.skipSuccessfulRequests&&i.status<400)n.count--;if(this.options.skipFailedRequests&&i.status>=400)n.count--;let o=new Headers(i.headers);return o.set("X-RateLimit-Limit",this.options.maxRequestsPerMinute.toString()),o.set("X-RateLimit-Remaining",Math.max(0,this.options.maxRequestsPerMinute-n.count).toString()),o.set("X-RateLimit-Reset",Math.ceil((n.firstRequest+this.options.windowSize)/1000).toString()),new Response(i.body,{status:i.status,statusText:i.statusText,headers:o})}destroy(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.requestStore.clear()}}function zs(e={}){let t=new Z(e);return async(r,s)=>t.handle(r,s)}class me{config;FILE_SIGNATURES={"image/jpeg":[new Uint8Array([255,216,255])],"image/png":[new Uint8Array([137,80,78,71,13,10,26,10])],"image/gif":[new Uint8Array([71,73,70,56,55,97]),new Uint8Array([71,73,70,56,57,97])],"application/pdf":[new Uint8Array([37,80,68,70])],"application/zip":[new Uint8Array([80,75,3,4]),new Uint8Array([80,75,5,6]),new Uint8Array([80,75,7,8])]};EXECUTABLE_EXTENSIONS=[".exe",".bat",".cmd",".com",".pif",".scr",".vbs",".js",".jar",".app",".deb",".pkg",".dmg",".sh",".ps1",".msi",".dll"];constructor(e={}){this.config={scanForMalware:e.scanForMalware??!1,checkMagicNumbers:e.checkMagicNumbers??!0,sanitizeFilenames:e.sanitizeFilenames??!0,preventExecutableUploads:e.preventExecutableUploads??!0,maxFilenameLength:e.maxFilenameLength??255}}validateFile(e){let t=[];if(e.originalName.length>this.config.maxFilenameLength)t.push(`Filename too long (max ${this.config.maxFilenameLength} characters)`);if(this.config.sanitizeFilenames){let r=this.sanitizeFilename(e.originalName);if(!r||r.length===0)t.push("Filename is invalid or empty after sanitization")}if(this.config.preventExecutableUploads){let r=this.getFileExtension(e.originalName).toLowerCase();if(this.EXECUTABLE_EXTENSIONS.includes(r))t.push("Executable files are not allowed")}if(this.config.checkMagicNumbers){if(!this.validateFileSignature(e))t.push("File signature does not match declared MIME type")}if(this.config.scanForMalware){if(this.basicMalwareScan(e))t.push("Potential malware detected")}return{isValid:t.length===0,errors:t}}validateFileSignature(e){let t=this.FILE_SIGNATURES[e.mimetype];if(!t)return!0;let r=new Uint8Array(e.buffer.slice(0,16));return t.some((s)=>{if(r.length<s.length)return!1;for(let n=0;n<s.length;n++)if(r[n]!==s[n])return!1;return!0})}sanitizeFilename(e){return e.replace(/[<>:"/\\|?*\u0000-\u001F]/u,"_").replace(/^\.+/,"").replace(/\.+$/,"").replace(/\s+/g,"_").substring(0,this.config.maxFilenameLength)}getFileExtension(e){let t=e.lastIndexOf(".");return t===-1?"":e.substring(t)}basicMalwareScan(e){let t=new Uint8Array(e.buffer),r=new TextDecoder("utf-8",{fatal:!1}).decode(t);return[/eval\s*\(/gi,/document\.write/gi,/window\.location/gi,/<script[^>]*>/gi,/javascript:/gi,/vbscript:/gi,/onload\s*=/gi,/onerror\s*=/gi].some((n)=>n.test(r))}getSafeFilename(e){return this.sanitizeFilename(e)}isAllowedFileType(e,t){if(t.length===0)return!0;return t.includes(e)}isWithinSizeLimit(e,t){return e<=t}}import{randomUUID as Ws}from"crypto";import{existsSync as Ks,mkdirSync as Js,writeFileSync as Gs}from"fs";import{basename as Xs,extname as mr,join as Ys}from"path";class O{config;fileSecurity;constructor(e={}){if(this.config={destination:e.destination||"./uploads",maxFileSize:e.maxFileSize||10485760,maxFiles:e.maxFiles||10,allowedMimeTypes:e.allowedMimeTypes||[],allowedExtensions:e.allowedExtensions||[],preserveOriginalName:e.preserveOriginalName??!1,generateUniqueFilename:e.generateUniqueFilename??!0,createDestination:e.createDestination??!0,scanForMalware:e.scanForMalware??!1,checkMagicNumbers:e.checkMagicNumbers??!0,sanitizeFilenames:e.sanitizeFilenames??!0,preventExecutableUploads:e.preventExecutableUploads??!0,maxFilenameLength:e.maxFilenameLength??255},this.fileSecurity=new me(e),this.config.createDestination&&!Ks(this.config.destination))Js(this.config.destination,{recursive:!0})}async handle(e,t){let r=e.headers.get("content-type");if(!r||!r.includes("multipart/form-data"))return await t()||new Response("Not Found",{status:404});try{let s=await e.formData(),n=[],i={};for(let[c,a]of s.entries())if(a instanceof File){if(n.length>=this.config.maxFiles)return this.createErrorResponse(`Maximum ${this.config.maxFiles} files allowed`,400);if(a.size>this.config.maxFileSize)return this.createErrorResponse(`File ${a.name} exceeds maximum size of ${this.formatBytes(this.config.maxFileSize)}`,413);if(this.config.allowedMimeTypes.length>0){let f=a.type.split(";")[0];if(!this.config.allowedMimeTypes.includes(f))return this.createErrorResponse(`File type ${f} not allowed. Allowed types: ${this.config.allowedMimeTypes.join(", ")}`,415)}let l=mr(a.name).toLowerCase();if(this.config.allowedExtensions.length>0&&!this.config.allowedExtensions.includes(l))return this.createErrorResponse(`File extension ${l} not allowed. Allowed extensions: ${this.config.allowedExtensions.join(", ")}`,415);let u=this.generateFilename(a.name),d=Ys(this.config.destination,u),m=await a.arrayBuffer(),p={fieldName:c,originalName:a.name,filename:u,path:d,size:a.size,mimetype:a.type,buffer:m},b=this.fileSecurity.validateFile(p);if(!b.isValid)return this.createErrorResponse(`Security validation failed: ${b.errors.join(", ")}`,400);Gs(d,new Uint8Array(m)),n.push(p)}else if(i[c])if(Array.isArray(i[c]))i[c].push(a);else i[c]=[i[c],a];else i[c]=a;return Object.defineProperty(e,"files",{value:n,writable:!0,enumerable:!0,configurable:!0}),Object.defineProperty(e,"file",{value:(c)=>n.find((a)=>a.fieldName===c)??null,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"formBody",{value:i,writable:!0,enumerable:!0,configurable:!0}),await t()||new Response("Not Found",{status:404})}catch(s){return this.createErrorResponse(`File upload failed: ${s instanceof Error?s.message:"Unknown error"}`,500)}}generateFilename(e){let t=this.fileSecurity.getSafeFilename(e);if(this.config.preserveOriginalName&&!this.config.generateUniqueFilename)return t;let r=mr(t),s=Xs(t,r);if(this.config.generateUniqueFilename){let n=Ws();return this.config.preserveOriginalName?`${s}_${n}${r}`:`${n}${r}`}return t}formatBytes(e){if(e===0)return"0 Bytes";let t=1024,r=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(t));return`${Number.parseFloat((e/t**s).toFixed(2))} ${r[s]}`}createErrorResponse(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}}function Zs(e={}){return new O(e)}function Qs(e,t={}){return new O({...t,maxFiles:1})}function en(e=10,t={}){return new O({...t,maxFiles:e})}function tn(e={}){return new O({...e,allowedMimeTypes:["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/svg+xml"],allowedExtensions:[".jpg",".jpeg",".png",".gif",".webp",".svg"]})}function rn(e={}){return new O({...e,allowedMimeTypes:["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain"],allowedExtensions:[".pdf",".doc",".docx",".txt"]})}class pe{options;constructor(e={}){let t=y.server?.security?.helmet||{};this.options={contentSecurityPolicy:e.contentSecurityPolicy??t.contentSecurityPolicy??{directives:{"default-src":["'self'"],"script-src":["'self'","'unsafe-inline'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","https:"],"font-src":["'self'"],"connect-src":["'self'"],"media-src":["'self'"],"object-src":["'none'"],"child-src":["'self'"],"worker-src":["'self'"],"frame-ancestors":["'none'"],"form-action":["'self'"],"base-uri":["'self'"],"manifest-src":["'self'"]}},crossOriginEmbedderPolicy:e.crossOriginEmbedderPolicy??!0,crossOriginOpenerPolicy:e.crossOriginOpenerPolicy??!0,crossOriginResourcePolicy:e.crossOriginResourcePolicy??!0,dnsPrefetchControl:e.dnsPrefetchControl??!0,expectCt:e.expectCt??t.expectCt??!1,frameguard:e.frameguard??{action:t.frameOptions?.toLowerCase()||"deny"},hidePoweredBy:e.hidePoweredBy??t.hidePoweredBy??!0,hsts:e.hsts??t.hsts??{maxAge:31536000,includeSubDomains:!0,preload:!0},ieNoOpen:e.ieNoOpen??!0,noSniff:e.noSniff??t.noSniff??!0,originAgentCluster:e.originAgentCluster??!0,permittedCrossDomainPolicies:e.permittedCrossDomainPolicies??{permittedPolicies:"none"},referrerPolicy:e.referrerPolicy??t.referrerPolicy??{policy:"strict-origin-when-cross-origin"},xssFilter:e.xssFilter??t.xssFilter??!0}}async handle(e,t){if((y.server?.security?.helmet||{}).enabled===!1)return await t()||new Response("Not Found",{status:404});let s=await t();if(!s)return new Response("Not Found",{status:404});let n=new Headers(s.headers);if(this.options.contentSecurityPolicy){let i=this.options.contentSecurityPolicy;if(typeof i==="object"&&i.directives){let o=Object.entries(i.directives).map(([a,l])=>`${a} ${l.join(" ")}`).join("; "),c=i.reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy";if(n.set(c,o),i.reportUri)n.set("Report-To",JSON.stringify({group:"csp-endpoint",max_age:10886400,endpoints:[{url:i.reportUri}]}))}}if(this.options.crossOriginEmbedderPolicy){let i=this.options.crossOriginEmbedderPolicy,o=typeof i==="object"?i.policy||"require-corp":"require-corp";n.set("Cross-Origin-Embedder-Policy",o)}if(this.options.crossOriginOpenerPolicy){let i=this.options.crossOriginOpenerPolicy,o=typeof i==="object"?i.policy||"same-origin":"same-origin";n.set("Cross-Origin-Opener-Policy",o)}if(this.options.crossOriginResourcePolicy){let i=this.options.crossOriginResourcePolicy,o=typeof i==="object"?i.policy||"same-origin":"same-origin";n.set("Cross-Origin-Resource-Policy",o)}if(this.options.dnsPrefetchControl){let i=this.options.dnsPrefetchControl,o=typeof i==="object"?i.allow:!1;n.set("X-DNS-Prefetch-Control",o?"on":"off")}if(this.options.expectCt){let i=this.options.expectCt;if(typeof i==="object"){let o=[];if(i.enforce)o.push("enforce");if(i.maxAge)o.push(`max-age=${i.maxAge}`);if(i.reportUri)o.push(`report-uri="${i.reportUri}"`);n.set("Expect-CT",o.join(", "))}}if(this.options.frameguard){let i=this.options.frameguard;if(typeof i==="object"){let o=i.action||"deny",c=o==="sameorigin"&&i.domain?`ALLOW-FROM ${i.domain}`:o.toUpperCase();n.set("X-Frame-Options",c)}}if(this.options.hidePoweredBy)n.delete("X-Powered-By");if(this.options.hsts){let i=this.options.hsts;if(typeof i==="object"){let o=[`max-age=${i.maxAge||31536000}`];if(i.includeSubDomains)o.push("includeSubDomains");if(i.preload)o.push("preload");n.set("Strict-Transport-Security",o.join("; "))}}if(this.options.ieNoOpen)n.set("X-Download-Options","noopen");if(this.options.noSniff)n.set("X-Content-Type-Options","nosniff");if(this.options.originAgentCluster)n.set("Origin-Agent-Cluster","?1");if(this.options.permittedCrossDomainPolicies){let i=this.options.permittedCrossDomainPolicies,o=typeof i==="object"?i.permittedPolicies||"none":"none";n.set("X-Permitted-Cross-Domain-Policies",o)}if(this.options.referrerPolicy){let i=this.options.referrerPolicy;if(typeof i==="object"){let o=Array.isArray(i.policy)?i.policy.join(", "):i.policy||"strict-origin-when-cross-origin";n.set("Referrer-Policy",o)}else n.set("Referrer-Policy","strict-origin-when-cross-origin")}if(this.options.xssFilter){let i=this.options.xssFilter,o=typeof i==="object"&&i.setOnOldIE?"1; mode=block":"0";n.set("X-XSS-Protection",o)}return new Response(s.body,{status:s.status,statusText:s.statusText,headers:n})}}var sn=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/,nn=/^[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 Q{options;constructor(e={}){let t=y.server?.security?.inputValidation||{};this.options={enabled:e.enabled??t.enabled??!0,schemas:e.schemas??t.schemas??{},sanitizeByDefault:e.sanitizeByDefault??t.sanitizeByDefault??!0,strictMode:e.strictMode??t.strictMode??!1,allowUnknownFields:e.allowUnknownFields??t.allowUnknownFields??!0,maxDepth:e.maxDepth??t.maxDepth??10,onValidationError:e.onValidationError}}validateValue(e,t,r){let s=[];if(t.required&&(e===void 0||e===null||e===""))return s.push({field:r,message:"Field is required",value:e,rule:"required"}),s;if(e===void 0||e===null)return s;switch(t.type){case"string":if(typeof e!=="string")s.push({field:r,message:"Must be a string",value:e,rule:"type"});else{if(t.min!==void 0&&e.length<t.min)s.push({field:r,message:`Must be at least ${t.min} characters`,value:e,rule:"min"});if(t.max!==void 0&&e.length>t.max)s.push({field:r,message:`Must be at most ${t.max} characters`,value:e,rule:"max"})}break;case"number":{let n=Number(e);if(Number.isNaN(n))s.push({field:r,message:"Must be a number",value:e,rule:"type"});else{if(t.min!==void 0&&n<t.min)s.push({field:r,message:`Must be at least ${t.min}`,value:e,rule:"min"});if(t.max!==void 0&&n>t.max)s.push({field:r,message:`Must be at most ${t.max}`,value:e,rule:"max"})}break}case"boolean":if(typeof e!=="boolean"&&e!=="true"&&e!=="false")s.push({field:r,message:"Must be a boolean",value:e,rule:"type"});break;case"email":{if(typeof e==="string"&&!sn.test(e))s.push({field:r,message:"Must be a valid email address",value:e,rule:"format"});break}case"url":try{new URL(e)}catch{s.push({field:r,message:"Must be a valid URL",value:e,rule:"format"})}break;case"uuid":{if(typeof e==="string"&&!nn.test(e))s.push({field:r,message:"Must be a valid UUID",value:e,rule:"format"});break}case"date":{let n=new Date(e);if(Number.isNaN(n.getTime()))s.push({field:r,message:"Must be a valid date",value:e,rule:"format"});break}case"regex":if(t.pattern&&typeof e==="string"&&!t.pattern.test(e))s.push({field:r,message:"Does not match required pattern",value:e,rule:"pattern"});break;case"custom":if(t.custom){let n=t.custom(e);if(n!==!0)s.push({field:r,message:typeof n==="string"?n:"Custom validation failed",value:e,rule:"custom"})}break}if(t.enum&&!t.enum.includes(e))s.push({field:r,message:`Must be one of: ${t.enum.join(", ")}`,value:e,rule:"enum"});if(t.type!=="regex"&&t.pattern&&typeof e==="string"&&!t.pattern.test(e))s.push({field:r,message:"Does not match required pattern",value:e,rule:"pattern"});return s}sanitizeValue(e,t){if(!t.sanitize&&!this.options.sanitizeByDefault)return e;if(typeof e==="string")e=e.replace(/[<>'"&]/g,(r)=>({"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","&":"&amp;"})[r]||r).trim();if(t.transform)e=t.transform(e);return e}validateObject(e,t,r="",s=0){let n=[];if(s>this.options.maxDepth)return n.push({field:r,message:"Maximum nesting depth exceeded",value:e,rule:"depth"}),n;if(this.options.strictMode&&!this.options.allowUnknownFields){for(let i in e)if(!(i in t))n.push({field:r?`${r}.${i}`:i,message:"Unknown field",value:e[i],rule:"unknown"})}for(let[i,o]of Object.entries(t)){let c=r?`${r}.${i}`:i,a=e?.[i];if(typeof o==="object"&&!("type"in o)){if(a&&typeof a==="object")n.push(...this.validateObject(a,o,c,s+1))}else{let l=o;if(n.push(...this.validateValue(a,l,c)),e&&(l.sanitize||this.options.sanitizeByDefault))e[i]=this.sanitizeValue(a,l)}}return n}async parseRequestBody(e){let t=e.headers.get("content-type")||"";try{if(t.includes("application/json"))return await e.json();else if(t.includes("application/x-www-form-urlencoded")){let r=await e.formData(),s={};for(let[n,i]of r.entries())s[n]=i;return s}else if(t.includes("multipart/form-data")){let r=await e.formData(),s={};for(let[n,i]of r.entries())s[n]=i;return s}}catch(r){throw console.error(r),Error("Invalid request body format")}return{}}async handle(e,t){if(!this.options.enabled)return await t()||new Response("Not Found",{status:404});let r=[],s=new URL(e.url);try{if(this.options.schemas?.query){let i={};for(let[c,a]of s.searchParams.entries())i[c]=a;let o=this.validateObject(i,this.options.schemas.query);r.push(...o)}if(this.options.schemas?.body&&e.method!=="GET"&&e.method!=="HEAD")try{let i=await this.parseRequestBody(e),o=this.validateObject(i,this.options.schemas.body);r.push(...o),e.validatedBody=i}catch(i){r.push({field:"body",message:i instanceof Error?i.message:"Invalid request body",value:null,rule:"parse"})}if(this.options.schemas?.headers){let i={};for(let[c,a]of e.headers.entries())i[c]=a;let o=this.validateObject(i,this.options.schemas.headers);r.push(...o)}if(this.options.schemas?.params&&e.params){let i=this.validateObject(e.params,this.options.schemas.params);r.push(...i)}if(r.length>0){if(this.options.onValidationError)return this.options.onValidationError(r);return new Response(JSON.stringify({error:"Validation Error",message:"Request validation failed",errors:r}),{status:400,headers:{"Content-Type":"application/json"}})}return await t()||new Response("Not Found",{status:404})}catch(n){return console.error("Input validation error:",n),new Response("Internal Server Error",{status:500})}}}function on(e={}){let t=new Q(e);return async(r,s)=>t.handle(r,s)}class De{options;rules=new Map;channels=[];notifications=[];lastAlertTimes=new Map;metricsBuffer=[];checkInterval;constructor(e={}){if(this.options={enabled:e.enabled??!0,defaultCooldown:e.defaultCooldown??300000,maxAlerts:e.maxAlerts??1000,autoResolve:e.autoResolve??!0,autoResolveTimeout:e.autoResolveTimeout??600000,...e},e.rules)for(let t of e.rules)this.rules.set(t.id,t);if(this.channels=e.channels||[],this.rules.size===0)this.addDefaultRules();if(this.channels.length===0)this.channels.push({type:"console",enabled:!0,config:{}});if(this.options.enabled)this.startAlertingEngine()}addDefaultRules(){let e=[{id:"high-response-time",name:"High Response Time",description:"Alert when average response time exceeds threshold",enabled:!0,metric:"responseTime",condition:"gt",threshold:1000,duration:60000,severity:"warning"},{id:"critical-response-time",name:"Critical Response Time",description:"Alert when response time is critically high",enabled:!0,metric:"responseTime",condition:"gt",threshold:5000,duration:30000,severity:"critical"},{id:"high-error-rate",name:"High Error Rate",description:"Alert when error rate exceeds threshold",enabled:!0,metric:"errorRate",condition:"gt",threshold:0.05,duration:120000,severity:"warning"},{id:"critical-error-rate",name:"Critical Error Rate",description:"Alert when error rate is critically high",enabled:!0,metric:"errorRate",condition:"gt",threshold:0.1,duration:60000,severity:"critical"},{id:"high-memory-usage",name:"High Memory Usage",description:"Alert when memory usage exceeds threshold",enabled:!0,metric:"memoryUsage",condition:"gt",threshold:536870912,duration:300000,severity:"warning"},{id:"low-request-rate",name:"Low Request Rate",description:"Alert when request rate drops significantly",enabled:!1,metric:"requestRate",condition:"lt",threshold:1,duration:300000,severity:"info"}];for(let t of e)this.rules.set(t.id,t)}startAlertingEngine(){this.checkInterval=setInterval(()=>{this.evaluateRules(),this.cleanupOldNotifications(),this.autoResolveAlerts()},1e4),this.checkInterval.unref?.()}evaluateRules(){let e=Date.now();for(let t of this.rules.values()){if(!t.enabled)continue;let r=this.lastAlertTimes.get(t.id),s=t.cooldown||this.options.defaultCooldown||300000;if(r&&e-r<s)continue;let n=t.duration||60000,i=this.metricsBuffer.filter((a)=>e-a.timestamp<=n);if(i.length===0)continue;let o=!1,c;if(t.metric==="custom"&&t.customEvaluator)o=t.customEvaluator(i),c="custom condition";else{let a=this.extractMetricValues(i,t.metric);if(a.length===0)continue;let l=a.reduce((u,d)=>u+d,0)/a.length;c=l,o=this.evaluateCondition(l,t.condition,t.threshold)}if(o)this.triggerAlert(t,c,i),this.lastAlertTimes.set(t.id,e)}}extractMetricValues(e,t){switch(t){case"responseTime":return e.map((r)=>r.responseTime);case"errorRate":return e.map((r)=>r.statusCode>=400?1:0);case"memoryUsage":return e.map((r)=>r.memoryUsage.heapUsed);case"cpuUsage":return e.map((r)=>r.cpuUsage.user+r.cpuUsage.system);case"requestRate":{if(e.length<2)return[];let r=(e[e.length-1].timestamp-e[0].timestamp)/1000;return[e.length/Math.max(r,1)]}default:return[]}}evaluateCondition(e,t,r){switch(t){case"gt":return e>r;case"gte":return e>=r;case"lt":return e<r;case"lte":return e<=r;case"eq":return Math.abs(e-r)<0.001;default:return!1}}async triggerAlert(e,t,r){let s={id:this.generateId(),ruleId:e.id,ruleName:e.name,severity:e.severity,message:this.formatAlertMessage(e,t,r),timestamp:Date.now(),resolved:!1,metadata:{rule:e,value:t,threshold:e.threshold,condition:e.condition,metricsCount:r.length}};this.notifications.push(s);for(let n of this.channels){if(!n.enabled)continue;if(n.filters?.severities&&!n.filters.severities.includes(e.severity))continue;if(n.filters?.rules&&!n.filters.rules.includes(e.id))continue;try{await this.sendNotification(n,s)}catch(i){console.error(`Failed to send alert to ${n.type}:`,i)}}if(this.notifications.length>(this.options.maxAlerts||1000))this.notifications=this.notifications.slice(-(this.options.maxAlerts||1000))}formatAlertMessage(e,t,r){let s=(o,c)=>{switch(c){case"responseTime":return`${Math.round(o)}ms`;case"errorRate":return`${Math.round(o*100)}%`;case"memoryUsage":return`${Math.round(o/1024/1024)}MB`;case"cpuUsage":return`${Math.round(o)}%`;case"requestRate":return`${Math.round(o)}/s`;default:return String(o)}},n=typeof t==="number"?s(t,e.metric):String(t),i=s(e.threshold,e.metric);return`${e.name}: ${n} ${e.condition} ${i} (${r.length} samples)`}async sendNotification(e,t){switch(e.type){case"console":this.sendConsoleNotification(t);break;case"webhook":await this.sendWebhookNotification(e,t);break;case"slack":await this.sendSlackNotification(e,t);break;case"email":await this.sendEmailNotification(e,t);break;case"custom":if(e.config.customHandler)await e.config.customHandler(t);break}}sendConsoleNotification(e){let t=e.severity==="critical"?"\uD83D\uDEA8":e.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";console.log(`${t} ALERT [${e.severity.toUpperCase()}]: ${e.message}`),console.log(` Rule: ${e.ruleName} (${e.ruleId})`),console.log(` Time: ${new Date(e.timestamp).toISOString()}`)}async sendWebhookNotification(e,t){if(!e.config.url)return;let r={alert:t,timestamp:new Date(t.timestamp).toISOString(),service:"bun-router"};await fetch(e.config.url,{method:"POST",headers:{"Content-Type":"application/json",...e.config.token&&{Authorization:`Bearer ${e.config.token}`}},body:JSON.stringify(r)})}async sendSlackNotification(e,t){if(!e.config.url)return;let r=t.severity==="critical"?"danger":t.severity==="warning"?"warning":"good",s=t.severity==="critical"?":rotating_light:":t.severity==="warning"?":warning:":":information_source:",n=(()=>({channel:e.config.channel,username:"Performance Monitor",icon_emoji:":chart_with_upwards_trend:",attachments:[{color:r,title:`${s} ${t.ruleName}`,text:t.message,fields:[{title:"Severity",value:t.severity.toUpperCase(),short:!0},{title:"Time",value:new Date(t.timestamp).toISOString(),short:!0}],footer:"bun-router Performance Monitor",ts:Math.floor(t.timestamp/1000)}]}))();await fetch(e.config.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async sendEmailNotification(e,t){console.log(`Email notification would be sent to ${e.config.email}:`,t.message)}cleanupOldNotifications(){let t=Date.now()-86400000;this.notifications=this.notifications.filter((r)=>r.timestamp>t)}autoResolveAlerts(){if(!this.options.autoResolve)return;let e=this.options.autoResolveTimeout||600000,t=Date.now()-e;for(let r of this.notifications)if(!r.resolved&&r.timestamp<t)r.resolved=!0,r.resolvedAt=Date.now()}generateId(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}addMetrics(e){this.metricsBuffer.push(e);let t=3600000,r=Date.now()-t;this.metricsBuffer=this.metricsBuffer.filter((s)=>s.timestamp>r)}addRule(e){this.rules.set(e.id,e)}removeRule(e){this.rules.delete(e)}updateRule(e,t){let r=this.rules.get(e);if(r)this.rules.set(e,{...r,...t})}addChannel(e){this.channels.push(e)}removeChannel(e){this.channels.splice(e,1)}getActiveAlerts(){return this.notifications.filter((e)=>!e.resolved)}getAllNotifications(){return[...this.notifications]}resolveAlert(e){let t=this.notifications.find((r)=>r.id===e);if(t&&!t.resolved)t.resolved=!0,t.resolvedAt=Date.now()}async handle(e,t){let r=await t();if(r)return r;return new Response("No response from next middleware",{status:500})}destroy(){if(this.checkInterval)clearInterval(this.checkInterval);this.rules.clear(),this.channels=[],this.notifications=[],this.lastAlertTimes.clear(),this.metricsBuffer=[]}}function an(e={}){return new De(e)}import ee from"process";class Oe{options;metricsHistory=[];alerts=[];startTime=Date.now();constructor(e={}){this.options={enabled:e.enabled??!0,path:e.path??"/performance",title:e.title??"Performance Dashboard",refreshInterval:e.refreshInterval??5000,maxMetrics:e.maxMetrics??1000,authentication:{enabled:!1,...e.authentication},features:{realTimeMetrics:!0,historicalCharts:!0,alertsPanel:!0,tracingView:!0,systemMetrics:!0,...e.features}}}isAuthenticated(e){if(!this.options.authentication?.enabled)return!0;let t=e.headers.get("authorization"),r=e.headers.get("x-api-key");if(this.options.authentication.apiKey&&r===this.options.authentication.apiKey)return!0;if(t&&this.options.authentication.username&&this.options.authentication.password){let[s,n]=t.split(" ");if(s==="Basic"){let i=atob(n),[o,c]=i.split(":");return o===this.options.authentication.username&&c===this.options.authentication.password}}return!1}generateDashboardHTML(e){return`
60
+ <!DOCTYPE html>
61
+ <html lang="en">
62
+ <head>
63
+ <meta charset="UTF-8">
64
+ <meta name='viewport' content='width=device-width, initial-scale=1.0'>
65
+ <title>${this.options.title}</title>
66
+ <style>
67
+ * { margin: 0; padding: 0; box-sizing: border-box; }
68
+ body {
69
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
70
+ background: #f5f5f5;
71
+ color: #333;
72
+ line-height: 1.6;
73
+ }
74
+ .header {
75
+ background: #2c3e50;
76
+ color: white;
77
+ padding: 1rem 2rem;
78
+ display: flex;
79
+ justify-content: space-between;
80
+ align-items: center;
81
+ }
82
+ .header h1 { font-size: 1.5rem; }
83
+ .status {
84
+ display: flex;
85
+ gap: 1rem;
86
+ align-items: center;
87
+ }
88
+ .status-item {
89
+ display: flex;
90
+ flex-direction: column;
91
+ align-items: center;
92
+ font-size: 0.8rem;
93
+ }
94
+ .status-value {
95
+ font-size: 1.2rem;
96
+ font-weight: bold;
97
+ }
98
+ .container {
99
+ max-width: 1400px;
100
+ margin: 0 auto;
101
+ padding: 2rem;
102
+ display: grid;
103
+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
104
+ gap: 2rem;
105
+ }
106
+ .card {
107
+ background: white;
108
+ border-radius: 8px;
109
+ padding: 1.5rem;
110
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
111
+ }
112
+ .card h2 {
113
+ margin-bottom: 1rem;
114
+ color: #2c3e50;
115
+ font-size: 1.2rem;
116
+ }
117
+ .metric {
118
+ display: flex;
119
+ justify-content: space-between;
120
+ align-items: center;
121
+ padding: 0.5rem 0;
122
+ border-bottom: 1px solid #eee;
123
+ }
124
+ .metric:last-child { border-bottom: none; }
125
+ .metric-label { font-weight: 500; }
126
+ .metric-value {
127
+ font-weight: bold;
128
+ color: #27ae60;
129
+ }
130
+ .metric-value.warning { color: #f39c12; }
131
+ .metric-value.critical { color: #e74c3c; }
132
+ .alert {
133
+ padding: 0.75rem;
134
+ margin: 0.5rem 0;
135
+ border-radius: 4px;
136
+ border-left: 4px solid;
137
+ }
138
+ .alert.warning {
139
+ background: #fff3cd;
140
+ border-color: #f39c12;
141
+ color: #856404;
142
+ }
143
+ .alert.critical {
144
+ background: #f8d7da;
145
+ border-color: #e74c3c;
146
+ color: #721c24;
147
+ }
148
+ .chart-container {
149
+ height: 200px;
150
+ background: #f8f9fa;
151
+ border-radius: 4px;
152
+ display: flex;
153
+ align-items: center;
154
+ justify-content: center;
155
+ color: #666;
156
+ }
157
+ .distribution {
158
+ display: grid;
159
+ grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
160
+ gap: 1rem;
161
+ margin-top: 1rem;
162
+ }
163
+ .distribution-item {
164
+ text-align: center;
165
+ padding: 1rem;
166
+ background: #f8f9fa;
167
+ border-radius: 4px;
168
+ }
169
+ .distribution-value {
170
+ font-size: 1.5rem;
171
+ font-weight: bold;
172
+ color: #2c3e50;
173
+ }
174
+ .distribution-label {
175
+ font-size: 0.8rem;
176
+ color: #666;
177
+ margin-top: 0.5rem;
178
+ }
179
+ .trace {
180
+ padding: 0.75rem;
181
+ margin: 0.5rem 0;
182
+ background: #f8f9fa;
183
+ border-radius: 4px;
184
+ border-left: 4px solid #3498db;
185
+ }
186
+ .trace-header {
187
+ display: flex;
188
+ justify-content: space-between;
189
+ align-items: center;
190
+ margin-bottom: 0.5rem;
191
+ }
192
+ .trace-operation {
193
+ font-weight: bold;
194
+ color: #2c3e50;
195
+ }
196
+ .trace-duration {
197
+ color: #666;
198
+ font-size: 0.9rem;
199
+ }
200
+ .trace-details {
201
+ font-size: 0.8rem;
202
+ color: #666;
203
+ }
204
+ .refresh-indicator {
205
+ position: fixed;
206
+ top: 1rem;
207
+ right: 1rem;
208
+ background: #27ae60;
209
+ color: white;
210
+ padding: 0.5rem 1rem;
211
+ border-radius: 4px;
212
+ font-size: 0.8rem;
213
+ opacity: 0;
214
+ transition: opacity 0.3s;
215
+ }
216
+ .refresh-indicator.active { opacity: 1; }
217
+ @media (max-width: 768px) {
218
+ .container {
219
+ grid-template-columns: 1fr;
220
+ padding: 1rem;
221
+ }
222
+ .header {
223
+ padding: 1rem;
224
+ flex-direction: column;
225
+ gap: 1rem;
226
+ }
227
+ }
228
+ </style>
229
+ </head>
230
+ <body>
231
+ <div class='header'>
232
+ <h1>${this.options.title}</h1>
233
+ <div class='status'>
234
+ <div class='status-item'>
235
+ <div class='status-value'>${e.metrics.current.totalRequests}</div>
236
+ <div>Total Requests</div>
237
+ </div>
238
+ <div class='status-item'>
239
+ <div class='status-value'>${Math.round(e.metrics.current.averageResponseTime)}ms</div>
240
+ <div>Avg Response</div>
241
+ </div>
242
+ <div class='status-item'>
243
+ <div class='status-value'>${Math.round(e.metrics.current.errorRate*100)}%</div>
244
+ <div>Error Rate</div>
245
+ </div>
246
+ <div class='status-item'>
247
+ <div class='status-value'>${Math.round(e.metrics.current.requestsPerSecond)}/s</div>
248
+ <div>Requests/sec</div>
249
+ </div>
250
+ </div>
251
+ </div>
252
+
253
+ <div class='container'>
254
+ ${this.options.features?.realTimeMetrics?`
255
+ <div class='card'>
256
+ <h2>Real-time Metrics</h2>
257
+ <div class='metric'>
258
+ <span class='metric-label'>Response Time</span>
259
+ <span class='metric-value'>${Math.round(e.metrics.current.averageResponseTime)}ms</span>
260
+ </div>
261
+ <div class='metric'>
262
+ <span class='metric-label'>Memory Usage</span>
263
+ <span class='metric-value'>${Math.round(e.metrics.current.memoryUsage/1024/1024)}MB</span>
264
+ </div>
265
+ <div class='metric'>
266
+ <span class='metric-label'>CPU Usage</span>
267
+ <span class='metric-value'>${Math.round(e.metrics.current.cpuUsage)}%</span>
268
+ </div>
269
+ <div class='metric'>
270
+ <span class='metric-label'>Requests/sec</span>
271
+ <span class='metric-value'>${Math.round(e.metrics.current.requestsPerSecond)}</span>
272
+ </div>
273
+ <div class='metric'>
274
+ <span class='metric-label'>Error Rate</span>
275
+ <span class='metric-value ${e.metrics.current.errorRate>0.1?"critical":e.metrics.current.errorRate>0.05?"warning":""}'>${Math.round(e.metrics.current.errorRate*100)}%</span>
276
+ </div>
277
+ </div>
278
+ `:""}
279
+
280
+ ${this.options.features?.historicalCharts?`
281
+ <div class='card'>
282
+ <h2>Historical Performance</h2>
283
+ <div class='chart-container'>
284
+ Response Time Chart (${e.metrics.historical.length} data points)
285
+ </div>
286
+ </div>
287
+ `:""}
288
+
289
+ <div class='card'>
290
+ <h2>Request Distribution</h2>
291
+ <div class='distribution'>
292
+ ${Object.entries(e.metrics.distribution.statusCodes).map(([t,r])=>`
293
+ <div class='distribution-item'>
294
+ <div class='distribution-value'>${r}</div>
295
+ <div class='distribution-label'>HTTP ${t}</div>
296
+ </div>
297
+ `).join("")}
298
+ </div>
299
+ </div>
300
+
301
+ <div class='card'>
302
+ <h2>Top Endpoints</h2>
303
+ ${Object.entries(e.metrics.distribution.paths).sort(([,t],[,r])=>r-t).slice(0,10).map(([t,r])=>`
304
+ <div class='metric'>
305
+ <span class='metric-label'>${t}</span>
306
+ <span class='metric-value'>${r}</span>
307
+ </div>
308
+ `).join("")}
309
+ </div>
310
+
311
+ ${this.options.features?.alertsPanel?`
312
+ <div class='card'>
313
+ <h2>Active Alerts</h2>
314
+ ${e.alerts.length===0?"<p>No active alerts</p>":""}
315
+ ${e.alerts.filter((t)=>!t.resolved).map((t)=>`
316
+ <div class='${t.type} alert'>
317
+ <strong>${t.type.toUpperCase()}:</strong> ${t.message}
318
+ <br><small>${new Date(t.timestamp).toLocaleString()}</small>
319
+ </div>
320
+ `).join("")}
321
+ </div>
322
+ `:""}
323
+
324
+ ${this.options.features?.tracingView?`
325
+ <div class='card'>
326
+ <h2>Recent Traces</h2>
327
+ ${e.traces.slice(0,10).map((t)=>`
328
+ <div class='trace'>
329
+ <div class='trace-header'>
330
+ <span class='trace-operation'>${t.operationName}</span>
331
+ <span class='trace-duration'>${Math.round((t.duration||0)*100)/100}ms</span>
332
+ </div>
333
+ <div class='trace-details'>
334
+ Trace ID: ${t.traceId} | Status: ${t.status}
335
+ ${t.error?` | Error: ${t.error}`:""}
336
+ </div>
337
+ </div>
338
+ `).join("")}
339
+ </div>
340
+ `:""}
341
+
342
+ ${this.options.features?.systemMetrics?`
343
+ <div class='card'>
344
+ <h2>System Information</h2>
345
+ <div class='metric'>
346
+ <span class='metric-label'>Uptime</span>
347
+ <span class='metric-value'>${Math.round(e.system.uptime/1000/60)} minutes</span>
348
+ </div>
349
+ <div class='metric'>
350
+ <span class='metric-label'>Node.js</span>
351
+ <span class='metric-value'>${e.system.nodeVersion}</span>
352
+ </div>
353
+ <div class='metric'>
354
+ <span class='metric-label'>Platform</span>
355
+ <span class='metric-value'>${e.system.platform} ${e.system.arch}</span>
356
+ </div>
357
+ <div class='metric'>
358
+ <span class='metric-label'>Heap Used</span>
359
+ <span class='metric-value'>${Math.round(e.system.memory.heapUsed/1024/1024)}MB</span>
360
+ </div>
361
+ <div class='metric'>
362
+ <span class='metric-label'>RSS</span>
363
+ <span class='metric-value'>${Math.round(e.system.memory.rss/1024/1024)}MB</span>
364
+ </div>
365
+ </div>
366
+ `:""}
367
+ </div>
368
+
369
+ <div class='refresh-indicator' id='refreshIndicator'>Updated</div>
370
+
371
+ <script>
372
+ let refreshInterval;
373
+
374
+ function startAutoRefresh() {
375
+ refreshInterval = setInterval(async () => {
376
+ try {
377
+ const response = await fetch('${this.options.path}/api/data');
378
+ if (response.ok) {
379
+ const indicator = document.getElementById('refreshIndicator');
380
+ indicator.classList.add('active');
381
+ setTimeout(() => indicator.classList.remove('active'), 1000);
382
+
383
+ // In a real implementation, we would update the DOM with new data
384
+ // For now, we'll just refresh the page
385
+ setTimeout(() => window.location.reload(), ${this.options.refreshInterval});
386
+ }
387
+ }
388
+ catch (error) {
389
+ console.error('Failed to refresh data:', error);
390
+ }
391
+ }, ${this.options.refreshInterval});
392
+ }
393
+
394
+ // Start auto-refresh
395
+ startAutoRefresh();
396
+
397
+ // Stop refresh when page is hidden
398
+ document.addEventListener('visibilitychange', () => {
399
+ if (document.hidden) {
400
+ clearInterval(refreshInterval);
401
+ }
402
+ else {
403
+ startAutoRefresh();
404
+ }
405
+ });
406
+ </script>
407
+ </body>
408
+ </html>
409
+ `}async getDashboardData(e,t){let r=Date.now(),s={current:{totalRequests:0,averageResponseTime:0,errorRate:0,requestsPerSecond:0,memoryUsage:0,cpuUsage:0},historical:this.metricsHistory,distribution:{statusCodes:{},paths:{},methods:{},responseTimes:[]}};if(e&&typeof e.getAggregatedMetrics==="function"){let o=e.getAggregatedMetrics(60000);s.current={totalRequests:o.totalRequests,averageResponseTime:o.averageResponseTime,errorRate:o.errorRate,requestsPerSecond:o.requestsPerSecond,memoryUsage:o.averageMemoryUsage,cpuUsage:0},s.distribution.statusCodes=o.statusCodeDistribution,s.distribution.paths=o.pathDistribution}let n=[];if(t&&typeof t.getActiveSpans==="function")n=t.getActiveSpans();let i={uptime:r-this.startTime,nodeVersion:ee.version,bunVersion:ee.versions.bun||"N/A",platform:ee.platform,arch:ee.arch,memory:ee.memoryUsage(),cpu:ee.cpuUsage()};return{metrics:s,alerts:this.alerts,traces:n,system:i}}async handle(e,t){if(!this.options.enabled)return await t()||new Response("Internal Server Error",{status:500});let r=new URL(e.url);if(r.pathname===this.options.path){if(!this.isAuthenticated(e))return new Response("Unauthorized",{status:401,headers:{"WWW-Authenticate":'Basic realm="Performance Dashboard"'}});let s=await this.getDashboardData(),n=this.generateDashboardHTML(s);return new Response(n,{headers:{"Content-Type":"text/html","Cache-Control":"no-cache, no-store, must-revalidate"}})}if(r.pathname===`${this.options.path}/api/data`){if(!this.isAuthenticated(e))return new Response("Unauthorized",{status:401});let s=await this.getDashboardData();return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json","Cache-Control":"no-cache, no-store, must-revalidate"}})}return await t()}addAlert(e,t){if(this.alerts.push({id:Math.random().toString(36).substring(2,15),type:e,message:t,timestamp:Date.now(),resolved:!1}),this.alerts.length>100)this.alerts=this.alerts.slice(-100)}resolveAlert(e){let t=this.alerts.find((r)=>r.id===e);if(t)t.resolved=!0}updateMetricsHistory(e){this.metricsHistory.push({timestamp:Date.now(),...e});let t=this.options.maxMetrics||1000;if(this.metricsHistory.length>t)this.metricsHistory=this.metricsHistory.slice(-t)}}function cn(e={}){let t=new Oe(e);return async(r,s)=>t.handle(r,s)}import pr from"crypto";import A from"process";class qe{options;metrics=[];lastAlertTime={};requestsThisSecond=0;lastSecondTimestamp=Date.now();requestContexts=new Map;samplingCounter=0;alertCooldowns=new Map;cleanupInterval;constructor(e={}){let t=y.server?.performance?.monitoring||{};if(this.options={enabled:e.enabled??t.enabled??!0,sampleRate:e.sampleRate??e.sampling?.rate??1,collectMetrics:{responseTime:!0,memoryUsage:!0,cpuUsage:!0,requestDetails:!0,headers:!1,queryParams:!0,...e.collectMetrics},sampling:{rate:e.sampling?.rate??e.sampleRate??1,maxRequestsPerSecond:e.sampling?.maxRequestsPerSecond??1000,...e.sampling},thresholds:{responseTime:{warning:1000,critical:5000},memoryUsage:{warning:536870912,critical:1073741824},errorRate:{warning:0.05,critical:0.1}},profiling:{enabled:!1,sampleInterval:100,maxSamples:10,includeStackTrace:!1,maxStackDepth:10},alerts:{enabled:!1,thresholds:{responseTime:1000,memoryUsage:104857600,errorRate:0.05},cooldown:60000},...e},this.options.storage?.type==="memory")this.startCleanupInterval()}startCleanupInterval(){this.cleanupInterval=setInterval(()=>{this.cleanupOldMetrics()},60000),this.cleanupInterval.unref?.()}cleanupOldMetrics(){let e=Date.now(),t=this.options.storage?.retentionPeriod||86400000;this.metrics=this.metrics.filter((s)=>e-s.timestamp<t);let r=this.options.storage?.maxEntries||1e4;if(this.metrics.length>r)this.metrics=this.metrics.slice(-r)}shouldSample(){let e=this.options.sampling?.rate||this.options.sampleRate||1;return Math.random()<e}generateTraceId(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}generateSpanId(){return Math.random().toString(36).substring(2,10)}getClientIP(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||e.headers.get("cf-connecting-ip")||"unknown"}async collectSystemMetrics(){let e=A.memoryUsage(),t=A.cpuUsage();return{memory:e,cpu:t}}takeSample(e){let t=A.memoryUsage(),r=A.cpuUsage(),s=Date.now();if(!e.systemSamples)e.systemSamples=[];if(!e.samples)e.samples=[];e.systemSamples.push({timestamp:s,memory:t,cpu:r}),e.samples.push({timestamp:s,memory:t,cpu:r,stack:this.options.profiling?.includeStackTrace?Error("Profile sample").stack?.slice(0,this.options.profiling.maxStackDepth||10):void 0})}calculateCpuPercent(e,t,r){let s=t.user-e.user,n=t.system-e.system;return{user:s/r*100,system:n/r*100}}async storeMetrics(e){if(this.metrics.push(e),console.warn(`[PerformanceMonitor] Stored metric: ${e.path} ${e.method} ${e.responseTime}ms`),console.warn(`[PerformanceMonitor] Added metric to internal array: ${e.path} ${e.method} ${e.responseTime}ms`),this.options.storage?.type)switch(this.options.storage.type){case"file":if(this.options.storage.filePath){let t=`${JSON.stringify(e)}
410
+ `;await Bun.write(this.options.storage.filePath,t,{createPath:!0})}break;case"custom":if(this.options.storage.customHandler)await this.options.storage.customHandler(e);break;case"memory":default:break}}async checkThresholds(e){let t=typeof this.options.alerts?.customHandler==="function";if(!this.options.alerts?.enabled&&!t)return;let r=this.options.alerts?.thresholds,s=this.options.thresholds;if(console.warn(`[PerformanceMonitor] Checking thresholds for ${e.path}: responseTime=${e.responseTime}ms, threshold=${r?.responseTime||s?.responseTime?.warning||"none"}`),r?.responseTime&&e.responseTime>r.responseTime)await this.sendAlert({type:"responseTime",message:`Response time threshold exceeded: ${e.responseTime}ms > ${r.responseTime}ms`,value:e.responseTime,threshold:r.responseTime,path:e.path,method:e.method,statusCode:e.statusCode,timestamp:e.timestamp,severity:"warning"});else if(s?.responseTime?.warning&&e.responseTime>s.responseTime.warning)await this.sendAlert({type:"responseTime",message:`Response time threshold exceeded: ${e.responseTime}ms > ${s.responseTime.warning}ms`,value:e.responseTime,threshold:s.responseTime.warning,path:e.path,method:e.method,statusCode:e.statusCode,timestamp:e.timestamp,severity:"warning"});let n=e.memoryUsage.heapUsed;if(r?.memoryUsage&&n>r.memoryUsage)await this.sendAlert({type:"memoryUsage",message:`Memory usage threshold exceeded: ${n} bytes > ${r.memoryUsage} bytes`,value:n,threshold:r.memoryUsage,path:e.path,method:e.method,statusCode:e.statusCode,timestamp:e.timestamp,severity:"warning"});else if(s?.memoryUsage?.warning&&n>s.memoryUsage.warning)await this.sendAlert({type:"memoryUsage",message:`Memory usage threshold exceeded: ${n} bytes > ${s.memoryUsage.warning} bytes`,value:n,threshold:s.memoryUsage.warning,path:e.path,method:e.method,statusCode:e.statusCode,timestamp:e.timestamp,severity:"warning"});if((r?.errorRate||s?.errorRate?.warning)&&e.statusCode>=500){let i=this.metrics.filter((u)=>u.timestamp>Date.now()-60000),o=i.length,c=i.filter((u)=>u.statusCode>=500).length,a=o>0?c/o:0,l=r?.errorRate||s?.errorRate?.warning;if(l&&a>l)await this.sendAlert({type:"errorRate",message:`Error rate threshold exceeded: ${a.toFixed(2)} > ${l.toFixed(2)}`,value:a,threshold:l,path:e.path,method:e.method,statusCode:e.statusCode,timestamp:e.timestamp,severity:"critical"})}}async sendAlert(e){let t=typeof this.options.alerts?.customHandler==="function";if(!t){let r=`${e.type}:${e.path}`,s=Date.now(),n=this.alertCooldowns.get(r)||0,i=this.options.alerts?.cooldown||60000;if(s-n<i)return;this.alertCooldowns.set(r,s)}if(t)try{await this.options.alerts.customHandler(e)}catch(r){console.error("Error in custom alert handler:",r)}if(this.options.alerts?.handler)try{await this.options.alerts.handler(e)}catch(r){console.error("Error in alert handler:",r)}console.warn(`[PerformanceMonitor] Alert: ${e.message} (${e.severity})`)}async sendAlerts(e,t){let r=`${t.path}-${e.join(",")}`,s=Date.now(),n=300000,i=this.alertCooldowns.get(r);if(i&&s-i<300000)return;this.alertCooldowns.set(r,s);let o={timestamp:new Date(t.timestamp).toISOString(),requestId:t.requestId,path:t.path,method:t.method,alerts:e,metrics:{responseTime:t.responseTime,memoryUsage:Math.round(t.memoryUsage.heapUsed/1024/1024),statusCode:t.statusCode}};if(this.options.alerts?.webhookUrl)try{await fetch(this.options.alerts.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(c){console.error("Failed to send webhook alert:",c)}if(this.options.alerts?.slackConfig?.webhookUrl)try{await fetch(this.options.alerts.slackConfig.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:this.options.alerts.slackConfig.channel,text:`\uD83D\uDEA8 Performance Alert: ${e.join(", ")}`,attachments:[{color:"danger",fields:[{title:"Path",value:t.path,short:!0},{title:"Response Time",value:`${t.responseTime}ms`,short:!0},{title:"Memory Usage",value:`${Math.round(t.memoryUsage.heapUsed/1024/1024)}MB`,short:!0},{title:"Status Code",value:t.statusCode.toString(),short:!0}]}]})})}catch(c){console.error("Failed to send Slack alert:",c)}}async collectMetrics(e){let{req:t,res:r,startTime:s,startMemory:n,startCPU:i,error:o}=e,c=performance.now(),a=A.memoryUsage(),l=A.cpuUsage(i),u=new URL(t.url),d=t.requestId||pr.randomUUID(),m={user:l.user,system:l.system},p={requestId:d,timestamp:Date.now(),responseTime:c-s,memoryUsage:{rss:a.rss,heapTotal:a.heapTotal,heapUsed:a.heapUsed,external:a.external,arrayBuffers:a.arrayBuffers},cpuUsage:m,statusCode:r?.status||500,method:t.method,path:u.pathname};if(o)p.error=o.message||String(o);if(t.traceId)p.traceId=t.traceId;if(t.spanId)p.spanId=t.spanId;if(r){let b=r.headers.get("content-length");if(b)p.contentLength=Number.parseInt(b,10)}return console.warn(`[PerformanceMonitor] Collected metrics for ${t.method} ${u.pathname}: responseTime=${p.responseTime}ms, memory=${p.memoryUsage.heapUsed} bytes`),p}async handle(e,t){if(!this.options.enabled)return t();let r=this.options.sampling?.rate??this.options.sampleRate??1,s=Math.random();if(r<=0||s>r)return t();let n=Date.now();if(n-this.lastSecondTimestamp>1000)this.lastSecondTimestamp=n,this.requestsThisSecond=0;if(this.options.maxRequestsPerSecond&&this.requestsThisSecond>=this.options.maxRequestsPerSecond)return t();this.requestsThisSecond++,console.warn(`[PerformanceMonitor] Handling request: ${e.method} ${new URL(e.url).pathname}`);let i=performance.now(),o=A.memoryUsage(),c=A.cpuUsage(),a=[],l;if(this.options.profiling?.enabled){let m=e.requestId||pr.randomUUID();if(!e.profiling)e.profiling={requestId:m,samples:[],systemSamples:[]};if(this.takeSample(e.profiling),this.options.profiling.sampleInterval)l=setInterval(()=>{if(e.profiling&&e.profiling.samples.length<(this.options.profiling?.maxSamples||100))this.takeSample(e.profiling)},this.options.profiling.sampleInterval)}let u=null,d;try{u=await t()}catch(m){throw d=m instanceof Error?m:Error(String(m)),d}finally{if(l)clearInterval(l);let m=await this.collectMetrics({req:e,res:u||new Response("Internal Server Error",{status:500}),startTime:i,startMemory:o,startCPU:c,profilingSamples:a,error:d});await this.storeMetrics(m),await this.checkThresholds(m)}if(!u)return new Response("Internal Server Error",{status:500});return u}addMetrics(e){this.metrics.push(e),console.warn(`[PerformanceMonitor] Added metric to internal array: ${e.path} ${e.method} ${e.responseTime}ms`)}async checkThresholdsPublic(e){return this.checkThresholds(e)}getMetrics(e){let t=this.metrics;if(e?.startTime)t=t.filter((r)=>r.timestamp>=e.startTime);if(e?.endTime)t=t.filter((r)=>r.timestamp<=e.endTime);if(e?.path)t=t.filter((r)=>r.path===e.path);if(e?.method)t=t.filter((r)=>r.method===e.method);if(e?.statusCode)t=t.filter((r)=>r.statusCode===e.statusCode);if(e?.limit)t=t.slice(-e.limit);return t}getAggregatedMetrics(e=60000){let r=Date.now()-e,s=this.metrics.filter((l)=>l.timestamp>=r);if(s.length===0)return{totalRequests:0,averageResponseTime:0,medianResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,errorRate:0,averageMemoryUsage:0,requestsPerSecond:0,statusCodeDistribution:{},pathDistribution:{}};let n=s.map((l)=>l.responseTime).sort((l,u)=>l-u),i=s.filter((l)=>l.statusCode>=400).length,o=s.map((l)=>l.memoryUsage.heapUsed),c={},a={};return s.forEach((l)=>{c[l.statusCode]=(c[l.statusCode]||0)+1,a[l.path]=(a[l.path]||0)+1}),{totalRequests:s.length,averageResponseTime:n.reduce((l,u)=>l+u,0)/n.length,medianResponseTime:n[Math.floor(n.length/2)],p95ResponseTime:n[Math.floor(n.length*0.95)],p99ResponseTime:n[Math.floor(n.length*0.99)],errorRate:i/s.length,averageMemoryUsage:o.reduce((l,u)=>l+u,0)/o.length,requestsPerSecond:s.length/(e/1000),statusCodeDistribution:c,pathDistribution:a}}getProfiles(){let e=[],t=A.memoryUsage(),r=A.cpuUsage();e.push({timestamp:Date.now(),memoryUsage:t,cpuUsage:r});for(let s of this.requestContexts.values())if(s.samples&&s.samples.length>0)for(let n of s.samples)e.push({timestamp:n.timestamp,memoryUsage:n.memory,cpuUsage:n.cpu});return e}destroy(){if(this.cleanupInterval)clearInterval(this.cleanupInterval);this.requestContexts.clear(),this.alertCooldowns.clear()}}function ln(e={}){let t=new qe(e);return async(r,s)=>t.handle(r,s)}class Ue{options;spans=new Map;activeSpans=new Map;exportQueue=[];exportInterval;constructor(e={}){let t=y.server?.performance?.monitoring?.tracing||{};if(this.options={enabled:e.enabled??t.enabled??!1,sampleRate:e.sampleRate??t.sampleRate??1,maxSpans:e.maxSpans??1e4,includeHeaders:e.includeHeaders??!1,includeQueryParams:e.includeQueryParams??!0,includeRequestBody:e.includeRequestBody??!1,includeResponseBody:e.includeResponseBody??!1,maxBodySize:e.maxBodySize??1048576,exporters:e.exporters??[{type:"console"}],propagation:{enabled:!0,headers:["x-trace-id","x-span-id","x-parent-span-id"],...e.propagation}},this.options.enabled)this.startExportInterval()}startExportInterval(){this.exportInterval=setInterval(async()=>{try{await this.exportSpans()}catch(e){console.warn("Error exporting spans:",e)}},100),this.exportInterval.unref?.()}shouldSample(){return Math.random()<(this.options.sampleRate||1)}generateId(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)}extractPropagationHeaders(e){if(!this.options.propagation?.enabled)return{};let t=this.options.propagation.headers||[],r;for(let n of t){let i=e.headers.get(n);if(i){r=i;break}}let s=e.headers.get("x-parent-span-id")||void 0;return{traceId:r,parentSpanId:s}}async captureRequestBody(e){if(!this.options.includeRequestBody)return;try{let t=e.headers.get("content-type")||"",r=Number.parseInt(e.headers.get("content-length")||"0",10);if(r>(this.options.maxBodySize||1048576))return{truncated:!0,reason:"Body too large",size:r};if(t.includes("application/json"))return await e.clone().json();else if(t.includes("application/x-www-form-urlencoded")){let n=await e.clone().formData(),i={};for(let[o,c]of n.entries())i[o]=c;return i}else if(t.includes("text/"))return await e.clone().text()}catch(t){return{error:"Failed to capture body",message:t instanceof Error?t.message:String(t)}}return}async captureResponseBody(e){if(!this.options.includeResponseBody)return;try{let t=e.headers.get("content-type")||"",r=Number.parseInt(e.headers.get("content-length")||"0",10);if(r>(this.options.maxBodySize||1048576))return{truncated:!0,reason:"Body too large",size:r};if(t.includes("application/json"))return await e.clone().json();else if(t.includes("text/"))return await e.clone().text()}catch(t){return{error:"Failed to capture body",message:t instanceof Error?t.message:String(t)}}return}createSpan(e,t,r,s){return{traceId:e,spanId:t,parentSpanId:s,operationName:r,startTime:performance.now(),tags:{},logs:[],status:"ok"}}addSpanTag(e,t,r){let s=this.spans.get(e);if(s)s.tags[t]=r}addSpanLog(e,t,r,s){let n=this.spans.get(e);if(n)n.logs.push({timestamp:performance.now(),level:t,message:r,fields:s})}finishSpan(e,t="ok",r){let s=this.spans.get(e);if(s){if(s.endTime=performance.now(),s.duration=s.endTime-s.startTime,s.status=t,r){if(s.error=r,this.options.includeHeaders)s.stackTrace=Error("Trace error stack").stack?.split(`
411
+ `)}this.exportQueue.push(s),this.spans.delete(e)}}async exportSpans(){if(this.spans.size>0){let r=performance.now()-60000;for(let[s,n]of this.spans)if(n.endTime===void 0&&n.startTime<r)this.spans.delete(s)}if(this.exportQueue.length===0){let r=Array.from(this.spans.values()).filter((s)=>s.endTime!==void 0);if(r.length>0){this.exportQueue.push(...r);for(let s of r)this.spans.delete(s.spanId)}if(this.exportQueue.length===0)return}let e=[...this.exportQueue];this.exportQueue=[];let t=this.options.exporters||[];if(t.length===0){this.exportToConsole(e);return}for(let r of t)try{switch(r.type){case"console":this.exportToConsole(e);break;case"jaeger":await this.exportToJaeger(e,r);break;case"zipkin":await this.exportToZipkin(e,r);break;case"custom":if(typeof r.customExporter==="function")await r.customExporter(e);break}}catch(s){console.warn(`Failed to export spans to ${r.type}:`,s)}}exportToConsole(e){for(let t of e)console.warn("Trace Span:",{traceId:t.traceId,spanId:t.spanId,operation:t.operationName,duration:`${Math.round((t.duration||0)*100)/100}ms`,status:t.status,tags:t.tags,logs:t.logs.length,error:t.error})}async exportToJaeger(e,t){if(!t.endpoint)return;let r=e.map((s)=>({traceID:s.traceId,spanID:s.spanId,parentSpanID:s.parentSpanId,operationName:s.operationName,startTime:Math.floor(s.startTime*1000),duration:Math.floor((s.duration||0)*1000),tags:Object.entries(s.tags).map(([n,i])=>({key:n,type:typeof i==="string"?"string":"number",value:String(i)})),logs:s.logs.map((n)=>({timestamp:Math.floor(n.timestamp*1000),fields:[{key:"level",value:n.level},{key:"message",value:n.message},...n.fields?Object.entries(n.fields).map(([i,o])=>({key:i,value:String(o)})):[]]})),process:{serviceName:"bun-router",tags:[{key:"hostname",value:Bun.env.HOSTNAME||"localhost"},{key:"pid",value:String(123)}]}}));await fetch(`${t.endpoint}/api/traces`,{method:"POST",headers:{"Content-Type":"application/json",...t.headers},body:JSON.stringify({data:[{spans:r}]})})}async exportToZipkin(e,t){if(!t.endpoint)return;let r=e.map((s)=>({traceId:s.traceId,id:s.spanId,parentId:s.parentSpanId,name:s.operationName,timestamp:Math.floor(s.startTime*1000),duration:Math.floor((s.duration||0)*1000),kind:"SERVER",localEndpoint:{serviceName:"bun-router"},tags:s.tags,annotations:s.logs.map((n)=>({timestamp:Math.floor(n.timestamp*1000),value:`${n.level}: ${n.message}`}))}));await fetch(`${t.endpoint}/api/v2/spans`,{method:"POST",headers:{"Content-Type":"application/json",...t.headers},body:JSON.stringify(r)})}async handle(e,t){if(!this.options.enabled||!this.shouldSample())return await t()||new Response("Internal Server Error",{status:500});let r=e.requestId||this.generateId(),s=this.extractPropagationHeaders(e),n=s.traceId||this.generateId(),i=this.generateId(),o=new URL(e.url);console.warn(`[RequestTracer] Creating span for ${e.method} ${o.pathname}, traceId=${n}, spanId=${i}`);let c=this.createSpan(n,i,`${e.method} ${o.pathname}`,s.parentSpanId);if(this.spans.set(i,c),this.activeSpans.set(r,i),e.traceId=n,e.spanId=i,Object.defineProperties(e,{traceId:{value:n,writable:!0,enumerable:!0,configurable:!0},spanId:{value:i,writable:!0,enumerable:!0,configurable:!0}}),this.addSpanTag(i,"http.method",e.method),this.addSpanTag(i,"http.url",e.url),this.addSpanTag(i,"http.path",o.pathname),this.addSpanTag(i,"user_agent",e.headers.get("user-agent")),this.options.includeHeaders){let u={};for(let[d,m]of e.headers.entries())u[d]=m;this.addSpanTag(i,"http.headers",u)}if(this.options.includeQueryParams&&o.searchParams.size>0){let u={};for(let[d,m]of o.searchParams.entries())u[d]=m;this.addSpanTag(i,"http.query_params",u)}if(this.options.includeRequestBody&&e.method!=="GET"&&e.method!=="HEAD")try{let u=await this.captureRequestBody(e);if(u!==void 0)this.addSpanTag(i,"http.request_body",u)}catch(u){this.addSpanLog(i,"warn","Failed to capture request body",{error:String(u)})}this.addSpanLog(i,"info","Request started");let a,l;try{if(a=await t()||new Response("Internal Server Error",{status:500}),this.addSpanTag(i,"http.status_code",a.status),this.addSpanTag(i,"http.status_text",a.statusText),this.options.includeResponseBody)try{let m=await this.captureResponseBody(a);if(m!==void 0)this.addSpanTag(i,"http.response_body",m)}catch(m){this.addSpanLog(i,"warn","Failed to capture response body",{error:String(m)})}this.addSpanLog(i,"info","Request completed",{status:a.status,statusText:a.statusText});let d=a.status>=400;if(d)this.addSpanTag(i,"error",!0),this.addSpanTag(i,"error.status_code",a.status);this.finishSpan(i,d?"error":"ok",d?`HTTP ${a.status}`:void 0)}catch(u){l=u instanceof Error?u.message:String(u),this.addSpanTag(i,"error",!0),this.addSpanTag(i,"error.message",l),this.addSpanTag(i,"error.type",u instanceof Error?u.constructor.name:"Unknown"),this.addSpanLog(i,"error","Request failed",{error:l}),this.finishSpan(i,"error",l);let d=this.spans.get(i);if(d){if(d.endTime===void 0)d.endTime=performance.now(),d.duration=d.endTime-d.startTime,d.status="error",d.error=l;this.exportQueue.push(d),this.spans.delete(i),this.exportSpans().catch((m)=>{console.warn("Failed to export error span:",m)})}a=new Response("Internal Server Error",{status:500})}if(this.activeSpans.delete(r),this.options.propagation?.enabled)a.headers.set("x-trace-id",n),a.headers.set("x-span-id",i);return a}getActiveSpans(){return Array.from(this.spans.values())}getSpanById(e){return this.spans.get(e)}createChildSpan(e,t){let r=this.spans.get(e);if(!r)return null;let s=this.generateId(),n=this.createSpan(r.traceId,s,t,e);return this.spans.set(s,n),s}addTag(e,t,r){this.addSpanTag(e,t,r)}addLog(e,t,r,s){this.addSpanLog(e,t,r,s)}finish(e,t="ok",r){this.finishSpan(e,t,r)}async flush(){let e=Array.from(this.spans.keys());console.warn(`[RequestTracer] Flushing ${e.length} active spans`);for(let t of e){let r=this.spans.get(t);if(r&&!r.endTime)this.finishSpan(t,"ok")}await this.exportSpans()}destroy(){if(this.exportInterval)clearInterval(this.exportInterval);this.spans.clear(),this.activeSpans.clear(),this.exportQueue=[]}}function un(e={}){let t=new Ue(e);return async(r,s)=>t.handle(r,s)}class te{options;suspiciousPatterns=[];sqlInjectionPatterns=[];xssPatterns=[];pathTraversalPatterns=[];commandInjectionPatterns=[];constructor(e={}){let t=y.server?.security||{};this.options={inputValidation:{enabled:!0,maxBodySize:10485760,maxUrlLength:2048,maxHeaderSize:8192,allowedContentTypes:["application/json","application/x-www-form-urlencoded","multipart/form-data","text/plain","text/html","application/xml","text/xml"],sanitizeInput:!0,validateEncoding:!0,...e.inputValidation},requestFiltering:{enabled:!0,blockSuspiciousPatterns:!0,maxRequestsPerMinute:1000,blockUserAgents:["sqlmap","nikto","nessus","openvas","nmap","masscan","zap","w3af"],allowedMethods:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],requireUserAgent:!1,...e.requestFiltering},ipFiltering:{enabled:!1,whitelist:[],blacklist:[],blockPrivateIPs:!1,blockCloudProviders:!1,geoBlocking:{enabled:!1,allowedCountries:[],blockedCountries:[]},...e.ipFiltering},attackPrevention:{enabled:!0,sqlInjection:!0,xss:!0,pathTraversal:!0,commandInjection:!0,ldapInjection:!0,xxe:!0,customPatterns:[],...e.attackPrevention},responseSecurity:{enabled:!0,removeServerHeaders:!0,addSecurityHeaders:!0,sanitizeErrors:!0,preventInfoDisclosure:!0,...e.responseSecurity}},this.initializePatterns()}initializePatterns(){this.suspiciousPatterns=[/\.\.\//g,/\.\.\\/g,/%2e%2e%2f/gi,/%2e%2e%5c/gi,/\/etc\/passwd/gi,/\/proc\/self\/environ/gi,/cmd\.exe/gi,/powershell/gi,/<script/gi,/javascript:/gi,/vbscript:/gi,/onload=/gi,/onerror=/gi],this.sqlInjectionPatterns=[/(\bunion\b.+\bselect\b)|(\bselect\b.+\bunion\b)/gi,/\b(select|insert|update|delete|drop|create|alter|exec|execute)\b.+\b(from|into|set|where|table|database|schema)\b/gi,/(\bor\b|\band\b).+['"]\s*=\s*['"]|['"]\s*=\s*['"].+(\bor\b|\band\b)/gi,/\b(sleep|benchmark|waitfor)\s*\(/gi,/\b(information_schema|sys\.databases|sysobjects)\b/gi,/('|(\\')).+(or|and)\s+(?:\S.*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])[=><]/gi,/\b(concat|group_concat|load_file|into\s+outfile)\b/gi],this.xssPatterns=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/<object[^>]*>.*?<\/object>/gi,/<embed[^>]*>/gi,/<link[^>]*>/gi,/<meta[^>]*>/gi,/javascript:/gi,/vbscript:/gi,/on\w+\s*=/gi,/<[^>]*\son\w+\s*=.*?>/gi,/expression\s*\(/gi,/url\s*\(\s*javascript:/gi],this.pathTraversalPatterns=[/\.\.\//g,/\.\.\\/g,/%2e%2e%2f/gi,/%2e%2e%5c/gi,/\.\.%2f/gi,/\.\.%5c/gi,/%252e%252e%252f/gi,/\.\/%2e%2e%2f/gi],this.commandInjectionPatterns=[/[;&|`${}[\]]/g,/\b(cat|ls|pwd|id|whoami|uname|ps|netstat|ifconfig|ping|nslookup|dig|curl|wget)\s/gi,/\b(cmd|powershell|bash|sh|zsh|fish)\s/gi,/\b(exec|system|shell_exec|passthru|eval)\s*\(/gi,/\$\{.*\}/g,/#\{.*\}/g]}getClientIP(e){return e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||e.headers.get("cf-connecting-ip")||e.headers.get("x-client-ip")||"unknown"}isPrivateIP(e){return[/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^127\./,/^169\.254\./,/^::1$/,/^fc00:/,/^fe80:/].some((r)=>r.test(e))}validateInput(e){let t=[];if(!this.options.attackPrevention?.enabled)return{isValid:!0,threats:t};if(this.options.attackPrevention.sqlInjection){for(let r of this.sqlInjectionPatterns)if(r.test(e)){t.push("SQL Injection");break}}if(this.options.attackPrevention.xss){for(let r of this.xssPatterns)if(r.test(e)){t.push("XSS");break}}if(this.options.attackPrevention.pathTraversal){for(let r of this.pathTraversalPatterns)if(r.test(e)){t.push("Path Traversal");break}}if(this.options.attackPrevention.commandInjection){for(let r of this.commandInjectionPatterns)if(r.test(e)){t.push("Command Injection");break}}if(this.options.attackPrevention.customPatterns){for(let r of this.options.attackPrevention.customPatterns)if(r.pattern.test(e))t.push(r.name)}return{isValid:t.length===0,threats:t}}sanitizeInput(e){if(!this.options.inputValidation?.sanitizeInput)return e;return e.replace(/[<>'"&]/g,(t)=>({"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","&":"&amp;"})[t]||t).replace(/javascript:/gi,"blocked:").replace(/vbscript:/gi,"blocked:").replace(/on\w+=/gi,"blocked=")}async handle(e,t){let r=this.getClientIP(e),s=e.headers.get("user-agent")||"",n=new URL(e.url);if(this.options.ipFiltering?.enabled){let o=this.options.ipFiltering;if(o.whitelist?.length&&!o.whitelist.includes(r))return new Response("Access Denied",{status:403});if(o.blacklist?.includes(r))return new Response("Access Denied",{status:403});if(o.blockPrivateIPs&&this.isPrivateIP(r))return new Response("Access Denied",{status:403})}if(this.options.requestFiltering?.enabled){let o=this.options.requestFiltering;if(o.allowedMethods&&!o.allowedMethods.includes(e.method))return new Response("Method Not Allowed",{status:405});if(o.requireUserAgent&&!s)return new Response("Bad Request",{status:400});if(o.blockUserAgents){if(o.blockUserAgents.some((a)=>s.toLowerCase().includes(a.toLowerCase())))return new Response("Access Denied",{status:403})}if(o.blockSuspiciousPatterns){let c=n.pathname+n.search;for(let a of this.suspiciousPatterns)if(a.test(c))return new Response("Suspicious Request Blocked",{status:400})}}if(this.options.inputValidation?.enabled){let o=this.options.inputValidation;if(o.maxUrlLength&&e.url.length>o.maxUrlLength)return new Response("URL Too Long",{status:414});let c=e.headers.get("content-type");if(c&&o.allowedContentTypes){if(!o.allowedContentTypes.some((l)=>c.toLowerCase().startsWith(l.toLowerCase())))return new Response("Unsupported Media Type",{status:415})}for(let[a,l]of n.searchParams.entries()){let u=this.validateInput(l);if(!u.isValid)return console.warn(`Security threat detected in query param ${a}:`,u.threats),new Response(`Security threat detected: ${u.threats.join(", ")}`,{status:400})}for(let[a,l]of e.headers.entries()){if(o.maxHeaderSize&&l.length>o.maxHeaderSize)return new Response("Header Too Large",{status:431});let u=this.validateInput(l);if(!u.isValid)return console.warn(`Security threat detected in header ${a}:`,u.threats),new Response(`Security threat detected: ${u.threats.join(", ")}`,{status:400})}}if(e.method!=="GET"&&e.method!=="HEAD"&&e.method!=="OPTIONS")try{let o=e.headers.get("content-length");if(o&&this.options.inputValidation?.maxBodySize){if(Number.parseInt(o,10)>this.options.inputValidation.maxBodySize)return new Response("Payload Too Large",{status:413})}}catch(o){console.error("Error checking content length:",o)}let i=await t();if(!i)return new Response("Not Found",{status:404});if(this.options.responseSecurity?.enabled){let o=new Headers(i.headers),c=this.options.responseSecurity;if(c.removeServerHeaders)o.delete("Server"),o.delete("X-Powered-By"),o.delete("X-AspNet-Version"),o.delete("X-AspNetMvc-Version");if(c.addSecurityHeaders)o.set("X-Content-Type-Options","nosniff"),o.set("X-Frame-Options","DENY"),o.set("X-XSS-Protection","0"),o.set("Referrer-Policy","strict-origin-when-cross-origin");return new Response(i.body,{status:i.status,statusText:i.statusText,headers:o})}return i}}function dn(e={}){let t=new te(e);return async(r,s)=>t.handle(r,s)}class Le{middlewares=[];constructor(e={}){let t=y.server?.security||{},r=["ddosProtection","security","helmet","contentSecurityPolicy","inputValidation"],s=e.order||r;for(let n of s)switch(n){case"ddosProtection":if(e.ddosProtection!==!1&&t.ddos?.enabled!==!1){let i=typeof e.ddosProtection==="object"?e.ddosProtection:{},o=new Z(i);this.middlewares.push((c,a)=>o.handle(c,a))}break;case"security":if(e.security!==!1){let i=typeof e.security==="object"?e.security:{},o=new te(i);this.middlewares.push((c,a)=>o.handle(c,a))}break;case"helmet":if(e.helmet!==!1&&t.helmet?.enabled!==!1){let i=typeof e.helmet==="object"?e.helmet:{},o=new pe(i);this.middlewares.push((c,a)=>o.handle(c,a))}break;case"contentSecurityPolicy":if(e.contentSecurityPolicy!==!1&&t.helmet?.contentSecurityPolicy!==!1){let i=typeof e.contentSecurityPolicy==="object"?e.contentSecurityPolicy:{},o=new Y(i);this.middlewares.push((c,a)=>o.handle(c,a))}break;case"inputValidation":if(e.inputValidation!==!1&&t.inputValidation?.enabled!==!1){let i=typeof e.inputValidation==="object"?e.inputValidation:{},o=new Q(i);this.middlewares.push((c,a)=>o.handle(c,a))}break}}async handle(e,t){let r=0,s=async()=>{if(r>=this.middlewares.length)return await t();let n=this.middlewares[r++];return await n(e,s)};return await s()}}function mn(e={}){let t=new Le(e);return async(r,s)=>t.handle(r,s)}var co=()=>new L,lo=()=>new j,uo=()=>new J,mo=()=>new X,po=()=>new x;function ho(){return new P({type:"bearer",validator:()=>!0})}var gt=null;function yt(){if(!gt)gt={"Middleware/Cors":new L,"Middleware/JsonBody":new j,"Middleware/RequestId":new J,"Middleware/Session":new X,"Middleware/Csrf":new x,"Middleware/Auth":new P({type:"bearer",validator:()=>!0}),"Middleware/RateLimit":pt(),"Middleware/RequestSigning":new G({secret:""})};return gt}var fo=new Proxy({},{get(e,t){return yt()[t]},ownKeys(){return Object.keys(yt())},getOwnPropertyDescriptor(e,t){let r=yt()[t];if(r!==void 0)return{configurable:!0,enumerable:!0,value:r};return}});
412
+ export{xt as Qo,fn as Ro,y as So,Rt as To,_e as Uo,kt as Vo,br as Wo,vr as Xo,Sr as Yo,xr as Zo,Rr as _o,L as $o,x as ap,j as bp,Te as cp,pt as dp,J as ep,E as fp,ur as gp,G as hp,Ls as ip,js as jp,Bs as kp,U as lp,Ie as mp,$e as np,Fe as op,mi as pp,ft as qp,Ne as rp,X as sp,Y as tp,Vs as up,Z as vp,zs as wp,me as xp,O as yp,Zs as zp,Qs as Ap,en as Bp,tn as Cp,rn as Dp,pe as Ep,Q as Fp,on as Gp,De as Hp,an as Ip,Oe as Jp,cn as Kp,qe as Lp,ln as Mp,Ue as Np,un as Op,te as Pp,dn as Qp,Le as Rp,mn as Sp,co as Tp,lo as Up,uo as Vp,mo as Wp,po as Xp,ho as Yp,fo as Zp};