@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,2 @@
1
+ // @bun
2
+ import{Pe as a,Qe as b,Re as c,Se as d,Te as e,Ue as f,Ve as g}from"./chunk-8wpj3fqe.js";import"./chunk-nf3kv7kv.js";export{b as createKeepAliveCache,d as generateKeepAliveCSS,e as generateKeepAliveRuntime,f as onActivated,g as onDeactivated,a as processKeepAliveDirectives,c as shouldCacheComponent};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{qs as F}from"./chunk-h1dj6v8q.js";import{Zu as C}from"./chunk-nf3kv7kv.js";import v from"fs";import d from"path";import A from"crypto";var R=new Set(["webp","avif","jpeg","png"]),S=new Set(["cover","contain","fill","inside","outside"]),D=new Set([".jpg",".jpeg",".png",".webp",".avif",".gif"]),k=4096,U=80,N="cover";async function L(e,t){let a=t.routePath??"/_stx/img",p=new URL(e.url);if(p.pathname!==a)return null;let s=M(p,t);if(!s.ok)return new Response(s.error,{status:s.status,headers:{"Content-Type":"text/plain"}});let{srcFsPath:i,srcUrl:g,width:l,height:n,format:r,quality:c,fit:h}=s,m;try{m=v.statSync(i)}catch{return new Response(`Source image not found: ${g}`,{status:404,headers:{"Content-Type":"text/plain"}})}if(!m.isFile())return new Response("Not a file",{status:404,headers:{"Content-Type":"text/plain"}});let w=t.cacheDir??".stx/cache/img";await v.promises.mkdir(w,{recursive:!0});let b=`${i}:${m.mtimeMs}:${m.size}`,x=`${l}x${n}:${r}:${c}:${h}`,f=A.createHash("sha256").update(`${b}|${x}`).digest("hex").slice(0,16),o=d.join(w,`${f}.${r}`),u={"Content-Type":F(r),"Cache-Control":"public, max-age=31536000, immutable",ETag:`"${f}"`,"X-Stx-Image-Cache":"HIT"};if(e.headers.get("if-none-match")===`"${f}"`)return new Response(null,{status:304,headers:u});let T=Bun.file(o);if(await T.exists())return new Response(T,{headers:u});try{let y=Buffer.from(await Bun.file(i).arrayBuffer()),{resizeAndConvert:I}=await q(),P=await I(y,{width:l,height:n,format:r,quality:c,fit:h});return await Bun.write(o,P),u["X-Stx-Image-Cache"]="MISS",new Response(new Uint8Array(P),{headers:u})}catch(y){let I=y.message;return new Response(`Image processing failed: ${I}`,{status:500,headers:{"Content-Type":"text/plain"}})}}function H(e){return async(t)=>await L(t,e)??new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain"}})}function M(e,t){let a=e.searchParams.get("src");if(!a)return{ok:!1,error:"Missing required param: src",status:400};if(!a.startsWith("/"))return{ok:!1,error:"src must be an absolute URL path (start with /)",status:400};if(a.startsWith("//"))return{ok:!1,error:"src must be a local path",status:400};let p=d.extname(a).toLowerCase();if(!D.has(p))return{ok:!1,error:`Unsupported source extension: ${p}`,status:400};let s=d.resolve(t.publicDir),i=d.resolve(s,a.slice(1));if(!i.startsWith(`${s}${d.sep}`)&&i!==s)return{ok:!1,error:"src is outside publicDir",status:400};let g=t.maxWidth??k,l=t.maxHeight??k,n=e.searchParams.get("w"),r=e.searchParams.get("h"),c=n?Number.parseInt(n,10):0,h=r?Number.parseInt(r,10):0;if(n&&(!Number.isFinite(c)||c<=0))return{ok:!1,error:"Invalid w (must be positive integer)",status:400};if(r&&(!Number.isFinite(h)||h<=0))return{ok:!1,error:"Invalid h (must be positive integer)",status:400};if(!n&&!r)return{ok:!1,error:"At least one of w or h is required",status:400};let m=Math.min(c||g,g),w=Math.min(h||l,l),b=e.searchParams.get("f")||"webp";if(!R.has(b))return{ok:!1,error:`Invalid f (must be one of: ${[...R].join(", ")})`,status:400};let x=b,f=e.searchParams.get("q"),o=f?Number.parseInt(f,10):t.defaultQuality??U;if(!Number.isFinite(o)||o<1||o>100)return{ok:!1,error:"Invalid q (must be 1-100)",status:400};let u=e.searchParams.get("fit")||t.defaultFit||N;if(!S.has(u))return{ok:!1,error:`Invalid fit (must be one of: ${[...S].join(", ")})`,status:400};return{ok:!0,srcFsPath:i,srcUrl:a,width:m,height:w,format:x,quality:o,fit:u}}async function q(){return await import("./chunk-cqgkxcb4.js")}
3
+ export{L as m,H as n};
@@ -0,0 +1,62 @@
1
+ // @bun
2
+ import{Zu as W}from"./chunk-nf3kv7kv.js";import ie from"process";import{existsSync as vr,statSync as $r}from"fs";import{existsSync as Ki,mkdirSync as fa,readdirSync as ua,readFileSync as zi,writeFileSync as ga}from"fs";import{homedir as oe}from"os";import{dirname as pa,resolve as _}from"path";import lt from"process";import{existsSync as Cr,statSync as Er}from"fs";import{existsSync as Nt,mkdirSync as Ji,readdirSync as Hi,writeFileSync as Gi}from"fs";import{homedir as le}from"os";import{dirname as kr,resolve as F}from"path";import ae from"process";import{join as Vi,relative as Zi,resolve as Sr}from"path";import Ge from"process";import{existsSync as oi,mkdirSync as xa,readdirSync as Aa,writeFileSync as Ta}from"fs";import{homedir as ut}from"os";import{dirname as Na,resolve as D}from"path";import Ce from"process";import{join as qi,relative as Yi,resolve as xr}from"path";import Ve from"process";import{existsSync as li,mkdirSync as Da,readdirSync as Fa,writeFileSync as ja}from"fs";import{dirname as _a,resolve as Ze}from"path";import Pt from"process";import{Buffer as se}from"buffer";import{createCipheriv as Xi,createDecipheriv as es,randomBytes as gt}from"crypto";import{closeSync as mt,createReadStream as Ar,createWriteStream as ts,existsSync as dt,fsyncSync as Tr,openSync as Or,writeFileSync as rs}from"fs";import{access as is,constants as Mr,mkdir as ss,readdir as Te,rename as Nr,stat as ce,unlink as Oe,writeFile as pt}from"fs/promises";import{join as he}from"path";import P from"process";import{pipeline as ns}from"stream/promises";import{createGzip as Pr}from"zlib";import fe from"process";import X from"process";import{Buffer as Z}from"buffer";import{createCipheriv as as,createDecipheriv as os,randomBytes as yt}from"crypto";import{closeSync as bt,createReadStream as Br,createWriteStream as ls,existsSync as Me,fsyncSync as Ir,openSync as Rr,writeFileSync as cs}from"fs";import{access as hs,constants as Dr,mkdir as fs,readdir as Ne,rename as Fr,stat as ue,unlink as Pe,writeFile as wt}from"fs/promises";import{isAbsolute as us,join as ge,resolve as gs}from"path";import b from"process";import{pipeline as ms}from"stream/promises";import{createGzip as jr}from"zlib";import me from"process";import ee from"process";import Be from"process";import{existsSync as Ie}from"fs";import{resolve as vt}from"path";import{existsSync as ds}from"fs";import{existsSync as ps,readdirSync as ys}from"fs";import{extname as $t,resolve as Lr}from"path";import bs from"process";import{join as ws,relative as vs,resolve as _r}from"path";import qe from"process";import{Buffer as q}from"buffer";import{createCipheriv as $s,createDecipheriv as Cs,randomBytes as Ct}from"crypto";import{closeSync as Et,createReadStream as Ur,createWriteStream as Es,existsSync as Re,fsyncSync as Qr,openSync as Wr,writeFileSync as ks}from"fs";import{access as Ss,constants as Kr,mkdir as xs,readdir as De,rename as zr,stat as de,unlink as Fe,writeFile as kt}from"fs/promises";import{isAbsolute as As,join as pe,resolve as Ts}from"path";import w from"process";import{pipeline as Os}from"stream/promises";import{createGzip as Jr}from"zlib";import ye from"process";import te from"process";import je from"process";import{existsSync as Le}from"fs";import{resolve as St}from"path";import{existsSync as Ms}from"fs";import{Buffer as Qe}from"buffer";import ea from"process";import ta from"process";import ve from"process";import{Buffer as ra}from"buffer";import ia from"process";class Wt{config;pendingAcks=new Map;timeouts=new Map;constructor(e={}){this.config={enabled:e.enabled??!1,timeout:e.timeout??5000,retryAttempts:e.retryAttempts??3}}isEnabled(){return this.config.enabled}register(e,t,r,i,s){if(!this.config.enabled)return Promise.resolve(!0);return new Promise((n,a)=>{let l={messageId:e,channel:t,event:r,data:i,socketId:s,timestamp:Date.now(),attempts:1,resolve:n,reject:a};this.pendingAcks.set(e,l);let o=setTimeout(()=>{this.handleTimeout(e)},this.config.timeout);this.timeouts.set(e,o)})}acknowledge(e){let t=this.pendingAcks.get(e);if(!t)return!1;let r=this.timeouts.get(e);if(r)clearTimeout(r),this.timeouts.delete(e);return t.resolve(!0),this.pendingAcks.delete(e),!0}handleTimeout(e){let t=this.pendingAcks.get(e);if(!t)return;if(t.attempts<this.config.retryAttempts){t.attempts++,t.timestamp=Date.now();let r=setTimeout(()=>{this.handleTimeout(e)},this.config.timeout);this.timeouts.set(e,r)}else t.reject(Error(`Message acknowledgment timeout after ${t.attempts} attempts`)),this.pendingAcks.delete(e),this.timeouts.delete(e)}getPending(){return Array.from(this.pendingAcks.values())}getPendingById(e){return this.pendingAcks.get(e)}clear(){for(let e of this.timeouts.values())clearTimeout(e);for(let e of this.pendingAcks.values())e.reject(Error("Acknowledgment cleared"));this.pendingAcks.clear(),this.timeouts.clear()}getStats(){if(this.pendingAcks.size===0)return{pending:0};let e=Array.from(this.pendingAcks.values()).map((r)=>r.timestamp),t=Math.min(...e);return{pending:this.pendingAcks.size,oldest:t}}}class Kt{config;channelManager;constructor(e={},t){this.config={enabled:e.enabled??!0,maxBatchSize:e.maxBatchSize??50,debounceMs:e.debounceMs??0},this.channelManager=t}async batchSubscribe(e,t){if(!this.config.enabled)throw Error("Batch operations are disabled");let{channels:r,channelData:i}=t;if(r.length>this.config.maxBatchSize)throw Error(`Batch size exceeds maximum: ${r.length} > ${this.config.maxBatchSize}`);let s={succeeded:[],failed:{}};for(let n of r)try{let a=i?.[n];if(await this.channelManager.subscribe(e,n,a))s.succeeded.push(n);else s.failed[n]="Authorization failed"}catch(a){s.failed[n]=a instanceof Error?a.message:"Unknown error"}return s}batchUnsubscribe(e,t){if(!this.config.enabled)throw Error("Batch operations are disabled");if(t.length>this.config.maxBatchSize)throw Error(`Batch size exceeds maximum: ${t.length} > ${this.config.maxBatchSize}`);let r={succeeded:[],failed:{}};for(let i of t)try{this.channelManager.unsubscribe(e,i),r.succeeded.push(i)}catch(s){r.failed[i]=s instanceof Error?s.message:"Unknown error"}return r}batchBroadcast(e,t){if(!this.config.enabled)throw Error("Batch operations are disabled");let{channels:r,event:i,data:s,excludeSocketId:n}=t;if(r.length>this.config.maxBatchSize)throw Error(`Batch size exceeds maximum: ${r.length} > ${this.config.maxBatchSize}`);let a={succeeded:[],failed:{}};for(let l of r)try{e(l,i,s,n),a.succeeded.push(l)}catch(o){a.failed[l]=o instanceof Error?o.message:"Unknown error"}return a}}class zt{server;config;queue=null;constructor(e,t){this.server=e,this.config=t}setQueue(e){return this.queue=e,this}async broadcast(e){if(!e.shouldBroadcast())return;if(e.broadcastWhen&&!e.broadcastWhen())return;let t=this.normalizeChannels(e.broadcastOn()),r=e.broadcastAs?e.broadcastAs():e.constructor.name,i=e.broadcastWith?e.broadcastWith():{},s={event:r,channel:t[0],data:i},n=e.broadcastQueue?.();if(n||this.queue)await this.queueBroadcast(s,t,n);else this.sendBroadcast(s,t)}send(e,t,r){let i=this.normalizeChannels(e),s={event:t,channel:i[0],data:r};this.sendBroadcast(s,i)}toOthers(e){return new Jt(this,e)}sendBroadcast(e,t){for(let r of t)this.server.broadcast(r,e.event,e.data,e.socketId)}async queueBroadcast(e,t,r){let i=this.server.queueManager;if(i&&i.isEnabled()){if(this.config.verbose)console.warn(`Queueing broadcast to queue: ${r||this.queue?.queue||"default"}`);await i.queueBroadcast(t,e.event,e.data,{excludeSocketId:e.socketId})}else{if(this.config.verbose)console.warn("Queue not available, broadcasting immediately");this.sendBroadcast(e,t)}}normalizeChannels(e){return Array.isArray(e)?e:[e]}}class Jt{broadcaster;excludeSocketId;constructor(e,t){this.broadcaster=e,this.excludeSocketId=t}async broadcast(e){await this.broadcaster.broadcast(e)}send(e,t,r){this.broadcaster.send(e,t,r)}}class Ht{config;state=new Map;constructor(e={}){this.config={enabled:e.enabled??!0,ttl:e.ttl??3600,maxSize:e.maxSize??1048576}}set(e,t,r){if(!this.config.enabled)return;if(!this.state.has(e))this.state.set(e,new Map);let i=this.state.get(e),s=JSON.stringify(r).length;if(s>this.config.maxSize)throw Error(`State value exceeds max size: ${s} > ${this.config.maxSize}`);i.set(t,r)}get(e,t){return this.state.get(e)?.get(t)}getAll(e){let t=this.state.get(e);if(!t)return{};return Object.fromEntries(t)}delete(e,t){this.state.get(e)?.delete(t)}clear(e){this.state.delete(e)}has(e,t){if(t)return this.state.get(e)?.has(t)??!1;return this.state.has(e)}getSize(e){let t=this.state.get(e);if(!t)return 0;return JSON.stringify(Object.fromEntries(t)).length}}class Gt{config;constructor(e={}){this.config={enabled:e.enabled??!1,separator:e.separator||":",validateNamespace:e.validateNamespace||(()=>!0)}}parse(e){if(!this.config.enabled)return{channel:e};let t=e.split(this.config.separator);if(t.length>1){let r=t[t.length-1],i=t.slice(0,-1).join(this.config.separator);if(this.config.validateNamespace(i))return{namespace:i,channel:r}}return{channel:e}}format(e,t){if(!this.config.enabled)return t;return`${e}${this.config.separator}${t}`}belongsTo(e,t){let r=this.parse(e);if(!r.namespace)return!1;return r.namespace===t||r.namespace.startsWith(t+this.config.separator)}getChannelsInNamespace(e,t){return e.filter((r)=>this.belongsTo(r,t))}}class Vt{channels=new Map;authorizers=new Map;channel(e,t){return this.authorizers.set(e,t),this}getChannel(e){if(!this.channels.has(e)){let t=this.getChannelType(e),r={name:e,type:t,subscribers:new Set};if(t==="presence")r.members=new Map;this.channels.set(e,r)}return this.channels.get(e)}getChannelType(e){if(e.startsWith("presence-"))return"presence";if(e.startsWith("private-"))return"private";return"public"}async subscribe(e,t,r){let i=this.getChannel(t),s=null;if(i.type!=="public"){let n=await this.authorize(e,t,r);if(!n)return!1;if(i.type==="presence"&&typeof n==="object")i.members.set(e.data.socketId,n),s=n}return i.subscribers.add(e.data.socketId),e.data.channels.add(t),e.subscribe(t),s||!0}unsubscribe(e,t){let r=this.channels.get(t);if(!r)return;if(r.subscribers.delete(e.data.socketId),e.data.channels.delete(t),e.unsubscribe(t),r.type==="presence")r.members.delete(e.data.socketId);if(r.subscribers.size===0)this.channels.delete(t)}unsubscribeAll(e){let t=Array.from(e.data.channels);for(let r of t)this.unsubscribe(e,r)}async authorize(e,t,r){for(let[i,s]of this.authorizers){let n=this.extractParams(i,t);if(n!==null)if(typeof s==="function")return await s(e,n);else return await s.join(e,n)}return!1}extractParams(e,t){let r=[],i=e.replace(/\{([^}]+)\}/g,(l,o)=>(r.push(o),"([^.]+)")),s=new RegExp(`^${i}$`),n=t.match(s);if(!n)return null;let a={};for(let l=0;l<r.length;l++)a[r[l]]=n[l+1];return a}patternToRegex(e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{[^}]+\\\}/g,"[^.]+");return new RegExp(`^${t}$`)}getSubscribers(e){return this.channels.get(e)?.subscribers||new Set}getPresenceMembers(e){let t=this.channels.get(e);if(t?.type==="presence")return t.members;return null}getSubscriberCount(e){return this.channels.get(e)?.subscribers.size||0}hasChannel(e){return this.channels.has(e)}getChannelNames(){return Array.from(this.channels.keys())}getChannelCount(){return this.channels.size}}class ci{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],[,i])=>r.timestamp.getTime()-i.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,i){if(!this.options.enabled)return;let s=this.generateKey(e,r),n=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:n,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!vr(e))return!0;return $r(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let s=vr(r)?$r(r):null,n=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,i)}catch{this.set(e,t,r,i)}}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((i,s)=>i+s.size,0),r=e.map((i)=>i.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 i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class hi{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),s=new Date;try{let n=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:s,...r}),n}catch(n){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:s,...r}),n}}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((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((s)=>s.duration),i=r.reduce((s,n)=>s+n,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Ye=new ci,Zt=new hi,Ns=Object.defineProperty,Ps=(e)=>e;function Bs(e,t){this[e]=Ps.bind(null,t)}var Is=(e,t)=>{for(var r in t)Ns(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Bs.bind(t,r)})},Rs=(e,t)=>()=>(e&&(t=e(e=0)),t),fi={};Is(fi,{withErrorRecovery:()=>mi,tryLoadConfig:()=>nn,loadConfigWithResult:()=>rn,loadConfig:()=>wi,isRetryableError:()=>Zs,isConfigNotFoundError:()=>Vs,isBunfigError:()=>di,globalPerformanceMonitor:()=>Se,globalCache:()=>be,getEnvOrDefault:()=>qs,generateConfigTypes:()=>an,defaultGeneratedDir:()=>Ai,defaultConfigDir:()=>xi,deepMergeWithArrayStrategy:()=>tr,deepMerge:()=>pi,createLibraryConfig:()=>on,config:()=>sn,bunfigPlugin:()=>ln,applyEnvVarsToConfig:()=>$e,TypeGenerationError:()=>Lt,SchemaValidationError:()=>ke,PluginError:()=>Ut,PerformanceMonitor:()=>Yt,FileSystemError:()=>jt,ErrorFactory:()=>ne,EnvVarError:()=>st,EnvProcessor:()=>ct,ConfigValidator:()=>rr,ConfigValidationError:()=>Dt,ConfigNotFoundError:()=>it,ConfigMergeError:()=>Ft,ConfigLoader:()=>ir,ConfigLoadError:()=>Ee,ConfigFileLoader:()=>ht,ConfigCache:()=>qt,CacheUtils:()=>$i,BunfigError:()=>j,BrowserConfigError:()=>_t,ArrayMergeStrategies:()=>ki});class qt{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],[,i])=>r.timestamp.getTime()-i.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,i){if(!this.options.enabled)return;let s=this.generateKey(e,r),n=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(s,{value:t,timestamp:new Date,ttl:n,hits:0,size:a}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Cr(e))return!0;return Er(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,i){try{let s=Cr(r)?Er(r):null,n=s?s.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,i)}catch{this.set(e,t,r,i)}}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((i,s)=>i+s.size,0),r=e.map((i)=>i.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 i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Yt{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),s=new Date;try{let n=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:s,...r}),n}catch(n){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:s,...r}),n}}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((s)=>s.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((s)=>s.duration),i=r.reduce((s,n)=>s+n,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Ds(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function Fs(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function js(e){return e.getStats().size*2}function Xt(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&E(t[0])&&"id"in t[0]&&t[0].id===3&&E(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(E(t)&&E(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(E(e)&&"arr"in e&&Array.isArray(e.arr)&&E(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&E(t[0])&&E(e[0])){let i=[...t];for(let s of e)if(E(s)&&"name"in s){if(!i.find((n)=>E(n)&&("name"in n)&&n.name===s.name))i.push(s)}else if(E(s)&&"path"in s){if(!i.find((n)=>E(n)&&("path"in n)&&n.path===s.path))i.push(s)}else if(!i.some((n)=>Xe(n,s)))i.push(s);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let s of e)if(!i.includes(s))i.push(s);return i}return t}if(!E(t)||!E(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let s=t[i];if(s===null||s===void 0)continue;else if(E(s)&&E(r[i]))r[i]=Xt(r[i],s);else if(Array.isArray(s)&&Array.isArray(r[i]))if(s.length>0&&r[i].length>0&&E(s[0])&&E(r[i][0])){let n=[...s];for(let a of r[i])if(E(a)&&"name"in a){if(!n.find((l)=>E(l)&&("name"in l)&&l.name===a.name))n.push(a)}else if(E(a)&&"path"in a){if(!n.find((l)=>E(l)&&("path"in l)&&l.path===a.path))n.push(a)}else if(!n.some((l)=>Xe(l,a)))n.push(a);r[i]=n}else if(s.every((n)=>typeof n==="string")&&r[i].every((n)=>typeof n==="string")){let n=[...s];for(let a of r[i])if(!n.includes(a))n.push(a);r[i]=n}else r[i]=s;else r[i]=s}return r}function Xe(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(!Xe(e[r],t[r]))return!1;return!0}if(E(e)&&E(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Xe(e[s],t[s]))return!1}return!0}return!1}function E(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Ls(e,t){if(!li(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Xt(t,i)}catch{return null}}catch{return null}}async function _s({name:e="",cwd:t,defaultConfig:r}){let i=t||Pt.cwd(),s=[".ts",".js",".mjs",".cjs",".json"],n=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let a of n)for(let l of s){let o=Ze(i,`${a}${l}`),c=await Ls(o,r);if(c!==null)return c}try{let a=Ze(i,"package.json");if(li(a)){let l=(await import(a))[e];if(l&&typeof l==="object"&&!Array.isArray(l))try{return Xt(r,l)}catch{}}}catch{}return r}function Us(e,t={}){let r=Ve.cwd();while(r.includes("storage"))r=xr(r,"..");let i=xr(r,e||"");if(t?.relative)return Yi(Ve.cwd(),i);return i}async function Qs(){try{let e=await _s({name:"clarity",defaultConfig:Ke,cwd:Ve.cwd(),endpoint:"",headers:{}});return{...Ke,...e}}catch{return Ke}}function S(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ws(){if(X.env.NODE_ENV==="test"||X.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X<"u"){let e=X.type;if(e==="renderer"||e==="worker")return!1;return!!(X.versions&&(X.versions.node||X.versions.bun))}return!1}class ui{async format(e){let t=await Ws(),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:fe.pid,hostname:t(),environment:fe.env.NODE_ENV||"development",platform:fe.platform,version:fe.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:fe.env.NODE_ENV||fe.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class et{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...It},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ui,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??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),n=this.generateKey();this.currentKeyId=s,this.keys.set(s,n),this.encryptionKeys.set(s,{key:n,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ze,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ze};return{...ze,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:It.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let i,s=0,n=3,a=1000;while(s<n)try{try{try{await is(this.config.logDirectory,Mr.F_OK|Mr.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await ss(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:se.from(e);try{if(!dt(this.currentLogFile))await pt(this.currentLogFile,"",{mode:420});if(i=Or(this.currentLogFile,"a",420),rs(i,l,{flag:"a"}),Tr(i),i!==void 0)mt(i),i=void 0;if((await ce(this.currentLogFile)).size===0){if(await pt(this.currentLogFile,l,{flag:"w",mode:420}),(await ce(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let c=o;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(s<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${n}:`,h);let f=a*2**s;await new Promise((g)=>setTimeout(g,f)),s++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(i!==void 0)try{mt(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(s===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}s++;let o=a*2**(s-1);await new Promise((c)=>setTimeout(c,o))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return he(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return he(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return he(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(S())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,l])=>l.createdAt.getTime()-a.createdAt.getTime()),s=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,s);if(i.length>n)for(let[a]of i.slice(n))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return gt(16).toString("hex")}generateKey(){return gt(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=gt(16),i=Xi("aes-256-gcm",t,r),s=se.concat([i.update(e,"utf8"),i.final()]),n=i.getAuthTag();return{encrypted:se.concat([r,s,n]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Pr(),s=[];i.on("data",(n)=>s.push(n)),i.on("end",()=>t(se.from(se.concat(s)))),i.on("error",r),i.write(e),i.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(S())return;let e=await ce(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Te(this.config.logDirectory),n=s.filter((o)=>o.startsWith(this.name)&&/\.log\.\d+$/.test(o)).sort((o,c)=>{let h=Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),a=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${a}`;if(await ce(r).catch(()=>null))try{if(await Nr(r,l),t.compress)try{let o=`${l}.gz`;await this.compressLogFile(l,o),await Oe(l)}catch(o){console.error("Error compressing rotated file:",o)}if(n.length===0&&!s.some((o)=>o.endsWith(".log.1")))try{let o=`${r}.1`;await pt(o,"")}catch(o){console.error("Error creating backup file:",o)}}catch(o){console.error(`Error during rotation: ${o instanceof Error?o.message:String(o)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${s}.log`);if(await ce(r).catch(()=>null))await Nr(r,n)}if(this.currentLogFile=i,t.maxFiles){let s=(await Te(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,a)=>a.localeCompare(n));for(let n of s.slice(t.maxFiles))await Oe(he(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=Ar(e),i=ts(t),s=Pr();await ns(r,s,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),dt(this.currentLogFile))try{let e=Or(this.currentLogFile,"r+");Tr(e),mt(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(!S()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Te(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Oe(he(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?C.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:s,level:n,showTimestamp:a=!0}=e,l=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(a)u.push(t);if(n==="warning")u.push("WARN");else if(n==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)u.push(i.replace(/[[\]]/g,""));return u.push(s),u.join(" ")}let o=P.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${s}`;else if(n==="info"||n==="success")c=`${r} ${i} ${s}`;else c=`${r} ${i} ${C.cyan(s)}`;if(!a)return c.trim();let h=l(c).trim().length,f=l(t).length,g=Math.max(1,o-2-h-f);return`${c.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,a)=>{let l=Number.parseInt(a,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,i=0,s=e.replace(r,(n,a)=>{if(a==="%")return"%";if(i>=t.length)return n;let l=t[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(i<t.length)s+=` ${t.slice(i).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return s}async log(e,t,...r){let i=new Date,s=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),a,l;if(t instanceof Error)a=t.message,l=t.stack;else a=this.formatMessage(t,r);if(this.fancy&&!S()){let c=Ci[e],h=this.options.showTags!==!1&&this.name?C.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:s,icon:c,tag:h,message:C.gray(a),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:s,icon:c,tag:h,message:a,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:s,icon:c,tag:h,message:C.green(a),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:s,icon:c,tag:h,message:a,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:s,icon:c,tag:h,message:a,level:e}),console.error(f),l){let g=l.split(`
3
+ `);for(let u of g)if(u.trim()&&!u.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:C.gray(` ${u}`),level:e,showTimestamp:!1}))}break}}else if(!S()){if(console.error(`${n} ${this.environment}.${e.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(e))return;let o=`${n} ${this.environment}.${e.toUpperCase()}: ${a}
4
+ `;if(l)o+=`${l}
5
+ `;o=o.replace(this.ANSI_PATTERN,""),await this.writeToFile(o)}time(e){let t=performance.now();if(this.fancy&&!S()){let r=this.options.showTags!==!1&&this.name?C.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:C.blue("\u25D0"),tag:r,message:`${C.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-t),n=`${e} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),o=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${n}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
6
+ `,o=o.replace(this.ANSI_PATTERN,""),this.fancy&&!S()){let c=this.options.showTags!==!1&&this.name?C.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:C.green("\u2713"),tag:c,message:`${n}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!S())console.error(o.trim());await this.writeToFile(o)}}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 et(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(S())throw Error("createReadStream is not supported in browser environments");if(!dt(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ar(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 i=se.isBuffer(e)?e:se.from(e,"base64"),s=i.slice(0,16),n=i.slice(-16),a=i.slice(16,-16),l=es("aes-256-gcm",r,s);return l.setAuthTag(n),se.concat([l.update(a),l.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return S()}isServerMode(){return!S()}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),i=this.formatFileTimestamp(t);if(this.fancy&&!S()){let n=e.split(`
7
+ `),a=Math.max(...n.map((h)=>h.length))+2,l=`\u250C${"\u2500".repeat(a)}\u2510`,o=`\u2514${"\u2500".repeat(a)}\u2518`,c=n.map((h)=>{let f=" ".repeat(a-h.length-2);return`\u2502 ${h}${f} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:C.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:C.cyan(l)})),c.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:r,message:C.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:C.cyan(o),showTimestamp:!1}))}else if(!S())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let s=`${i} ${this.environment}.INFO: [BOX] ${e}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}async prompt(e){if(S())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${C.cyan("?")} ${e} (y/n) `);let r=(i)=>{let s=i.toString().trim().toLowerCase();P.stdin.removeListener("data",r);try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!1)}catch{}P.stdin.pause(),console.error(""),t(s==="y"||s==="yes")};try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!0)}catch{}P.stdin.resume(),P.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 s=/%([sdijfo%])/g,n=0;if(r=e.replace(s,(a,l)=>{if(l==="%")return"%";if(n>=t.length)return a;let o=t[n++];switch(l){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return a}}),n<t.length)r+=` ${t.slice(n).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!S()){let s=this.options.showTags!==!1&&this.name?C.gray(this.formatTag(this.name)):"",n=C.blue("\u25D0");console.error(`${n} ${s} ${C.cyan(r)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||S()||e<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(i,s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,i)),s!==void 0)this.activeProgressBar.message=s;let n=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,n)},finish:(i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;if(this.activeProgressBar.current=this.activeProgressBar.total,i!==void 0)this.activeProgressBar.message=i;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(i,s="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||S())return;P.stdout.write(`${"\r".padEnd(P.stdout.columns||80)}\r`),this.log(s,i),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||S()||!P.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),s=e.barLength-i,n=C.green("\u2501".repeat(i)),a=C.gray("\u2501".repeat(s)),l=`[${n}${a}]`,o=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",h=t||r===100?C.green("\u2713"):C.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${C.gray(this.formatTag(this.name))}`:"",g=`\r${h}${f} ${l} ${o}${c}`,u=P.stdout.columns||80,d=" ".repeat(Math.max(0,u-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${d}`,P.stdout.write(e.lastRenderedLine),t)P.stdout.write(`
10
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||S()||!P.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(S()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Te(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=he(this.config.logDirectory,i);if(e.before)try{if((await ce(s)).mtime>=e.before)continue}catch(n){console.error(`Failed to get stats for file ${s}:`,n);continue}r.push(s)}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 i of r)try{await Oe(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function We(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&v(t[0])&&"id"in t[0]&&t[0].id===3&&v(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(v(t)&&v(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(v(e)&&"arr"in e&&Array.isArray(e.arr)&&v(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&v(t[0])&&v(e[0])){let i=[...t];for(let s of e)if(v(s)&&"name"in s){if(!i.find((n)=>v(n)&&("name"in n)&&n.name===s.name))i.push(s)}else if(v(s)&&"path"in s){if(!i.find((n)=>v(n)&&("path"in n)&&n.path===s.path))i.push(s)}else if(!i.some((n)=>tt(n,s)))i.push(s);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let s of e)if(!i.includes(s))i.push(s);return i}return t}if(!v(t)||!v(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let s=t[i];if(s===null||s===void 0)continue;else if(v(s)&&v(r[i]))r[i]=We(r[i],s);else if(Array.isArray(s)&&Array.isArray(r[i]))if(s.length>0&&r[i].length>0&&v(s[0])&&v(r[i][0])){let n=[...s];for(let a of r[i])if(v(a)&&"name"in a){if(!n.find((l)=>v(l)&&("name"in l)&&l.name===a.name))n.push(a)}else if(v(a)&&"path"in a){if(!n.find((l)=>v(l)&&("path"in l)&&l.path===a.path))n.push(a)}else if(!n.some((l)=>tt(l,a)))n.push(a);r[i]=n}else if(s.every((n)=>typeof n==="string")&&r[i].every((n)=>typeof n==="string")){let n=[...s];for(let a of r[i])if(!n.includes(a))n.push(a);r[i]=n}else r[i]=s;else r[i]=s}return r}function er(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:We(e,t);if(Array.isArray(e))return r==="replace"?t:We(e,t);if(!v(t)||!v(e))return t;let i={...e};for(let s of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=t[s],a=i[s];if(n===null||n===void 0)continue;if(Array.isArray(n)||Array.isArray(a))if(r==="replace")i[s]=n;else i[s]=We(a,n);else if(v(n)&&v(a))i[s]=er(a,n,r);else i[s]=n}return i}function tt(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(!tt(e[r],t[r]))return!1;return!0}if(v(e)&&v(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!tt(e[s],t[s]))return!1}return!0}return!1}function v(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function _e(e,t,r="replace"){if(!oi(e))return null;try{let i=await import(e),s=i.default||i;if(typeof s!=="object"||s===null||Array.isArray(s))return null;try{return er(t,s,r)}catch{return null}}catch{return null}}function Ks(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),s={...t};function n(a,l=[]){let o={...a};for(let[c,h]of Object.entries(a)){let f=[...l,c],g=(m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${i}_${f.map(g).join("_")}`,d=`${i}_${f.map((m)=>m.toUpperCase()).join("_")}`;if(r)I.info(`Checking environment variable ${u} for config ${e}.${f.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))o[c]=n(h,f);else{let m=Ce.env[u]||Ce.env[d];if(m!==void 0){if(r)I.info(`Using environment variable ${m?u:d} for config ${e}.${f.join(".")}`);if(typeof h==="number")o[c]=Number(m);else if(typeof h==="boolean")o[c]=m.toLowerCase()==="true";else if(Array.isArray(h))try{let k=JSON.parse(m);if(Array.isArray(k))o[c]=k;else o[c]=m.split(",").map((N)=>N.trim())}catch{o[c]=m.split(",").map((k)=>k.trim())}else o[c]=m}}}return o}return n(s)}async function zs({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:s,verbose:n=!1,checkEnv:a=!0,arrayStrategy:l="replace"}){let o=a&&typeof s==="object"&&s!==null&&!Array.isArray(s)?Ks(e,s,n):s,c=r||Ce.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(n)I.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${c}`);let f=[e,`.${e}`].filter(Boolean),g=[`${e}.config`,`.${e}.config`].filter(Boolean),u=t?[t,`.${t}`]:[],d=t?[`${t}.config`,`.${t}.config`]:[],m=Array.from(new Set([c,D(c,"config"),D(c,".config"),i?D(c,i):void 0].filter(Boolean)));for(let k of m){if(n)I.info(`Searching for configuration in: ${k}`);let N=[D(c,"config"),D(c,".config")].concat(i?[D(c,i)]:[]).includes(k)?[...f,...g,...u,...d]:[...g,...f,...d,...u];for(let R of N)for(let V of h){let z=D(k,`${R}${V}`),J=await _e(z,o,l);if(J!==null){if(n)I.success(`Configuration loaded from: ${z}`);return J}}}if(e){let k=D(ut(),".config",e),N=["config",`${e}.config`];if(t)N.push(`${t}.config`);if(n)I.info(`Checking user config directory: ${k}`);for(let R of N)for(let V of h){let z=D(k,`${R}${V}`),J=await _e(z,o,l);if(J!==null){if(n)I.success(`Configuration loaded from user config directory: ${z}`);return J}}}if(e){let k=D(ut(),".config"),N=[`.${e}.config`];if(t)N.push(`.${t}.config`);if(n)I.info(`Checking user config directory for dotfile configs: ${k}`);for(let R of N)for(let V of h){let z=D(k,`${R}${V}`),J=await _e(z,o,l);if(J!==null){if(n)I.success(`Configuration loaded from user config directory dotfile: ${z}`);return J}}}if(e){let k=ut(),N=[`.${e}.config`,`.${e}`];if(t)N.push(`.${t}.config`),N.push(`.${t}`);if(n)I.info(`Checking user home directory for dotfile configs: ${k}`);for(let R of N)for(let V of h){let z=D(k,`${R}${V}`),J=await _e(z,o,l);if(J!==null){if(n)I.success(`Configuration loaded from user home directory: ${z}`);return J}}}try{let k=D(c,"package.json");if(oi(k)){let N=await import(k),R=N[e];if(!R&&t){if(R=N[t],R&&n)I.success(`Using alias "${t}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(n)I.success(`Configuration loaded from package.json: ${R===N[e]?e:t}`);return er(o,R,l)}catch(V){if(n)I.warn("Failed to merge package.json config:",V)}}}catch(k){if(n)I.warn("Failed to load package.json:",k)}if(n)I.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return o}function Js(e,t={}){let r=Ge.cwd();while(r.includes("storage"))r=Sr(r,"..");let i=Sr(r,e||"");if(t?.relative)return Zi(Ge.cwd(),i);return i}async function Hs(){try{let e=await zs({name:"clarity",alias:"logging",defaultConfig:Je,cwd:Ge.cwd()});return{...Je,...e||{}}}catch{return Je}}function x(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Gs(){if(ee.env.NODE_ENV==="test"||ee.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ee<"u"){let e=ee.type;if(e==="renderer"||e==="worker")return!1;return!!(ee.versions&&(ee.versions.node||ee.versions.bun))}return!1}class gi{async format(e){let t=await Gs(),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:me.pid,hostname:t(),environment:me.env.NODE_ENV||"development",platform:me.platform,version:me.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:me.env.NODE_ENV||me.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rt{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={...Rt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new gi,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??b.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),n=this.generateKey();this.currentKeyId=s,this.keys.set(s,n),this.encryptionKeys.set(s,{key:n,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{...He,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...He};return{...He,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Rt.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(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!x()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,s=0,n=3,a=1000;while(s<n)try{try{try{await hs(this.config.logDirectory,Dr.F_OK|Dr.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await fs(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Z.from(e);try{if(!Me(this.currentLogFile))await wt(this.currentLogFile,"",{mode:420});if(i=Rr(this.currentLogFile,"a",420),cs(i,l,{flag:"a"}),Ir(i),i!==void 0)bt(i),i=void 0;if((await ue(this.currentLogFile)).size===0){if(await wt(this.currentLogFile,l,{flag:"w",mode:420}),(await ue(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let c=o;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(s<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${n}:`,h);let f=a*2**s;await new Promise((g)=>setTimeout(g,f)),s++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(i!==void 0)try{bt(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(s===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}s++;let o=a*2**(s-1);await new Promise((c)=>setTimeout(c,o))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 ge(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 ge(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ge(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(x())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,l])=>l.createdAt.getTime()-a.createdAt.getTime()),s=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,s);if(i.length>n)for(let[a]of i.slice(n))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return yt(16).toString("hex")}generateKey(){return yt(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=yt(16),i=as("aes-256-gcm",t,r),s=Z.isBuffer(e)?e:Z.from(e,"utf8"),n=i.update(s),a=i.final(),l=n.length+a.length,o=i.getAuthTag(),c=Z.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),a.copy(c,16+n.length),o.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=jr(),s=[];i.on("data",(n)=>s.push(n)),i.on("end",()=>t(Z.from(Z.concat(s)))),i.on("error",r),i.write(e),i.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(x())return;if(!this.shouldWriteToFile())return;let e=await ue(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await Ne(this.config.logDirectory),n=s.filter((o)=>o.startsWith(this.name)&&/\.log\.\d+$/.test(o)).sort((o,c)=>{let h=Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),a=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${a}`;if(await ue(r).catch(()=>null))try{if(await Fr(r,l),t.compress)try{let o=`${l}.gz`;await this.compressLogFile(l,o),await Pe(l)}catch(o){console.error("Error compressing rotated file:",o)}if(n.length===0&&!s.some((o)=>o.endsWith(".log.1")))try{let o=`${r}.1`;await wt(o,"")}catch(o){console.error("Error creating backup file:",o)}}catch(o){console.error(`Error during rotation: ${o instanceof Error?o.message:String(o)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${s}.log`);if(await ue(r).catch(()=>null))await Fr(r,n)}if(this.currentLogFile=i,t.maxFiles){let s=(await Ne(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,a)=>a.localeCompare(n));for(let n of s.slice(t.maxFiles))await Pe(ge(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=Br(e),i=ls(t),s=jr();await ms(r,s,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(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()})),Me(this.currentLogFile))try{let e=Rr(this.currentLogFile,"r+");Ir(e),bt(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(!x()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ne(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Pe(ge(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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()?p.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||x())return!1;let e=typeof b.env.NO_COLOR<"u",t=b.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof b.stderr<"u"&&b.stderr.isTTY||typeof b.stdout<"u"&&b.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:s,level:n,showTimestamp:a=!0}=e,l=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(a)u.push(t);if(n==="warning")u.push("WARN");else if(n==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)u.push(i.replace(/[[\]]/g,""));return u.push(s),u.join(" ")}let o=b.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${s}`;else if(n==="info"||n==="success")c=`${r} ${i} ${s}`;else c=`${r} ${i} ${p.cyan(s)}`;if(!a)return c.trim();let h=l(c).trim().length,f=l(t).length,g=Math.max(1,o-2-h-f);return`${c.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,a)=>{let l=Number.parseInt(a,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,i=0,s=e.replace(r,(n,a)=>{if(a==="%")return"%";if(i>=t.length)return n;let l=t[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(i<t.length)s+=` ${t.slice(i).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return s}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,s)=>{let n=p.underline(p.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,o="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,i)=>p.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>p.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>p.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>p.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>p.strikethrough(i)),t}supportsHyperlinks(){if(x())return!1;let e=b.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=b.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(us(t)||t.startsWith("./")||t.startsWith("../"))t=gs(t);else return null;return Me(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,s=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),a,l;if(t instanceof Error)a=t.message,l=t.stack;else a=this.formatMessage(t,r);let{consoleText:o,fileText:c}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Ei[e],g=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:p.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:p.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.error(u),l){let d=l.split(`
11
+ `);for(let m of d)if(m.trim()&&!m.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:p.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!x()){if(console.error(`${n} ${this.environment}.${e.toUpperCase()}: ${a}`),l)console.error(l)}if(!this.shouldLog(e))return;let h=`${n} ${this.environment}.${e.toUpperCase()}: ${c}
12
+ `;if(l)h+=`${l}
13
+ `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(e,t=""){let r={update:(s,n)=>{},finish:(s)=>{},interrupt:(s,n)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!x()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(s,n)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,s),this.activeProgressBar.total),n!==void 0)this.activeProgressBar.message=n;if(this.shouldStyleConsole()&&!x()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(s)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,s)},interrupt:(s,n="info")=>{if(!x()&&b.stdout.isTTY)b.stdout.write(`
14
+ `);if(this[n==="warning"?"warn":n](s),this.activeProgressBar&&this.shouldStyleConsole()&&!x()&&b.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":p.blue("\u25D0"),tag:r,message:`${p.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-t),n=`${e} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),o=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${n}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
15
+ `,o=o.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":p.green("\u2713"),tag:c,message:`${n}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!x())console.error(o.trim());if(this.shouldWriteToFile())await this.writeToFile(o)}}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 rt(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(x())throw Error("createReadStream is not supported in browser environments");if(!Me(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Br(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 i=Z.isBuffer(e)?e:Z.from(e,"base64"),s=i.subarray(0,16),n=i.subarray(i.length-16),a=i.subarray(16,i.length-16),l=os("aes-256-gcm",r,s);l.setAuthTag(n);let o=l.update(a),c=l.final(),h=o.length+c.length,f=Z.allocUnsafe(h);return o.copy(f,0),c.copy(f,o.length),f.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return x()}isServerMode(){return!x()}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),i=this.formatFileTimestamp(t),{consoleText:s,fileText:n}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=s.split(`
16
+ `),o=Math.max(...l.map((g)=>g.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,h=`\u2514${"\u2500".repeat(o)}\u2518`,f=l.map((g)=>this.formatConsoleMessage({timestamp:r,message:p.cyan(g),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:p.cyan(c),showTimestamp:!1})),f.forEach((g)=>console.error(g)),console.error(this.formatConsoleMessage({timestamp:r,message:p.cyan(h),showTimestamp:!1}))}else if(!x())console.error(`${i} ${this.environment}.INFO: [BOX] ${n}`);let a=`${i} ${this.environment}.INFO: [BOX] ${n}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(x())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${p.cyan("?")} ${e} (y/n) `);let r=(i)=>{let s=i.toString().trim().toLowerCase();b.stdin.removeListener("data",r);try{if(typeof b.stdin.setRawMode==="function")b.stdin.setRawMode(!1)}catch{}b.stdin.pause(),console.error(""),t(s==="y"||s==="yes")};try{if(typeof b.stdin.setRawMode==="function")b.stdin.setRawMode(!0)}catch{}b.stdin.resume(),b.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,(o,c)=>{if(c==="%")return"%";if(l>=t.length)return o;let h=t[l++];switch(c){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return o}}),l<t.length)r+=` ${t.slice(l).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}let{consoleText:i,fileText:s}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${p.blue("\u25D0")} `;console.error(`${l}${a} ${p.cyan(i)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(n)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!b.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),s=e.barLength-i,n=p.green("\u2501".repeat(i)),a=p.gray("\u2501".repeat(s)),l=`[${n}${a}]`,o=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",h=this.options.showIcons===!1?"":t||r===100?p.green("\u2713"):p.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${p.gray(this.formatTag(this.name))}`:"",g=`\r${h}${f} ${l} ${o}${c}`,u=b.stdout.columns||80,d=" ".repeat(Math.max(0,u-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${d}`,b.stdout.write(e.lastRenderedLine),t)b.stdout.write(`
19
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||x()||!b.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(x()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ne(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=ge(this.config.logDirectory,i);if(e.before)try{if((await ue(s)).mtime>=e.before)continue}catch(n){console.error(`Failed to get stats for file ${s}:`,n);continue}r.push(s)}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 i of r)try{await Pe(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function mi(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:s=()=>!0,fallback:n}=t,a=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(o){if(a=o instanceof Error?o:Error(String(o)),l===r||!s(a))break;if(i>0)await new Promise((c)=>setTimeout(c,i))}if(n!==void 0)return n;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function di(e){return e instanceof j}function Vs(e){return e instanceof it}function Zs(e){if(di(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class ct{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:i,useCamelCase:s=!0,useBackwardCompatibility:n=!0,customParsers:a={},verbose:l=!1,trackPerformance:o=!0}=r,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],h,{useCamelCase:s,useBackwardCompatibility:n,customParsers:a,verbose:l,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(o)return Se.track("applyEnvironmentVariables",c,{configName:e});return c()}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,i){for(let[s,n]of Object.entries(e)){let a=[...t,s],l=a.map((h)=>this.formatEnvKey(h,i.useCamelCase)),o=`${r}_${l.join("_")}`,c=i.useBackwardCompatibility?`${r}_${a.map((h)=>h.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof n==="object"&&n!==null&&!Array.isArray(n))this.processObject(n,a,r,i);else{let h=Be.env[o]||(c?Be.env[c]:void 0);if(h!==void 0){if(i.verbose){let f=Be.env[o]?o:c}try{e[s]=this.parseEnvironmentValue(h,typeof n,o,i.customParsers,i.configName)}catch(f){if(f instanceof st)throw f;throw ne.envVar(o,h,typeof n,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,s){for(let[n,a]of Object.entries(i))try{return a(e)}catch{continue}for(let n of this.defaultParsers)if(n.canParse(e,t))try{return n.parse(e)}catch{throw ne.envVar(r,e,`${t} (via ${n.name} parser)`,s)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,s]of Object.entries(Be.env))if(i.startsWith(r)&&s!==void 0)t[i]=s;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(s){i.push(`Cannot parse value "${t}" as ${r}: ${s}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:s="text"}=r,n=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],n,a),s){case"markdown":return this.formatAsMarkdown(a,e);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,e)}}extractEnvVarInfo(e,t,r,i){for(let[s,n]of Object.entries(e)){let a=[...t,s],l=`${r}_${a.map((o)=>this.formatEnvKey(o,!0)).join("_")}`;if(typeof n==="object"&&n!==null&&!Array.isArray(n))this.extractEnvVarInfo(n,a,r,i);else i.push({key:l,type:Array.isArray(n)?"array":typeof n,description:`Configuration for ${a.join(".")}`,example:this.generateExample(n)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
20
+
21
+ `;for(let i of e)r+=`${i.key}
22
+ `,r+=` Type: ${i.type}
23
+ `,r+=` Description: ${i.description}
24
+ `,r+=` Example: ${i.example}
25
+
26
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
27
+
28
+ `;r+=`| Variable | Type | Description | Example |
29
+ `,r+=`|----------|------|-------------|----------|
30
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
31
+ `;return r}}function qs(e,t){let r=vi("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function pi(e,t,r={}){return yi(e,t,r,new WeakMap)}function yi(e,t,r,i){let{arrayMergeMode:s="replace",skipNullish:n=!1,customMerger:a}=r;if(t===null||t===void 0)return n?e:t;if(a){let l=a(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return bi(e,t,s,i);if(!U(t)||!U(e))return t;return tn(e,t,r,i)}function bi(e,t,r,i){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 Ys(e,t);case"smart":return Xs(e,t,i);default:return t}return t}function Ys(e,t){let r=[...t];for(let i of e)if(!r.some((s)=>Bt(s,i)))r.push(i);return r}function Xs(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(U(t[0])&&U(e[0]))return en(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let s of e)if(!i.includes(s))i.push(s);return i}return t}function en(e,t,r){let i=[...t];for(let s of e){if(!U(s)){i.push(s);continue}let n=["id","name","key","path","type"],a=!1;for(let l of n)if(l in s){if(i.find((o)=>U(o)&&(l in o)&&o[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function tn(e,t,r,i){let s=t;if(U(s)&&i.has(s))return i.get(s);let n={...e};if(U(s))i.set(s,n);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],o=n[a];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){n[a]=l;continue}if(U(l)&&U(o))n[a]=yi(o,l,r,i);else if(Array.isArray(l)||Array.isArray(o))n[a]=bi(o,l,r.arrayMergeMode||"smart",i);else n[a]=l}return n}function tr(e,t,r="replace"){return pi(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Bt(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(!Bt(e[r],t[r]))return!1;return!0}if(U(e)&&U(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Bt(e[s],t[s]))return!1}return!0}return!1}function U(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ht{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:n,trackPerformance:a=!0,verbose:l=!1}=r;if(s){let c=be.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let o=async()=>{if(!Ie(e))return null;try{let c=`?t=${Date.now()}`,h=await import(e+c),f=h.default||h,g="default"in h,u=Object.keys(h).length>0;if(!g&&!u)throw new Ee(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Ee(e,Error("Configuration must export a valid object"),"unknown");let d={config:tr(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)be.setWithFileCheck("file",d,e,n);return d}catch(c){throw c instanceof Error?ne.configLoad(e,c):ne.configLoad(e,Error(String(c)))}};if(a)return Se.track("loadFromPath",o,{path:e});return o()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let s=await this.loadFromPath(i,t,r);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(r.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),s=[];for(let n of i)for(let a of this.extensions)s.push(vt(t,`${n}${a}`));return s}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return mi(async()=>Ie(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Ie(e))return i;if(t||r){let s=this.generateNamePatterns(t||"",r);for(let n of s)for(let a of this.extensions){let l=vt(e,`${n}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),n=s(e);for(let a of n)if(this.looksLikeConfigFile(a)){let l=vt(e,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Ie(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),n=s(e,"utf8");JSON.parse(n)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}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(i)=>{try{let s=await this.loadFromPath(i,{},t);if(s)r.set(i,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${i}:`,s)}})),r}}class rr{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:n=!0,customRules:a=[],trackPerformance:l=!0,verbose:o=!1}=r,c=async()=>{let h=[],f=[],g={stopOnFirstError:i,validateRequired:s,validateTypes:n,customRules:a,trackPerformance:l,verbose:o};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],g);else return this.validateWithJSONSchema(e,t,g)}catch(u){return h.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:h,warnings:f}}};if(l)return await Se.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!ds(t))throw new ke(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),s=i.default||i;if(Array.isArray(s))return this.validateWithRules(e,s,r);else return this.validateWithJSONSchema(e,s,r)}catch(i){throw new ke(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],s=[];return this.validateObjectAgainstSchema(e,t,"",i,s,r),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(e,t,r,i,s,n){if(n.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(a)){if(i.push({path:r,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),n.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),n.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.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)i.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))i.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)i.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)i.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 a=0;a<e.length;a++){let l=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,l,i,s,n),n.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(n.validateRequired&&t.required){for(let l of t.required)if(!(l in a)){if(i.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),n.stopOnFirstError)return}}if(t.properties){for(let[l,o]of Object.entries(t.properties))if(l in a){let c=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],o,c,i,s,n),n.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let o of Object.keys(a))if(!l.has(o))s.push({path:r?`${r}.${o}`:o,message:`Additional property '${o}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],s=[];for(let n of t)try{let a=this.getValueByPath(e,n.path),l=this.validateWithRule(a,n,n.path);if(i.push(...l),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:n.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let s=Array.isArray(e)?"array":typeof e;if(s!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.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))i.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 s=t.validator(e);if(s)i.push({path:r,message:t.message||s,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let s of r)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,s,n,a]=i;t.push({path:s,required:!n,type:this.mapTypeScriptType(a)})}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:Si},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ir{fileLoader=new ht;envProcessor=new ct;validator=new rr;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:s,validate:n,...a}=e;try{if(r?.enabled){let o=this.checkCache(a.name||"",a);if(o)return o}let l;try{l=await this.loadConfigurationStrategies(a,!0,r)}catch(o){let c=a.__strictErrorHandling;if(o instanceof Error&&o.name==="ConfigNotFoundError"){if(c)throw o;l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(o instanceof Error&&o.name==="ConfigLoadError"){let h=o.message.includes("EACCES")||o.message.includes("EPERM")||o.message.includes("permission denied"),f=!h&&(o.message.includes("syntax")||o.message.includes("Expected")||o.message.includes("Unexpected")||o.message.includes("BuildMessage")||o.message.includes("errors building")),g=o.message.includes("Configuration must export a valid object")||o.message.includes("Configuration file is empty and exports nothing");if(c&&(g||h))throw o;if(f&&(!c||!g))l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${o.message}`]};else throw o}else l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${o instanceof Error?o.message:String(o)}`]}}if(s||n)await this.validateConfiguration(l.config,s,n,a.name);if(r?.enabled&&l)this.cacheResult(a.name||"",l,r,a);if(i?.enabled){let o={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(o);if(i.slowThreshold&&o.duration>i.slowThreshold)H.warn(`Slow configuration loading detected: ${o.duration}ms for ${a.name}`);l.metrics=o}return l}catch(l){let o=Date.now()-t;throw H.error(`Configuration loading failed after ${o}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:s,cwd:n,configDir:a,defaultConfig:l,checkEnv:o=!0,arrayStrategy:c="replace",verbose:h=!1}=e,f=n||ae.cwd(),g=[],u=await this.loadLocalConfiguration(i,s,f,a,l,c,h,o,r);if(u)return g.push(...this.getLocalSearchPaths(i,s,f,a)),this.finalizeResult(u,g,o,i,h);let d=await this.loadHomeConfiguration(i,s,l,c,h,o);if(d)return g.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,g,o,i,h);let m=await this.loadPackageJsonConfiguration(i,s,f,l,c,h,o);if(m)return g.push(F(f,"package.json")),this.finalizeResult(m,g,o,i,h);if(g.push(...this.getAllSearchPaths(i,s,f,a)),t)throw ne.configNotFound(i,g,s);return{...await this.applyEnvironmentVariables(i,l,o,h),warnings:[`No configuration file found for "${i}"${s?` or alias "${s}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,s,n,a,l,o){let c=l?$e(e,s,a):s,h=this.getLocalDirectories(r,i);for(let f of h){if(a)H.info(`Searching for configuration in: ${f}`);let g=this.fileLoader.generateConfigPaths(e,f,t),u=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:n,verbose:a,cacheTtl:o?.ttl,useCache:!o?.ttl||o.ttl>100});if(u){if(a)H.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(e,t,r,i,s,n){if(!e)return null;let a=n?$e(e,r,s):r,l=[F(le(),".config",e),F(le(),".config"),le()];for(let o of l){if(s)H.info(`Checking home directory: ${o}`);let c=this.fileLoader.generateConfigPaths(e,o,t),h=await this.fileLoader.tryLoadFromPaths(c,a,{arrayStrategy:i,verbose:s});if(h){if(s)H.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(e,t,r,i,s,n,a){let l=a?$e(e,i,n):i;try{let o=F(r,"package.json");if(!Nt(o))return null;let c=await import(o),h=c[e],f=e;if(!h&&t)h=c[t],f=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(n)H.success(`Configuration loaded from package.json: ${f}`);return{config:tr(l,h,s),source:{type:"package.json",path:o,priority:30,timestamp:new Date}}}}catch(o){if(n)H.warn("Failed to load package.json:",[o instanceof Error?o:Error(String(o))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:$e(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let s=[];if(r){let n=r(e);if(n)s.push(...n)}if(t){let n=await this.validator.validateConfiguration(e,t);if(!n.isValid)s.push(...n.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw ne.configValidation(i||"unknown",s,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return be.get(r)||null}cacheResult(e,t,r,i){let s=this.generateCacheKey(e,i);be.set(s,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,F(e,"config"),F(e,".config"),t?F(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let s=[];return s.push(...this.getLocalSearchPaths(e,t,r,i)),s.push(...this.getHomeSearchPaths(e,t)),s.push(F(r,"package.json")),s}getLocalSearchPaths(e,t,r,i){let s=this.getLocalDirectories(r,i),n=[];for(let a of s)n.push(...this.fileLoader.generateConfigPaths(e,a,t));return n}getHomeSearchPaths(e,t){if(!e)return[];let r=[F(le(),".config",e),F(le(),".config"),le()],i=[];for(let s of r)i.push(...this.fileLoader.generateConfigPaths(e,s,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Hr(e){let t=!(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")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function rn(e){return re.loadConfig({...e,__strictErrorHandling:!0})}async function wi(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 i;if(r)i=await re.loadConfig(e);else i=await re.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let s=i instanceof Error?i.name:"UnknownError",n=i instanceof Error?i.message:String(i);if(!(s==="ConfigNotFoundError"||s==="ConfigLoadError"||s==="ConfigValidationError"||n.includes("config"))&&e.verbose)H.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await re.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function sn(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await re.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"&&Hr(r)))return(await re.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await re.loadConfig({...e,cwd:e.cwd||ae.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Hr(t)))return(await re.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function nn(e,t,r="replace"){let i=new ht;try{let s=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return s?s.config:null}catch{return null}}function $e(e,t,r=!1){let i=new ct,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function n(a,l=[]){let o={...a};for(let[c,h]of Object.entries(a)){let f=[...l,c],g=[`${s}_${f.join("_").toUpperCase()}`,`${s}_${f.map((m)=>m.toUpperCase()).join("")}`,`${s}_${f.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,d;for(let m of g)if(u=ae.env[m],u!==void 0){d=m;break}if(u!==void 0&&d)if(typeof h==="boolean")o[c]=["true","1","yes"].includes(u.toLowerCase());else if(typeof h==="number"){let m=Number(u);if(!Number.isNaN(m))o[c]=m}else if(Array.isArray(h))try{o[c]=JSON.parse(u)}catch{o[c]=u.split(",").map((m)=>m.trim())}else o[c]=u;else if(h&&typeof h==="object"&&!Array.isArray(h))o[c]=n(h,f)}return o}return n(t)}function an(e){let t=F(ae.cwd(),e.configDir),r=F(ae.cwd(),e.generatedDir),i=F(r,"config-types.ts");if(!Nt(kr(i)))Ji(kr(i),{recursive:!0,mode:511});let s=Nt(t)?Hi(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],n=`// Generated by bunfig v${Rn}
32
+ export type ConfigNames = ${s.length?`'${s.join("' | '")}'`:"string"}
33
+ `;Gi(i,n,{mode:438})}function on(e){let t=null,r=null,i=()=>{if(!r)r=wi(e).then((n)=>(t=n,n),(n)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)H.warn("Config loading failed, using defaults:",[n instanceof Error?n:Error(String(n))]);return a});return r},s="defaultConfig"in e?e.defaultConfig:{};return t=s,i(),new Proxy({},{get(n,a){if(t)return t[a];let l=s[a];return i(),l},has(n,a){return a in(t||s)},ownKeys(){return Object.keys(t||s)},getOwnPropertyDescriptor(n,a){return Object.getOwnPropertyDescriptor(t||s,a)},set(n,a,l){if(!t)t={...s};return t[a]=l,!0}})}function ln(e){let t=Lr(bs.cwd(),e?.configDir||"./config");function r(){if(!ps(t))return[];let s=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),n=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=ys(t).filter((o)=>s.has($t(o))).map((o)=>({base:o.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:o})),l=new Map;for(let{base:o,file:c}of a){let h=$t(c).toLowerCase(),f=l.get(o);if(!f){l.set(o,c);continue}let g=$t(f).toLowerCase();if(n.indexOf(h)<n.indexOf(g))l.set(o,c)}return Array.from(l.entries()).map(([o,c])=>({base:o,file:c})).sort((o,c)=>o.base.localeCompare(c.base))}function i(){let s=r(),n=s.map((o)=>o.base),a=n.length?n.map((o)=>`'${o}'`).join(" | "):"string",l=s.length?`{
34
+ ${s.map((o)=>{let c=Lr(t,o.file).replace(/\\/g,"/");return` '${o.base}': typeof import('${c}').default`}).join(`,
35
+ `)}
36
+ }`:"Record<string, any>";return`export type ConfigNames = ${a}
37
+ export type ConfigByName = ${l}
38
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
+ export type ConfigOf = Config
40
+ `}return{name:"bunfig-plugin",setup(s){s.onResolve({filter:/^virtual:bunfig-types$/},(n)=>({path:n.path,namespace:"bunfig-virtual"})),s.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var vi,be,Se,$i,cn,hn,Gr,Ke,It,B,C,fn,Vr,un,Zr,gn,mn,xt,dn,qr,Yr,At,pn,yn,bn,wn,ze,Ci,vn,I,$n,Cn,Xr,Je,Rt,A,p,En,ei,kn,ti,Sn,xn,Tt,An,ri,ii,Tn,Ot,On,Mn,Nn,Pn,Bn,He,Ei,In,Rn="0.15.6",j,it,Ee,Dt,Ft,st,jt,Lt,ke,_t,Ut,ne,ki,Si,H,re,xi,Ai,Dn=Rs(async()=>{vi=import.meta.require,be=new qt,Se=new Yt,$i={createKey:Ds,isEquivalent:Fs,estimateMemoryUsage:js},cn=Ze(Pt.cwd(),"config"),hn=Ze(Pt.cwd(),"src/generated"),Gr=Ve.env.CLARITY_LOG_DIR||qi(Us(),"logs"),Ke={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Gr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},It=await Qs(),B={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},C=B,fn=B.red,Vr=B.green,un=B.yellow,Zr=B.blue,gn=B.magenta,mn=B.cyan,xt=B.white,dn=B.gray,qr=B.bgRed,Yr=B.bgYellow,At=B.bold,pn=B.dim,yn=B.italic,bn=B.underline,wn=B.reset,ze={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ci={debug:"\uD83D\uDD0D",info:Zr("\u2139"),success:Vr("\u2713"),warning:Yr(xt(At(" WARN "))),error:qr(xt(At(" ERROR ")))},vn=new et("stacks"),I=new et("bunfig",{showTags:!0}),$n=D(Ce.cwd(),"config"),Cn=D(Ce.cwd(),"src/generated"),Xr=Ge.env.CLARITY_LOG_DIR||Vi(Js(),"logs"),Je={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Xr,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Rt=await Hs(),A={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},p=A,En=A.red,ei=A.green,kn=A.yellow,ti=A.blue,Sn=A.magenta,xn=A.cyan,Tt=A.white,An=A.gray,ri=A.bgRed,ii=A.bgYellow,Tn=A.bgGray,Ot=A.bold,On=A.dim,Mn=A.italic,Nn=A.underline,Pn=A.strikethrough,Bn=A.reset,He={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ei={debug:"\uD83D\uDD0D",info:ti("\u2139"),success:ei("\u2713"),warning:ii(Tt(Ot(" WARN "))),error:ri(Tt(Ot(" ERROR ")))},In=new rt("stacks"),j=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},it=class extends j{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},Ee=class extends j{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Dt=class extends j{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Ft=class extends j{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},st=class extends j{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},jt=class extends j{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Lt=class extends j{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},ke=class extends j{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},_t=class extends j{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},Ut=class extends j{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},ne={configNotFound(e,t,r){return new it(e,t,r)},configLoad(e,t,r){return new Ee(e,t,r)},configValidation(e,t,r){return new Dt(e,t,r)},configMerge(e,t,r,i){return new Ft(e,t,r,i)},envVar(e,t,r,i){return new st(e,t,r,i)},fileSystem(e,t,r){return new jt(e,t,r)},typeGeneration(e,t,r){return new Lt(e,t,r)},schemaValidation(e,t,r){return new ke(e,t,r)},browserConfig(e,t,r,i){return new _t(e,t,r,i)},plugin(e,t,r){return new Ut(e,t,r)}},ki={replace:"replace",concat:"concat",smart:"smart"},Si=/^https?:\/\//,H=new rt("bunfig",{showTags:!0}),re=new ir,xi=F(ae.cwd(),"config"),Ai=F(ae.cwd(),"src/generated")});function Fn(e,t={}){let r=qe.cwd();while(r.includes("storage"))r=_r(r,"..");let i=_r(r,e||"");if(t?.relative)return vs(qe.cwd(),i);return i}var jn=qe.env.CLARITY_LOG_DIR||ws(Fn(),"logs"),Ti={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:jn,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},nt={...Ti},Po=(async()=>{try{let{loadConfig:e}=await Dn().then(()=>fi),t=await e({name:"clarity",alias:"logging",defaultConfig:Ti,cwd:qe.cwd()});if(t)Object.assign(nt,t)}catch{}return nt})();function T(){if(te.env.NODE_ENV==="test"||te.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ln(){if(te.env.NODE_ENV==="test"||te.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof te<"u"){let e=te.type;if(e==="renderer"||e==="worker")return!1;return!!(te.versions&&(te.versions.node||te.versions.bun))}return!1}class Oi{async format(e){let t=await Ln(),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:ye.pid,hostname:t(),environment:ye.env.NODE_ENV||"development",platform:ye.platform,version:ye.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ye.env.NODE_ENV||ye.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var O={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"},y=O,Bo=O.red,_n=O.green,Io=O.yellow,Un=O.blue,Ro=O.magenta,Do=O.cyan,si=O.white,Fo=O.gray,Qn=O.bgRed,Wn=O.bgYellow,jo=O.bgGray,ni=O.bold,Lo=O.dim,_o=O.italic,Uo=O.underline,Qo=O.strikethrough,Wo=O.reset,Mt={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Kn={debug:"\uD83D\uDD0D",info:Un("\u2139"),success:_n("\u2713"),warning:Wn(si(ni(" WARN "))),error:Qn(si(ni(" ERROR ")))};class ft{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={...nt},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Oi,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??w.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let s=this.generateKeyId(),n=this.generateKey();this.currentKeyId=s,this.keys.set(s,n),this.encryptionKeys.set(s,{key:n,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{...Mt,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Mt};return{...Mt,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:nt.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(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!T()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,s=0,n=3,a=1000;while(s<n)try{try{try{await Ss(this.config.logDirectory,Kr.F_OK|Kr.W_OK)}catch(o){if(o instanceof Error&&"code"in o)if(o.code==="ENOENT")await xs(this.config.logDirectory,{recursive:!0,mode:493});else if(o.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw o;else throw o}}catch(o){throw console.error("Debug: [writeToFile] Failed to create log directory:",o),o}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:q.from(e);try{if(!Re(this.currentLogFile))await kt(this.currentLogFile,"",{mode:420});if(i=Wr(this.currentLogFile,"a",420),ks(i,l,{flag:"a"}),Qr(i),i!==void 0)Et(i),i=void 0;if((await de(this.currentLogFile)).size===0){if(await kt(this.currentLogFile,l,{flag:"w",mode:420}),(await de(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(o){let c=o;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(s<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${n}:`,h);let f=a*2**s;await new Promise((g)=>setTimeout(g,f)),s++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(i!==void 0)try{Et(i)}catch(o){console.error("Debug: [writeToFile] Error closing file descriptor:",o)}}}catch(l){if(s===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}s++;let o=a*2**(s-1);await new Promise((c)=>setTimeout(c,o))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return pe(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return pe(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return pe(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(T())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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,a],[,l])=>l.createdAt.getTime()-a.createdAt.getTime()),s=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,s);if(i.length>n)for(let[a]of i.slice(n))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return Ct(16).toString("hex")}generateKey(){return Ct(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=Ct(16),i=$s("aes-256-gcm",t,r),s=q.isBuffer(e)?e:q.from(e,"utf8"),n=i.update(s),a=i.final(),l=n.length+a.length,o=i.getAuthTag(),c=q.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),a.copy(c,16+n.length),o.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Jr(),s=[];i.on("data",(n)=>s.push(n)),i.on("end",()=>t(q.from(q.concat(s)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(T())return;if(!this.shouldWriteToFile())return;let e=await de(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,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let s=await De(this.config.logDirectory),n=s.filter((o)=>o.startsWith(this.name)&&/\.log\.\d+$/.test(o)).sort((o,c)=>{let h=Number.parseInt(o.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),a=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${a}`;if(await de(r).catch(()=>null))try{if(await zr(r,l),t.compress)try{let o=`${l}.gz`;await this.compressLogFile(l,o),await Fe(l)}catch(o){console.error("Error compressing rotated file:",o)}if(n.length===0&&!s.some((o)=>o.endsWith(".log.1")))try{let o=`${r}.1`;await kt(o,"")}catch(o){console.error("Error creating backup file:",o)}}catch(o){console.error(`Error during rotation: ${o instanceof Error?o.message:String(o)}`)}}else{let s=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${s}.log`);if(await de(r).catch(()=>null))await zr(r,n)}if(this.currentLogFile=i,t.maxFiles){let s=(await De(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,a)=>a.localeCompare(n));for(let n of s.slice(t.maxFiles))await Fe(pe(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=Ur(e),i=Es(t),s=Jr();await Os(r,s,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(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()})),Re(this.currentLogFile))try{let e=Wr(this.currentLogFile,"r+");Qr(e),Et(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!T()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await De(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Fe(pe(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}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()?y.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T())return!1;let e=typeof w.env.NO_COLOR<"u",t=w.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof w.stderr<"u"&&w.stderr.isTTY||typeof w.stdout<"u"&&w.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:s,level:n,showTimestamp:a=!0}=e,l=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(a)u.push(t);if(n==="warning")u.push("WARN");else if(n==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)u.push(i.replace(/[[\]]/g,""));return u.push(s),u.join(" ")}let o=w.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${s}`;else if(n==="info"||n==="success")c=`${r} ${i} ${s}`;else c=`${r} ${i} ${y.cyan(s)}`;if(!a)return c.trim();let h=l(c).trim().length,f=l(t).length,g=Math.max(1,o-2-h-f);return`${c.trim()}${" ".repeat(g)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,a)=>{let l=Number.parseInt(a,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,i=0,s=e.replace(r,(n,a)=>{if(a==="%")return"%";if(i>=t.length)return n;let l=t[i++];switch(a){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(i<t.length)s+=` ${t.slice(i).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return s}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,s)=>{let n=y.underline(y.blue(i)),a=this.toAbsoluteFilePath(s);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(a)}`,o="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${s}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,i)=>y.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>y.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>y.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>y.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>y.strikethrough(i)),t}supportsHyperlinks(){if(T())return!1;let e=w.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=w.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(As(t)||t.startsWith("./")||t.startsWith("../"))t=Ts(t);else return null;return Re(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 i=new Date,s=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),a,l;if(t instanceof Error)a=t.message,l=t.stack;else a=this.formatMessage(t,r);let{consoleText:o,fileText:c}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Kn[e],g=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:y.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:y.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:s,icon:f,tag:g,message:o,level:e}),console.error(u),l){let d=l.split(`
41
+ `);for(let m of d)if(m.trim()&&!m.includes(a))console.error(this.formatConsoleMessage({timestamp:s,message:y.gray(` ${m}`),level:e,showTimestamp:!1}))}break}}else if(!T()){if(console.error(`${n} ${this.environment}.${e.toUpperCase()}: ${a}`),l)console.error(l)}let h=`${n} ${this.environment}.${e.toUpperCase()}: ${c}
42
+ `;if(l)h+=`${l}
43
+ `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(e,t=""){let r={update:(s,n)=>{},finish:(s)=>{},interrupt:(s,n)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(s,n)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,s),this.activeProgressBar.total),n!==void 0)this.activeProgressBar.message=n;if(this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(s)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,s)},interrupt:(s,n="info")=>{if(!T()&&w.stdout.isTTY)w.stdout.write(`
44
+ `);if(this[n==="warning"?"warn":n](s),this.activeProgressBar&&this.shouldStyleConsole()&&!T()&&w.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":y.blue("\u25D0"),tag:r,message:`${y.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),s=Math.round(i-t),n=`${e} completed in ${s}ms`,a=new Date,l=this.formatConsoleTimestamp(a),o=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${n}`;if(r)o+=` ${JSON.stringify(r)}`;if(o+=`
45
+ `,o=o.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:l,icon:this.options.showIcons===!1?"":y.green("\u2713"),tag:c,message:`${n}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!T())console.error(o.trim());if(this.shouldWriteToFile())await this.writeToFile(o)}}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 ft(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(T())throw Error("createReadStream is not supported in browser environments");if(!Re(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ur(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 i=q.isBuffer(e)?e:q.from(e,"base64"),s=i.subarray(0,16),n=i.subarray(i.length-16),a=i.subarray(16,i.length-16),l=Cs("aes-256-gcm",r,s);l.setAuthTag(n);let o=l.update(a),c=l.final(),h=o.length+c.length,f=q.allocUnsafe(h);return o.copy(f,0),c.copy(f,o.length),f.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T()}isServerMode(){return!T()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:s,fileText:n}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let l=s.split(`
46
+ `),o=Math.max(...l.map((g)=>g.length))+2,c=`\u250C${"\u2500".repeat(o)}\u2510`,h=`\u2514${"\u2500".repeat(o)}\u2518`,f=l.map((g)=>this.formatConsoleMessage({timestamp:r,message:y.cyan(g),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(c),showTimestamp:!1})),f.forEach((g)=>console.error(g)),console.error(this.formatConsoleMessage({timestamp:r,message:y.cyan(h),showTimestamp:!1}))}else if(!T())console.error(`${i} ${this.environment}.INFO: [BOX] ${n}`);let a=`${i} ${this.environment}.INFO: [BOX] ${n}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(T())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${y.cyan("?")} ${e} (y/n) `);let r=(i)=>{let s=i.toString().trim().toLowerCase();w.stdin.removeListener("data",r);try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!1)}catch{}w.stdin.pause(),console.error(""),t(s==="y"||s==="yes")};try{if(typeof w.stdin.setRawMode==="function")w.stdin.setRawMode(!0)}catch{}w.stdin.resume(),w.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(o,c)=>{if(c==="%")return"%";if(l>=t.length)return o;let h=t[l++];switch(c){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return o}}),l<t.length)r+=` ${t.slice(l).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}let{consoleText:i,fileText:s}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?y.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${y.blue("\u25D0")} `;console.error(`${l}${a} ${y.cyan(i)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${s}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(n)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!w.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),s=e.barLength-i,n=y.green("\u2501".repeat(i)),a=y.gray("\u2501".repeat(s)),l=`[${n}${a}]`,o=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",h=this.options.showIcons===!1?"":t||r===100?y.green("\u2713"):y.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${y.gray(this.formatTag(this.name))}`:"",g=`\r${h}${f} ${l} ${o}${c}`,u=w.stdout.columns||80,d=" ".repeat(Math.max(0,u-g.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${g}${d}`,w.stdout.write(e.lastRenderedLine),t)w.stdout.write(`
49
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||T()||!w.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(T()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await De(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=pe(this.config.logDirectory,i);if(e.before)try{if((await de(s)).mtime>=e.before)continue}catch(n){console.error(`Failed to get stats for file ${s}:`,n);continue}r.push(s)}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 i of r)try{await Fe(i),console.warn(`Deleted log file: ${i}`)}catch(s){console.error(`Failed to delete log file ${i}:`,s)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var Ko=new ft("stacks");class G extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class Mi extends G{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],s="";if(i.length===1)s=` or alias "${i[0]}"`;else if(i.length>1)s=` or aliases ${i.map((n)=>`"${n}"`).join(", ")}`;super(`Configuration "${e}"${s} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class at extends G{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class Ni extends G{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Pi extends G{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class sr extends G{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}}class Bi extends G{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ii extends G{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class ot extends G{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Ri extends G{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}}class Di extends G{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var we={configNotFound(e,t,r){return new Mi(e,t,r)},configLoad(e,t,r){return new at(e,t,r)},configValidation(e,t,r){return new Ni(e,t,r)},configMerge(e,t,r,i){return new Pi(e,t,r,i)},envVar(e,t,r,i){return new sr(e,t,r,i)},fileSystem(e,t,r){return new Bi(e,t,r)},typeGeneration(e,t,r){return new Ii(e,t,r)},schemaValidation(e,t,r){return new ot(e,t,r)},browserConfig(e,t,r,i){return new Ri(e,t,r,i)},plugin(e,t,r){return new Di(e,t,r)}};async function zn(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:s=()=>!0,fallback:n}=t,a=Error("Unknown error occurred");for(let l=0;l<=r;l++)try{return await e()}catch(o){if(a=o instanceof Error?o:Error(String(o)),l===r||!s(a))break;if(i>0)await new Promise((c)=>setTimeout(c,i))}if(n!==void 0)return n;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}class nr{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:i,useCamelCase:s=!0,useBackwardCompatibility:n=!0,customParsers:a={},verbose:l=!1,trackPerformance:o=!0}=r,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],h,{useCamelCase:s,useBackwardCompatibility:n,customParsers:a,verbose:l,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(o)return Zt.track("applyEnvironmentVariables",c,{configName:e});return c()}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,i){for(let[s,n]of Object.entries(e)){let a=[...t,s],l=a.map((h)=>this.formatEnvKey(h,i.useCamelCase)),o=`${r}_${l.join("_")}`,c=i.useBackwardCompatibility?`${r}_${a.map((h)=>h.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof n==="object"&&n!==null&&!Array.isArray(n))this.processObject(n,a,r,i);else{let h=je.env[o]||(c?je.env[c]:void 0);if(h!==void 0){if(i.verbose){let f=je.env[o]?o:c}try{e[s]=this.parseEnvironmentValue(h,typeof n,o,i.customParsers,i.configName)}catch(f){if(f instanceof sr)throw f;throw we.envVar(o,h,typeof n,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,s){for(let[n,a]of Object.entries(i))try{return a(e)}catch{continue}for(let n of this.defaultParsers)if(n.canParse(e,t))try{return n.parse(e)}catch{throw we.envVar(r,e,`${t} (via ${n.name} parser)`,s)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,s]of Object.entries(je.env))if(i.startsWith(r)&&s!==void 0)t[i]=s;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(s){i.push(`Cannot parse value "${t}" as ${r}: ${s}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:s="text"}=r,n=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],n,a),s){case"markdown":return this.formatAsMarkdown(a,e);case"json":return JSON.stringify(a,null,2);default:return this.formatAsText(a,e)}}extractEnvVarInfo(e,t,r,i){for(let[s,n]of Object.entries(e)){let a=[...t,s],l=`${r}_${a.map((o)=>this.formatEnvKey(o,!0)).join("_")}`;if(typeof n==="object"&&n!==null&&!Array.isArray(n))this.extractEnvVarInfo(n,a,r,i);else i.push({key:l,type:Array.isArray(n)?"array":typeof n,description:`Configuration for ${a.join(".")}`,example:this.generateExample(n)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
50
+
51
+ `;for(let i of e)r+=`${i.key}
52
+ `,r+=` Type: ${i.type}
53
+ `,r+=` Description: ${i.description}
54
+ `,r+=` Example: ${i.example}
55
+
56
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
57
+
58
+ `;r+=`| Variable | Type | Description | Example |
59
+ `,r+=`|----------|------|-------------|----------|
60
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
61
+ `;return r}}function Jn(e,t,r={}){return Fi(e,t,r,new WeakMap)}function Fi(e,t,r,i){let{arrayMergeMode:s="replace",skipNullish:n=!1,customMerger:a}=r;if(t===null||t===void 0)return n?e:t;if(a){let l=a(e,t);if(l!==void 0)return l}if(Array.isArray(t)||Array.isArray(e))return ji(e,t,s,i);if(!Q(t)||!Q(e))return t;return Zn(e,t,r,i)}function ji(e,t,r,i){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 Hn(e,t);case"smart":return Gn(e,t,i);default:return t}return t}function Hn(e,t){let r=[...t];for(let i of e)if(!r.some((s)=>Qt(s,i)))r.push(i);return r}function Gn(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Q(t[0])&&Q(e[0]))return Vn(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let s of e)if(!i.includes(s))i.push(s);return i}return t}function Vn(e,t,r){let i=[...t];for(let s of e){if(!Q(s)){i.push(s);continue}let n=["id","name","key","path","type"],a=!1;for(let l of n)if(l in s){if(i.find((o)=>Q(o)&&(l in o)&&o[l]===s[l])){a=!0;break}}if(!a)i.push(s)}return i}function Zn(e,t,r,i){let s=t;if(Q(s)&&i.has(s))return i.get(s);let n={...e};if(Q(s))i.set(s,n);for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;let l=s[a],o=n[a];if(r.skipNullish&&(l===null||l===void 0))continue;if(l===null||l===void 0){n[a]=l;continue}if(Q(l)&&Q(o))n[a]=Fi(o,l,r,i);else if(Array.isArray(l)||Array.isArray(o))n[a]=ji(o,l,r.arrayMergeMode||"smart",i);else n[a]=l}return n}function Li(e,t,r="replace"){return Jn(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Qt(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(!Qt(e[r],t[r]))return!1;return!0}if(Q(e)&&Q(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Qt(e[s],t[s]))return!1}return!0}return!1}function Q(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class _i{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:s=!0,cacheTtl:n,trackPerformance:a=!0,verbose:l=!1}=r;if(s){let c=Ye.getWithFileCheck("file",e);if(c){if(l)console.log(`Configuration loaded from cache: ${e}`);return c}}let o=async()=>{if(!Le(e))return null;try{let c=`?t=${Date.now()}`,h=await import(e+c),f=h.default||h,g="default"in h,u=Object.keys(h).length>0;if(!g&&!u)throw new at(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new at(e,Error("Configuration must export a valid object"),"unknown");let d={config:Li(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(s)Ye.setWithFileCheck("file",d,e,n);return d}catch(c){throw c instanceof Error?we.configLoad(e,c):we.configLoad(e,Error(String(c)))}};if(a)return Zt.track("loadFromPath",o,{path:e});return o()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let s=await this.loadFromPath(i,t,r);if(s)return s}catch(s){if(s instanceof Error&&s.name==="ConfigLoadError")throw s;if(r.verbose)console.warn(`Failed to load config from ${i}:`,s)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),s=[];for(let n of i)for(let a of this.extensions)s.push(St(t,`${n}${a}`));return s}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let n of i){if(!n)continue;if(r.push(n,`.${n}.config`,`${n}.config`,`.${n}`),e)r.push(`${e}.${n}.config`,`.${e}.${n}.config`)}let s=new Set;return r.filter((n)=>{if(!n||s.has(n))return!1;return s.add(n),!0})}checkFileAccess(e){return zn(async()=>Le(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Le(e))return i;if(t||r){let s=this.generateNamePatterns(t||"",r);for(let n of s)for(let a of this.extensions){let l=St(e,`${n}${a}`);if(await this.checkFileAccess(l))i.push(l)}}else try{let{readdirSync:s}=await import("fs"),n=s(e);for(let a of n)if(this.looksLikeConfigFile(a)){let l=St(e,a);if(await this.checkFileAccess(l))i.push(l)}}catch{return[]}return i}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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Le(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:s}=await import("fs"),n=s(e,"utf8");JSON.parse(n)}catch(s){t.push(`Invalid JSON syntax: ${s}`)}}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(i)=>{try{let s=await this.loadFromPath(i,{},t);if(s)r.set(i,s.config)}catch(s){if(t.verbose)console.warn(`Failed to preload ${i}:`,s)}})),r}}var qn=/^https?:\/\//;class Ui{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:s=!0,validateTypes:n=!0,customRules:a=[],trackPerformance:l=!0,verbose:o=!1}=r,c=async()=>{let h=[],f=[],g={stopOnFirstError:i,validateRequired:s,validateTypes:n,customRules:a,trackPerformance:l,verbose:o};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,g);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],g);else return this.validateWithJSONSchema(e,t,g)}catch(u){return h.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:h,warnings:f}}};if(l)return await Zt.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!Ms(t))throw new ot(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),s=i.default||i;if(Array.isArray(s))return this.validateWithRules(e,s,r);else return this.validateWithJSONSchema(e,s,r)}catch(i){throw new ot(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],s=[];return this.validateObjectAgainstSchema(e,t,"",i,s,r),{isValid:i.length===0,errors:i,warnings:s}}validateObjectAgainstSchema(e,t,r,i,s,n){if(n.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,l=Array.isArray(t.type)?t.type:[t.type];if(!l.includes(a)){if(i.push({path:r,message:`Expected type ${l.join(" or ")}, got ${a}`,expected:l.join(" or "),actual:a,rule:"type"}),n.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),n.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.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)i.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))i.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)i.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)i.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 a=0;a<e.length;a++){let l=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,l,i,s,n),n.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(n.validateRequired&&t.required){for(let l of t.required)if(!(l in a)){if(i.push({path:r?`${r}.${l}`:l,message:`Missing required property '${l}'`,expected:"required",rule:"required"}),n.stopOnFirstError)return}}if(t.properties){for(let[l,o]of Object.entries(t.properties))if(l in a){let c=r?`${r}.${l}`:l;if(this.validateObjectAgainstSchema(a[l],o,c,i,s,n),n.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let l=new Set(Object.keys(t.properties||{}));for(let o of Object.keys(a))if(!l.has(o))s.push({path:r?`${r}.${o}`:o,message:`Additional property '${o}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],s=[];for(let n of t)try{let a=this.getValueByPath(e,n.path),l=this.validateWithRule(a,n,n.path);if(i.push(...l),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:n.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:s}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let s=Array.isArray(e)?"array":typeof e;if(s!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${s}`,expected:t.type,actual:s,rule:"type"})}if(t.min!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:s,rule:"min"})}if(t.max!==void 0){let s=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(s>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:s,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.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))i.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 s=t.validator(e);if(s)i.push({path:r,message:t.message||s,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let s of r)if(i&&typeof i==="object"&&s in i)i=i[s];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,s,n,a]=i;t.push({path:s,required:!n,type:this.mapTypeScriptType(a)})}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:qn},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Y=new ft("bunfig",{showTags:!0});function Yn(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 Qi{fileLoader=new _i;envProcessor=new nr;validator=new Ui;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:s,validate:n,...a}=e;try{if(r?.enabled){let o=this.checkCache(a.name||"",a);if(o)return o}let l;try{l=await this.loadConfigurationStrategies(a,!0,r)}catch(o){let c=a.__strictErrorHandling;if(o instanceof Error&&o.name==="ConfigNotFoundError"){if(c)throw o;l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`No configuration file found for "${a.name||"config"}", using defaults with environment variables`]}}else if(o instanceof Error&&o.name==="ConfigLoadError"){let h=o.message.includes("EACCES")||o.message.includes("EPERM")||o.message.includes("permission denied"),f=!h&&(o.message.includes("syntax")||o.message.includes("Expected")||o.message.includes("Unexpected")||o.message.includes("BuildMessage")||o.message.includes("errors building")),g=o.message.includes("Configuration must export a valid object")||o.message.includes("Configuration file is empty and exports nothing");if(c&&(g||h))throw o;if(f&&(!c||!g))l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!c)l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${o.message}`]};else throw o}else l={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${o instanceof Error?o.message:String(o)}`]}}if(s||n)await this.validateConfiguration(l.config,s,n,a.name);if(r?.enabled&&l)this.cacheResult(a.name||"",l,r,a);if(i?.enabled){let o={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(o);if(i.slowThreshold&&o.duration>i.slowThreshold)Y.warn(`Slow configuration loading detected: ${o.duration}ms for ${a.name}`);l.metrics=o}return l}catch(l){if(l instanceof Error&&l.name==="ConfigNotFoundError")throw l;let o=Date.now()-t;throw Y.error(`Configuration loading failed after ${o}ms:`,[l instanceof Error?l:Error(String(l))]),l}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:s,cwd:n,configDir:a,defaultConfig:l,checkEnv:o=!0,arrayStrategy:c="replace",verbose:h=!1}=e,f=n||lt.cwd(),g=[],u=await this.loadLocalConfiguration(i,s,f,a,l,c,h,o,r);if(u)return g.push(...this.getLocalSearchPaths(i,s,f,a)),this.finalizeResult(u,g,o,i,h);let d=await this.loadHomeConfiguration(i,s,l,c,h,o);if(d)return g.push(...this.getHomeSearchPaths(i,s)),this.finalizeResult(d,g,o,i,h);let m=await this.loadPackageJsonConfiguration(i,s,f,l,c,h,o);if(m)return g.push(_(f,"package.json")),this.finalizeResult(m,g,o,i,h);if(g.push(...this.getAllSearchPaths(i,s,f,a)),t)throw we.configNotFound(i,g,s);return{...await this.applyEnvironmentVariables(i,l,o,h),warnings:[`No configuration file found for "${i}"${Yn(s)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,s,n,a,l,o){let c=l?Ue(e,s,a):s,h=this.getLocalDirectories(r,i);for(let f of h){if(a)Y.info(`Searching for configuration in: ${f}`);let g=this.fileLoader.generateConfigPaths(e,f,t),u=await this.fileLoader.tryLoadFromPaths(g,c,{arrayStrategy:n,verbose:a,cacheTtl:o?.ttl,useCache:!o?.ttl||o.ttl>100});if(u){if(a)Y.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(e,t,r,i,s,n){if(!e)return null;let a=n?Ue(e,r,s):r,l=[_(oe(),".config",e),_(oe(),".config"),oe()];for(let o of l){if(s)Y.info(`Checking home directory: ${o}`);let c=this.fileLoader.generateConfigPaths(e,o,t),h=await this.fileLoader.tryLoadFromPaths(c,a,{arrayStrategy:i,verbose:s});if(h){if(s)Y.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(e,t,r,i,s,n,a){let l=a?Ue(e,i,n):i;try{let o=_(r,"package.json");if(!Ki(o))return null;let c={};try{c=JSON.parse(zi(o,"utf8"))}catch(g){if(n)Y.warn("Failed to parse package.json:",[g instanceof Error?g:Error(String(g))]);return null}let h=c[e],f=e;if(!h&&t){let g=Array.isArray(t)?t:[t];for(let u of g){if(!u)continue;if(c[u]){h=c[u],f=u;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(n)Y.success(`Configuration loaded from package.json: ${f}`);return{config:Li(l,h,s),source:{type:"package.json",path:o,priority:30,timestamp:new Date}}}}catch(o){if(n)Y.warn("Failed to load package.json:",[o instanceof Error?o:Error(String(o))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ue(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,s){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let s=[];if(r){let n=r(e);if(n)s.push(...n)}if(t){let n=await this.validator.validateConfiguration(e,t);if(!n.isValid)s.push(...n.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(s.length>0)throw we.configValidation(i||"unknown",s,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Ye.get(r)||null}cacheResult(e,t,r,i){let s=this.generateCacheKey(e,i);Ye.set(s,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}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,_(e,"config"),_(e,".config"),t?_(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let s=[];return s.push(...this.getLocalSearchPaths(e,t,r,i)),s.push(...this.getHomeSearchPaths(e,t)),s.push(_(r,"package.json")),s}getLocalSearchPaths(e,t,r,i){let s=this.getLocalDirectories(r,i),n=[];for(let a of s)n.push(...this.fileLoader.generateConfigPaths(e,a,t));return n}getHomeSearchPaths(e,t){if(!e)return[];let r=[_(oe(),".config",e),_(oe(),".config"),oe()],i=[];for(let s of r)i.push(...this.fileLoader.generateConfigPaths(e,s,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}var zo=new Qi;function Ue(e,t,r=!1){let i=new nr,s=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function n(a,l=[]){let o={...a};for(let[c,h]of Object.entries(a)){let f=[...l,c],g=[`${s}_${f.join("_").toUpperCase()}`,`${s}_${f.map((m)=>m.toUpperCase()).join("")}`,`${s}_${f.map((m)=>m.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,d;for(let m of g)if(u=lt.env[m],u!==void 0){d=m;break}if(u!==void 0&&d)if(typeof h==="boolean")o[c]=["true","1","yes"].includes(u.toLowerCase());else if(typeof h==="number"){let m=Number(u);if(!Number.isNaN(m))o[c]=m}else if(Array.isArray(h))try{o[c]=JSON.parse(u)}catch{o[c]=u.split(",").map((m)=>m.trim())}else o[c]=u;else if(h&&typeof h==="object"&&!Array.isArray(h))o[c]=n(h,f)}return o}return n(t)}var Jo=_(lt.cwd(),"config"),Ho=_(lt.cwd(),"src/generated"),Xn={verbose:!1,driver:"bun",default:"bun",connections:{bun:{driver:"bun",host:"0.0.0.0",port:6001,scheme:"ws",options:{idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,closeOnBackpressureLimit:!1,sendPings:!0,publishToSelf:!1,perMessageDeflate:!0}},reverb:{driver:"reverb",host:"127.0.0.1",port:8080,scheme:"ws",key:ie.env.REVERB_APP_KEY,secret:ie.env.REVERB_APP_SECRET,appId:ie.env.REVERB_APP_ID,options:{idleTimeout:120,maxPayloadLength:16777216}},pusher:{driver:"pusher",key:ie.env.PUSHER_APP_KEY,secret:ie.env.PUSHER_APP_SECRET,appId:ie.env.PUSHER_APP_ID,cluster:ie.env.PUSHER_APP_CLUSTER||"mt1",useTLS:!0},ably:{driver:"ably",key:ie.env.ABLY_KEY},log:{driver:"log"},null:{driver:"null"}}};class ar{config;keys=new Map;channelKeys=new Map;constructor(e={}){this.config={enabled:e.enabled??!1,algorithm:e.algorithm||"aes-256-gcm",keyRotationInterval:e.keyRotationInterval||86400000,channelKeys:e.channelKeys||new Map},this.channelKeys=new Map(this.config.channelKeys)}isEnabled(){return this.config.enabled}async setChannelKey(e,t){this.channelKeys.set(e,t);let r=Qe.from(t,"hex"),i=await crypto.subtle.importKey("raw",r,{name:"AES-GCM"},!1,["encrypt","decrypt"]);this.keys.set(e,i)}async generateChannelKey(e){let t=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("raw",t),i=Qe.from(r).toString("hex");return await this.setChannelKey(e,i),i}async encrypt(e,t){if(!this.config.enabled){if(t===void 0)return"undefined";return JSON.stringify(t)}let r=this.keys.get(e);if(!r)throw Error(`No encryption key found for channel: ${e}`);let i=t===void 0?"undefined":JSON.stringify(t),s=crypto.getRandomValues(new Uint8Array(12)),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},r,new TextEncoder().encode(i)),a=new Uint8Array(s.length+n.byteLength);return a.set(s,0),a.set(new Uint8Array(n),s.length),Qe.from(a).toString("base64")}async decrypt(e,t){if(!this.config.enabled){if(t==="undefined")return;return JSON.parse(t)}let r=this.keys.get(e);if(!r)throw Error(`No encryption key found for channel: ${e}`);let i=Qe.from(t,"base64"),s=i.slice(0,12),n=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,n),l=new TextDecoder().decode(a);if(l==="undefined")return;return JSON.parse(l)}hasChannelKey(e){return this.channelKeys.has(e)}getChannelKey(e){return this.channelKeys.get(e)}async rotateChannelKey(e){return this.generateChannelKey(e)}removeChannelKey(e){this.channelKeys.delete(e),this.keys.delete(e)}}class or{server;broadcaster;constructor(e,t){this.server=e,this.broadcaster=t}toUser(e,t,r){this.broadcaster.send(`private-user.${e}`,t,r)}toUsers(e,t,r){let i=e.map((s)=>`private-user.${s}`);this.broadcaster.send(i,t,r)}exceptUsers(e,t,r,i){let s=this.server.channels.getSubscribers(t),n=new Set(e.map((a)=>`private-user.${a}`));for(let a of s)if(!Array.from(n).some((l)=>this.server.channels.getChannel(l).subscribers.has(a))){this.broadcaster.send(t,r,i);break}}toAll(e,t){this.broadcaster.send("broadcast",e,t)}toRole(e,t,r){this.broadcaster.send(`role.${e}`,t,r)}notify(e,t){this.toUser(e,"notification",t)}notifyUsers(e,t){this.toUsers(e,"notification",t)}systemMessage(e,t="info"){this.toAll("system.message",{message:e,type:t,timestamp:Date.now()})}modelUpdated(e,t,r){this.broadcaster.send(`model.${e}.${t}`,"updated",r)}modelCreated(e,t){this.broadcaster.send(`model.${e}`,"created",t)}modelDeleted(e,t){this.broadcaster.send(`model.${e}.${t}`,"deleted",{id:t})}getUserConnectionCount(e){return this.server.channels.getSubscriberCount(`private-user.${e}`)}isUserOnline(e){return this.getUserConnectionCount(e)>0}getOnlineUsers(e){let t=e.startsWith("presence-")?e:`presence-${e}`,r=this.server.channels.getPresenceMembers(t);if(!r)return[];return Array.from(r.values())}getPresenceCount(e){let t=e.startsWith("presence-")?e:`presence-${e}`;return this.server.channels.getSubscriberCount(t)}}class lr{hooks=new Map;on(e,t){if(!this.hooks.has(e))this.hooks.set(e,new Set);this.hooks.get(e).add(t)}off(e,t){this.hooks.get(e)?.delete(t)}async fire(e){let t=this.hooks.get(e.event);if(t)for(let i of t)try{await i(e)}catch(s){console.error(`Error in lifecycle hook for ${e.event}:`,s)}let r=this.hooks.get("all");if(r)for(let i of r)try{await i(e)}catch(s){console.error("Error in 'all' lifecycle hook:",s)}}async channelCreated(e,t){await this.fire({channel:e,event:"created",timestamp:Date.now(),socketId:t})}async channelSubscribed(e,t,r){await this.fire({channel:e,event:"subscribed",timestamp:Date.now(),socketId:t,subscriberCount:r})}async channelUnsubscribed(e,t,r){await this.fire({channel:e,event:"unsubscribed",timestamp:Date.now(),socketId:t,subscriberCount:r})}async channelEmpty(e){await this.fire({channel:e,event:"empty",timestamp:Date.now(),subscriberCount:0})}async channelDestroyed(e){await this.fire({channel:e,event:"destroyed",timestamp:Date.now()})}}class cr{config;connectionCount=0;channelCount=0;channelsPerConnection=new Map;constructor(e={}){this.config={maxConnections:e.maxConnections??1e4,maxChannelsPerConnection:e.maxChannelsPerConnection??100,maxGlobalChannels:e.maxGlobalChannels??50000,shedLoadAt:e.shedLoadAt??90,backpressureThreshold:e.backpressureThreshold??1048576}}canAcceptConnection(){return this.connectionCount<this.config.maxConnections}shouldShedLoad(){let e=this.connectionCount/this.config.maxConnections*100,t=this.channelCount/this.config.maxGlobalChannels*100;return e>=this.config.shedLoadAt||t>=this.config.shedLoadAt}registerConnection(e){this.connectionCount++,this.channelsPerConnection.set(e,0)}unregisterConnection(e){this.connectionCount=Math.max(0,this.connectionCount-1);let t=this.channelsPerConnection.get(e)||0;this.channelCount=Math.max(0,this.channelCount-t),this.channelsPerConnection.delete(e)}canSubscribe(e){if((this.channelsPerConnection.get(e)||0)>=this.config.maxChannelsPerConnection)return!1;if(this.channelCount>=this.config.maxGlobalChannels)return!1;return!0}registerSubscription(e){let t=this.channelsPerConnection.get(e)||0;this.channelsPerConnection.set(e,t+1),this.channelCount++}unregisterSubscription(e){let t=this.channelsPerConnection.get(e)||0;if(t>0)this.channelsPerConnection.set(e,t-1),this.channelCount=Math.max(0,this.channelCount-1)}shouldApplyBackpressure(e){return e>this.config.backpressureThreshold}getStats(){let e=Array.from(this.channelsPerConnection.values()).reduce((r,i)=>r+i,0),t=this.connectionCount>0?e/this.connectionCount:0;return{connections:this.connectionCount,channels:this.channelCount,averageChannelsPerConnection:t,memoryUsage:ea.memoryUsage().heapUsed,isOverloaded:this.shouldShedLoad()}}getConnectionUsage(){return this.connectionCount/this.config.maxConnections*100}getChannelUsage(){return this.channelCount/this.config.maxGlobalChannels*100}}class hr{callback=null;config;constructor(e={}){this.config={enabled:e.enabled??!0,cookie:{name:e.cookie?.name||"auth_token",secure:e.cookie?.secure??!0},jwt:{secret:e.jwt?.secret||ta.env.JWT_SECRET||"",algorithm:e.jwt?.algorithm||"HS256"},session:{key:e.session?.key||"session_id"}}}authenticate(e){this.callback=e}async authenticateRequest(e){if(!this.config.enabled)return null;if(this.callback)return await this.callback(e);let t=e.headers.get("cookie");if(t){let i=this.parseCookies(t)[this.config.cookie.name];if(i)return this.verifyToken(i)}let r=e.headers.get("authorization");if(r?.startsWith("Bearer ")){let i=r.slice(7);return this.verifyToken(i)}return null}parseCookies(e){let t={};for(let r of e.split(";")){let[i,...s]=r.split("=");t[i.trim()]=s.join("=").trim()}return t}async verifyToken(e){try{let t=e.split(".");if(t.length===3){let r=JSON.parse(atob(t[1]));return{id:r.sub||r.id,...r}}}catch(t){console.error("Error verifying token:",t)}return null}}class fr{limits=new Map;config;cleanupTimer;constructor(e){this.config={max:e.max||100,window:e.window||60000,perChannel:e.perChannel??!1,perUser:e.perUser??!1},this.cleanupTimer=setInterval(()=>this.cleanup(),60000)}check(e,t){let r=this.getKey(e,t),i=Date.now(),s=this.limits.get(r);if(!s||s.resetAt<i)return this.limits.set(r,{count:1,resetAt:i+this.config.window}),!1;if(s.count>=this.config.max)return!0;return s.count++,!1}getRemaining(e,t){let r=this.getKey(e,t),i=this.limits.get(r);if(!i||i.resetAt<Date.now())return this.config.max;return Math.max(0,this.config.max-i.count)}getResetAt(e,t){let r=this.getKey(e,t);return this.limits.get(r)?.resetAt||Date.now()}getKey(e,t){let r=[];if(this.config.perUser&&e.data.user)r.push(`user:${e.data.user.id}`);else r.push(`socket:${e.data.socketId}`);if(this.config.perChannel&&t)r.push(`channel:${t}`);return r.join(":")}cleanup(){let e=Date.now();for(let[t,r]of this.limits.entries())if(r.resetAt<e)this.limits.delete(t)}clear(){this.limits.clear()}stop(){clearInterval(this.cleanupTimer)}}class ur{validators=new Set;addValidator(e){this.validators.add(e)}removeValidator(e){this.validators.delete(e)}validate(e){for(let t of this.validators){let r=t(e);if(r===!1)return{valid:!1,error:"Validation failed"};if(typeof r==="string")return{valid:!1,error:r}}return{valid:!0}}}class gr{callbacks=new Map;metrics=new Map;on(e,t){if(!this.callbacks.has(e))this.callbacks.set(e,new Set);this.callbacks.get(e).add(t)}off(e,t){let r=this.callbacks.get(e);if(r)r.delete(t)}emit(e){this.incrementMetric(e.type);let t=this.callbacks.get(e.type);if(t)for(let i of t)i(e);let r=this.callbacks.get("all");if(r)for(let i of r)i(e)}incrementMetric(e,t=1){let r=this.metrics.get(e)||0;this.metrics.set(e,r+t)}getMetric(e){return this.metrics.get(e)||0}getMetrics(){return Object.fromEntries(this.metrics)}resetMetrics(){this.metrics.clear()}}class mr{config;constructor(e={}){this.config={cors:{enabled:e.cors?.enabled??!0,origins:e.cors?.origins||["*"],credentials:e.cors?.credentials??!0},maxPayloadSize:e.maxPayloadSize||1048576,sanitizeMessages:e.sanitizeMessages??!0}}checkOrigin(e){if(!this.config.cors?.enabled)return!0;if(this.config.cors.origins?.includes("*"))return!0;return this.config.cors.origins?.includes(e)??!1}sanitize(e){if(!this.config.sanitizeMessages)return e;if(typeof e==="string")return e.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\x27/g,"&#x27;").replace(/\//g,"&#x2F;");if(Array.isArray(e))return e.map((t)=>this.sanitize(t));if(e&&typeof e==="object"){let t={};for(let[r,i]of Object.entries(e))t[r]=this.sanitize(i);return t}return e}checkSize(e){return e.length<=this.config.maxPayloadSize}}class dr{config;redis;inMemoryStore=new Map;constructor(e={},t){this.config={enabled:e.enabled??!1,ttl:e.ttl??3600,maxMessages:e.maxMessages??100,excludeEvents:e.excludeEvents||["ping","pong"]},this.redis=t}async store(e,t,r,i){if(!this.config.enabled)return;if(this.config.excludeEvents.includes(t))return;let s={id:crypto.randomUUID(),event:t,data:r,timestamp:Date.now(),socketId:i};if(this.redis)await this.storeInRedis(e,s);else this.storeInMemory(e,s)}async getHistory(e,t,r){if(!this.config.enabled)return[];if(this.redis)return this.getHistoryFromRedis(e,t,r);return this.getHistoryFromMemory(e,t,r)}async clear(e){if(this.redis){let t=this.getRedisKey(e),r=this.redis;if(r.publisher)await r.publisher.del(t)}else this.inMemoryStore.delete(e)}async storeInRedis(e,t){if(!this.redis)return;let r=this.getRedisKey(e),i=JSON.stringify(t),s=this.redis;if(!s.publisher)return;await s.publisher.zadd(r,t.timestamp,i);let n=-this.config.maxMessages-1;await s.publisher.send("ZREMRANGEBYRANK",[r,"0",n.toString()]),await s.publisher.expire(r,this.config.ttl)}async getHistoryFromRedis(e,t,r){if(!this.redis)return[];let i=this.getRedisKey(e),s=t?.toString()||"-inf",n="+inf",a=r||this.config.maxMessages,l=this.redis;if(!l.publisher)return[];return(await l.publisher.send("ZRANGEBYSCORE",[i,s,n,"LIMIT","0",a.toString()])).map((o)=>JSON.parse(o))}storeInMemory(e,t){if(!this.inMemoryStore.has(e))this.inMemoryStore.set(e,[]);let r=this.inMemoryStore.get(e);if(r.push(t),r.length>this.config.maxMessages)r.shift();let i=Date.now()-this.config.ttl*1000,s=r.filter((n)=>n.timestamp>i);this.inMemoryStore.set(e,s)}getHistoryFromMemory(e,t,r){let i=this.inMemoryStore.get(e)||[],s=i;if(t!==void 0)s=i.filter((n)=>n.timestamp>=t);if(r)s=s.slice(0,r);return s}getRedisKey(e){return`history:${e}`}async getStats(){if(this.redis){let r=this.redis;if(!r.publisher)return{totalChannels:0,totalMessages:0,channels:{}};let i=await r.publisher.send("KEYS",["history:*"]),s=0,n={};for(let a of i){let l=await r.publisher.send("ZCARD",[a]),o=a.replace("history:",""),c=Number(l);n[o]=c,s+=c}return{totalChannels:i.length,totalMessages:s,channels:n}}let e=0,t={};for(let[r,i]of this.inMemoryStore.entries())t[r]=i.length,e+=i.length;return{totalChannels:this.inMemoryStore.size,totalMessages:e,channels:t}}}class pr{config;presenceUsers=new Map;heartbeatTimer;onRemove;constructor(e={}){this.config={enabled:e.enabled??!0,interval:e.interval??30000,timeout:e.timeout??60000,requireClientHeartbeat:e.requireClientHeartbeat??!0}}start(){if(!this.config.enabled)return;this.heartbeatTimer=setInterval(()=>{this.checkHeartbeats()},this.config.interval)}stop(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer)}onUserRemove(e){this.onRemove=e}heartbeat(e,t,r){if(!this.config.enabled)return;if(!this.presenceUsers.has(e))this.presenceUsers.set(e,new Map);let i=this.presenceUsers.get(e),s=i.get(t);i.set(t,{socketId:t,lastSeen:Date.now(),data:r||s?.data})}remove(e,t){let r=this.presenceUsers.get(e);if(r){if(r.delete(t),r.size===0)this.presenceUsers.delete(e)}}checkHeartbeats(){let e=Date.now(),t=this.config.timeout;for(let[r,i]of this.presenceUsers.entries()){let s=[];for(let[n,a]of i.entries())if(e-a.lastSeen>t)s.push(n);for(let n of s){let a=i.get(n);if(i.delete(n),this.onRemove&&a)this.onRemove(r,n,a.data)}if(i.size===0)this.presenceUsers.delete(r)}}getActiveUsers(e){let t=this.presenceUsers.get(e);if(!t)return[];return Array.from(t.values())}isActive(e,t){let r=this.presenceUsers.get(e)?.get(t);if(!r)return!1;return Date.now()-r.lastSeen<this.config.timeout}getStats(){let e=0;for(let t of this.presenceUsers.values())e+=t.size;return{channels:this.presenceUsers.size,totalUsers:e}}}var{RedisClient:ai}=globalThis.Bun;class yr{publisher;subscriber;config;serverId;messageHandlers=new Set;get client(){return this.publisher}constructor(e){this.serverId=crypto.randomUUID(),this.config={host:e.host||ve.env.REDIS_HOST||"localhost",port:e.port||Number.parseInt(ve.env.REDIS_PORT||"6379"),password:e.password||ve.env.REDIS_PASSWORD||"",database:e.database||Number.parseInt(ve.env.REDIS_DB||"0"),url:e.url||ve.env.REDIS_URL||"",keyPrefix:e.keyPrefix||"broadcasting:"};let t=this.config.url||this.buildRedisUrl();this.publisher=new ai(t||"redis://localhost:6379"),this.subscriber=new ai(t||"redis://localhost:6379")}buildRedisUrl(){return`redis://${this.config.password?`:${this.config.password}@`:""}${this.config.host}:${this.config.port}/${this.config.database}`}async connect(){await Promise.all([this.publisher.connect(),this.subscriber.connect()]),await this.subscriber.subscribe(`${this.config.keyPrefix}channel`,(e)=>{this.handleRedisMessage(e)})}close(){this.publisher.close(),this.subscriber.close()}async broadcast(e,t,r,i){let s={type:"broadcast",channel:e,event:t,data:r,socketId:i,serverId:this.serverId};await this.publisher.publish(`${this.config.keyPrefix}channel`,JSON.stringify(s))}onMessage(e){this.messageHandlers.add(e)}offMessage(e){this.messageHandlers.delete(e)}handleRedisMessage(e){try{let t=JSON.parse(e);if(t.serverId===this.serverId)return;for(let r of this.messageHandlers)r(t)}catch(t){console.error("Error handling Redis message:",t)}}async storeChannel(e,t){let r=`${this.config.keyPrefix}channels:${e}`;await this.publisher.sadd(r,t),await this.publisher.expire(r,3600)}async removeChannel(e,t){let r=`${this.config.keyPrefix}channels:${e}`;await this.publisher.srem(r,t)}async getChannelSubscribers(e){let t=`${this.config.keyPrefix}channels:${e}`;return await this.publisher.smembers(t)}async storePresenceMember(e,t,r){let i=`${this.config.keyPrefix}presence:${e}`;await this.publisher.hmset(i,[t,JSON.stringify(r)]),await this.publisher.expire(i,3600)}async removePresenceMember(e,t){let r=`${this.config.keyPrefix}presence:${e}`;await this.publisher.send("HDEL",[r,t])}async getPresenceMembers(e){let t=`${this.config.keyPrefix}presence:${e}`,r=await this.publisher.send("HGETALL",[t]),i=new Map;for(let s=0;s<r.length;s+=2){let n=r[s],a=r[s+1];try{i.set(n,JSON.parse(a))}catch{console.error(`Error parsing presence member data for ${n}`)}}return i}async incrementStat(e){let t=`${this.config.keyPrefix}stats:${e}`;await this.publisher.incr(t)}async getStats(){let e=await this.publisher.send("KEYS",[`${this.config.keyPrefix}stats:*`]),t={};for(let r of e){let i=await this.publisher.get(r),s=r.replace(`${this.config.keyPrefix}stats:`,"");t[s]=Number.parseInt(i||"0")}return t}async storeConnection(e,t){let r=`${this.config.keyPrefix}connections:${e}`;await this.publisher.set(r,JSON.stringify(t)),await this.publisher.expire(r,7200)}async removeConnection(e){let t=`${this.config.keyPrefix}connections:${e}`;await this.publisher.del(t)}async getConnection(e){let t=`${this.config.keyPrefix}connections:${e}`,r=await this.publisher.get(t);if(!r)return null;try{return JSON.parse(r)}catch{return console.error(`Error parsing connection data for ${e}`),null}}async getTotalConnections(){return(await this.publisher.send("KEYS",[`${this.config.keyPrefix}connections:*`])).length}async getTotalChannels(){return(await this.publisher.send("KEYS",[`${this.config.keyPrefix}channels:*`])).length}async healthCheck(){try{return await this.publisher.send("PING",[]),!0}catch{return!1}}getServerId(){return this.serverId}}class br{config;endpoints;constructor(e={}){this.config={enabled:e.enabled??!1,endpoints:e.endpoints||[],retryAttempts:e.retryAttempts??3,retryDelay:e.retryDelay??1000,timeout:e.timeout??5000,secret:e.secret||""},this.endpoints=this.config.endpoints}register(e){this.endpoints.push(e)}async fire(e,t){if(!this.config.enabled)return;let r={event:e,timestamp:Date.now(),data:t};if(this.config.secret)r.signature=await this.generateSignature(r);let i=this.endpoints.filter((s)=>s.events.includes(e)).map((s)=>this.sendWebhook(s,r));await Promise.allSettled(i)}async sendWebhook(e,t,r=1){try{let i=new AbortController,s=setTimeout(()=>i.abort(),this.config.timeout),n=await fetch(e.url,{method:e.method||"POST",headers:{"Content-Type":"application/json","User-Agent":"ts-broadcasting/1.0","X-Webhook-Signature":t.signature||"",...e.headers},body:JSON.stringify(t),signal:i.signal});if(clearTimeout(s),!n.ok&&n.status>=500&&r<=this.config.retryAttempts)return await new Promise((a)=>setTimeout(a,this.config.retryDelay*r)),this.sendWebhook(e,t,r+1)}catch{if(r<=this.config.retryAttempts)return await new Promise((i)=>setTimeout(i,this.config.retryDelay*r)),this.sendWebhook(e,t,r+1)}}async generateSignature(e){let t=new TextEncoder,r=t.encode(JSON.stringify(e)),i=await crypto.subtle.importKey("raw",t.encode(this.config.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await crypto.subtle.sign("HMAC",i,r);return ra.from(s).toString("hex")}async verifySignature(e,t){if(!this.config.secret)return!0;let r=await this.generateSignature(e);return t===r}}class xe{server;connections=new Map;config;channels;broadcaster;helpers;redis;auth;rateLimit;monitoring;validator;security;encryption;webhooks;persistence;channelState;namespace;presenceHeartbeat;acknowledgments;batchOps;lifecycle;loadManager;queueManager;constructor(e){if(this.config=e,this.channels=new Vt,this.broadcaster=new zt(this,e),this.helpers=new or(this,this.broadcaster),e.auth)this.auth=new hr(e.auth);if(e.rateLimit)this.rateLimit=new fr(e.rateLimit);if(e.security)this.security=new mr(e.security);if(this.monitoring=new gr,this.validator=new ur,e.encryption)this.encryption=new ar(e.encryption);if(e.webhooks)this.webhooks=new br(e.webhooks);if(e.persistence)this.persistence=new dr(e.persistence);if(this.channelState=new Ht,this.namespace=new Gt,e.heartbeat)this.presenceHeartbeat=new pr(e.heartbeat);if(e.acknowledgments)this.acknowledgments=new Wt(e.acknowledgments);if(e.batch)this.batchOps=new Kt(e.batch,this.channels);if(this.lifecycle=new lr,e.loadManagement)this.loadManager=new cr(e.loadManagement);if(e.queue?.enabled)this.initializeQueueManager();if(this.presenceHeartbeat)this.presenceHeartbeat.onUserRemove((t,r,i)=>{if(this.broadcast(t,"member_removed",{id:r,user:i},r),this.config.verbose)console.warn(`Removed inactive user ${r} from ${t}`)});this.setupDefaultValidators()}async initializeQueueManager(){try{let{BroadcastQueueManager:e}=await import("./chunk-gf28608k.js");if(this.queueManager=new e(this,this.config.queue),this.config.verbose)console.warn("Queue manager initialized")}catch(e){console.error("Failed to initialize queue manager:",e)}}async start(){if(this.presenceHeartbeat){if(this.presenceHeartbeat.start(),this.config.verbose)console.warn("Started presence heartbeat monitoring")}if(this.config.redis){if(this.redis=new yr(this.config.redis),await this.redis.connect(),this.redis.onMessage((i)=>{if(i.type==="broadcast")this.broadcast(i.channel,i.event,i.data,i.socketId)}),this.config.verbose)console.warn("Connected to Redis for horizontal scaling")}let e=this.config.connections?.[this.config.default||"bun"],t=e?.host??this.config.host??"0.0.0.0",r=e?.port??this.config.port??6001;if(this.server=Bun.serve({hostname:t,port:r,fetch:async(i,s)=>{let n=new URL(i.url);if(n.pathname==="/health"){let a={status:"ok",redis:this.redis?await this.redis.healthCheck():null};return Response.json(a)}if(n.pathname==="/stats")return Response.json(await this.getStats());if(n.pathname==="/metrics"){let{PrometheusExporter:a}=await import("./chunk-6rv8w5jk.js"),l=await new a(this).export();return new Response(l,{headers:{"Content-Type":"text/plain; version=0.0.4"}})}if(n.pathname==="/app"||n.pathname==="/ws"){let a=null;if(this.auth)a=await this.auth.authenticateRequest(i);if(s.upgrade(i,{data:{id:crypto.randomUUID(),socketId:crypto.randomUUID(),channels:new Set,connectedAt:Date.now(),user:a??void 0}}))return;return new Response("WebSocket upgrade failed",{status:400})}return new Response("Not found",{status:404})},websocket:{open:(i)=>{this.handleOpen(i)},message:(i,s)=>{this.handleMessage(i,s)},close:(i,s,n)=>{this.handleClose(i,s,n)},drain:(i)=>{this.handleDrain(i)},idleTimeout:e?.options?.idleTimeout,maxPayloadLength:e?.options?.maxPayloadLength,backpressureLimit:e?.options?.backpressureLimit,closeOnBackpressureLimit:e?.options?.closeOnBackpressureLimit,sendPings:e?.options?.sendPings,perMessageDeflate:e?.options?.perMessageDeflate}}),this.config.verbose)console.warn(`Broadcasting server started on ${t}:${r}`);this.monitoring?.emit({type:"connection",timestamp:Date.now(),socketId:"server",data:{event:"server_start"}})}async stop(){if(this.rateLimit)this.rateLimit.stop();if(this.presenceHeartbeat)this.presenceHeartbeat.stop();if(this.acknowledgments)this.acknowledgments.clear();if(this.queueManager)await this.queueManager.close();if(this.redis)this.redis.close();if(this.server){if(this.server.stop(),this.connections.clear(),this.config.verbose)console.warn("Broadcasting server stopped")}this.monitoring?.emit({type:"disconnection",timestamp:Date.now(),socketId:"server",data:{event:"server_stop"}})}handleOpen(e){if(this.loadManager&&!this.loadManager.canAcceptConnection()){e.close(1008,"Server at capacity");return}if(this.loadManager?.shouldShedLoad()){e.close(1008,"Server load too high");return}if(this.loadManager)this.loadManager.registerConnection(e.data.socketId);if(this.connections.set(e.data.socketId,e),this.redis)this.redis.storeConnection(e.data.socketId,{connectedAt:e.data.connectedAt,channels:Array.from(e.data.channels),user:e.data.user}).catch((t)=>console.error("Redis store connection error:",t));if(this.webhooks)this.webhooks.fire("connection",{socketId:e.data.socketId,connectedAt:e.data.connectedAt,user:e.data.user}).catch((t)=>console.error("Webhook error:",t));if(this.send(e,{event:"connection_established",data:{socket_id:e.data.socketId,activity_timeout:this.config.connections?.[this.config.default||"bun"]?.options?.idleTimeout||120}}),this.monitoring?.emit({type:"connection",timestamp:Date.now(),socketId:e.data.socketId}),this.config.verbose)console.warn(`WebSocket connected: ${e.data.socketId}`)}async handleMessage(e,t){if(this.rateLimit&&this.rateLimit.check(e)){this.send(e,{event:"error",data:{type:"RateLimitExceeded",error:"Too many requests",retryAfter:this.rateLimit.getResetAt(e)}});return}let r=typeof t==="string"?t:t.toString();if(this.security&&!this.security.checkSize(r)){this.send(e,{event:"error",data:{type:"PayloadTooLarge",error:"Message size exceeds maximum allowed"}});return}try{let i=JSON.parse(r);if(this.validator){let n=this.validator.validate(i);if(!n.valid){this.send(e,{event:"error",data:{type:"ValidationError",error:n.error}});return}}let s=this.security?this.security.sanitize(i):i;switch(this.monitoring?.emit({type:"message",timestamp:Date.now(),socketId:e.data.socketId,data:{event:s.event}}),s.event){case"subscribe":await this.handleSubscribe(e,s);break;case"unsubscribe":await this.handleUnsubscribe(e,s);break;case"batch_subscribe":await this.handleBatchSubscribe(e,s);break;case"batch_unsubscribe":await this.handleBatchUnsubscribe(e,s);break;case"heartbeat":case"presence_heartbeat":await this.handleHeartbeat(e,s);break;case"ping":this.send(e,{event:"pong"});break;default:if(this.acknowledgments&&s.ack&&s.messageId)this.send(e,{event:"ack",messageId:s.messageId});if(s.event.startsWith("client-"))await this.handleClientEvent(e,s);break}}catch(i){if(this.monitoring?.emit({type:"error",timestamp:Date.now(),socketId:e.data.socketId,data:{error:i instanceof Error?i.message:"Unknown error"}}),this.config.verbose)console.error("Error handling message:",i)}}async handleSubscribe(e,t){let{channel:r,channel_data:i}=t;try{if(this.loadManager&&!this.loadManager.canSubscribe(e.data.socketId)){this.send(e,{event:"subscription_error",channel:r,data:{type:"CapacityError",error:"Subscription limit reached",status:429}});return}let s=await this.channels.subscribe(e,r,i);if(!s){this.send(e,{event:"subscription_error",channel:r,data:{type:"AuthError",error:"Unauthorized",status:401}});return}if(this.loadManager)this.loadManager.registerSubscription(e.data.socketId);if(this.redis){if(await this.redis.storeChannel(r,e.data.socketId),this.channels.getChannelType(r)==="presence"&&typeof s==="object")await this.redis.storePresenceMember(r,e.data.socketId,s)}let n=this.channels.getChannelType(r);if(this.lifecycle){if(this.channels.getSubscriberCount(r)===1)await this.lifecycle.channelCreated(r,e.data.socketId);await this.lifecycle.channelSubscribed(r,e.data.socketId,this.channels.getSubscriberCount(r))}if(n==="presence"){if(this.presenceHeartbeat&&typeof s==="object")this.presenceHeartbeat.heartbeat(r,e.data.socketId,s);let a=this.channels.getPresenceMembers(r),l={presence:{ids:Array.from(a?.keys()||[]),hash:Object.fromEntries(a||[]),count:a?.size||0}};if(this.send(e,{event:"subscription_succeeded",channel:r,data:l}),typeof s==="object")this.broadcast(r,"member_added",s,e.data.socketId)}else this.send(e,{event:"subscription_succeeded",channel:r});if(this.webhooks)this.webhooks.fire("subscribe",{socketId:e.data.socketId,channel:r,channelData:i}).catch((a)=>console.error("Webhook error:",a));if(this.monitoring?.emit({type:"subscribe",timestamp:Date.now(),socketId:e.data.socketId,channel:r}),this.config.verbose)console.warn(`Socket ${e.data.socketId} subscribed to ${r}`)}catch(s){this.send(e,{event:"subscription_error",channel:r,data:{type:"ServerError",error:s instanceof Error?s.message:"Internal server error",status:500}})}}async handleUnsubscribe(e,t){let{channel:r}=t,i=this.channels.getChannelType(r),s=null;if(i==="presence")s=this.channels.getPresenceMembers(r)?.get(e.data.socketId);if(this.redis){if(await this.redis.removeChannel(r,e.data.socketId),i==="presence")await this.redis.removePresenceMember(r,e.data.socketId)}if(this.channels.unsubscribe(e,r),i==="presence"&&s)this.broadcast(r,"member_removed",s,e.data.socketId);if(this.monitoring?.emit({type:"unsubscribe",timestamp:Date.now(),socketId:e.data.socketId,channel:r}),this.config.verbose)console.warn(`Socket ${e.data.socketId} unsubscribed from ${r}`)}async handleClientEvent(e,t){let{event:r,channel:i,data:s}=t;if(this.channels.getChannelType(i)==="public")return;this.broadcast(i,r,s,e.data.socketId)}handleClose(e,t,r){let i=new Map;for(let s of e.data.channels)if(this.channels.getChannelType(s)==="presence"){let n=this.channels.getPresenceMembers(s)?.get(e.data.socketId);if(n)i.set(s,n)}this.channels.unsubscribeAll(e);for(let[s,n]of i)this.broadcast(s,"member_removed",n,e.data.socketId);if(this.loadManager)this.loadManager.unregisterConnection(e.data.socketId);if(this.connections.delete(e.data.socketId),this.redis)this.redis.removeConnection(e.data.socketId).catch((s)=>console.error("Redis remove connection error:",s));if(this.webhooks)this.webhooks.fire("disconnection",{socketId:e.data.socketId,code:t,reason:r}).catch((s)=>console.error("Webhook error:",s));if(this.monitoring?.emit({type:"disconnection",timestamp:Date.now(),socketId:e.data.socketId,data:{code:t,reason:r}}),this.config.verbose)console.warn(`WebSocket closed: ${e.data.socketId} (${t}: ${r})`)}handleError(e,t){if(this.monitoring?.emit({type:"error",timestamp:Date.now(),socketId:e.data.socketId,data:{error:t.message}}),this.config.verbose)console.error(`WebSocket error for ${e.data.socketId}:`,t)}handleDrain(e){if(this.config.verbose)console.warn(`WebSocket drained: ${e.data.socketId}`)}send(e,t){return e.send(JSON.stringify(t))}broadcast(e,t,r,i){let s=JSON.stringify({event:t,channel:e,data:r});if(this.server)if(i){let n=this.channels.getSubscribers(e);for(let a of n)if(a!==i){let l=this.connections.get(a);if(l)l.send(s)}}else this.server.publish(e,s);if(this.redis)this.redis.broadcast(e,t,r,i).catch((n)=>{console.error("Redis broadcast error:",n)});this.monitoring?.emit({type:"broadcast",timestamp:Date.now(),socketId:i||"server",channel:e,data:{event:t,dataSize:JSON.stringify(r).length}})}getConnectionCount(){return this.connections.size}getSubscriberCount(e){return this.channels.getSubscriberCount(e)}async getStats(){let e={connections:this.getConnectionCount(),channels:this.channels.getChannelCount(),uptime:ia.uptime()};if(this.redis){let t={totalConnections:await this.redis.getTotalConnections(),totalChannels:await this.redis.getTotalChannels(),redisHealthy:await this.redis.healthCheck(),serverId:this.redis.getServerId()};return{...e,...t,metrics:this.monitoring?.getMetrics()||{}}}return{...e,metrics:this.monitoring?.getMetrics()||{}}}async handleBatchSubscribe(e,t){if(!this.batchOps){this.send(e,{event:"error",data:{type:"NotSupported",error:"Batch operations are not enabled"}});return}try{let r=await this.batchOps.batchSubscribe(e,{channels:t.channels,channelData:t.channelData});this.send(e,{event:"batch_subscribe_result",messageId:t.messageId,data:r})}catch(r){this.send(e,{event:"error",data:{type:"BatchError",error:r instanceof Error?r.message:"Batch subscribe failed"}})}}handleBatchUnsubscribe(e,t){if(!this.batchOps){this.send(e,{event:"error",data:{type:"NotSupported",error:"Batch operations are not enabled"}});return}try{let r=this.batchOps.batchUnsubscribe(e,t.channels);this.send(e,{event:"batch_unsubscribe_result",messageId:t.messageId,data:r})}catch(r){this.send(e,{event:"error",data:{type:"BatchError",error:r instanceof Error?r.message:"Batch unsubscribe failed"}})}}async handleHeartbeat(e,t){if(!this.presenceHeartbeat)return;if(t.channel)this.presenceHeartbeat.heartbeat(t.channel,e.data.socketId)}setupDefaultValidators(){if(!this.validator)return;this.validator.addValidator((e)=>{if(!e||typeof e!=="object")return"Invalid message format";if(!e.event||typeof e.event!=="string")return"Missing or invalid event name";if(e.channel&&typeof e.channel!=="string")return"Invalid channel name";return!0}),this.validator.addValidator((e)=>{let t=e.event;if(t.length>100)return"Event name too long";if(!/^[\w.-]+$/.test(t))return"Event name contains invalid characters";return!0})}}var K=null;class M{static setServer(e){K=e}static getServer(){return K}static get broadcaster(){if(!K)throw Error("Broadcast server not initialized. Call Broadcast.setServer() first.");return K.broadcaster}static get channels(){if(!K)throw Error("Broadcast server not initialized. Call Broadcast.setServer() first.");return K.channels}static channel(e,t){if(!K)throw Error("Broadcast server not initialized. Call Broadcast.setServer() first.");return K.channels.channel(e,t),M}static async event(e){return M.broadcaster.broadcast(e)}static send(e,t,r){M.broadcaster.send(e,t,r)}static private(e,t,r){let i=e.startsWith("private-")?e:`private-${e}`;M.send(i,t,r)}static presence(e,t,r){let i=e.startsWith("presence-")?e:`presence-${e}`;M.send(i,t,r)}static toUser(e,t,r){M.private(`user.${e}`,t,r)}static toUsers(e,t,r){let i=e.map((s)=>`private-user.${s}`);M.send(i,t,r)}static toOthers(e){return M.broadcaster.toOthers(e)}static getConnectionCount(){if(!K)return 0;return K.getConnectionCount()}static getSubscriberCount(e){if(!K)return 0;return K.getSubscriberCount(e)}}function sa(e,t){M.channel(e,t)}var L=null,wr=[];function Tl(){return L}async function Ol(e){if(L)return L;let t=e.driver??"bun",r=e.host??"0.0.0.0",i=e.port??6001,s=e.scheme??"ws",n={verbose:e.verbose??!1,driver:t,default:t,connections:{[t]:{driver:t,host:r,port:i,scheme:s}}};return L=new xe(n),M.setServer(L),await L.start(),L}async function Ml(){for(let e of wr)clearInterval(e);if(wr.length=0,!L)return;await L.stop(),L=null}async function Nl(e){let t=await import(e),r=t.default??t;if(typeof r!=="function")throw Error(`routes/channels.ts must export a default function, got ${typeof r}`);let i=0;return r({channel(s,n){if(i++,n.authorize&&L)L.channels.channel(s,n.authorize);if(n.interval&&n.data){let a=n.event??`${s}.updated`,l=n.data,o=setInterval(async()=>{try{let c=await l();na(s,a,c)}catch{}},n.interval);wr.push(o)}}}),i}var Wi=!1;function Ae(){if(L)return!0;if(!Wi)Wi=!0,console.warn("[stx] broadcast() called before server started \u2014 messages will be sent once broadcasting is ready");return!1}function na(e,t,r){if(!Ae())return;M.send(e,t,r)}function Pl(e,t,r){if(!Ae())return;M.toUser(e,t,r)}function Bl(e,t,r){if(!Ae())return;M.toUsers(e,t,r)}function Il(e,t,r){if(!Ae())return;M.send(`private-${e}`,t,r)}function Rl(e,t,r){if(!Ae())return;M.presence(e,t,r)}
62
+ export{xe as a,M as b,sa as c,Tl as d,Ol as e,Ml as f,Nl as g,na as h,Pl as i,Bl as j,Il as k,Rl as l};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Qu as a,Ru as b,Su as c,Tu as d,Uu as e,Vu as f,Wu as g,Xu as h}from"./chunk-6bbmkwng.js";import"./chunk-nf3kv7kv.js";export{b as PluginManager,d as createDirectivePlugin,e as createFilterPlugin,h as createVariablesPlugin,f as debugPlugin,a as definePlugin,c as pluginManager,g as timingPlugin};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Fu as I,Ku as d,Lu as k,Mu as D,Nu as P}from"./chunk-6x1feysm.js";import{Zu as U}from"./chunk-nf3kv7kv.js";import{resolve as E,basename as W,dirname as oe,extname as V,join as A}from"path";import{mkdir as B,writeFile as ue}from"fs/promises";var L={enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:500,cacheVariants:!0,cachePlaceholders:!0};class q{config;constructor(e={}){this.config={...L,...e}}async get(e,i){return k(e,i,"image",this.config)}async set(e,i,r){return D(e,i,r,"image",this.config)}async clear(){return P("image",this.config)}updateConfig(e){this.config={...this.config,...e}}}var b=null;function F(e){if(!b)b=new q(e);else if(e)b.updateConfig(e);return b}async function v(e,i,r){let t=r?{directory:`${r.outputDir}/../.cache`}:{};return F(t).get(e,i)}async function x(e,i,r,t){let a=t?{directory:`${t.outputDir}/../.cache`}:{};return F(a).set(e,i,r)}async function H(){return F().clear()}async function R(){try{return await import("./chunk-9b6a58ac.js")}catch{return null}}function T(e){switch(e){case"quality":return{jpeg:{quality:90,mozjpeg:!0,progressive:!0},png:{compressionLevel:6,palette:!1},webp:{quality:90,effort:6,smartSubsample:!0},avif:{quality:85,effort:6}};case"performance":return{jpeg:{quality:70,mozjpeg:!0,progressive:!0},png:{compressionLevel:9,palette:!0},webp:{quality:70,effort:4,smartSubsample:!0},avif:{quality:60,effort:2}};case"web":default:return{jpeg:{quality:82,mozjpeg:!0,progressive:!0},png:{compressionLevel:8,palette:!1},webp:{quality:82,effort:5,smartSubsample:!0},avif:{quality:75,effort:4}}}}function M(e,i){let r=i?T(i):T("web"),t=e.formatQuality||{};return{jpeg:{...r.jpeg,...t.jpeg},png:{...r.png,...t.png},webp:{...r.webp,...t.webp},avif:{...r.avif,...t.avif}}}async function O(e,i,r){let t=await R();if(!t)return console.warn("[stx-media] ts-images not installed, skipping optimization"),{src:e,processed:!1};let a=await v(e,i,r);if(a)return a;try{let u=E(e);if(!await d(u))return{src:e,processed:!1,errors:[`Source file not found: ${e}`]};let n=M(r,i.preset),m=r.outputDir||"dist/images",C=r.baseUrl||"/images";await B(m,{recursive:!0});let w=await I(u),z=W(e,V(e)),j=i.outputFormat?[i.outputFormat]:r.defaultFormats||["avif","webp","jpeg"],o={src:e,processed:!0,variants:[],hash:w},h=null;if(i.transformations&&i.transformations.length>0)h=await Q(u,i.transformations,t);for(let s of j){let p=n[s]||{},l=`${z}-${w}.${s}`,g=A(m,l);try{let c=await t.optimizeImage({input:h||u,output:g,format:s,quality:p.quality,progressive:p.progressive});if(c){if(o.variants.push({path:g,url:`${C}/${l}`,width:c.width||0,height:c.height||0,format:s,size:c.outputSize||0}),!o.originalWidth&&c.width)o.originalWidth=c.width,o.originalHeight=c.height}}catch(c){o.errors=o.errors||[],o.errors.push(`Failed to optimize ${s}: ${c}`)}}if(i.embedThumbhash||i.placeholder==="thumbhash")try{let s=await t.generateThumbHash(u);o.placeholder=s.dataUrl}catch(s){o.errors=o.errors||[],o.errors.push(`Failed to generate thumbhash: ${s}`)}if(i.useDominantColor)try{let s=await t.generatePlaceholder(u,{strategy:"dominant-color"});o.dominantColor=s.dominantColor}catch(s){o.errors=o.errors||[],o.errors.push(`Failed to extract dominant color: ${s}`)}return await x(e,i,o,r),o}catch(u){return{src:e,processed:!1,errors:[`Processing failed: ${u}`]}}}async function _(e,i,r,t){let a=await R();if(!a)return{success:!1,error:"ts-images not installed"};try{return{success:!0,size:(await a.optimizeImage({input:e,output:t,format:i,quality:r}))?.outputSize}}catch(u){return{success:!1,error:String(u)}}}async function Q(e,i,r){let t=r||await R();if(!t)return console.warn("[stx-media] ts-images not installed, skipping transformations"),null;try{let a=await t.decode(e);for(let u of i){let n=u.options||{};switch(u.type){case"resize":if(n.width||n.height)a=await t.resize(a,{width:n.width,height:n.height,fit:n.fit});break;case"blur":if(n.sigma!==void 0)a=await t.blur(a,n.sigma);break;case"sharpen":if(n.amount!==void 0)a=await t.sharpen(a,n.amount);break;case"grayscale":a=await t.grayscale(a);break;case"rotate":if(n.angle!==void 0)a=await t.rotate(a,n.angle);break;case"flip":a=await t.flip(a);break;case"flop":a=await t.flop(a);break;case"brightness":if(n.value!==void 0)a=await t.brightness(a,n.value);break;case"contrast":if(n.value!==void 0)a=await t.contrast(a,n.value);break;case"saturation":if(n.value!==void 0)a=await t.saturation(a,n.value);break}}return await t.encode(a,"png")}catch(a){return console.error(`[stx-media] Transformation failed: ${a}`),null}}import{resolve as N,basename as G,extname as J,join as K}from"path";import{mkdir as X}from"fs/promises";async function Y(){try{return await import("./chunk-9b6a58ac.js")}catch{return null}}var Z=[320,480,640,768,1024,1280,1536,1920];async function ee(e,i,r){let t=await Y();if(!t)return console.warn("[stx-media] ts-images not installed, skipping responsive generation"),null;let a=N(e);if(!await d(a))return console.warn(`[stx-media] Source file not found: ${e}`),null;try{let u=i.responsiveWidths||r.breakpoints||Z,n=i.formats||r.defaultFormats||["avif","webp","jpeg"],m=r.outputDir||"dist/images",C=r.baseUrl||"/images";await X(m,{recursive:!0});let w=await I(a),z=G(e,J(e)),j=r.formatQuality||{jpeg:{quality:82},png:{quality:80},webp:{quality:82},avif:{quality:75}},o={src:e,byFormat:{},srcsets:{}};for(let s of n){o.byFormat[s]=[];let p=[];for(let l of u){let g=`${z}-${l}w-${w}.${s}`,c=K(m,g),y=`${C}/${g}`;try{let S=j[s]?.quality||80;if(await d(c)){o.byFormat[s].push({path:c,url:y,width:l,height:0,format:s,size:0}),p.push(`${y} ${l}w`);continue}let f=await t.processImage({input:a,output:c,format:s,quality:S,resize:{width:l}});if(f)o.byFormat[s].push({path:c,url:y,width:l,height:f.height||Math.round(l*(f.height||1)/(f.width||1)),format:s,size:f.outputSize||0}),p.push(`${y} ${l}w`)}catch(S){console.warn(`[stx-media] Failed to generate ${s} at ${l}w: ${S}`)}}o.srcsets[s]=p.join(", ")}let h=i.placeholder||r.placeholderStrategy||"thumbhash";if(h!=="none")try{if(h==="thumbhash"){let s=await t.generateThumbHash(a);o.placeholder={dataURL:s.dataUrl,width:s.width||32,height:s.height||32,strategy:"thumbhash"}}else{let s=await t.generatePlaceholder(a,{strategy:h,width:20});o.placeholder={dataURL:s.dataURL,width:s.width,height:s.height,strategy:h}}}catch(s){console.warn(`[stx-media] Failed to generate placeholder: ${s}`)}return o.sizes=i.sizes||te(u),o}catch(u){return console.error(`[stx-media] Responsive generation failed: ${u}`),null}}function te(e){let i=[...e].sort((t,a)=>t-a),r=[];for(let t=0;t<i.length-1;t++){let a=i[t];r.push(`(max-width: ${a}px) ${a}px`)}return r.push(`${i[i.length-1]}px`),r.join(", ")}function ae(e,i="width"){if(!e||e.length===0)return"";if(i==="dpr")return e.filter((r)=>r.dpr).map((r)=>`${r.url} ${r.dpr}x`).join(", ");return e.map((r)=>`${r.url} ${r.width}w`).join(", ")}export{q as lu,v as mu,x as nu,H as ou,O as pu,_ as qu,Q as ru,ee as su,ae as tu};