@stacksjs/bun-router 0.1.0 → 0.1.1

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,246 @@
1
+ // @bun
2
+ import{Zu as Fe}from"./chunk-nf3kv7kv.js";import{readFile as Tm,stat as Nm}from"fs/promises";import{readFile as Om}from"fs/promises";import{extname as Rm}from"path";import{Buffer as wn}from"buffer";import{mkdir as uf,readdir as Dm,readFile as pi,stat as ut,writeFile as Xt}from"fs/promises";import{dirname as ff,extname as ii,join as Zi}from"path";import{existsSync as Ul,statSync as Vl}from"fs";import{join as Lm,relative as jm,resolve as Gl}from"path";import bn from"process";import{Buffer as bt}from"buffer";import{createCipheriv as Bm,createDecipheriv as Im,randomBytes as wa}from"crypto";import{closeSync as ba,createReadStream as Wl,createWriteStream as zm,existsSync as Ci,fsyncSync as ql,openSync as Kl,writeFileSync as _m}from"fs";import{access as Um,constants as Yl,mkdir as Vm,readdir as Ai,rename as Hl,stat as or,unlink as Ei,writeFile as va}from"fs/promises";import{isAbsolute as Gm,join as lr,resolve as Wm}from"path";import te from"process";import{pipeline as qm}from"stream/promises";import{createGzip as Jl}from"zlib";import cr from"process";import $t from"process";import ki from"process";import{existsSync as Mi}from"fs";import{resolve as Sa}from"path";import{existsSync as Km}from"fs";import{existsSync as gs,mkdirSync as Ym,readdirSync as Hm,readFileSync as Jm,writeFileSync as Zm}from"fs";import{homedir as ur}from"os";import{dirname as Zl,resolve as je}from"path";import er from"process";import{existsSync as Qm,readdirSync as Xm}from"fs";import{extname as xa,resolve as Ql}from"path";import ep from"process";import{existsSync as Xl,statSync as ec}from"fs";import{join as tp,relative as rp,resolve as tc}from"path";import vn from"process";import{Buffer as vt}from"buffer";import{createCipheriv as ip,createDecipheriv as np,randomBytes as $a}from"crypto";import{closeSync as Ca,createReadStream as rc,createWriteStream as ap,existsSync as Ti,fsyncSync as ic,openSync as nc,writeFileSync as sp}from"fs";import{access as op,constants as ac,mkdir as lp,readdir as Ni,rename as sc,stat as fr,unlink as Pi,writeFile as Aa}from"fs/promises";import{isAbsolute as cp,join as hr,resolve as up}from"path";import re from"process";import{pipeline as fp}from"stream/promises";import{createGzip as oc}from"zlib";import dr from"process";import Ct from"process";import Fi from"process";import{existsSync as Oi}from"fs";import{resolve as Ea}from"path";import{existsSync as hp}from"fs";import{existsSync as ys,mkdirSync as dp,readdirSync as mp,readFileSync as pp,writeFileSync as gp}from"fs";import{homedir as mr}from"os";import{dirname as lc,resolve as Be}from"path";import tr from"process";import{existsSync as yp,readdirSync as wp}from"fs";import{extname as ka,resolve as cc}from"path";import bp from"process";import{Buffer as vp}from"buffer";import{stat as $2}from"fs/promises";import{relative as C2,resolve as A2}from"path";import{existsSync as yu,statSync as wu}from"fs";import{existsSync as Vs,mkdirSync as E2,readdirSync as k2,writeFileSync as M2}from"fs";import{homedir as yr}from"os";import{dirname as bu,resolve as Ie}from"path";import rr from"process";import{join as T2,relative as N2,resolve as vu}from"path";import Nn from"process";import{existsSync as od,mkdirSync as mA,readdirSync as pA,writeFileSync as gA}from"fs";import{homedir as Ha}from"os";import{dirname as bA,resolve as Le}from"path";import fi from"process";import{join as P2,relative as F2,resolve as Su}from"path";import Pn from"process";import{existsSync as ld,mkdirSync as CA,readdirSync as AA,writeFileSync as EA}from"fs";import{dirname as MA,resolve as Fn}from"path";import Gs from"process";import{Buffer as It}from"buffer";import{createCipheriv as O2,createDecipheriv as R2,randomBytes as Ja}from"crypto";import{closeSync as Za,createReadStream as xu,createWriteStream as D2,existsSync as Qa,fsyncSync as $u,openSync as Cu,writeFileSync as L2}from"fs";import{access as j2,constants as Au,mkdir as B2,readdir as Bi,rename as Eu,stat as wr,unlink as Ii,writeFile as Xa}from"fs/promises";import{join as br}from"path";import Te from"process";import{pipeline as I2}from"stream/promises";import{createGzip as ku}from"zlib";import vr from"process";import Et from"process";import{Buffer as St}from"buffer";import{createCipheriv as z2,createDecipheriv as _2,randomBytes as es}from"crypto";import{closeSync as ts,createReadStream as Mu,createWriteStream as U2,existsSync as zi,fsyncSync as Tu,openSync as Nu,writeFileSync as V2}from"fs";import{access as G2,constants as Pu,mkdir as W2,readdir as _i,rename as Fu,stat as Sr,unlink as Ui,writeFile as rs}from"fs/promises";import{isAbsolute as q2,join as xr,resolve as K2}from"path";import ie from"process";import{pipeline as Y2}from"stream/promises";import{createGzip as Ou}from"zlib";import $r from"process";import kt from"process";import Vi from"process";import{existsSync as Gi}from"fs";import{resolve as is}from"path";import{existsSync as H2}from"fs";import{existsSync as J2,readdirSync as Z2}from"fs";import{extname as ns,resolve as Ru}from"path";import Q2 from"process";import{join as X2,relative as eS,resolve as Du}from"path";import On from"process";import{Buffer as xt}from"buffer";import{createCipheriv as tS,createDecipheriv as rS,randomBytes as as}from"crypto";import{closeSync as ss,createReadStream as Lu,createWriteStream as iS,existsSync as Wi,fsyncSync as ju,openSync as Bu,writeFileSync as nS}from"fs";import{access as aS,constants as Iu,mkdir as sS,readdir as qi,rename as zu,stat as Cr,unlink as Ki,writeFile as os}from"fs/promises";import{isAbsolute as oS,join as Ar,resolve as lS}from"path";import ne from"process";import{pipeline as cS}from"stream/promises";import{createGzip as _u}from"zlib";import Er from"process";import Mt from"process";import{mkdir as rf,readFile as qd,writeFile as mi}from"fs/promises";import{join as zr,resolve as Kd}from"path";import{readFile as f$,writeFile as ms}from"fs/promises";import{join as ps}from"path";function U(e,t,r={}){let{colorSpace:i="srgb",hasAlpha:n=!0,bitDepth:s=8,fill:a}=r,o=n?4:4,l=s===16?o*2:o,c=e*t*l,u=s===16?new Uint8Array(c):new Uint8ClampedArray(c);if(a){let f=Math.min(255,Math.max(0,a.r)),h=Math.min(255,Math.max(0,a.g)),d=Math.min(255,Math.max(0,a.b)),m=a.a!==void 0?Math.min(255,Math.max(0,a.a)):255;for(let p=0;p<u.length;p+=4)u[p]=f,u[p+1]=h,u[p+2]=d,u[p+3]=m}return{data:u,width:e,height:t,colorSpace:i,hasAlpha:n,bitDepth:s}}function fm(e){return{data:new Uint8ClampedArray(e.data),width:e.width,height:e.height,colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}}function He(e,t,r){if(t<0||t>=e.width||r<0||r>=e.height)return{r:0,g:0,b:0,a:0};let i=(r*e.width+t)*4;return{r:e.data[i],g:e.data[i+1],b:e.data[i+2],a:e.data[i+3]}}function _r(e,t,r,i){if(t<0||t>=e.width||r<0||r>=e.height)return;let n=(r*e.width+t)*4;e.data[n]=Math.min(255,Math.max(0,i.r)),e.data[n+1]=Math.min(255,Math.max(0,i.g)),e.data[n+2]=Math.min(255,Math.max(0,i.b)),e.data[n+3]=i.a!==void 0?Math.min(255,Math.max(0,i.a)):255}function nf(e,t,r){let i=Math.floor(t),n=Math.floor(r),s=Math.min(i+1,e.width-1),a=Math.min(n+1,e.height-1),o=t-i,l=r-n,c=He(e,i,n),u=He(e,s,n),f=He(e,i,a),h=He(e,s,a),d=(m,p,y)=>m+(p-m)*y;return{r:Math.round(d(d(c.r,u.r,o),d(f.r,h.r,o),l)),g:Math.round(d(d(c.g,u.g,o),d(f.g,h.g,o),l)),b:Math.round(d(d(c.b,u.b,o),d(f.b,h.b,o),l)),a:Math.round(d(d(c.a,u.a,o),d(f.a,h.a,o),l))}}function nr(e,t,r,i={}){let{channels:n=4,colorSpace:s="srgb"}=i,a;if(n===3){a=new Uint8ClampedArray(t*r*4);for(let o=0,l=0;o<e.length;o+=3,l+=4)a[l]=e[o],a[l+1]=e[o+1],a[l+2]=e[o+2],a[l+3]=255}else a=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e);return{data:a,width:t,height:r,colorSpace:s,hasAlpha:n===4,bitDepth:8}}function Ur(e,t={}){let{channels:r=4}=t;if(r===3){let i=new Uint8ClampedArray(e.width*e.height*3);for(let n=0,s=0;n<e.data.length;n+=4,s+=3)i[s]=e.data[n],i[s+1]=e.data[n+1],i[s+2]=e.data[n+2];return i}return e.data instanceof Uint8ClampedArray?e.data:new Uint8ClampedArray(e.data)}function so(e,t,r={}){let{background:i={r:0,g:0,b:0,a:0},expand:n=!0}=r;if(t=(t%360+360)%360,t===0)return{...e,data:new Uint8ClampedArray(e.data)};if(t===90)return gn(e);if(t===180)return oo(e);if(t===270)return yn(e);let s=t*Math.PI/180,a=Math.cos(s),o=Math.sin(s),l,c;if(n)l=Math.ceil(Math.abs(e.width*a)+Math.abs(e.height*o)),c=Math.ceil(Math.abs(e.width*o)+Math.abs(e.height*a));else l=e.width,c=e.height;let u=U(l,c,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth,fill:i}),f=e.width/2,h=e.height/2,d=l/2,m=c/2;for(let p=0;p<c;p++)for(let y=0;y<l;y++){let g=y-d,w=p-m,b=g*a+w*o+f,v=-g*o+w*a+h;if(b>=0&&b<e.width&&v>=0&&v<e.height){let S=nf(e,b,v);_r(u,y,p,S)}}return u}function gn(e){let t=U(e.height,e.width,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let r=0;r<e.height;r++)for(let i=0;i<e.width;i++){let n=(r*e.width+i)*4,s=(i*t.width+(e.height-1-r))*4;t.data[s]=e.data[n],t.data[s+1]=e.data[n+1],t.data[s+2]=e.data[n+2],t.data[s+3]=e.data[n+3]}return t}function oo(e){let t=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}),r=e.data.length-4;for(let i=0;i<e.data.length;i+=4){let n=r-i;t.data[i]=e.data[n],t.data[i+1]=e.data[n+1],t.data[i+2]=e.data[n+2],t.data[i+3]=e.data[n+3]}return t}function yn(e){let t=U(e.height,e.width,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let r=0;r<e.height;r++)for(let i=0;i<e.width;i++){let n=(r*e.width+i)*4,s=((e.width-1-i)*t.width+r)*4;t.data[s]=e.data[n],t.data[s+1]=e.data[n+1],t.data[s+2]=e.data[n+2],t.data[s+3]=e.data[n+3]}return t}function Xr(e){let t=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}),r=e.width*4;for(let i=0;i<e.height;i++){let n=i*r,s=(e.height-1-i)*r;for(let a=0;a<r;a++)t.data[s+a]=e.data[n+a]}return t}function lo(e){let t=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let r=0;r<e.height;r++)for(let i=0;i<e.width;i++){let n=(r*e.width+i)*4,s=(r*e.width+(e.width-1-i))*4;t.data[s]=e.data[n],t.data[s+1]=e.data[n+1],t.data[s+2]=e.data[n+2],t.data[s+3]=e.data[n+3]}return t}function co(e,t){let{left:r,top:i,width:n,height:s}=t,a=Math.max(0,Math.min(r,e.width)),o=Math.max(0,Math.min(i,e.height)),l=Math.min(n,e.width-a),c=Math.min(s,e.height-o),u=U(l,c,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let f=0;f<c;f++){let h=((o+f)*e.width+a)*4,d=f*l*4,m=l*4;for(let p=0;p<m;p++)u.data[d+p]=e.data[h+p]}return u}var hm=co;function dm(e,t){let{top:r=0,bottom:i=0,left:n=0,right:s=0,background:a={r:0,g:0,b:0,a:255}}=t,o=e.width+n+s,l=e.height+r+i,c=U(o,l,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth,fill:a});for(let u=0;u<e.height;u++)for(let f=0;f<e.width;f++){let h=(u*e.width+f)*4,d=((u+r)*o+(f+n))*4;c.data[d]=e.data[h],c.data[d+1]=e.data[h+1],c.data[d+2]=e.data[h+2],c.data[d+3]=e.data[h+3]}return c}function mm(e,t={}){let{threshold:r=10,background:i}=t,n=i||{r:e.data[0],g:e.data[1],b:e.data[2],a:e.data[3]},s=e.width,a=e.height,o=0,l=0;for(let c=0;c<e.height;c++)for(let u=0;u<e.width;u++){let f=(c*e.width+u)*4;if(Math.abs(e.data[f]-n.r)+Math.abs(e.data[f+1]-n.g)+Math.abs(e.data[f+2]-n.b)+Math.abs(e.data[f+3]-(n.a??255))>r)s=Math.min(s,u),a=Math.min(a,c),o=Math.max(o,u),l=Math.max(l,c)}if(s>o||a>l)return U(1,1,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});return co(e,{left:s,top:a,width:o-s+1,height:l-a+1})}function af(e){if(e.length<4||e[0]!==255||e[1]!==216)return 1;let t=2;while(t+4<=e.length){if(e[t]!==255)return 1;while(t<e.length&&e[t]===255)t++;let r=e[t++];if(r===218||r===217)return 1;if(r>=208&&r<=215)continue;if(t+2>e.length)return 1;let i=e[t]<<8|e[t+1];if(i<2||t+i>e.length)return 1;if(r===225&&i>=10&&e[t+2]===69&&e[t+3]===120&&e[t+4]===105&&e[t+5]===102&&e[t+6]===0&&e[t+7]===0)return pm(e.subarray(t+8,t+i));t+=i}return 1}function pm(e){if(e.length<8)return 1;let t;if(e[0]===73&&e[1]===73)t=!0;else if(e[0]===77&&e[1]===77)t=!1;else return 1;let r=(a)=>t?e[a]|e[a+1]<<8:e[a]<<8|e[a+1],i=(a)=>t?(e[a]|e[a+1]<<8|e[a+2]<<16|e[a+3]<<24)>>>0:(e[a]<<24|e[a+1]<<16|e[a+2]<<8|e[a+3])>>>0;if(r(2)!==42)return 1;let n=i(4);if(n+2>e.length)return 1;let s=r(n);for(let a=0;a<s;a++){let o=n+2+a*12;if(o+12>e.length)return 1;if(r(o)===274){let l=r(o+8);return l>=1&&l<=8?l:1}}return 1}function sf(e,t){switch(t){case 2:return lo(e);case 3:return oo(e);case 4:return Xr(e);case 5:return gn(Xr(e));case 6:return gn(e);case 7:return yn(Xr(e));case 8:return yn(e);default:return e}}var ya=Object.create(null);async function et(e){let t=ya[e];if(t){if(t.available)return t.module;throw Error(`ts-images: codec package "${e}" failed to load. Install it with \`bun add ${e}\` (or \`npm install ${e}\`).`,{cause:t.error})}try{let r=await import(e);return ya[e]={module:r,available:!0},r}catch(r){throw ya[e]={module:null,available:!1,error:r},Error(`ts-images: codec package "${e}" is not installed. Install it with \`bun add ${e}\` (or \`npm install ${e}\`).`,{cause:r})}}function Vr(e){if(e.length<12)return null;if(e[0]===255&&e[1]===216&&e[2]===255)return"jpeg";if(e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10)return"png";if(e[0]===71&&e[1]===73&&e[2]===70)return"gif";if(e[0]===66&&e[1]===77)return"bmp";if(e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"webp";if(e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112){let t=String.fromCharCode(e[8],e[9],e[10],e[11]);if(t==="avif"||t==="avis"||t==="mif1"||t==="miaf")return"avif";if(t==="heic"||t==="heix"||t==="hevc"||t==="hevx")return"heif"}if(e[0]===73&&e[1]===73&&e[2]===42&&e[3]===0||e[0]===77&&e[1]===77&&e[2]===0&&e[3]===42)return"tiff";return null}function of(e){let t=Vr(e);if(!t)return null;let r=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(t){case"png":if(e.length<24)return null;return{width:r.getUint32(16,!1),height:r.getUint32(20,!1)};case"gif":if(e.length<10)return null;return{width:r.getUint16(6,!0),height:r.getUint16(8,!0)};case"bmp":if(e.length<26)return null;return{width:r.getInt32(18,!0),height:Math.abs(r.getInt32(22,!0))};case"webp":{let i=String.fromCharCode(e[12],e[13],e[14],e[15]);if(i==="VP8 "){if(e.length<30)return null;let n=r.getUint16(26,!0)&16383,s=r.getUint16(28,!0)&16383;return{width:n,height:s}}if(i==="VP8L"){if(e.length<25)return null;let n=e[21],s=e[22],a=e[23],o=e[24],l=1+((s&63)<<8|n),c=1+((o&15)<<10|a<<2|(s&192)>>6);return{width:l,height:c}}if(i==="VP8X"){if(e.length<30)return null;let n=1+(e[24]|e[25]<<8|e[26]<<16),s=1+(e[27]|e[28]<<8|e[29]<<16);return{width:n,height:s}}return null}case"jpeg":{let i=2,n=e.length;while(i<n-8){if(e[i]!==255)return null;while(i<n&&e[i]===255)i++;let s=e[i++];if(s===216||s===217)return null;if(s>=208&&s<=215)continue;let a=e[i]<<8|e[i+1];if(s>=192&&s<=207&&s!==196&&s!==200&&s!==204){let o=e[i+3]<<8|e[i+4];return{width:e[i+5]<<8|e[i+6],height:o}}i+=a}return null}default:return null}}async function Re(e,t={}){let r=Vr(e);if(!r)throw Error("ts-images: unknown image format (no matching magic bytes)");switch(r){case"jpeg":{let i=await gm(e,t);if(t.applyOrientation===!1)return i;return sf(i,af(e))}case"png":return wm(e,t);case"gif":return vm(e,t);case"bmp":return xm(e,t);case"webp":return Cm(e,t);case"avif":return Em(e,t);default:throw Error(`ts-images: unsupported format "${r}"`)}}async function tt(e,t,r={}){switch(t){case"jpeg":case"jpg":return ym(e,r);case"png":return bm(e,r);case"gif":return Sm(e,r);case"bmp":return $m(e,r);case"webp":return Am(e,r);case"avif":return km(e,r);default:throw Error(`ts-images: unsupported format "${t}"`)}}async function lf(e){let t=Vr(e);if(!t)throw Error("ts-images: unknown image format (no matching magic bytes)");let r=of(e);if(r)return{width:r.width,height:r.height,format:t,channels:4,bitDepth:8,hasAlpha:t!=="jpeg"&&t!=="bmp",colorSpace:"srgb"};let i=await Re(e);return{width:i.width,height:i.height,format:t,channels:4,bitDepth:i.bitDepth,hasAlpha:i.hasAlpha,colorSpace:i.colorSpace}}async function gm(e,t){let r=(await et("ts-jpeg")).decode(e,{colorTransform:t.colorTransform,formatAsRGBA:t.formatAsRGBA??!0}),i=r.width*r.height*4,n=r.data.length===i?4:3,s=nr(r.data,r.width,r.height,{channels:n});return s.hasAlpha=!1,s}async function ym(e,t){let r=await et("ts-jpeg"),i=Ur(e,{channels:4}),n=r.encode({width:e.width,height:e.height,data:i},t.quality??80);return new Uint8Array(n.data)}async function wm(e,t){let r=(await et("@stacksjs/ts-png")).png.sync.read(Buffer.from(e));return nr(r.data,r.width,r.height,{channels:4})}async function bm(e,t){let r=await et("@stacksjs/ts-png"),i=Buffer.from(Uint8Array.from(Ur(e,{channels:4}))),n=r.png.sync.write({width:e.width,height:e.height,data:i},{deflateLevel:t.effort??9});return new Uint8Array(n)}async function vm(e,t){let r=new(await et("ts-gif")).Reader(Buffer.from(e)),i=r.frameInfo(0),n=new Uint8Array(i.width*i.height*4);return r.decodeAndBlitFrameRGBA(0,n),nr(n,i.width,i.height,{channels:4})}async function Sm(e,t){let r=await et("ts-gif"),{indexedPixels:i,palette:n}=Mm(e),s=e.width*e.height+1024,a=Buffer.alloc(s),o=new r.Writer(a,e.width,e.height,{palette:n});o.addFrame(0,0,e.width,e.height,i);let l=o.end();return new Uint8Array(a.slice(0,l))}async function xm(e,t){let r=(await et("@stacksjs/ts-bmp")).decode(e);return nr(r.data,r.width,r.height,{channels:4})}async function $m(e,t){let r=await et("@stacksjs/ts-bmp"),i=Ur(e,{channels:4});return r.encode({width:e.width,height:e.height,data:i})}async function Cm(e,t){let r=(await et("@stacksjs/ts-webp")).decode(e),i=4,n=nr(r.data,r.width,r.height,{channels:4});if(typeof r.hasAlpha==="boolean")n.hasAlpha=r.hasAlpha;return n}async function Am(e,t){let r=await et("@stacksjs/ts-webp"),i=Ur(e,{channels:4}),n=typeof r.encodeAsync==="function",s=async(a)=>{let o=[{width:e.width,height:e.height,data:i instanceof Uint8Array?i:new Uint8Array(i),hasAlpha:e.hasAlpha},{quality:t.quality,lossless:a,effort:t.effort}];return n?r.encodeAsync(...o):r.encode(...o)};try{return await s(t.lossless??!1)}catch(a){if(a instanceof Error&&/lossy.*not implemented/i.test(a.message))return s(!0);throw a}}async function Em(e,t){let r=(await et("@stacksjs/ts-avif")).decode(e);return nr(r.data,r.width,r.height,{channels:4})}async function km(e,t){let r=await et("@stacksjs/ts-avif"),i=Ur(e,{channels:4}),n=typeof r.encodeAsync==="function",s=[{width:e.width,height:e.height,data:i instanceof Uint8Array?i:new Uint8Array(i),hasAlpha:e.hasAlpha},{quality:t.quality,lossless:t.lossless,effort:t.effort}];return n?r.encodeAsync(...s):r.encode(...s)}function Mm(e){let t=[];for(let i=0;i<6;i++)for(let n=0;n<6;n++)for(let s=0;s<6;s++){let a=Math.round(i*255/5),o=Math.round(n*255/5),l=Math.round(s*255/5);t.push(a<<16|o<<8|l)}for(let i=0;i<40;i++){let n=Math.round(i*255/39);t.push(n<<16|n<<8|n)}let r=new Uint8Array(e.width*e.height);for(let i=0,n=0;i<e.data.length;i+=4,n++){let s=Math.round(e.data[i]*5/255),a=Math.round(e.data[i+1]*5/255),o=Math.round(e.data[i+2]*5/255);r[n]=s*36+a*6+o}return{indexedPixels:r,palette:t}}async function cf(e){let t=[],r=await Nm(e),i=await Tm(e),n=new Uint8Array(i),s=Vr(n)??"unknown",a=0,o=0,l=of(n);if(l)a=l.width,o=l.height;else try{let p=await lf(n);a=p.width,o=p.height}catch{}let c=!1,u="srgb",f=4;try{let p=await Re(n);if(c=p.hasAlpha,u=p.colorSpace,!a)a=p.width;if(!o)o=p.height}catch{}let h="low",d=(a||1)*(o||1),m=r.size/d;if(m>4)h="high";else if(m>2)h="medium";if(a>2000||o>2000)t.push("Image dimensions are very large"),h="high";if(r.size>1048576)t.push("File size exceeds 1MB"),h="high";if(s==="png"&&f===4&&!c)t.push("PNG has alpha channel but no transparency");return{path:e,size:r.size,format:s,width:a,height:o,aspectRatio:o?a/o:0,hasAlpha:c,isAnimated:!1,colorSpace:u,channels:f,density:72,compression:void 0,quality:void 0,optimizationPotential:h,metadata:{format:s,width:a,height:o,hasAlpha:c,colorSpace:u},warnings:t}}async function Pm(e){let t=await Promise.all(e.map(cf)),r=t.reduce((a,o)=>a+o.size,0),i=t.reduce((a,o)=>(a[o.format]=(a[o.format]||0)+1,a),{}),n=Array.from(new Set(t.flatMap((a)=>a.warnings))),s=t.reduce((a,o)=>{switch(o.optimizationPotential){case"high":return a+o.size*0.7;case"medium":return a+o.size*0.4;case"low":return a+o.size*0.1;default:return a}},0);return{stats:t,summary:{totalSize:r,averageSize:t.length?r/t.length:0,totalImages:t.length,formatBreakdown:i,potentialSavings:`${Math.round(s/1024)}KB`,warnings:n}}}var Fm={verbose:!0,cache:!0,cacheDir:".imgx-cache",concurrent:4,skipOptimized:!1,quality:80,format:"webp",progressive:!0,preserveMetadata:!1,appIcon:{outputDir:"assets/app-icons",platform:"all"},responsive:{sizes:[320,640,960,1280,1920],formats:["webp","jpeg"],quality:80,generateSrcset:!0,filenameTemplate:"[name]-[width].[ext]"},sprites:{padding:2,maxWidth:2048,prefix:"sprite",format:"png",quality:90,scale:1},placeholders:{width:20,quality:50,format:"webp",blurLevel:40,base64Encode:!0,useThumbhash:!1,strategy:"blur",saturation:1.2,cssFilter:!1},batch:{formats:["webp"],quality:80,recursive:!1,filter:".(jpe?g|png|gif|bmp|tiff?)$",skipExisting:!0,concurrency:4,preserveStructure:!0,filenameTemplate:"[name].[format]",preserveMetadata:!1,optimizationPreset:"web"},optimization:{quality:80,lossless:!1,progressive:!0,effort:7,preserveMetadata:!1,jpeg:{quality:85,progressive:!0,optimizeCoding:!0,mozjpeg:!0,chromaSubsampling:"4:2:0"},png:{quality:80,progressive:!0,compressionLevel:9,effort:7,palette:!0,adaptiveFiltering:!0},webp:{quality:80,lossless:!1,effort:6,smartSubsample:!0},avif:{quality:70,lossless:!1,effort:7}},conversion:{quality:80,lossless:!1,progressive:!0,filenamePrefix:"",filenameSuffix:"",preserveMetadata:!1,optimizationLevel:6,effort:6,chromaSubsampling:"4:2:0",smartSubsample:!0},social:{quality:85,customSizes:{"og-github":{width:1280,height:640},"og-facebook":{width:1200,height:630},"og-twitter":{width:1200,height:600},"og-linkedin":{width:1104,height:736},"og-instagram":{width:1080,height:1080}}},transformations:{presets:{webOptimized:[{type:"resize",options:{width:1200,withoutEnlargement:!0}}],thumbnail:[{type:"resize",options:{width:300,height:300,fit:"inside"}}],grayscale:[{type:"grayscale"}],sharpen:[{type:"sharpen",options:{sigma:1}}]}},watermark:{position:"bottom-right",opacity:0.5,margin:20,scale:0.2,textOptions:{font:"sans-serif",fontSize:24,color:"rgba(255, 255, 255, 0.7)",background:"rgba(0, 0, 0, 0.3)",padding:10}}},N=Fm,Sp=Object.defineProperty,xp=(e)=>e;function $p(e,t){this[e]=xp.bind(null,t)}var D=(e,t)=>{for(var r in t)Sp(e,r,{get:t[r],enumerable:!0,configurable:!0,set:$p.bind(t,r)})},Cp=Object.defineProperty,Ap=(e)=>e;function Ep(e,t){this[e]=Ap.bind(null,t)}var kp=(e,t)=>{for(var r in t)Cp(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ep.bind(t,r)})},Lt=(e,t)=>()=>(e&&(t=e(e=0)),t),Mp=import.meta.require;class uo{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 n=this.generateKey(e,r),s=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,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(!Ul(e))return!0;return Vl(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 n=Ul(r)?Vl(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},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,n)=>i+n.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 fo{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:n,...r}),s}catch(s){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,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 Tp(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function Np(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Pp(e){return e.getStats().size*2}var Or,gi,hf,yi=Lt(()=>{Or=new uo,gi=new fo,hf={createKey:Tp,isEquivalent:Np,estimateMemoryUsage:Pp}});function Fp(e,t={}){let r=bn.cwd();while(r.includes("storage"))r=Gl(r,"..");let i=Gl(r,e||"");if(t?.relative)return jm(bn.cwd(),i);return i}function ye(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Op(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let e=$t.type;if(e==="renderer"||e==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class df{async format(e){let t=await Op(),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:cr.pid,hostname:t(),environment:cr.env.NODE_ENV||"development",platform:cr.platform,version:cr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:cr.env.NODE_ENV||cr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Un{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={...ei},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new df,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??te.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 n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,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{...Qi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Qi};return{...Qi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ei.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!ye()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await Um(this.config.logDirectory,Yl.F_OK|Yl.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Vm(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:bt.from(e);try{if(!Ci(this.currentLogFile))await va(this.currentLogFile,"",{mode:420});if(i=Kl(this.currentLogFile,"a",420),_m(i,o,{flag:"a"}),ql(i),i!==void 0)ba(i),i=void 0;if((await or(this.currentLogFile)).size===0){if(await va(this.currentLogFile,o,{flag:"w",mode:420}),(await or(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let c=l;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(n<s-1){let u=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=a*2**n;await new Promise((h)=>setTimeout(h,f)),n++;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{ba(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(o){if(n===s-1){let c=o,u=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let l=a*2**(n-1);await new Promise((c)=>setTimeout(c,l))}})();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 lr(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 lr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return lr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ye())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],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return wa(16).toString("hex")}generateKey(){return wa(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=wa(16),i=Bm("aes-256-gcm",t,r),n=bt.isBuffer(e)?e:bt.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,l=i.getAuthTag(),c=bt.allocUnsafe(16+o+16);return r.copy(c,0),s.copy(c,16),a.copy(c,16+s.length),l.copy(c,16+o),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Jl(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(bt.from(bt.concat(n)))),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(ye())return;if(!this.shouldWriteToFile())return;let e=await or(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 n=await Ai(this.config.logDirectory),s=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,c)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await or(r).catch(()=>null))try{if(await Hl(r,o),t.compress)try{let l=`${o}.gz`;await this.compressLogFile(o,l),await Ei(o)}catch(l){console.error("Error compressing rotated file:",l)}if(s.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await va(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await or(r).catch(()=>null))await Hl(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Ai(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Ei(lr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Wl(e),i=zm(t),n=Jl();await qm(r,n,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()})),Ci(this.currentLogFile))try{let e=Kl(this.currentLogFile,"r+");ql(e),ba(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(!ye()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ai(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ei(lr(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()?H.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ye())return!1;let e=typeof te.env.NO_COLOR<"u",t=te.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof te.stderr<"u"&&te.stderr.isTTY||typeof te.stdout<"u"&&te.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let l=te.stdout.columns||120,c="";if(s==="warning"||s==="error")c=`${r} ${n}`;else if(s==="info"||s==="success")c=`${r} ${i} ${n}`;else c=`${r} ${i} ${H.cyan(n)}`;if(!a)return c.trim();let u=o(c).trim().length,f=o(t).length,h=Math.max(1,l-2-u-f);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=H.underline(H.blue(i)),a=this.toAbsoluteFilePath(n);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,l="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${o}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>H.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>H.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>H.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>H.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>H.strikethrough(i)),t}supportsHyperlinks(){if(ye())return!1;let e=te.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=te.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Gm(t)||t.startsWith("./")||t.startsWith("../"))t=Wm(t);else return null;return Ci(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,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:l,fileText:c}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":mf[e],h=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:H.gray(l),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:H.green(l),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.error(d),o){let m=o.split(`
3
+ `);for(let p of m)if(p.trim()&&!p.includes(a))console.error(this.formatConsoleMessage({timestamp:n,message:H.gray(` ${p}`),level:e,showTimestamp:!1}))}break}}else if(!ye()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${c}
4
+ `;if(o)u+=`${o}
5
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};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()&&!ye()&&te.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!ye()&&te.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!ye()&&te.stdout.isTTY)te.stdout.write(`
6
+ `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!ye()&&te.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":H.blue("\u25D0"),tag:r,message:`${H.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,a=new Date,o=this.formatConsoleTimestamp(a),l=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
7
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":H.green("\u2713"),tag:c,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ye())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Un(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(ye())throw Error("createReadStream is not supported in browser environments");if(!Ci(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Wl(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=bt.isBuffer(e)?e:bt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),a=i.subarray(16,i.length-16),o=Im("aes-256-gcm",r,n);o.setAuthTag(s);let l=o.update(a),c=o.final(),u=l.length+c.length,f=bt.allocUnsafe(u);return l.copy(f,0),c.copy(f,l.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 ye()}isServerMode(){return!ye()}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:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let o=n.split(`
8
+ `),l=Math.max(...o.map((h)=>h.length))+2,c=`\u250C${"\u2500".repeat(l)}\u2510`,u=`\u2514${"\u2500".repeat(l)}\u2518`,f=o.map((h)=>this.formatConsoleMessage({timestamp:r,message:H.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(c),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(u),showTimestamp:!1}))}else if(!ye())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let a=`${i} ${this.environment}.INFO: [BOX] ${s}
9
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(ye())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${H.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();te.stdin.removeListener("data",r);try{if(typeof te.stdin.setRawMode==="function")te.stdin.setRawMode(!1)}catch{}te.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof te.stdin.setRawMode==="function")te.stdin.setRawMode(!0)}catch{}te.stdin.resume(),te.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,o=0;if(r=e.replace(a,(l,c)=>{if(c==="%")return"%";if(o>=t.length)return l;let u=t[o++];switch(c){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),o<t.length)r+=` ${t.slice(o).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${H.blue("\u25D0")} `;console.error(`${o}${a} ${H.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
10
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!te.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),n=e.barLength-i,s=H.green("\u2501".repeat(i)),a=H.gray("\u2501".repeat(n)),o=`[${s}${a}]`,l=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?H.green("\u2713"):H.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${H.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${o} ${l}${c}`,d=te.stdout.columns||80,m=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,te.stdout.write(e.lastRenderedLine),t)te.stdout.write(`
11
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ye()||!te.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(ye()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ai(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 n=lr(this.config.logDirectory,i);if(e.before)try{if((await or(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 Ei(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var uc,Ma,ei,Rp,we,H,Dp,fc,Lp,hc,jp,Bp,Ta,Ip,dc,mc,zp,Na,_p,Up,Vp,Gp,Wp,Qi,mf,qp,Kp=Lt(()=>{uc=bn.env.CLARITY_LOG_DIR||Lm(Fp(),"logs"),Ma={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ei={...Ma},Rp=(async()=>{try{let{loadConfig:e}=await Promise.resolve().then(()=>(Tf(),Mf)),t=await e({name:"clarity",alias:"logging",defaultConfig:Ma,cwd:bn.cwd()});if(t)Object.assign(ei,t)}catch{}return ei})(),we={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"},H=we,Dp=we.red,fc=we.green,Lp=we.yellow,hc=we.blue,jp=we.magenta,Bp=we.cyan,Ta=we.white,Ip=we.gray,dc=we.bgRed,mc=we.bgYellow,zp=we.bgGray,Na=we.bold,_p=we.dim,Up=we.italic,Vp=we.underline,Gp=we.strikethrough,Wp=we.reset,Qi={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},mf={debug:"\uD83D\uDD0D",info:hc("\u2139"),success:fc("\u2713"),warning:mc(Ta(Na(" WARN "))),error:dc(Ta(Na(" ERROR ")))},qp=new Un("stacks")}),Yp="0.15.9",Hp=()=>{};async function pf(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,a=Error("Unknown error occurred");for(let o=0;o<=r;o++)try{return await e()}catch(l){if(a=l instanceof Error?l:Error(String(l)),o===r||!n(a))break;if(i>0)await new Promise((c)=>setTimeout(c,i))}if(s!==void 0)return s;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function gf(e){return e instanceof Ge}function Jp(e){return e instanceof Sn}function Zp(e){if(gf(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()))}var Ge,Sn,ni,ws,bs,xn,vs,Ss,ai,xs,$s,Ut,Rr=Lt(()=>{Ge=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}`}},Sn=class extends Ge{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},ni=class extends Ge{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}},ws=class extends Ge{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},bs=class extends Ge{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}},xn=class extends Ge{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})}},vs=class extends Ge{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}},Ss=class extends Ge{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}},ai=class extends Ge{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})}},xs=class extends Ge{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})}},$s=class extends Ge{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}},Ut={configNotFound(e,t,r){return new Sn(e,t,r)},configLoad(e,t,r){return new ni(e,t,r)},configValidation(e,t,r){return new ws(e,t,r)},configMerge(e,t,r,i){return new bs(e,t,r,i)},envVar(e,t,r,i){return new xn(e,t,r,i)},fileSystem(e,t,r){return new vs(e,t,r)},typeGeneration(e,t,r){return new Ss(e,t,r)},schemaValidation(e,t,r){return new ai(e,t,r)},browserConfig(e,t,r,i){return new xs(e,t,r,i)},plugin(e,t,r){return new $s(e,t,r)}}});class Vn{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:n=!0,useBackwardCompatibility:s=!0,customParsers:a={},verbose:o=!1,trackPerformance:l=!0}=r,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:a,verbose:o,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return gi.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[n,s]of Object.entries(e)){let a=[...t,n],o=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),l=`${r}_${o.join("_")}`,c=i.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,a,r,i);else{let u=ki.env[l]||(c?ki.env[c]:void 0);if(u!==void 0){if(i.verbose){let f=ki.env[l]?l:c}try{e[n]=this.parseEnvironmentValue(u,typeof s,l,i.customParsers,i.configName)}catch(f){if(f instanceof xn)throw f;throw Ut.envVar(l,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,a]of Object.entries(i))try{return a(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Ut.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(ki.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;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(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],s,a),n){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[n,s]of Object.entries(e)){let a=[...t,n],o=`${r}_${a.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,a,r,i);else i.push({key:o,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${a.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
12
+
13
+ `;for(let i of e)r+=`${i.key}
14
+ `,r+=` Type: ${i.type}
15
+ `,r+=` Description: ${i.description}
16
+ `,r+=` Example: ${i.example}
17
+
18
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
19
+
20
+ `;r+=`| Variable | Type | Description | Example |
21
+ `,r+=`|----------|------|-------------|----------|
22
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
23
+ `;return r}}var yf=Lt(()=>{yi(),Rr()});function Qp(e,t){let r=Mp("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function wf(e,t,r={}){return bf(e,t,r,new WeakMap)}function bf(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return vf(e,t,n,i);if(!Je(t)||!Je(e))return t;return rg(e,t,r,i)}function vf(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 Xp(e,t);case"smart":return eg(e,t,i);default:return t}return t}function Xp(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Cs(n,i)))r.push(i);return r}function eg(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Je(t[0])&&Je(e[0]))return tg(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function tg(e,t,r){let i=[...t];for(let n of e){if(!Je(n)){i.push(n);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in n){if(i.find((l)=>Je(l)&&(o in l)&&l[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function rg(e,t,r,i){let n=t;if(Je(n)&&i.has(n))return i.get(n);let s={...e};if(Je(n))i.set(n,s);for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let o=n[a],l=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(Je(o)&&Je(l))s[a]=bf(l,o,r,i);else if(Array.isArray(o)||Array.isArray(l))s[a]=vf(l,o,r.arrayMergeMode||"smart",i);else s[a]=o}return s}function ho(e,t,r="replace"){return wf(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Cs(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(!Cs(e[r],t[r]))return!1;return!0}if(Je(e)&&Je(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Cs(e[n],t[n]))return!1}return!0}return!1}function Je(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}var Sf,mo=Lt(()=>{Sf={replace:"replace",concat:"concat",smart:"smart"}});class Gn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(n){let c=Or.getWithFileCheck("file",e);if(c){if(o)console.log(`Configuration loaded from cache: ${e}`);return c}}let l=async()=>{if(!Mi(e))return null;try{let c=`?t=${Date.now()}`,u=await import(e+c),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new ni(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new ni(e,Error("Configuration must export a valid object"),"unknown");let m={config:ho(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Or.setWithFileCheck("file",m,e,s);return m}catch(c){throw c instanceof Error?Ut.configLoad(e,c):Ut.configLoad(e,Error(String(c)))}};if(a)return gi.track("loadFromPath",l,{path:e});return l()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let a of this.extensions)n.push(Sa(t,`${s}${a}`));return n}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 s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return pf(async()=>Mi(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Mi(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let a of this.extensions){let o=Sa(e,`${s}${a}`);if(await this.checkFileAccess(o))i.push(o)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=Sa(e,a);if(await this.checkFileAccess(o))i.push(o)}}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(!Mi(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:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}var xf=Lt(()=>{yi(),Rr(),mo()});class po{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:l=!1}=r,c=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:a,trackPerformance:o,verbose:l};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(o)return await gi.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!Km(t))throw new ai(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new ai(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(i.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,rule:"type"}),s.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"}),s.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 o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(i.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,l]of Object.entries(t.properties))if(o in a){let c=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],l,c,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let l of Object.keys(a))if(!o.has(l))n.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(i.push(...o),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}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 n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))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 n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,a]=i;t.push({path:n,required:!s,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:$f},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var $f,Cf=Lt(()=>{yi(),Rr(),$f=/^https?:\/\//});function ig(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 go{fileLoader=new Gn;envProcessor=new Vn;validator=new po;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...a}=e;try{if(r?.enabled){let l=this.checkCache(a.name||"",a);if(l)return l}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(l){let c=a.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(c)throw l;o={...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(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),f=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),h=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(c&&(h||u))throw l;if(f&&(!c||!h))o={...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)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(n||s)await this.validateConfiguration(o.config,n,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(i?.enabled){let l={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(l);if(i.slowThreshold&&l.duration>i.slowThreshold)Ke.warn(`Slow configuration loading detected: ${l.duration}ms for ${a.name}`);o.metrics=l}return o}catch(o){let l=Date.now()-t;throw Ke.error(`Configuration loading failed after ${l}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:a,defaultConfig:o,checkEnv:l=!0,arrayStrategy:c="replace",verbose:u=!1}=e,f=s||er.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,a,o,c,u,l,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,a)),this.finalizeResult(d,h,l,i,u);let m=await this.loadHomeConfiguration(i,n,o,c,u,l);if(m)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(m,h,l,i,u);let p=await this.loadPackageJsonConfiguration(i,n,f,o,c,u,l);if(p)return h.push(je(f,"package.json")),this.finalizeResult(p,h,l,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,a)),t)throw Ut.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,o,l,u),warnings:[`No configuration file found for "${i}"${ig(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,l){let c=o?Kr(e,n,a):n,u=this.getLocalDirectories(r,i);for(let f of u){if(a)Ke.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:s,verbose:a,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(d){if(a)Ke.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let a=s?Kr(e,r,n):r,o=[je(ur(),".config",e),je(ur(),".config"),ur()];for(let l of o){if(n)Ke.info(`Checking home directory: ${l}`);let c=this.fileLoader.generateConfigPaths(e,l,t),u=await this.fileLoader.tryLoadFromPaths(c,a,{arrayStrategy:i,verbose:n});if(u){if(n)Ke.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,a){let o=a?Kr(e,i,s):i;try{let l=je(r,"package.json");if(!gs(l))return null;let c={};try{c=JSON.parse(Jm(l,"utf8"))}catch(h){if(s)Ke.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=c[e],f=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(c[d]){u=c[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Ke.success(`Configuration loaded from package.json: ${f}`);return{config:ho(o,u,n),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(s)Ke.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}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:Kr(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(n.length>0)throw Ut.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Or.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Or.set(n,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,je(e,"config"),je(e,".config"),t?je(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(je(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let a of n)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[je(ur(),".config",e),je(ur(),".config"),ur()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function pc(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 ng(e){return Nt.loadConfig({...e,__strictErrorHandling:!0})}async function Af(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 Nt.loadConfig(e);else i=await Nt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)Ke.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 Nt.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function ag(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Nt.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"&&pc(r)))return(await Nt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Nt.loadConfig({...e,cwd:e.cwd||er.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&pc(t)))return(await Nt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function sg(e,t,r="replace"){let i=new Gn;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Kr(e,t,r=!1){let i=new Vn,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let l={...a};for(let[c,u]of Object.entries(a)){let f=[...o,c],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((p)=>p.toUpperCase()).join("")}`,`${n}_${f.map((p)=>p.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,m;for(let p of h)if(d=er.env[p],d!==void 0){m=p;break}if(d!==void 0&&m)if(typeof u==="boolean")l[c]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let p=Number(d);if(!Number.isNaN(p))l[c]=p}else if(Array.isArray(u))try{l[c]=JSON.parse(d)}catch{l[c]=d.split(",").map((p)=>p.trim())}else l[c]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))l[c]=s(u,f)}return l}return s(t)}function og(e){let t=je(er.cwd(),e.configDir),r=je(er.cwd(),e.generatedDir),i=je(r,"config-types.ts");if(!gs(Zl(i)))Ym(Zl(i),{recursive:!0,mode:511});let n=gs(t)?Hm(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${Yp}
24
+ export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
25
+ `;Zm(i,s,{mode:438})}function lg(e){let t=null,r=null,i=()=>{if(!r)r=Af(e).then((s)=>(t=s,s),(s)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)Ke.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return a});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,a){if(t)return t[a];let o=n[a];return i(),o},has(s,a){return a in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,a){return Object.getOwnPropertyDescriptor(t||n,a)},set(s,a,o){if(!t)t={...n};return t[a]=o,!0}})}var Ke,Nt,Ef,kf,cg=Lt(()=>{Kp(),Hp(),yi(),Rr(),yf(),xf(),Cf(),mo(),Ke=new Un("bunfig",{showTags:!0}),Nt=new go,Ef=je(er.cwd(),"config"),kf=je(er.cwd(),"src/generated")});function ug(e){let t=Ql(ep.cwd(),e?.configDir||"./config");function r(){if(!Qm(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=Xm(t).filter((l)=>n.has(xa(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),o=new Map;for(let{base:l,file:c}of a){let u=xa(c).toLowerCase(),f=o.get(l);if(!f){o.set(l,c);continue}let h=xa(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))o.set(l,c)}return Array.from(o.entries()).map(([l,c])=>({base:l,file:c})).sort((l,c)=>l.base.localeCompare(c.base))}function i(){let n=r(),s=n.map((l)=>l.base),a=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",o=n.length?`{
26
+ ${n.map((l)=>{let c=Ql(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${c}').default`}).join(`,
27
+ `)}
28
+ }`:"Record<string, any>";return`export type ConfigNames = ${a}
29
+ export type ConfigByName = ${o}
30
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
31
+ export type ConfigOf = Config
32
+ `}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var fg=()=>{},Mf={};kp(Mf,{withErrorRecovery:()=>pf,tryLoadConfig:()=>sg,loadConfigWithResult:()=>ng,loadConfig:()=>Af,isRetryableError:()=>Zp,isConfigNotFoundError:()=>Jp,isBunfigError:()=>gf,globalPerformanceMonitor:()=>gi,globalCache:()=>Or,getEnvOrDefault:()=>Qp,generateConfigTypes:()=>og,defaultGeneratedDir:()=>kf,defaultConfigDir:()=>Ef,deepMergeWithArrayStrategy:()=>ho,deepMerge:()=>wf,createLibraryConfig:()=>lg,config:()=>ag,bunfigPlugin:()=>ug,applyEnvVarsToConfig:()=>Kr,TypeGenerationError:()=>Ss,SchemaValidationError:()=>ai,PluginError:()=>$s,PerformanceMonitor:()=>fo,FileSystemError:()=>vs,ErrorFactory:()=>Ut,EnvVarError:()=>xn,EnvProcessor:()=>Vn,ConfigValidator:()=>po,ConfigValidationError:()=>ws,ConfigNotFoundError:()=>Sn,ConfigMergeError:()=>bs,ConfigLoader:()=>go,ConfigLoadError:()=>ni,ConfigFileLoader:()=>Gn,ConfigCache:()=>uo,CacheUtils:()=>hf,BunfigError:()=>Ge,BrowserConfigError:()=>xs,ArrayMergeStrategies:()=>Sf});var Tf=Lt(()=>{cg(),Rr(),yi(),Rr(),fg(),yf(),xf(),Cf(),mo()});Tf();var hg={verbose:!1,tolerance:0.25,background:"transparent",currentColor:"black",maxUseDepth:16},qC={...hg},dg={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},KC=new Map(Object.entries(dg)),YC=new Uint8Array(0),HC=new Float32Array(0),JC=new Uint8Array([137,80,78,71,13,10,26,10]);var _t={GRAYSCALE:0,PALETTE:1,COLOR:2,ALPHA:4},$n={PALETTE_COLOR:3,COLOR_ALPHA:6},ZC={[_t.GRAYSCALE]:1,[_t.COLOR]:3,[$n.PALETTE_COLOR]:1,[_t.GRAYSCALE|_t.ALPHA]:2,[$n.COLOR_ALPHA]:4};var{GRAYSCALE:QC,PALETTE:XC,COLOR:eA,ALPHA:tA}=_t,rA=$n.PALETTE_COLOR,iA=$n.COLOR_ALPHA,mg=new Uint32Array(256);(function(){for(let e=0;e<256;e++){let t=e;for(let r=0;r<8;r++)t=t&1?3988292384^t>>>1:t>>>1;mg[e]=t}})();function Nf(e,t,r){return Math.round(0.2126*e+0.7152*t+0.0722*r)}function pg(e,t,r){return`#${(16777216|e<<16|t<<8|r).toString(16).slice(1)}`}function yo(e,t,r){return e<<16|t<<8|r}function gc(e,t,r){let i=[];for(let n=0;n<r;n++){let s=0;while(s<t){while(s<t&&e[n*t+s]===0)s++;if(s>=t)break;let a=s;while(s<t&&e[n*t+s]===1)s++;let o=s-a;i.push(`M${a} ${n}h${o}v1h-${o}Z`)}}return i.join("")}function gg(e,t){let{data:r,width:i,height:n}=e,s=new Uint8Array(i*n);for(let a=0,o=0;a<r.length;a+=4,o++){if(r[a+3]===0){s[o]=0;continue}s[o]=Nf(r[a],r[a+1],r[a+2])<t?1:0}return s}function yg(e,t){let{data:r,width:i,height:n}=e,s=new Map,a=255/Math.max(1,t-1);for(let o=0,l=0;o<r.length;o+=4,l++){if(r[o+3]===0)continue;let c=Math.round(Math.round(r[o]/a)*a),u=Math.round(Math.round(r[o+1]/a)*a),f=Math.round(Math.round(r[o+2]/a)*a),h=yo(c,u,f),d=s.get(h);if(!d)d=new Uint8Array(i*n),s.set(h,d);d[l]=1}return s}function wg(e,t){let{data:r,width:i,height:n}=e,s=new Map,a=255/Math.max(1,t-1);for(let o=0,l=0;o<r.length;o+=4,l++){if(r[o+3]===0)continue;let c=Nf(r[o],r[o+1],r[o+2]),u=Math.round(Math.round(c/a)*a),f=yo(u,u,u),h=s.get(f);if(!h)h=new Uint8Array(i*n),s.set(f,h);h[l]=1}return s}function bg(e,t){let{data:r,width:i,height:n}=e,s=6,a=new Uint32Array(216);for(let f=0;f<r.length;f+=4){if(r[f+3]===0)continue;let h=Math.min(5,Math.floor(r[f]*6/256)),d=Math.min(5,Math.floor(r[f+1]*6/256)),m=Math.min(5,Math.floor(r[f+2]*6/256));a[h*6*6+d*6+m]++}let o=[];for(let f=0;f<a.length;f++)if(a[f]>0)o.push({idx:f,count:a[f]});o.sort((f,h)=>h.count-f.count);let l=[],c=Math.min(t,256,o.length);for(let f=0;f<c;f++){let h=o[f].idx,d=Math.floor(h/36),m=Math.floor(h/6%6),p=h%6,y=Math.round((d+0.5)*256/6),g=Math.round((m+0.5)*256/6),w=Math.round((p+0.5)*256/6);l.push({key:yo(y,g,w),r:y,g,b:w})}let u=new Map;for(let f of l)u.set(f.key,new Uint8Array(i*n));for(let f=0,h=0;f<r.length;f+=4,h++){if(r[f+3]===0)continue;let d=r[f],m=r[f+1],p=r[f+2],y=l[0].key,g=Number.POSITIVE_INFINITY;for(let w=0;w<l.length;w++){let b=d-l[w].r,v=m-l[w].g,S=p-l[w].b,E=b*b+v*v+S*S;if(E<g)g=E,y=l[w].key}u.get(y)[h]=1}return u}function vg(e,t={}){let{width:r,height:i}=e;if(!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0)throw Error("ts-svg: traceImage requires positive integer width and height");if(e.data.length<r*i*4)throw Error("ts-svg: traceImage data buffer is too small for the given dimensions");let{mode:n="color",threshold:s=128,colorCount:a=16,steps:o=4,background:l,bwFill:c="black"}=t,u=l?`<rect width="100%" height="100%" fill="${l}"/>`:"",f=`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${i}" viewBox="0 0 ${r} ${i}">`,h="</svg>";if(n==="bw"){let y=gg(e,s),g=gc(y,r,i),w=`<path fill="${c}" d="${g}"/>`;return{svg:`${f}${u}${w}${h}`,width:r,height:i}}let d;if(n==="posterized")d=yg(e,o);else if(n==="grayscale")d=wg(e,Math.max(2,o));else d=bg(e,a);let m=Array.from(d.entries()).map(([y,g])=>{let w=0;for(let b=0;b<g.length;b++)w+=g[b];return{key:y,mask:g,count:w}});m.sort((y,g)=>g.count-y.count);let p=[];for(let{key:y,mask:g}of m){let w=gc(g,r,i);if(!w)continue;let b=y>>16&255,v=y>>8&255,S=y&255;p.push(`<path fill="${pg(b,v,S)}" d="${w}"/>`)}return{svg:`${f}${u}${p.join("")}${h}`,width:r,height:i}}var Pf={};D(Pf,{name:()=>Sg,fn:()=>$g,description:()=>xg});var Sg="addAttributesToSVGElement",xg="adds attributes to an outer <svg> element",$g=(e,t)=>{if(!t||!Array.isArray(t.attributes)&&!t.attribute)return console.error(`Error in plugin "addAttributesToSVGElement": absent parameters.
33
+ It should have a list of "attributes" or one "attribute".`),null;let r=t.attributes||[t.attribute];return{element:{enter:(i,n)=>{if(i.name==="svg"&&n.type==="root")for(let s of r){if(typeof s==="string"){if(i.attributes[s]==null)i.attributes[s]=void 0}if(typeof s==="object"&&s!=null){for(let a of Object.keys(s))if(i.attributes[a]==null)i.attributes[a]=s[a]}}}}}},Ff={};D(Ff,{name:()=>Cg,fn:()=>Eg,description:()=>Ag});var Cg="addClassesToSVGElement",Ag="adds classnames to an outer <svg> element",Eg=(e,t,r)=>{if(!(t&&Array.isArray(t.classNames)&&t.classNames.length!==0)&&!t?.className)return console.error('Error in plugin "addClassesToSVGElement": absent parameters.'),null;let i=t.classNames||[t.className];return{element:{enter:(n,s)=>{if(n.name==="svg"&&s.type==="root"){let a=new Set(n.attributes.class==null?null:n.attributes.class.split(" "));for(let o of i)if(o!=null){let l=typeof o==="string"?o:o(n,r);a.add(l)}n.attributes.class=Array.from(a).join(" ")}}}}},wo={};D(wo,{name:()=>kg,fn:()=>Fg,description:()=>Mg});var kg="cleanupAttrs",Mg="cleanups attributes from newlines, trailing and repeating spaces",Tg=/(\S)\r?\n(\S)/g,Ng=/\r?\n/g,Pg=/\s{2,}/g,Fg=(e,t)=>{let{newlines:r=!0,trim:i=!0,spaces:n=!0}=t||{};return{element:{enter:(s)=>{for(let a of Object.keys(s.attributes)){if(r)s.attributes[a]=s.attributes[a].replace(Tg,(o,l,c)=>`${l} ${c}`),s.attributes[a]=s.attributes[a].replace(Ng,"");if(i)s.attributes[a]=s.attributes[a].trim();if(n)s.attributes[a]=s.attributes[a].replace(Pg," ")}}}}},bo={};D(bo,{name:()=>H0,fn:()=>Q0,description:()=>J0});var Og=Object.defineProperty,Rg=(e)=>e;function Dg(e,t){this[e]=Rg.bind(null,t)}var Wn=(e,t)=>{for(var r in t)Og(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Dg.bind(t,r)})},G={};Wn(G,{walk:()=>Kn,parse:()=>So,makeList:()=>Lg,generate:()=>Ue,decodeName:()=>Df,clone:()=>jg,Tokenizer:()=>vo,TokenType:()=>Of,List:()=>Ze});function mt(e){return{prev:null,next:null,data:e}}class Ze{head=null;tail=null;cursors=[];allocateCursor(e,t){let r={prev:e,next:t};return this.cursors.push(r),r}releaseCursor(){this.cursors.pop()}updateCursors(e,t,r,i){for(let n of this.cursors){if(n.prev===e)n.prev=t;if(n.next===r)n.next=i}}static createItem(e){return mt(e)}createItem(e){return mt(e)}get isEmpty(){return this.head===null}get first(){return this.head?.data??null}get last(){return this.tail?.data??null}*[Symbol.iterator](){for(let e=this.head;e!=null;e=e.next)yield e.data}fromArray(e){let t=null;this.head=null;for(let r of e){let i=mt(r);if(i.prev=t,t)t.next=i;else this.head=i;t=i}return this.tail=t,this}toArray(){let e=[];for(let t=this.head;t!=null;t=t.next)e.push(t.data);return e}toJSON(){return this.toArray()}forEach(e,t){let r=this.allocateCursor(null,this.head);while(r.next!==null){let i=r.next;r.prev=i,r.next=i.next,e.call(t,i.data,i,this)}this.releaseCursor()}forEachRight(e,t){let r=this.allocateCursor(this.tail,null);while(r.prev!==null){let i=r.prev;r.next=i,r.prev=i.prev,e.call(t,i.data,i,this)}this.releaseCursor()}reduce(e,t){let r=t,i=0;for(let n=this.head;n!=null;n=n.next)r=e(r,n.data,i++,this);return r}some(e){let t=0;for(let r=this.head;r!=null;r=r.next)if(e(r.data,t++,this))return!0;return!1}map(e){let t=new Ze,r=null,i=0;for(let n=this.head;n!=null;n=n.next){let s=mt(e(n.data,i++,this));if(s.prev=r,r)r.next=s;else t.head=s;r=s}return t.tail=r,t}filter(e){let t=new Ze,r=null,i=0;for(let n=this.head;n!=null;n=n.next)if(e(n.data,i++,this)){let s=mt(n.data);if(s.prev=r,r)r.next=s;else t.head=s;r=s}return t.tail=r,t}clear(){let e=this.head;while(e){let t=e.next;e.prev=null,e.next=null,e=t}this.head=null,this.tail=null}copy(){let e=new Ze,t=null;for(let r=this.head;r!=null;r=r.next){let i=mt(r.data);if(i.prev=t,t)t.next=i;else e.head=i;t=i}return e.tail=t,e}prepend(e){return this.insert(e,this.head)}prependData(e){return this.insert(mt(e),this.head)}append(e){return this.insert(e,null)}appendData(e){return this.insert(mt(e),null)}insert(e,t=null){if(t!=null)if(this.updateCursors(t.prev,e,t,e),t.prev===null){if(this.head!==t)throw Error("before doesn't belong to list");this.head=e,t.prev=e,e.next=t,this.updateCursors(null,e,null,null)}else t.prev.next=e,e.prev=t.prev,t.prev=e,e.next=t;else if(this.updateCursors(this.tail,e,null,e),this.tail!==null)this.tail.next=e,e.prev=this.tail,this.tail=e;else this.head=e,this.tail=e;return this}insertData(e,t=null){return this.insert(mt(e),t)}remove(e){if(this.updateCursors(e,e.prev,e,e.next),e.prev!==null)e.prev.next=e.next;else if(this.head===e)this.head=e.next;else throw Error("item doesn't belong to list");if(e.next!==null)e.next.prev=e.prev;else if(this.tail===e)this.tail=e.prev;else throw Error("item doesn't belong to list");return e.prev=null,e.next=null,e}push(e){this.insert(mt(e),null)}pop(){if(this.tail===null)return null;return this.remove(this.tail)}unshift(e){this.prependData(e)}shift(){if(this.head===null)return null;return this.remove(this.head)}prependList(e){return this.insertList(e,this.head)}appendList(e){return this.insertList(e,null)}insertList(e,t=null){if(e.head===null)return this;if(t!==null){if(this.updateCursors(t.prev,e.tail,t,e.head),t.prev!==null)t.prev.next=e.head,e.head.prev=t.prev;else this.head=e.head;t.prev=e.tail,e.tail.next=t}else{if(this.updateCursors(this.tail,e.tail,null,e.head),this.tail!==null)this.tail.next=e.head,e.head.prev=this.tail;else this.head=e.head;this.tail=e.tail}return e.head=null,e.tail=null,this}replace(e,t){if(t instanceof Ze)this.insertList(t,e),this.remove(e);else this.insert(t,e),this.remove(e)}}function Lg(){return new Ze}function jg(e){return Yr(e)}function Yr(e){if(e===null||typeof e!=="object")return e;if(e instanceof Ze){let r=new Ze;for(let i of e)r.appendData(Yr(i));return r}if(Array.isArray(e))return e.map(Yr);if("type"in e&&typeof e.type==="string"){let r={type:e.type};for(let i of Object.keys(e)){if(i==="type")continue;r[i]=Yr(e[i])}return r}let t={};for(let r of Object.keys(e))t[r]=Yr(e[r]);return t}function Ue(e){switch(e.type){case"StyleSheet":return Ve(e.children,"");case"Rule":return`${Ue(e.prelude)}{${Ue(e.block)}}`;case"Block":return Bg(e.children);case"Atrule":{let t=`@${e.name}`;if(e.prelude){let r=Ue(e.prelude);if(r)t+=` ${r}`}if(e.block)t+=`{${Ue(e.block)}}`;else t+=";";return t}case"AtrulePrelude":return Ve(e.children,"");case"SelectorList":return Ve(e.children,",");case"Selector":return Ve(e.children,"");case"TypeSelector":return e.name;case"IdSelector":return`#${e.name}`;case"ClassSelector":return`.${e.name}`;case"NestingSelector":return"&";case"AttributeSelector":{let t=`[${e.name.name}`;if(e.matcher&&e.value)if(t+=e.matcher,e.value.type==="String")t+=`"${Pa(e.value.value)}"`;else t+=e.value.name;if(e.flags)t+=` ${e.flags}`;return t+="]",t}case"PseudoClassSelector":return e.children?`:${e.name}(${Ve(e.children,"")})`:`:${e.name}`;case"PseudoElementSelector":return e.children?`::${e.name}(${Ve(e.children,"")})`:`::${e.name}`;case"Combinator":return e.name===" "?" ":e.name;case"Declaration":return`${e.property}:${Ue(e.value)}${e.important?"!important":""}`;case"DeclarationList":return Ve(e.children,";");case"Value":return Ve(e.children,"");case"Identifier":return e.name;case"Number":return e.value;case"Percentage":return`${e.value}%`;case"Dimension":return e.value+e.unit;case"String":return`"${Pa(e.value)}"`;case"Url":return/[\s"'()\\\u0000-\u001F\u007F]/.test(e.value)?`url("${Pa(e.value)}")`:`url(${e.value})`;case"Hash":return`#${e.name}`;case"Operator":return e.value;case"Function":return`${e.name}(${Ve(e.children,"")})`;case"Parentheses":return`(${Ve(e.children,"")})`;case"Brackets":return`[${Ve(e.children,"")}]`;case"Raw":return e.value;case"Comment":return e.value.startsWith("!")?`/*${e.value}*/`:"";case"WhiteSpace":return" ";case"CDO":return"<!--";case"CDC":return"-->";case"AnPlusB":{let t=e.a??"",r=e.b??"";if(t&&r){let i=Number(r);return`${t==="1"?"":t==="-1"?"-":t}n${i>=0?`+${r}`:r}`}if(t)return`${t==="1"?"":t==="-1"?"-":t}n`;return r}case"Ratio":return`${e.left.value}/${e.right.value}`;case"UnicodeRange":return e.value;case"Nth":return e.selector?`${Ue(e.nth)} of ${Ue(e.selector)}`:Ue(e.nth);case"MediaQueryList":return Ve(e.children,",");case"MediaQuery":return Ve(e.children,"");case"MediaFeature":{let t=`(${e.name}`;if(e.value)t+=`:${Ue(e.value)}`;return t+=")",t}}return""}function Ve(e,t){let r="",i=!0,n=null,s=e.head;while(s!=null){let a=s.data;if(a.type==="WhiteSpace"){let l=s.next?s.next.data:null;if(yc(n)||yc(l)){s=s.next;continue}}let o=Ue(a);if(!o){s=s.next;continue}if(!i&&t&&!zg(n))r+=t;i=!1,r+=o,n=a,s=s.next}return r}function Bg(e){let t="",r=null,i=e.head;while(i!=null){let n=i.data,s=Ue(n);if(!s){i=i.next;continue}if(r&&Ig(r,n))t+=";";t+=s,r=n,i=i.next}return t}function Ig(e,t){return e.type==="Declaration"&&t.type!=="Comment"}function yc(e){if(!e||e.type!=="Operator")return!1;let t=e.value;return t===":"||t===","||t==="/"}function zg(e){if(!e)return!1;return e.type==="Operator"||e.type==="Combinator"}function Pa(e){let t="";for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i===92)t+="\\\\";else if(i===34)t+="\\\"";else if(i<32||i===127){let n=i.toString(16),s=r+1<e.length?e.charCodeAt(r+1):-1,a=s===32||s===9||s===10||s===12||s===13||s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102;t+=`\\${n}${a?" ":""}`}else t+=e[r]}return t}var Of;((e)=>{e[e.EOF=0]="EOF",e[e.Ident=1]="Ident",e[e.Function=2]="Function",e[e.AtKeyword=3]="AtKeyword",e[e.Hash=4]="Hash",e[e.String=5]="String",e[e.BadString=6]="BadString",e[e.Url=7]="Url",e[e.BadUrl=8]="BadUrl",e[e.Delim=9]="Delim",e[e.Number=10]="Number",e[e.Percentage=11]="Percentage",e[e.Dimension=12]="Dimension",e[e.WhiteSpace=13]="WhiteSpace",e[e.CDO=14]="CDO",e[e.CDC=15]="CDC",e[e.Colon=16]="Colon",e[e.Semicolon=17]="Semicolon",e[e.Comma=18]="Comma",e[e.LeftSquareBracket=19]="LeftSquareBracket",e[e.RightSquareBracket=20]="RightSquareBracket",e[e.LeftParenthesis=21]="LeftParenthesis",e[e.RightParenthesis=22]="RightParenthesis",e[e.LeftCurlyBracket=23]="LeftCurlyBracket",e[e.RightCurlyBracket=24]="RightCurlyBracket",e[e.Comment=25]="Comment"})(Of||={});var As=65533,ar=(()=>{let e=new Uint8Array(128);for(let t=0;t<128;t++){let r=0;if(t===32||t===9||t===10||t===12||t===13)r|=1;if(t>=48&&t<=57)r|=2;if(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102)r|=4;if(t>=65&&t<=90||t>=97&&t<=122||t===95)r|=8;if(t===10||t===12||t===13)r|=16;e[t]=r}return e})();function at(e){return e<128&&(ar[e]&2)!==0}function si(e){return e<128&&(ar[e]&4)!==0}function wc(e){return e>=128||e<128&&(ar[e]&8)!==0}function _g(e){return e===45||e>=128||e<128&&(ar[e]&10)!==0}function Ug(e){return e>=0&&e<=8||e===11||e>=14&&e<=31||e===127}function Es(e){return e<128&&(ar[e]&16)!==0}function At(e){return e<128&&(ar[e]&1)!==0}function Jt(e,t){if(e!==92)return!1;if(Es(t))return!1;return!0}function Fa(e,t,r){if(e===45)return wc(t)||t===45||Jt(t,r);if(wc(e))return!0;if(e===92)return Jt(e,t);return!1}function Vg(e,t,r){if(e===43||e===45){if(at(t))return!0;if(t===46&&at(r))return!0;return!1}if(e===46)return at(t);return at(e)}class vo{source;offset=0;types;starts;ends;count=0;_tokens=null;_lineStarts=null;constructor(e){this.source=e;let t=Math.max(64,Math.ceil(e.length/3));this.types=new Uint8Array(t),this.starts=new Uint32Array(t),this.ends=new Uint32Array(t),this.tokenize()}get lineStarts(){if(this._lineStarts==null)this._lineStarts=Gg(this.source);return this._lineStarts}get tokens(){if(this._tokens!=null)return this._tokens;let e=Array.from({length:this.count});for(let t=0;t<this.count;t++)e[t]={type:this.types[t],start:this.starts[t],end:this.ends[t]};return this._tokens=e,e}addToken(e,t,r){if(this.count>=this.types.length)this.grow();this.types[this.count]=e,this.starts[this.count]=t,this.ends[this.count]=r,this.count++}grow(){let e=this.types.length*2,t=new Uint8Array(e);t.set(this.types),this.types=t;let r=new Uint32Array(e);r.set(this.starts),this.starts=r;let i=new Uint32Array(e);i.set(this.ends),this.ends=i}tokenize(){let e=this.source,t=0,r=e.length;while(t<r){let i=e.charCodeAt(t);if(i===47&&e.charCodeAt(t+1)===42){let a=t;t+=2;while(t<r&&!(e.charCodeAt(t)===42&&e.charCodeAt(t+1)===47))t++;t=t<r?t+2:r,this.addToken(25,a,t);continue}if(At(i)){let a=t;while(t<r&&At(e.charCodeAt(t)))t++;this.addToken(13,a,t);continue}if(i===34||i===39){t=this.consumeString(i,t);continue}if(i===35){if(t+1<r&&(_g(e.charCodeAt(t+1))||Jt(e.charCodeAt(t+1),e.charCodeAt(t+2)))){let a=t;t++,t=this.consumeName(t),this.addToken(4,a,t);continue}this.addToken(9,t,t+1),t++;continue}switch(i){case 40:this.addToken(21,t,t+1),t++;continue;case 41:this.addToken(22,t,t+1),t++;continue;case 91:this.addToken(19,t,t+1),t++;continue;case 93:this.addToken(20,t,t+1),t++;continue;case 123:this.addToken(23,t,t+1),t++;continue;case 125:this.addToken(24,t,t+1),t++;continue;case 44:this.addToken(18,t,t+1),t++;continue;case 58:this.addToken(16,t,t+1),t++;continue;case 59:this.addToken(17,t,t+1),t++;continue}if(i===60&&e.startsWith("!--",t+1)){this.addToken(14,t,t+4),t+=4;continue}if(i===45&&e.startsWith("->",t+1)){this.addToken(15,t,t+3),t+=3;continue}if(i===64){let a=e.charCodeAt(t+1),o=e.charCodeAt(t+2),l=e.charCodeAt(t+3);if(Fa(a,o,l)){let c=t;t++,t=this.consumeName(t),this.addToken(3,c,t);continue}this.addToken(9,t,t+1),t++;continue}let n=e.charCodeAt(t+1),s=e.charCodeAt(t+2);if(Vg(i,n,s)){t=this.consumeNumeric(t);continue}if(Fa(i,n,s)){t=this.consumeIdentLike(t);continue}if(i===92){if(Jt(i,n)){t=this.consumeIdentLike(t);continue}this.addToken(9,t,t+1),t++;continue}this.addToken(9,t,t+1),t++}this.addToken(0,r,r)}consumeString(e,t){let r=this.source,i=r.length,n=t+1;while(n<i){let s=r.charCodeAt(n);if(s===e)return n++,this.addToken(5,t,n),n;if(Es(s))return this.addToken(6,t,n),n;if(s===92){let a=r.charCodeAt(n+1);if(Es(a)){n+=2;continue}if(n+1<i){n=this.consumeEscapeSkip(n+1);continue}}n++}return this.addToken(5,t,n),n}consumeEscapeSkip(e){let t=this.source;if(e>=t.length)return e;let r=t.charCodeAt(e);if(si(r)){let i=1;e++;while(i<6&&e<t.length&&si(t.charCodeAt(e)))e++,i++;if(e<t.length&&At(t.charCodeAt(e)))e++;return e}return e+1}consumeName(e){let t=this.source,r=t.length,i=e;while(i<r){let n=t.charCodeAt(i);if(n<128&&(ar[n]&10)!==0){i++;continue}if(n===45){i++;continue}if(n>=128){i++;continue}if(n===92&&Jt(n,t.charCodeAt(i+1))){i=this.consumeEscapeSkip(i+1);continue}break}return i}consumeNumber(e){let t=this.source,r=e;if(t.charCodeAt(r)===43||t.charCodeAt(r)===45)r++;while(r<t.length&&at(t.charCodeAt(r)))r++;if(t.charCodeAt(r)===46&&at(t.charCodeAt(r+1))){r+=2;while(r<t.length&&at(t.charCodeAt(r)))r++}let i=t.charCodeAt(r);if(i===69||i===101){let n=t.charCodeAt(r+1),s=t.charCodeAt(r+2);if(at(n)){r+=2;while(r<t.length&&at(t.charCodeAt(r)))r++}else if((n===43||n===45)&&at(s)){r+=3;while(r<t.length&&at(t.charCodeAt(r)))r++}}return r}consumeNumeric(e){let t=this.source,r=this.consumeNumber(e),i=t.charCodeAt(r),n=t.charCodeAt(r+1),s=t.charCodeAt(r+2);if(Fa(i,n,s)){let a=this.consumeName(r);return this.addToken(12,e,a),a}if(i===37)return this.addToken(11,e,r+1),r+1;return this.addToken(10,e,r),r}consumeIdentLike(e){let t=this.source,r=this.consumeName(e),i=t.charCodeAt(r);if(i===40&&r-e===3){let n=t.charCodeAt(e)|32,s=t.charCodeAt(e+1)|32,a=t.charCodeAt(e+2)|32;if(n===117&&s===114&&a===108){let o=r+1;while(o<t.length&&At(t.charCodeAt(o)))o++;let l=t.charCodeAt(o);if(l===34||l===39)return this.addToken(2,e,r+1),r+1;return this.consumeUrl(e,r)}}if(i===40)return this.addToken(2,e,r+1),r+1;return this.addToken(1,e,r),r}consumeUrl(e,t){let r=this.source,i=r.length,n=t+1;while(n<i&&At(r.charCodeAt(n)))n++;while(n<i){let s=r.charCodeAt(n);if(s===41)return n++,this.addToken(7,e,n),n;if(At(s)){let a=n;while(n<i&&At(r.charCodeAt(n)))n++;if(n>=i)return this.addToken(7,e,n),n;if(r.charCodeAt(n)===41)return n++,this.addToken(7,e,n),n;return this.consumeBadUrl(e,a)}if(s===34||s===39||s===40||Ug(s))return this.consumeBadUrl(e,n);if(s===92){if(Jt(s,r.charCodeAt(n+1))){n=this.consumeEscapeSkip(n+1);continue}return this.consumeBadUrl(e,n)}n++}return this.addToken(7,e,n),n}consumeBadUrl(e,t){let r=this.source,i=t;while(i<r.length){let n=r.charCodeAt(i);if(n===41){i++;break}if(n===92&&Jt(n,r.charCodeAt(i+1))){i=this.consumeEscapeSkip(i+1);continue}i++}return this.addToken(8,e,i),i}locate(e){let t=this.lineStarts,r=0,i=t.length-1;while(r<i){let s=r+i+1>>1;if(t[s]<=e)r=s;else i=s-1}let n=t[r];return{line:r+1,column:e-n+1}}}function Gg(e){let t=[0],r=e.length;for(let i=0;i<r;i++){let n=e.charCodeAt(i);if(n===10)t.push(i+1);else if(n===13){if(e.charCodeAt(i+1)!==10)t.push(i+1)}}return t}function Rf(e,t,r){for(let i=t;i<r;i++)if(e.charCodeAt(i)===92)return Wg(e,t,r,i);return e.slice(t,r)}function Wg(e,t,r,i){let n=e.slice(t,i),s=i;while(s<r){if(e.charCodeAt(s)!==92){n+=e[s],s++;continue}if(s+1>=r){s++;continue}let a=e.charCodeAt(s+1);if(a===10){s+=2;continue}if(a===13){s+=e.charCodeAt(s+2)===10?3:2;continue}if(si(a)){let o=s+1,l="";while(l.length<6&&o<r&&si(e.charCodeAt(o)))l+=e[o],o++;let c=Number.parseInt(l,16);if(o<r&&At(e.charCodeAt(o)))o++;n+=c===0||c>=55296&&c<=57343||c>1114111?String.fromCodePoint(As):String.fromCodePoint(c),s=o;continue}n+=e[s+1],s+=2}return n}function Df(e,t,r){for(let i=t;i<r;i++)if(e.charCodeAt(i)===92)return qg(e,t,r,i);return e.slice(t,r)}function qg(e,t,r,i){let n=e.slice(t,i),s=i;while(s<r){if(e.charCodeAt(s)!==92){n+=e[s],s++;continue}let a=s+1,o="";while(o.length<6&&a<r&&si(e.charCodeAt(a)))o+=e[a],a++;if(o.length>0){let l=Number.parseInt(o,16);if(a<r&&At(e.charCodeAt(a)))a++;n+=l===0||l>=55296&&l<=57343||l>1114111?String.fromCodePoint(As):String.fromCodePoint(l),s=a;continue}if(a<r){n+=e[a],s=a+1;continue}n+=String.fromCodePoint(As),s=a}return n}function Lf(e,t){let r=new vo(e);return{source:e,types:r.types,starts:r.starts,ends:r.ends,count:r.count,end:r.count,pos:0,positions:t.positions??!1,filename:t.filename,parseValue:t.parseValue??!0,parseAtrulePrelude:t.parseAtrulePrelude??!0,parseCustomProperty:t.parseCustomProperty??!1,parseRulePrelude:t.parseRulePrelude??!0,onParseError:t.onParseError,tokenizer:r}}function j(e){return e.pos<e.end?e.types[e.pos]:0}function B(e){let t=e.pos;if(t>=e.end)return{type:0,start:e.starts[t]??e.source.length,end:e.ends[t]??e.source.length};return{type:e.types[t],start:e.starts[t],end:e.ends[t]}}function I(e){let t=e.pos++;if(t>=e.end)return{type:0,start:e.starts[t]??e.source.length,end:e.ends[t]??e.source.length};return{type:e.types[t],start:e.starts[t],end:e.ends[t]}}function gt(e,t){return e.source.slice(t.start,t.end)}function lt(e){let{types:t,end:r}=e;while(e.pos<r){let i=t[e.pos];if(i===13||i===25)e.pos++;else break}}function bc(e){let{types:t,end:r}=e;while(e.pos<r&&t[e.pos]===13)e.pos++}function z(e,t,r){if(!e.positions)return null;let i=e.tokenizer.locate(t.start),n=e.tokenizer.locate(r.end);return{source:e.filename??"<unknown>",start:{offset:t.start,line:i.line,column:i.column},end:{offset:r.end,line:n.line,column:n.column}}}function jf(e){if(!e.positions)return null;let t=B(e),r=e.tokenizer.locate(t.start);return{source:e.filename??"<unknown>",start:{offset:t.start,line:r.line,column:r.column},end:{offset:t.start,line:r.line,column:r.column}}}function Xi(e,t,r,i){return{type:"Raw",value:e,loc:z(i,t,r)}}function _e(){return new Ze}function ks(e,t,r,i){if(e.onParseError){let{line:n,column:s}=e.tokenizer.locate(r.start),a=SyntaxError(`${e.filename??"<input>"}:${n}:${s}: ${t}`);a.line=n,a.column=s,a.offset=r.start,e.onParseError(a,i)}return i}function So(e,t={}){let r=Lf(e,t);switch(t.context??"stylesheet"){case"stylesheet":return xc(r);case"atrule":return qn(r)??vc(r);case"atrulePrelude":return Hg(r);case"mediaQuery":case"mediaQueryList":return Sc(r);case"rule":return $o(r);case"selectorList":return Eo(r);case"selector":return _f(r);case"block":return Co(r);case"declarationList":return Qg(r);case"declaration":return Ao(r)??vc(r);case"value":return Xg(r);case"raw":return Sc(r);default:return xc(r)}}function vc(e){return{type:"StyleSheet",children:_e(),loc:jf(e)}}function Sc(e){let t=B(e),r=t;while(j(e)!==0)r=I(e);return{type:"Raw",value:e.source.slice(t.start,r.end),loc:z(e,t,r)}}function xc(e){let t=B(e),r=_e(),i=e.types,n=e.end;while(e.pos<n){let o=i[e.pos];if(o===13){e.pos++;continue}if(o===25){let u={type:25,start:e.starts[e.pos],end:e.ends[e.pos]},f=xo(e,u);e.pos++,r.appendData(f);continue}if(o===0)break;if(o===14||o===15){e.pos++;continue}if(o===3){let u=qn(e);if(u)r.appendData(u);continue}if(o===24){e.pos++;continue}let l=e.pos,c=$o(e);if(r.appendData(c),e.pos===l)e.pos++}let s=e.end-1,a=s>=0?{type:e.types[s],start:e.starts[s],end:e.ends[s]}:{type:0,start:0,end:0};return{type:"StyleSheet",children:r,loc:z(e,t,a)}}function xo(e,t){return{type:"Comment",value:e.source.slice(t.start+2,t.end-2),loc:z(e,t,t)}}function qn(e){let t=B(e);if(t.type!==3)return null;e.pos++;let r=Cn(e.source,t.start+1,t.end);lt(e);let i=e.pos,n=B(e),s=e.types,a=e.end,o=i,l=i;while(o<a){let f=s[o];if(f===0||f===17||f===23)break;if(f!==13&&f!==25)l=o+1;o++}let c=null;if(l>i){let f=e.starts[i],h=e.ends[l-1],d={type:s[l-1],start:e.starts[l-1],end:h},m=e.source.slice(f,h).trim();if(m.length>0)if(e.parseAtrulePrelude)try{let p=e.end;e.end=l,e.pos=i;let y=_e();while(j(e)!==0){let g=sr(e);if(g)y.appendData(g)}if(If(y),e.end=p,e.pos=o,y.isEmpty)c=Xi(m,n,d,e);else c={type:"AtrulePrelude",children:y,loc:null}}catch(p){let y=Xi(m,n,d,e);ks(e,`Failed to parse @${r} prelude: ${p.message}`,n,y),c=y,e.pos=o}else c=Xi(m,n,d,e),e.pos=o;else e.pos=o}else e.pos=o;let u=null;if(j(e)===17)I(e);else if(j(e)===23)u=Co(e,Yg.has(r));return{type:"Atrule",name:r,prelude:c,block:u,loc:z(e,t,B(e))}}var Kg=new Set(["is","not","where","has","matches","-moz-any","-webkit-any"]),Yg=new Set(["media","supports","document","layer","container","scope","starting-style","-moz-document","keyframes","-webkit-keyframes","-moz-keyframes","-o-keyframes"]);function Hg(e){let t=B(e),r=_e();while(j(e)!==0){if(B(e).type===13){e.pos++;continue}let i=sr(e);if(i)r.appendData(i)}return{type:"AtrulePrelude",children:r,loc:z(e,t,B(e))}}function $o(e){let t=B(e),r;if(e.parseRulePrelude)r=Eo(e);else{let n=B(e),s=n;while(j(e)!==0&&j(e)!==23)s=I(e);let a=e.source.slice(n.start,s.end).trim();r=Xi(a,n,s,e)}let i=Co(e,!0);return{type:"Rule",prelude:r,block:i,loc:z(e,t,B(e))}}function Co(e,t=!1){let r=B(e);if(j(e)!==23)return{type:"Block",children:_e(),loc:jf(e)};e.pos++;let i=_e(),n=e.types,s=e.end;while(e.pos<s){let a=n[e.pos];if(a===24||a===0)break;if(a===13){e.pos++;continue}if(a===25){let l={type:25,start:e.starts[e.pos],end:e.ends[e.pos]};e.pos++,i.appendData(xo(e,l));continue}if(a===3){let l=qn(e);if(l)i.appendData(l);continue}if(t&&Jg(e,Zg)){let l=$o(e);i.appendData(l);continue}let o=Ao(e);if(o)i.appendData(o);if(e.pos<s&&n[e.pos]===17)e.pos++}if(j(e)===24)e.pos++;return{type:"Block",children:i,loc:z(e,r,B(e))}}function Jg(e,t){let r=e.pos,i=t(e);return e.pos=r,i}function Zg(e){let{types:t,end:r}=e;while(e.pos<r){let i=t[e.pos];if(i===23)return!0;if(i===17||i===24||i===0)return!1;e.pos++}return!1}function Qg(e){let t=B(e),r=_e();while(j(e)!==0&&j(e)!==24){let i=B(e);if(i.type===13){e.pos++;continue}if(i.type===25){r.appendData(xo(e,I(e)));continue}if(i.type===17){e.pos++;continue}if(i.type===3){let s=qn(e);if(s)r.appendData(s);continue}let n=Ao(e);if(n)r.appendData(n);if(j(e)===17)I(e)}return{type:"DeclarationList",children:r,loc:z(e,t,B(e))}}function Ao(e){lt(e);let t=B(e);if(t.type!==1&&t.type!==4&&!(t.type===9&&e.source[t.start]==="*"&&e.source[t.start+1]===" "))if(t.type===9&&e.source[t.start]==="*")e.pos++;else{ks(e,"Expected property name",t,{type:"Raw",value:"",loc:null});let{types:S,end:E}=e;while(e.pos<E){let C=S[e.pos];if(C===0||C===17||C===24)break;e.pos++}return null}let r=e.starts[e.pos],i=e.ends[e.pos];e.pos++;let n=e.source.slice(r,i);if(bc(e),j(e)!==16){ks(e,`Expected ':' after property "${n}"`,B(e),{type:"Raw",value:"",loc:null});let{types:S,end:E}=e;while(e.pos<E){let C=S[e.pos];if(C===0||C===17||C===24)break;e.pos++}return null}e.pos++,bc(e);let{types:s,starts:a,end:o,pos:l}=e,c=l,u=l,f=-1,h=-1;while(c<o){let S=s[c];if(S===0||S===17||S===24)break;if(S===9&&e.source.charCodeAt(a[c])===33){let E=c+1;while(E<o&&s[E]===13)E++;if(E<o&&s[E]===1){let C=a[E];if(e.ends[E]-C===9&&(e.source.charCodeAt(C)|32)===105&&(e.source.charCodeAt(C+1)|32)===109&&(e.source.charCodeAt(C+2)|32)===112&&(e.source.charCodeAt(C+3)|32)===111&&(e.source.charCodeAt(C+4)|32)===114&&(e.source.charCodeAt(C+5)|32)===116&&(e.source.charCodeAt(C+6)|32)===97&&(e.source.charCodeAt(C+7)|32)===110&&(e.source.charCodeAt(C+8)|32)===116){h=c,f=E,c=E+1;continue}}}if(S!==13&&S!==25)u=c+1;c++}let d=u,m=f>=0?{type:1,start:a[f],end:e.ends[f]}:null,p=n.startsWith("--"),y,g=a[l],w=d>l?e.ends[d-1]:g,b={type:s[l],start:g,end:e.ends[l]},v=d>l?{type:s[d-1],start:a[d-1],end:w}:b;if(p&&!e.parseCustomProperty||!e.parseValue)y={type:"Raw",value:e.source.slice(g,w).trim(),loc:z(e,b,v)};else if(d===l)y={type:"Value",children:_e(),loc:z(e,b,v)};else{let S=e.end;e.end=d,e.pos=l,y=Bf(e),e.end=S}return e.pos=c,{type:"Declaration",property:n,important:m?!0:!1,value:y,loc:z(e,t,B(e))}}function Xg(e){return Bf(e)}function Bf(e){let t=B(e),r=_e();while(j(e)!==0&&j(e)!==17&&j(e)!==24&&j(e)!==22&&j(e)!==20){let i=sr(e);if(i)r.appendData(i)}return zf(r),{type:"Value",children:r,loc:z(e,t,B(e))}}function If(e){for(let t of e)if("children"in t&&t.children instanceof Ze)If(t.children);zf(e)}function zf(e){let t=e.head;while(t){if(t.data.type==="Number"){let r=t.next;while(r&&r.data.type==="WhiteSpace")r=r.next;if(r&&r.data.type==="Operator"&&r.data.value==="/"){let i=r.next;while(i&&i.data.type==="WhiteSpace")i=i.next;if(i&&i.data.type==="Number"){let n={type:"Ratio",left:t.data,right:i.data,loc:null},s=t.next;while(s&&s!==i.next){let a=s.next;e.remove(s),s=a}e.replace(t,e.createItem(n)),t=e.head;continue}}}t=t.next}}function sr(e){let t=e.pos;if(t>=e.end)return null;let r=e.types[t],i=e.starts[t],n=e.ends[t],s=e.source;switch(r){case 13:return e.pos++,e.positions?{type:"WhiteSpace",value:" ",loc:De(e,i,n)}:{type:"WhiteSpace",value:" ",loc:null};case 25:return e.pos++,{type:"Comment",value:s.slice(i+2,n-2),loc:e.positions?De(e,i,n):null};case 10:return e.pos++,{type:"Number",value:s.slice(i,n),loc:e.positions?De(e,i,n):null};case 11:return e.pos++,{type:"Percentage",value:s.slice(i,n-1),loc:e.positions?De(e,i,n):null};case 12:{e.pos++;let a=i,o=s.charCodeAt(a);if(o===43||o===45)a++;let l=!1;while(a<n){let u=s.charCodeAt(a);if(u>=48&&u<=57){a++;continue}if(u===46&&!l){l=!0,a++;continue}break}let c=s.charCodeAt(a);if(c===69||c===101){let u=a+1,f=s.charCodeAt(u);if(f===43||f===45)u++;let h=!1;while(u<n){let d=s.charCodeAt(u);if(d>=48&&d<=57){u++,h=!0;continue}break}if(h)a=u}return{type:"Dimension",value:s.slice(i,a),unit:s.slice(a,n),loc:e.positions?De(e,i,n):null}}case 1:return e.pos++,{type:"Identifier",name:Df(s,i,n),loc:e.positions?De(e,i,n):null};case 5:{e.pos++;let a=i+1,o=n-i>=2&&s.charCodeAt(n-1)===s.charCodeAt(i)?n-1:n;return{type:"String",value:Rf(s,a,o),loc:e.positions?De(e,i,n):null}}case 7:{e.pos++;let a=i+4;while(a<n&&$c(s.charCodeAt(a)))a++;let o=n;if(o>a&&s.charCodeAt(o-1)===41)o--;while(o>a&&$c(s.charCodeAt(o-1)))o--;let l;if(o-a>=2){let c=s.charCodeAt(a),u=s.charCodeAt(o-1);if((c===34||c===39)&&c===u)l=s.slice(a+1,o-1);else l=s.slice(a,o)}else l=s.slice(a,o);return{type:"Url",value:l,loc:e.positions?De(e,i,n):null}}case 4:return e.pos++,{type:"Hash",name:s.slice(i+1,n),loc:e.positions?De(e,i,n):null};case 2:return ty(e);case 21:return ry(e);case 18:return e.pos++,{type:"Operator",value:",",loc:e.positions?De(e,i,n):null};case 16:return e.pos++,{type:"Operator",value:":",loc:e.positions?De(e,i,n):null};case 9:{e.pos++;let a=s.charCodeAt(i),o=s[i];if(ey(a))return{type:"Operator",value:o,loc:e.positions?De(e,i,n):null};return{type:"Identifier",name:o,loc:e.positions?De(e,i,n):null}}case 19:{e.pos++;let a=_e();while(j(e)!==0&&j(e)!==20){let l=sr(e);if(l)a.appendData(l)}let o=e.pos<e.end?e.ends[e.pos]:n;if(j(e)===20)e.pos++;return{type:"Brackets",children:a,loc:e.positions?De(e,i,o):null}}case 3:case 23:case 24:case 22:case 20:case 17:case 0:case 14:case 15:case 6:case 8:return e.pos++,{type:"Raw",value:s.slice(i,n),loc:e.positions?De(e,i,n):null}}return e.pos++,null}function $c(e){return e===32||e===9||e===10||e===12||e===13}function ey(e){return e===47||e===43||e===45||e===42||e===61||e===62||e===60||e===126||e===124||e===36||e===94||e===33||e===38}function Cn(e,t,r){for(let i=t;i<r;i++){let n=e.charCodeAt(i);if(n>=65&&n<=90)return e.slice(t,r).toLowerCase()}return e.slice(t,r)}function De(e,t,r){let i=e.tokenizer.locate(t),n=e.tokenizer.locate(r);return{source:e.filename??"<unknown>",start:{offset:t,line:i.line,column:i.column},end:{offset:r,line:n.line,column:n.column}}}function ty(e){let t=I(e),r=Cn(e.source,t.start,t.end-1),i=_e();while(j(e)!==0&&j(e)!==22){let n=sr(e);if(n)i.appendData(n)}if(j(e)===22)I(e);if(r==="url"){for(let n=i.head;n!=null;n=n.next)if(n.data.type==="String")return{type:"Url",value:n.data.value,loc:z(e,t,B(e))}}return{type:"Function",name:r,children:i,loc:z(e,t,B(e))}}function ry(e){let t=I(e),r=_e();while(j(e)!==0&&j(e)!==22){let i=sr(e);if(i)r.appendData(i)}if(j(e)===22)I(e);return{type:"Parentheses",children:r,loc:z(e,t,B(e))}}function Eo(e){let t=B(e),r=_e();while(j(e)!==0){if(lt(e),j(e)===0||j(e)===23)break;let i=_f(e);if(i.children.head!==null)r.appendData(i);if(lt(e),j(e)===18){I(e);continue}break}return{type:"SelectorList",children:r,loc:z(e,t,B(e))}}function _f(e){let t=B(e),r=_e(),i=!0;while(j(e)!==0&&j(e)!==18&&j(e)!==23){let n=B(e);if(n.type===13){if(I(e),!i&&j(e)!==0&&j(e)!==18&&j(e)!==23&&!Cc(e)&&!iy(e)){let a={type:"Combinator",name:" ",loc:z(e,n,n)};r.appendData(a),i=!0}continue}if(n.type===9&&e.source.charCodeAt(n.start)===124&&e.types[e.pos+1]===9&&e.source.charCodeAt(e.starts[e.pos+1])===124){let a=B(e);I(e);let o=I(e),l={type:"Combinator",name:"||",loc:z(e,a,o)};r.appendData(l),i=!0,lt(e);continue}if(Cc(e)){let a=I(e),o={type:"Combinator",name:e.source[a.start],loc:z(e,a,a)};r.appendData(o),i=!0,lt(e);continue}let s=ny(e);if(!s)break;r.appendData(s),i=!1}while(r.tail&&r.tail.data.type==="Combinator")r.remove(r.tail);return{type:"Selector",children:r,loc:z(e,t,B(e))}}function Cc(e){let t=B(e);if(t.type!==9)return!1;let r=e.source[t.start];return r===">"||r==="+"||r==="~"}function iy(e){if(e.types[e.pos]!==9)return!1;if(e.source.charCodeAt(e.starts[e.pos])!==124)return!1;if(e.types[e.pos+1]!==9)return!1;return e.source.charCodeAt(e.starts[e.pos+1])===124}function ny(e){let t=B(e);switch(t.type){case 1:{if(I(e),j(e)===9&&e.source[B(e).start]==="|"&&e.source[B(e).start+1]!=="="&&!(e.types[e.pos+1]===9&&e.source.charCodeAt(e.starts[e.pos+1])===124)){if(I(e),j(e)===1){let r=I(e);return{type:"TypeSelector",name:`${gt(e,t)}|${gt(e,r)}`,loc:z(e,t,r)}}if(j(e)===9&&e.source[B(e).start]==="*"){let r=I(e);return{type:"TypeSelector",name:`${gt(e,t)}|*`,loc:z(e,t,r)}}}return{type:"TypeSelector",name:gt(e,t),loc:z(e,t,t)}}case 11:return I(e),{type:"TypeSelector",name:gt(e,t),loc:z(e,t,t)};case 10:return I(e),{type:"TypeSelector",name:gt(e,t),loc:z(e,t,t)};case 9:{let r=e.source[t.start];if(r==="*")return I(e),{type:"TypeSelector",name:"*",loc:z(e,t,t)};if(r==="."){if(I(e),j(e)===1){let i=I(e);return{type:"ClassSelector",name:gt(e,i),loc:z(e,t,i)}}return null}if(r==="&")return I(e),{type:"NestingSelector",loc:z(e,t,t)};return I(e),null}case 4:return I(e),{type:"IdSelector",name:e.source.slice(t.start+1,t.end),loc:z(e,t,t)};case 16:{I(e);let r=j(e)===16;if(r)I(e);return ay(e,r,t)}case 19:return sy(e)}return null}function ay(e,t,r){let i=B(e);if(i.type===1){I(e);let n=Cn(e.source,i.start,i.end);return t?{type:"PseudoElementSelector",name:n,children:null,loc:z(e,r,i)}:{type:"PseudoClassSelector",name:n,children:null,loc:z(e,r,i)}}if(i.type===2){I(e);let n=Cn(e.source,i.start,i.end-1),s=_e();if(!t&&Kg.has(n)){let a=B(e),o=a,l=1;while(j(e)!==0&&l>0){if(j(e)===21||j(e)===2)l++;else if(j(e)===22){if(l--,l===0)break}o=I(e)}if(j(e)===22)I(e);let c=e.source.slice(a.start,o.end).trim();if(c.length>0){let u=Lf(c,{positions:!1}),f=Eo(u);s.appendData(f)}}else{while(j(e)!==0&&j(e)!==22){let a=sr(e);if(a)s.appendData(a)}if(j(e)===22)I(e)}if(t)return{type:"PseudoElementSelector",name:n,children:s,loc:z(e,r,B(e))};return{type:"PseudoClassSelector",name:n,children:s,loc:z(e,r,B(e))}}return null}function sy(e){let t=I(e);lt(e);let r=B(e);if(r.type!==1)return null;I(e);let i={type:"Identifier",name:gt(e,r),loc:z(e,r,r)};lt(e);let n=null,s=null,a=null,o=B(e);if(o.type===9){let c=e.source[o.start],u=e.source[o.start+1];if(c==="=")n="=",I(e);else if((c==="~"||c==="|"||c==="^"||c==="$"||c==="*")&&u==="="){I(e);let d=B(e);if(d.type===9&&e.source[d.start]==="=")I(e),n=`${c}=`}lt(e);let f=B(e);if(f.type===5){I(e);let d=f.end-f.start>=2&&e.source.charCodeAt(f.end-1)===e.source.charCodeAt(f.start);s={type:"String",value:Rf(e.source,f.start+1,d?f.end-1:f.end),loc:z(e,f,f)}}else if(f.type===1)I(e),s={type:"Identifier",name:gt(e,f),loc:z(e,f,f)};lt(e);let h=B(e);if(h.type===1)I(e),a=gt(e,h)}lt(e);let l=B(e);if(j(e)===20)l=I(e);return{type:"AttributeSelector",name:i,matcher:n,value:s,flags:a,loc:z(e,t,l)}}var Uf=Symbol("walkSkip"),pe=Symbol("walkStop");function oy(e){return{root:e,stylesheet:null,atrule:null,atrulePrelude:null,rule:null,selector:null,block:null,declaration:null,function:null}}function ly(e,t){let r=oy(e),i=typeof t==="function"?t:t.enter,n=typeof t==="function"?null:t.leave??null,s=typeof t==="function"?null:t.visit??null,a=typeof t==="function"?!1:t.reverse??!1;function o(l,c,u){let f=null,h;switch(l.type){case"StyleSheet":f="stylesheet",h=r.stylesheet,r.stylesheet=l;break;case"Atrule":f="atrule",h=r.atrule,r.atrule=l;break;case"AtrulePrelude":f="atrulePrelude",h=r.atrulePrelude,r.atrulePrelude=l;break;case"Rule":f="rule",h=r.rule,r.rule=l;break;case"Selector":f="selector",h=r.selector,r.selector=l;break;case"Block":f="block",h=r.block,r.block=l;break;case"Declaration":f="declaration",h=r.declaration,r.declaration=l;break;case"Function":f="function",h=r.function,r.function=l;break}let d;if((s===null||s===l.type)&&i){let m=i.call(r,l,c,u);if(m===Uf){if(f)r[f]=h;return}if(m===pe){if(f)r[f]=h;return pe}}if(d=cy(l,a,o),d===pe){if(f)r[f]=h;return pe}if((s===null||s===l.type)&&n){if(n.call(r,l,c,u)===pe){if(f)r[f]=h;return pe}}if(f)r[f]=h;return}return o(e,null,null)}var Kn=Object.assign(ly,{skip:Uf,stop:pe});function cy(e,t,r){if("children"in e&&e.children instanceof Ze)return uy(e.children,t,r);if(e.type==="Rule"){if(r(e.prelude,null,null)===pe)return pe;if(r(e.block,null,null)===pe)return pe;return}if(e.type==="Atrule"){if(e.prelude){if(r(e.prelude,null,null)===pe)return pe}if(e.block){if(r(e.block,null,null)===pe)return pe}return}if(e.type==="Declaration")return r(e.value,null,null);if(e.type==="AttributeSelector"){if(r(e.name,null,null)===pe)return pe;if(e.value)return r(e.value,null,null);return}return}function uy(e,t,r){let i;if(t)e.forEachRight((n,s,a)=>{if(i)return;if(r(n,s,a)===pe)i=pe});else e.forEach((n,s,a)=>{if(i)return;if(r(n,s,a)===pe)i=pe});return i}var ti={};Wn(ti,{stringify:()=>qf,parse:()=>Yn,isTraversal:()=>$y,IgnoreCaseMode:()=>Cy});var Ac=/(?:\\(?:[\dA-Fa-f]{1,6} ?|[^])|[\w\-\u00B0-\uFFFF])+/y,fy=/\\([\dA-Fa-f]{1,6} ?|[^])/g;function hy(e){return e.replace(fy,(t,r)=>{if(r.length>1&&/^[\dA-Fa-f]/.test(r)){let i=Number.parseInt(r,16);if(i>=55296&&i<=57343)return"\uFFFD";return String.fromCodePoint(i)}return r})}function Vf(e){return e.indexOf("\\")<0?e:hy(e)}var dy=new Set(["accept","accept-charset","align","alink","axis","bgcolor","charset","checked","clear","codetype","color","compact","declare","defer","dir","direction","disabled","enctype","face","frame","hreflang","http-equiv","lang","language","link","media","method","multiple","nohref","noresize","noshade","nowrap","readonly","rel","rev","rules","scope","scrolling","selected","shape","target","text","type","valign","valuetype","vlink"]);function my(e){switch(e){case 126:return"element";case 94:return"start";case 36:return"end";case 42:return"any";case 33:return"not";case 124:return"hyphen";default:return null}}function en(e){return e===32||e===9||e===10||e===13||e===12}function Yn(e,t={}){let r=[],i=Gf(r,e,t,0);if(i<e.length)throw Error(`Unmatched selector: ${e.slice(i)}`);return r}function ct(e,t){Ac.lastIndex=t;let r=Ac.exec(e);if(!r)throw Error(`Expected name, found ${e.slice(t)}`);return{value:Vf(r[0]),end:t+r[0].length}}function Zt(e,t){while(t<e.length&&en(e.charCodeAt(t)))t++;return t}function Gf(e,t,r,i){let n=[],s=Zt(t,i),a=t.length,o=r.xmlMode===!0,l=r.lowerCaseAttributeNames!==!1&&!o,c=r.lowerCaseTags!==!1;while(s<a){let u=t.charCodeAt(s);if(en(u)){let f=s+1;while(f<a&&en(t.charCodeAt(f)))f++;if(n.length===0)return f;s=f,pr(n,"descendant");continue}if(u===62||u===60||u===126||u===43||u===124){let f=s+1;while(f<a&&en(t.charCodeAt(f)))f++;switch(s=f,u){case 62:pr(n,"child");break;case 60:pr(n,"parent");break;case 126:pr(n,"sibling");break;case 43:pr(n,"adjacent");break;case 124:if(s<a&&t.charCodeAt(s)===124)s++,s=Zt(t,s),pr(n,"column-combinator");else n.push({type:"tag",name:"",namespace:""});break}continue}if(u===44){if(n.length===0)throw Error("Empty sub-selector");e.push(n),n=[],s=Zt(t,s+1);continue}if(u===47&&t.charCodeAt(s+1)===42){let f=t.indexOf("*/",s+2);if(f<0)throw Error("Unmatched comment");s=Zt(t,f+2);continue}if(u===42){s++,n.push({type:"universal",namespace:null});continue}if(u===35){let f=ct(t,s+1);s=f.end,n.push({type:"attribute",name:"id",action:"equals",value:f.value,namespace:null,ignoreCase:!1});continue}if(u===46){let f=ct(t,s+1);s=f.end,n.push({type:"attribute",name:"class",action:"element",value:f.value,namespace:null,ignoreCase:!1});continue}if(u===91){s=py(t,s,n,r,o,l);continue}if(u===58){s=gy(t,s,n,r);continue}if(u===124){s++;let f=ct(t,s);s=f.end,n.push({type:"tag",name:c?f.value.toLowerCase():f.value,namespace:""});continue}{let f=ct(t,s);if(s=f.end,s<a&&t.charCodeAt(s)===124&&t.charCodeAt(s+1)!==61){s++;let h=ct(t,s);s=h.end,n.push({type:"tag",name:c?h.value.toLowerCase():h.value,namespace:f.value})}else n.push({type:"tag",name:c?f.value.toLowerCase():f.value,namespace:null})}}if(n.length>0)e.push(n);return s}function py(e,t,r,i,n,s){let a=t+1,o=e.length,l;if(e.charCodeAt(a)===124)throw Error("Empty namespace not supported");if(e.charCodeAt(a)===42&&e.charCodeAt(a+1)===124){a+=2;let d=ct(e,a);a=d.end,l=d.value}else{let d=ct(e,a);if(a=d.end,l=d.value,e.charCodeAt(a)===124&&e.charCodeAt(a+1)!==61){a++;let m=ct(e,a);a=m.end,l=m.value}}a=Zt(e,a);let c="exists",u="",f=null,h=e.charCodeAt(a);if(h===61)c="equals",a++;else if(h===33&&e.charCodeAt(a+1)===61)c="not",a+=2;else{let d=my(h);if(d!==null&&e.charCodeAt(a+1)===61)c=d,a+=2}if(c!=="exists"){a=Zt(e,a);let d=e.charCodeAt(a);if(d===34||d===39){let p=Wf(e,a+1,d);u=Vf(e.slice(a+1,p)),a=p+1}else{let p=ct(e,a);u=p.value,a=p.end}a=Zt(e,a);let m=e.charCodeAt(a);if(m===105||m===73)f=!0,a++;else if(m===115||m===83)f=!1,a++}if(e.charCodeAt(a)!==93)throw Error("Expected ]");if(a++,f===null&&!n&&dy.has(l.toLowerCase()))f="quirks";return r.push({type:"attribute",name:s?l.toLowerCase():l,action:c,value:u,namespace:null,ignoreCase:f}),a}function gy(e,t,r,i){if(e.charCodeAt(t+1)===58){let o=t+2,l=ct(e,o);o=l.end;let c=l.value.toLowerCase(),u=null;if(e.charCodeAt(o)===40){let f=Ec(e,o);u=e.slice(o+1,f).trim(),o=f+1}return r.push({type:"pseudo-element",name:c,data:u}),o}let n=t+1,s=ct(e,n);n=s.end;let a=s.value.toLowerCase();if(e.charCodeAt(n)===40){let o=Ec(e,n),l=e.slice(n+1,o);if(n=o+1,a==="is"||a==="not"||a==="where"||a==="has"||a==="matches"||a==="-moz-any"||a==="-webkit-any"){let c=[];Gf(c,l.trim(),i,0),r.push({type:"pseudo",name:a,data:c})}else r.push({type:"pseudo",name:a,data:l.trim()})}else r.push({type:"pseudo",name:a,data:null});return n}function pr(e,t){if(e.length>0&&e[e.length-1].type==="descendant"&&t!=="descendant")e.pop();if(e.length>0&&e[e.length-1].type===t)return;e.push({type:t})}function Wf(e,t,r){let i=t,n=e.length;while(i<n){let s=e.charCodeAt(i);if(s===92){i+=2;continue}if(s===r)return i;i++}throw Error("Unterminated string")}function Ec(e,t){let r=1,i=t+1,n=e.length;while(i<n){let s=e.charCodeAt(i);if(s===92){i+=2;continue}if(s===34||s===39){i=Wf(e,i+1,s)+1;continue}if(s===40)r++;else if(s===41){if(r--,r===0)return i}i++}throw Error("Unterminated parenthesis")}var yy={child:" > ",parent:" < ",sibling:" ~ ",adjacent:" + ",descendant:" ","column-combinator":" || "};function qf(e){return e.map(wy).join(", ")}function wy(e){return e.map((t,r)=>by(t,e[r-1])).join("")}function by(e,t){switch(e.type){case"tag":return`${Oa(e.namespace)}${Hr(e.name)}`;case"universal":return`${Oa(e.namespace)}*`;case"attribute":{if(e.name==="id"&&e.action==="equals"&&!e.ignoreCase&&!e.namespace)return`#${Hr(e.value)}`;if(e.name==="class"&&e.action==="element"&&!e.ignoreCase&&!e.namespace)return`.${Hr(e.value)}`;let r=`[${Oa(e.namespace)}${Hr(e.name)}`;if(e.action!=="exists"){let i=vy[e.action]??"=";if(r+=i,r+=`"${e.value.replace(/"/g,"\\\"")}"`,e.ignoreCase===!0)r+=" i";else if(e.ignoreCase===!1)r+=" s"}return r+="]",r}case"pseudo":if(e.data===null)return`:${e.name}`;if(typeof e.data==="string")return`:${e.name}(${e.data})`;return`:${e.name}(${qf(e.data)})`;case"pseudo-element":return e.data===null?`::${e.name}`:`::${e.name}(${e.data})`;case"descendant":case"child":case"parent":case"sibling":case"adjacent":case"column-combinator":return yy[e.type]??" "}return""}var vy={equals:"=",element:"~=",start:"^=",end:"$=",any:"*=",not:"!=",hyphen:"|="};function Oa(e){if(e===null)return"";if(e==="")return"|";return`${Hr(e)}|`}var Sy=/[^\w\u00B0-\uFFFF-]/g;function Hr(e){if(e==="")return"";return e.replace(Sy,(t)=>`\\${t}`)}var xy=new Set(["adjacent","child","descendant","parent","sibling","column-combinator"]);function $y(e){return xy.has(e.type)}var Cy={Unknown:null,QuirksMode:"quirks",IgnoreCase:!0,CaseSensitive:!1},Ay={};Wn(Ay,{selectOne:()=>Jf,selectAll:()=>Hf,parseAndCompile:()=>Nr,is:()=>Zf,compile:()=>Hn,clearSelectorCache:()=>Vy});function Ey(e,t,r,i){let n=[],s=[t],a=[0];for(;;){if(a[0]>=s[0].length){if(s.length===1)return n;s.shift(),a.shift();continue}let o=s[0][a[0]++];if(!r.isTag(o))continue;if(e(o))n.push(o);if(i||r.getName(o)!=="template"){let l=r.getChildren(o);if(l.length>0)s.unshift(l),a.unshift(0)}}}function ky(e,t,r,i){let n=[t],s=[0];for(;;){if(s[0]>=n[0].length){if(n.length===1)return null;n.shift(),s.shift();continue}let a=n[0][s[0]++];if(!r.isTag(a))continue;if(e(a))return a;if(i||r.getName(a)!=="template"){let o=r.getChildren(a);if(o.length>0)n.unshift(o),s.unshift(0)}}}function Kf(e,t){if(Array.isArray(e))return t.removeSubsets(e);return t.getChildren(e)}var ko=(e)=>!0;function kc(e){return e===32||e===9||e===10||e===12||e===13}function Ri(e,t){let r=t.length,i=e.length;if(r===0||r>i)return!1;let n=e.indexOf(t);while(n>=0){let s=n===0||kc(e.charCodeAt(n-1)),a=n+r,o=a===i||kc(e.charCodeAt(a));if(s&&o)return!0;n=e.indexOf(t,n+1)}return!1}function My(e,t,r){if(t.ignoreCase===!0)return!0;if(t.ignoreCase===!1)return!1;if(t.ignoreCase==="quirks")return!r.xmlMode;return!1}function Ty(e,t,r){let i=t.adapter,n=e.action,s=e.name,a=e.value,o=My(a,e,t);if(o)a=a.toLowerCase();return Ny(n,s,a,o,i,r)}function Ny(e,t,r,i,n,s){let a=s===ko;switch(e){case"exists":if(a)return(o)=>n.hasAttrib(o,t);return(o)=>n.hasAttrib(o,t)&&s(o);case"equals":if(!i){if(a)return(o)=>n.getAttributeValue(o,t)===r;return(o)=>n.getAttributeValue(o,t)===r&&s(o)}if(a)return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return l.toLowerCase()===r};return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return l.toLowerCase()===r&&s(o)};case"not":return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return s(o);return(i?l.toLowerCase():l)!==r&&s(o)};case"start":if(r==="")return()=>!1;if(a)return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return(i?l.toLowerCase():l).startsWith(r)};return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return(i?l.toLowerCase():l).startsWith(r)&&s(o)};case"end":if(r==="")return()=>!1;if(a)return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return(i?l.toLowerCase():l).endsWith(r)};return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return(i?l.toLowerCase():l).endsWith(r)&&s(o)};case"any":{if(r==="")return()=>!1;if(i){if(a)return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return l.toLowerCase().indexOf(r)>=0};return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return l.toLowerCase().indexOf(r)>=0&&s(o)}}if(a)return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return l.indexOf(r)>=0};return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return l.indexOf(r)>=0&&s(o)}}case"element":{if(r===""||/\s/.test(r))return()=>!1;if(i){if(a)return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return Ri(l.toLowerCase(),r)};return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return Ri(l.toLowerCase(),r)&&s(o)}}if(a)return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return Ri(l,r)};return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return Ri(l,r)&&s(o)}}case"hyphen":if(a)return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;let c=i?l.toLowerCase():l;if(c===r)return!0;if(c.startsWith(r)&&c.charAt(r.length)==="-")return!0;return!1};return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;let c=i?l.toLowerCase():l;if(c===r)return s(o);if(c.startsWith(r)&&c.charAt(r.length)==="-")return s(o);return!1}}return(o)=>!1}var Py=new Set(["link","any-link","visited","hover","active","focus","focus-visible","focus-within","target","target-within","enabled","disabled","checked","required","optional","valid","invalid","selected","placeholder-shown","read-only","read-write","in-range","out-of-range","default","indeterminate"]),Fy=new Set(["is","where","matches","-moz-any","-webkit-any"]),Oy=new Set(["nth-child","nth-last-child","nth-of-type","nth-last-of-type"]);function Ry(e,t,r){let i=t.adapter,n=e.name,s=e.data;if(e.type==="pseudo"&&Fy.has(n)){if(!Array.isArray(s))return r;let a=s.map((o)=>Nr(o,t));if(a.length===1){let o=a[0];return(l)=>o(l)&&r(l)}return(o)=>{for(let l of a)if(l(o))return r(o);return!1}}if(e.type==="pseudo"&&n==="not"){if(!Array.isArray(s))return r;let a=s.map((o)=>Nr(o,t));if(a.length===1){let o=a[0];return(l)=>!o(l)&&r(l)}return(o)=>{for(let l of a)if(l(o))return!1;return r(o)}}if(e.type==="pseudo"&&n==="has"){if(!Array.isArray(s))return r;let a=s.map((l)=>Nr(l,t)),o=a.length===1?a[0]:(l)=>{for(let c of a)if(c(l))return!0;return!1};return(l)=>{let c=i.getChildren(l).slice();while(c.length>0){let u=c.pop();if(!i.isTag(u))continue;if(o(u))return r(l);let f=i.getChildren(u);for(let h=0;h<f.length;h++)c.push(f[h])}return!1}}if(e.type==="pseudo"&&Oy.has(n)){let a=Ly(typeof s==="string"?s:"",n,t);return(o)=>a(o)&&r(o)}if(e.type==="pseudo"&&n==="first-child")return(a)=>{let o=i.getSiblings(a);for(let l of o){if(!i.isTag(l))continue;return l===a&&r(a)}return!1};if(e.type==="pseudo"&&n==="last-child")return(a)=>{let o=i.getSiblings(a);for(let l=o.length-1;l>=0;l--){let c=o[l];if(!i.isTag(c))continue;return c===a&&r(a)}return!1};if(e.type==="pseudo"&&n==="first-of-type")return(a)=>{let o=i.getName(a),l=i.getSiblings(a);for(let c of l){if(!i.isTag(c)||i.getName(c)!==o)continue;return c===a&&r(a)}return!1};if(e.type==="pseudo"&&n==="last-of-type")return(a)=>{let o=i.getName(a),l=i.getSiblings(a);for(let c=l.length-1;c>=0;c--){let u=l[c];if(!i.isTag(u)||i.getName(u)!==o)continue;return u===a&&r(a)}return!1};if(e.type==="pseudo"&&n==="only-child")return(a)=>{let o=i.getSiblings(a),l=0,c=!1;for(let u of o){if(!i.isTag(u))continue;if(l++,l>1)return!1;if(u===a)c=!0}return l===1&&c&&r(a)};if(e.type==="pseudo"&&n==="only-of-type")return(a)=>{let o=i.getName(a),l=i.getSiblings(a),c=0,u=!1;for(let f of l){if(!i.isTag(f)||i.getName(f)!==o)continue;if(c++,c>1)return!1;if(f===a)u=!0}return c===1&&u&&r(a)};if(e.type==="pseudo"&&n==="empty")return(a)=>i.getChildren(a).length===0&&r(a);if(e.type==="pseudo"&&n==="root")return(a)=>{let o=i.getParent(a);return(o==null||!i.isTag(o))&&r(a)};if(e.type==="pseudo"&&n==="scope"){if(t.context&&Array.isArray(t.context)){let a=new Set(t.context);return(o)=>a.has(o)&&r(o)}if(t.context){let a=t.context;return(o)=>o===a&&r(o)}return(a)=>{let o=i.getParent(a);return(o==null||!i.isTag(o))&&r(a)}}if(e.type==="pseudo"&&Py.has(n)){if(t.pseudos&&t.pseudos[n]){let a=t.pseudos[n];if(typeof a==="function")return(o)=>a(o,void 0)&&r(o)}return(a)=>!1}if(e.type==="pseudo-element")return r;if(t.pseudos&&t.pseudos[n]){let a=t.pseudos[n];if(typeof a==="function")return(o)=>a(o,typeof s==="string"?s:void 0)&&r(o);if(typeof a==="string"){let o=Yn(a),l=Mo(o,t);return(c)=>l(c)&&r(c)}}return(a)=>!1}function Dy(e){let t=e.trim();if(t==="odd")return{a:2,b:1};if(t==="even")return{a:2,b:0};let r=/^([+-]?\d*)n([+-]\d+)?$/.exec(t.replace(/\s+/g,""));if(r){let n=r[1]===""||r[1]==="+"?1:r[1]==="-"?-1:Number(r[1]),s=r[2]?Number(r[2]):0;return{a:n,b:s}}let i=Number(t);if(!Number.isNaN(i))return{a:0,b:i};return null}function Ly(e,t,r){let i=Dy(e);if(!i)return()=>!1;let{a:n,b:s}=i,a=r.adapter,o=t==="nth-of-type"||t==="nth-last-of-type",l=t==="nth-last-child"||t==="nth-last-of-type";return(c)=>{let u=a.getSiblings(c),f=o?a.getName(c):"",h=0,d=0;for(let p of u){if(!a.isTag(p))continue;if(o&&a.getName(p)!==f)continue;if(d++,p===c)h=d}if(h===0)return!1;let m=l?d-h+1:h;if(n===0)return m===s;return(m-s)/n>=0&&(m-s)%n===0}}function jy(e,t,r){let i=t.adapter,n=r===ko;switch(e.type){case"tag":{let s=t.lowerCaseTags!==!1&&!t.xmlMode?e.name.toLowerCase():e.name;if(n)return(a)=>i.getName(a)===s;return(a)=>i.getName(a)===s&&r(a)}case"universal":return r;case"attribute":return Ty(e,t,r);case"pseudo":case"pseudo-element":return Ry(e,t,r);case"descendant":case"child":case"parent":case"sibling":case"adjacent":case"column-combinator":return r}return(s)=>!1}var By={universal:50,tag:30,attribute:1,pseudo:0,"pseudo-element":0},Iy={exists:10,equals:8,not:7,start:6,end:6,hyphen:5,any:4,element:3};function Mc(e){let t=By[e.type]??0;if(e.type==="attribute")return t+(Iy[e.action]??0);return t}function Mo(e,t){if(e.length===1)return Nr(e[0],t);let r=e.map((i)=>Nr(i,t));return(i)=>r.some((n)=>n(i))}function Nr(e,t){let r=t.adapter,i=[[]],n=[];for(let a of e)if(a.type==="descendant"||a.type==="child"||a.type==="sibling"||a.type==="adjacent"||a.type==="parent"||a.type==="column-combinator")n.push(a),i.push([]);else i[i.length-1].push(a);let s=ko;for(let a=0;a<i.length;a++){let o=i[a].slice().sort((l,c)=>Mc(l)-Mc(c));for(let l of o)s=jy(l,t,s);if(a<n.length)s=zy(n[a],s,r)}return s}function zy(e,t,r){switch(e.type){case"descendant":case"column-combinator":return(i)=>{let n=r.getParent(i);while(n){if(r.isTag(n)&&t(n))return!0;n=r.getParent(n)}return!1};case"child":return(i)=>{let n=r.getParent(i);return n!=null&&r.isTag(n)&&t(n)};case"sibling":return(i)=>{let n=r.getSiblings(i);for(let s of n){if(s===i)return!1;if(r.isTag(s)&&t(s))return!0}return!1};case"adjacent":return(i)=>{let n=r.getSiblings(i),s=null;for(let a of n){if(a===i)return s!=null&&r.isTag(s)&&t(s);s=a}return!1};case"parent":return(i)=>r.existsOne(t,r.getChildren(i))}return(i)=>!1}function Yf(e){if(!e||!e.adapter)throw Error("css-select: adapter is required");return e.adapter}var An=new WeakMap;function _y(e){return(e.xmlMode?1:0)<<0|(e.lowerCaseAttributeNames===!1?1:0)<<1|(e.lowerCaseTags===!1?1:0)<<2}function Uy(e,t){let r=An.get(e);if(!r)r=[],An.set(e,r);let i=r[t];if(!i)i=new Map,r[t]=i;return i}function Tc(e,t){let r=Yn(e,{xmlMode:t.xmlMode,lowerCaseAttributeNames:t.lowerCaseAttributeNames,lowerCaseTags:t.lowerCaseTags});return Mo(r,t)}function Hn(e,t){if(typeof e!=="string")return Mo(e,t);if(t.cacheResults===!1||!t.adapter)return Tc(e,t);let r=Uy(t.adapter,_y(t)),i=r.get(e);if(i!==void 0)return i;return i=Tc(e,t),r.set(e,i),i}function Vy(e,t){if(t===void 0){An.delete(e);return}let r=An.get(e);if(!r)return;for(let i of r)if(i)i.delete(t)}function Hf(e,t,r){let i=Yf(r),n=typeof e==="function"?e:Hn(e,r),s=Kf(t,i);return Ey(n,s,i,r.xmlMode===!0)}function Jf(e,t,r){let i=Yf(r),n=typeof e==="function"?e:Hn(e,r),s=Kf(t,i);return ky(n,s,i,r.xmlMode===!0)}function Zf(e,t,r){return(typeof t==="function"?t:Hn(t,r))(e)}var oi={};Wn(oi,{syntax:()=>s0,specificityToString:()=>a0,specificity:()=>No,removeComments:()=>tn,minifyBlock:()=>n0,minify:()=>i0,dedupeDeclarations:()=>Qf,compressTree:()=>eh});function tn(e,t={}){let r=t.exclamation??!1,i=!1;Kn(e,(n,s,a)=>{if(n.type!=="Comment")return;let o=n.value.startsWith("!");if(r===!0&&o)return;if(r==="first-exclamation"&&o&&!i){i=!0;return}if(s&&a)a.remove(s)})}function Qf(e){Kn(e,(t)=>{if(t.type!=="Block"&&t.type!=="DeclarationList")return;if(!("children"in t)||!t.children)return;let r=t.children,i=r.head;if(i==null||i.next==null)return;let n=0;for(let o=i;o!=null;o=o.next)if(o.data.type==="Declaration"){if(n++,n>=2)break}if(n<2)return;let s=new Map,a=[];for(let o=i;o!=null;o=o.next){let l=o.data;if(l.type!=="Declaration")continue;let c=l.property,u=s.get(c);if(u){let f=!!u.decl.important,h=!!l.important;if(h||f===h)a.push(u.item),s.set(c,{item:o,decl:l});else a.push(o)}else s.set(c,{item:o,decl:l})}for(let o of a)r.remove(o)})}var Gy={black:"#000",fuchsia:"#f0f",white:"#fff",red:"#f00",cyan:"#0ff",blue:"#00f",yellow:"#ff0",magenta:"#f0f",lime:"#0f0",silver:"#c0c0c0",gray:"#808080",maroon:"#800000",olive:"#808000",green:"#008000",purple:"#800080",teal:"#008080",navy:"#000080"},Wy={"#f00":"red","#ff0000":"red","#000080":"navy","#008080":"teal"};function Xf(e){if(!e.startsWith("#"))return e;let t=e.slice(1);if(t.length===6){if(t[0]===t[1]&&t[2]===t[3]&&t[4]===t[5])return`#${t[0]}${t[2]}${t[4]}`}if(t.length===8){if(t[0]===t[1]&&t[2]===t[3]&&t[4]===t[5]&&t[6]===t[7])return`#${t[0]}${t[2]}${t[4]}${t[6]}`}return e}function qy(e){let t=e.toLowerCase();return Gy[t]??null}function Ky(e){let t=e.toLowerCase();return Wy[t]??null}function Yy(e,t,r){let i=(e<<16|t<<8|r).toString(16).padStart(6,"0");return Xf(`#${i}`)}var Hy=/^rgba?\(\s*([+-]?\d*\.?\d+%?)\s*[,\s]\s*([+-]?\d*\.?\d+%?)\s*[,\s]\s*([+-]?\d*\.?\d+%?)\s*(?:[,/]\s*([+-]?\d*\.?\d+%?)\s*)?\)$/;function Jy(e){let t=Hy.exec(e.trim());if(!t)return e;let r=Ra(t[1]),i=Ra(t[2]),n=Ra(t[3]);if(t[4]!==void 0&&!Zy(t[4]))return e;return Yy(r,i,n)}function Zy(e){if(e.endsWith("%"))return Number.parseFloat(e)>=100;return Number.parseFloat(e)>=1}function Ra(e){if(e.endsWith("%"))return Math.max(0,Math.min(255,Math.round(Number.parseFloat(e)*2.55)));return Math.max(0,Math.min(255,Math.round(Number.parseFloat(e))))}var Qy=new Set(["px","pt","pc","in","cm","mm","q","em","rem","ex","ch","cap","ic","lh","rlh","vw","vh","vi","vb","vmin","vmax","svw","svh","svi","svb","svmin","svmax","lvw","lvh","lvi","lvb","lvmin","lvmax","dvw","dvh","dvi","dvb","dvmin","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"]);function To(e){if(e.charCodeAt(0)===43)e=e.slice(1);if(e.includes(".")){let t=e.replace(/(\.\d*?)0+($|[eE])/,"$1$2");t=t.replace(/\.($|[eE])/,"$1"),e=t}if(e.startsWith("0.")&&e.length>2)e=e.slice(1);else if(e.startsWith("-0.")&&e.length>3)e=`-${e.slice(2)}`;if(e==="-0"||e==="-.0"||e==="-0.0")e="0";return e}function Xy(e,t){let r=To(e);if((r==="0"||r==="-0")&&Qy.has(t.toLowerCase()))return{value:"0",unit:""};return{value:r,unit:t}}function e0(e){return To(e)}function t0(e,t){let r=Number.parseFloat(e);if(!Number.isFinite(r))return e;let i=t<0?0:t;return r.toFixed(i)}var Nc=new Set(["color","background","background-color","border","border-color","border-top","border-top-color","border-right","border-right-color","border-bottom","border-bottom-color","border-left","border-left-color","border-block","border-block-color","border-block-start-color","border-block-end-color","border-inline","border-inline-color","border-inline-start-color","border-inline-end-color","outline","outline-color","caret-color","fill","stroke","flood-color","lighting-color","stop-color","column-rule","column-rule-color","text-decoration","text-decoration-color","text-emphasis","text-emphasis-color","text-shadow","box-shadow","accent-color","scrollbar-color"]);function Pc(e){if(!e||e.type!=="Operator")return!1;let t=e.value;return t===":"||t===","||t==="/"}function r0(e){let t=e.children;if(!t)return;while(t.head&&t.head.data.type==="WhiteSpace")t.remove(t.head);while(t.tail&&t.tail.data.type==="WhiteSpace")t.remove(t.tail);let r=t.head;while(r){let i=r.next;if(r.data.type==="WhiteSpace"){let n=r.prev&&Pc(r.prev.data),s=i&&Pc(i.data);if(n||s)t.remove(r)}r=i}}function eh(e,t={}){let r=t.floatPrecision??null,i=r===null?null:(n)=>t0(n,r);Kn(e,{enter(n,s,a){switch(n.type){case"Number":{let o=i?i(n.value):n.value;n.value=To(o);return}case"Percentage":{let o=i?i(n.value):n.value;n.value=e0(o);return}case"Dimension":{let o=i?i(n.value):n.value,l=Xy(o,n.unit);n.value=l.value,n.unit=l.unit;return}case"Hash":{let o=Xf(`#${n.name}`).slice(1);if(n.name=o,s&&a&&this.declaration&&Nc.has(this.declaration.property.toLowerCase())){let l=Ky(`#${o}`);if(l&&l.length<o.length+1){let c={type:"Identifier",name:l,loc:n.loc};a.replace(s,a.createItem(c))}}return}case"Identifier":{if(!s||!a||!this.declaration)return;if(!Nc.has(this.declaration.property.toLowerCase()))return;let o=qy(n.name);if(o&&o.length<n.name.length){let l={type:"Hash",name:o.slice(1),loc:n.loc};a.replace(s,a.createItem(l))}return}case"Url":return;case"Function":{let o=n.name.toLowerCase();if((o==="rgb"||o==="rgba")&&s&&a)n.__rgbReplaceCandidate=!0}}},leave(n,s,a){if(n.type==="Parentheses"||n.type==="Function"||n.type==="Value")r0(n);if(n.type==="Function"&&n.__rgbReplaceCandidate&&s&&a){let o=Ue(n),l=Jy(o);if(l!==o&&l.startsWith("#")){let c={type:"Hash",name:l.slice(1),loc:n.loc};a.replace(s,a.createItem(c))}}}})}function i0(e,t={}){let r=So(e,{context:"stylesheet"});return th(r,t)}function n0(e,t={}){let r=So(e,{context:"declarationList"});return th(r,t)}function th(e,t){if(t.comments===!1)tn(e,{exclamation:!1});else if(t.comments==="first-exclamation")tn(e,{exclamation:"first-exclamation"});else tn(e,{exclamation:!0});return eh(e,{floatPrecision:t.floatPrecision??null}),Qf(e),{css:Ue(e),ast:e}}function No(e){let t=[0,0,0];if(typeof e==="string"){let r=Yn(e);return Fc(r,t),t}if(Array.isArray(e)){if(e.length===0)return t;if(Array.isArray(e[0]))Fc(e,t);else Po(e,t);return t}return rh(e,t),t}function rh(e,t){switch(e.type){case"IdSelector":t[0]++;return;case"ClassSelector":case"AttributeSelector":t[1]++;return;case"TypeSelector":if(e.name!=="*")t[2]++;return;case"PseudoClassSelector":{let r=e.name.toLowerCase();if(r==="is"||r==="matches"||r==="-moz-any"||r==="-webkit-any"||r==="not"||r==="has"){if(e.children){let i=[];for(let s of e.children)if(s.type==="SelectorList"&&"children"in s&&s.children)for(let a of s.children)i.push(a);else if(s.type==="Selector")i.push(s);let n=[0,0,0];for(let s of i){let a=No(s);if(ih(a,n)>0)n=a}t[0]+=n[0],t[1]+=n[1],t[2]+=n[2]}return}if(r==="where")return;t[1]++;return}case"PseudoElementSelector":t[2]++;return;case"Selector":case"SelectorList":case"AtrulePrelude":if("children"in e&&e.children)for(let r of e.children)rh(r,t);return;case"NestingSelector":return}}function Fc(e,t){for(let r of e)Po(r,t)}function Po(e,t){for(let r of e)switch(r.type){case"tag":if(r.name!=="*")t[2]++;break;case"attribute":if(r.name==="id"&&r.action==="equals")t[0]++;else t[1]++;break;case"pseudo":{let i=r.name.toLowerCase();if(i==="is"||i==="matches"||i==="not"||i==="has"||i==="-moz-any"||i==="-webkit-any"){if(Array.isArray(r.data)){let n=[0,0,0];for(let s of r.data){let a=[0,0,0];if(Po(s,a),ih(a,n)>0)n=a}t[0]+=n[0],t[1]+=n[1],t[2]+=n[2]}break}if(i==="where")break;t[1]++;break}case"pseudo-element":t[2]++;break}}function ih(e,t){for(let r=0;r<3;r++)if(e[r]!==t[r])return e[r]-t[r];return 0}function a0(e){return e.join(",")}var s0={specificity:No},o0=Object.defineProperty,l0=(e)=>e;function c0(e,t){this[e]=l0.bind(null,t)}var u0=(e,t)=>{for(var r in t)o0(e,r,{get:t[r],enumerable:!0,configurable:!0,set:c0.bind(t,r)})},jt=(e,t)=>()=>(e&&(t=e(e=0)),t),f0=import.meta.require;class Fo{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 n=this.generateKey(e,r),s=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,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(!Xl(e))return!0;return ec(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 n=Xl(r)?ec(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},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,n)=>i+n.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 Oo{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:n,...r}),s}catch(s){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,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 h0(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function d0(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function m0(e){return e.getStats().size*2}var Dr,wi,nh,bi=jt(()=>{Dr=new Fo,wi=new Oo,nh={createKey:h0,isEquivalent:d0,estimateMemoryUsage:m0}});function p0(e,t={}){let r=vn.cwd();while(r.includes("storage"))r=tc(r,"..");let i=tc(r,e||"");if(t?.relative)return rp(vn.cwd(),i);return i}function be(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function g0(){if(Ct.env.NODE_ENV==="test"||Ct.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ct<"u"){let e=Ct.type;if(e==="renderer"||e==="worker")return!1;return!!(Ct.versions&&(Ct.versions.node||Ct.versions.bun))}return!1}class ah{async format(e){let t=await g0(),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:dr.pid,hostname:t(),environment:dr.env.NODE_ENV||"development",platform:dr.platform,version:dr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:dr.env.NODE_ENV||dr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Jn{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={...ri},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ah,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??re.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 n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,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{...rn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...rn};return{...rn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ri.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!be()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await op(this.config.logDirectory,ac.F_OK|ac.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await lp(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:vt.from(e);try{if(!Ti(this.currentLogFile))await Aa(this.currentLogFile,"",{mode:420});if(i=nc(this.currentLogFile,"a",420),sp(i,o,{flag:"a"}),ic(i),i!==void 0)Ca(i),i=void 0;if((await fr(this.currentLogFile)).size===0){if(await Aa(this.currentLogFile,o,{flag:"w",mode:420}),(await fr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let c=l;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(n<s-1){let u=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=a*2**n;await new Promise((h)=>setTimeout(h,f)),n++;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{Ca(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(o){if(n===s-1){let c=o,u=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let l=a*2**(n-1);await new Promise((c)=>setTimeout(c,l))}})();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 hr(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 hr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return hr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(be())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],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return $a(16).toString("hex")}generateKey(){return $a(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=$a(16),i=ip("aes-256-gcm",t,r),n=vt.isBuffer(e)?e:vt.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,l=i.getAuthTag(),c=vt.allocUnsafe(16+o+16);return r.copy(c,0),s.copy(c,16),a.copy(c,16+s.length),l.copy(c,16+o),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=oc(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(vt.from(vt.concat(n)))),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(be())return;if(!this.shouldWriteToFile())return;let e=await fr(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 n=await Ni(this.config.logDirectory),s=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,c)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await fr(r).catch(()=>null))try{if(await sc(r,o),t.compress)try{let l=`${o}.gz`;await this.compressLogFile(o,l),await Pi(o)}catch(l){console.error("Error compressing rotated file:",l)}if(s.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Aa(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await fr(r).catch(()=>null))await sc(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Ni(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Pi(hr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=rc(e),i=ap(t),n=oc();await fp(r,n,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()})),Ti(this.currentLogFile))try{let e=nc(this.currentLogFile,"r+");ic(e),Ca(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(!be()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ni(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Pi(hr(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()?J.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||be())return!1;let e=typeof re.env.NO_COLOR<"u",t=re.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof re.stderr<"u"&&re.stderr.isTTY||typeof re.stdout<"u"&&re.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let l=re.stdout.columns||120,c="";if(s==="warning"||s==="error")c=`${r} ${n}`;else if(s==="info"||s==="success")c=`${r} ${i} ${n}`;else c=`${r} ${i} ${J.cyan(n)}`;if(!a)return c.trim();let u=o(c).trim().length,f=o(t).length,h=Math.max(1,l-2-u-f);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=J.underline(J.blue(i)),a=this.toAbsoluteFilePath(n);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,l="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${o}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>J.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>J.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>J.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>J.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>J.strikethrough(i)),t}supportsHyperlinks(){if(be())return!1;let e=re.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=re.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(cp(t)||t.startsWith("./")||t.startsWith("../"))t=up(t);else return null;return Ti(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,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:l,fileText:c}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":sh[e],h=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:J.gray(l),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:J.green(l),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.error(d),o){let m=o.split(`
34
+ `);for(let p of m)if(p.trim()&&!p.includes(a))console.error(this.formatConsoleMessage({timestamp:n,message:J.gray(` ${p}`),level:e,showTimestamp:!1}))}break}}else if(!be()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${c}
35
+ `;if(o)u+=`${o}
36
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};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()&&!be()&&re.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!be()&&re.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!be()&&re.stdout.isTTY)re.stdout.write(`
37
+ `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!be()&&re.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":J.blue("\u25D0"),tag:r,message:`${J.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,a=new Date,o=this.formatConsoleTimestamp(a),l=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
38
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":J.green("\u2713"),tag:c,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!be())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Jn(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(be())throw Error("createReadStream is not supported in browser environments");if(!Ti(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return rc(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=vt.isBuffer(e)?e:vt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),a=i.subarray(16,i.length-16),o=np("aes-256-gcm",r,n);o.setAuthTag(s);let l=o.update(a),c=o.final(),u=l.length+c.length,f=vt.allocUnsafe(u);return l.copy(f,0),c.copy(f,l.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 be()}isServerMode(){return!be()}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:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let o=n.split(`
39
+ `),l=Math.max(...o.map((h)=>h.length))+2,c=`\u250C${"\u2500".repeat(l)}\u2510`,u=`\u2514${"\u2500".repeat(l)}\u2518`,f=o.map((h)=>this.formatConsoleMessage({timestamp:r,message:J.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:J.cyan(c),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:J.cyan(u),showTimestamp:!1}))}else if(!be())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let a=`${i} ${this.environment}.INFO: [BOX] ${s}
40
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(be())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${J.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();re.stdin.removeListener("data",r);try{if(typeof re.stdin.setRawMode==="function")re.stdin.setRawMode(!1)}catch{}re.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof re.stdin.setRawMode==="function")re.stdin.setRawMode(!0)}catch{}re.stdin.resume(),re.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,o=0;if(r=e.replace(a,(l,c)=>{if(c==="%")return"%";if(o>=t.length)return l;let u=t[o++];switch(c){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),o<t.length)r+=` ${t.slice(o).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${J.blue("\u25D0")} `;console.error(`${o}${a} ${J.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
41
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!re.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),n=e.barLength-i,s=J.green("\u2501".repeat(i)),a=J.gray("\u2501".repeat(n)),o=`[${s}${a}]`,l=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?J.green("\u2713"):J.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${J.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${o} ${l}${c}`,d=re.stdout.columns||80,m=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,re.stdout.write(e.lastRenderedLine),t)re.stdout.write(`
42
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||be()||!re.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(be()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ni(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 n=hr(this.config.logDirectory,i);if(e.before)try{if((await fr(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 Pi(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var Oc,Da,ri,y0,ve,J,w0,Rc,b0,Dc,v0,S0,La,x0,Lc,jc,$0,ja,C0,A0,E0,k0,M0,rn,sh,T0,N0=jt(()=>{Oc=vn.env.CLARITY_LOG_DIR||tp(p0(),"logs"),Da={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Oc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ri={...Da},y0=(async()=>{try{let{loadConfig:e}=await Promise.resolve().then(()=>(Sh(),vh)),t=await e({name:"clarity",alias:"logging",defaultConfig:Da,cwd:vn.cwd()});if(t)Object.assign(ri,t)}catch{}return ri})(),ve={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"},J=ve,w0=ve.red,Rc=ve.green,b0=ve.yellow,Dc=ve.blue,v0=ve.magenta,S0=ve.cyan,La=ve.white,x0=ve.gray,Lc=ve.bgRed,jc=ve.bgYellow,$0=ve.bgGray,ja=ve.bold,C0=ve.dim,A0=ve.italic,E0=ve.underline,k0=ve.strikethrough,M0=ve.reset,rn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sh={debug:"\uD83D\uDD0D",info:Dc("\u2139"),success:Rc("\u2713"),warning:jc(La(ja(" WARN "))),error:Lc(La(ja(" ERROR ")))},T0=new Jn("stacks")}),P0="0.15.9",F0=()=>{};async function oh(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,a=Error("Unknown error occurred");for(let o=0;o<=r;o++)try{return await e()}catch(l){if(a=l instanceof Error?l:Error(String(l)),o===r||!n(a))break;if(i>0)await new Promise((c)=>setTimeout(c,i))}if(s!==void 0)return s;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function lh(e){return e instanceof We}function O0(e){return e instanceof En}function R0(e){if(lh(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()))}var We,En,li,Ms,Ts,kn,Ns,Ps,ci,Fs,Os,Vt,Lr=jt(()=>{We=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}`}},En=class extends We{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},li=class extends We{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}},Ms=class extends We{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Ts=class extends We{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}},kn=class extends We{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})}},Ns=class extends We{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}},Ps=class extends We{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}},ci=class extends We{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})}},Fs=class extends We{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})}},Os=class extends We{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}},Vt={configNotFound(e,t,r){return new En(e,t,r)},configLoad(e,t,r){return new li(e,t,r)},configValidation(e,t,r){return new Ms(e,t,r)},configMerge(e,t,r,i){return new Ts(e,t,r,i)},envVar(e,t,r,i){return new kn(e,t,r,i)},fileSystem(e,t,r){return new Ns(e,t,r)},typeGeneration(e,t,r){return new Ps(e,t,r)},schemaValidation(e,t,r){return new ci(e,t,r)},browserConfig(e,t,r,i){return new Fs(e,t,r,i)},plugin(e,t,r){return new Os(e,t,r)}}});class Zn{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:n=!0,useBackwardCompatibility:s=!0,customParsers:a={},verbose:o=!1,trackPerformance:l=!0}=r,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:a,verbose:o,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return wi.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[n,s]of Object.entries(e)){let a=[...t,n],o=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),l=`${r}_${o.join("_")}`,c=i.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,a,r,i);else{let u=Fi.env[l]||(c?Fi.env[c]:void 0);if(u!==void 0){if(i.verbose){let f=Fi.env[l]?l:c}try{e[n]=this.parseEnvironmentValue(u,typeof s,l,i.customParsers,i.configName)}catch(f){if(f instanceof kn)throw f;throw Vt.envVar(l,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,a]of Object.entries(i))try{return a(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Vt.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(Fi.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;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(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],s,a),n){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[n,s]of Object.entries(e)){let a=[...t,n],o=`${r}_${a.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,a,r,i);else i.push({key:o,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${a.join(".")}`,example:this.generateExample(s)})}}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}:
43
+
44
+ `;for(let i of e)r+=`${i.key}
45
+ `,r+=` Type: ${i.type}
46
+ `,r+=` Description: ${i.description}
47
+ `,r+=` Example: ${i.example}
48
+
49
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
50
+
51
+ `;r+=`| Variable | Type | Description | Example |
52
+ `,r+=`|----------|------|-------------|----------|
53
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
54
+ `;return r}}var ch=jt(()=>{bi(),Lr()});function D0(e,t){let r=f0("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function uh(e,t,r={}){return fh(e,t,r,new WeakMap)}function fh(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return hh(e,t,n,i);if(!Qe(t)||!Qe(e))return t;return I0(e,t,r,i)}function hh(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 L0(e,t);case"smart":return j0(e,t,i);default:return t}return t}function L0(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Rs(n,i)))r.push(i);return r}function j0(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Qe(t[0])&&Qe(e[0]))return B0(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function B0(e,t,r){let i=[...t];for(let n of e){if(!Qe(n)){i.push(n);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in n){if(i.find((l)=>Qe(l)&&(o in l)&&l[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function I0(e,t,r,i){let n=t;if(Qe(n)&&i.has(n))return i.get(n);let s={...e};if(Qe(n))i.set(n,s);for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let o=n[a],l=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(Qe(o)&&Qe(l))s[a]=fh(l,o,r,i);else if(Array.isArray(o)||Array.isArray(l))s[a]=hh(l,o,r.arrayMergeMode||"smart",i);else s[a]=o}return s}function Ro(e,t,r="replace"){return uh(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Rs(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(!Rs(e[r],t[r]))return!1;return!0}if(Qe(e)&&Qe(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Rs(e[n],t[n]))return!1}return!0}return!1}function Qe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}var dh,Do=jt(()=>{dh={replace:"replace",concat:"concat",smart:"smart"}});class Qn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(n){let c=Dr.getWithFileCheck("file",e);if(c){if(o)console.log(`Configuration loaded from cache: ${e}`);return c}}let l=async()=>{if(!Oi(e))return null;try{let c=`?t=${Date.now()}`,u=await import(e+c),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new li(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new li(e,Error("Configuration must export a valid object"),"unknown");let m={config:Ro(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Dr.setWithFileCheck("file",m,e,s);return m}catch(c){throw c instanceof Error?Vt.configLoad(e,c):Vt.configLoad(e,Error(String(c)))}};if(a)return wi.track("loadFromPath",l,{path:e});return l()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let a of this.extensions)n.push(Ea(t,`${s}${a}`));return n}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 s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return oh(async()=>Oi(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Oi(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let a of this.extensions){let o=Ea(e,`${s}${a}`);if(await this.checkFileAccess(o))i.push(o)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=Ea(e,a);if(await this.checkFileAccess(o))i.push(o)}}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(!Oi(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:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}var mh=jt(()=>{bi(),Lr(),Do()});class Lo{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:l=!1}=r,c=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:a,trackPerformance:o,verbose:l};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(o)return await wi.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!hp(t))throw new ci(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new ci(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(i.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,rule:"type"}),s.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"}),s.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 o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(i.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,l]of Object.entries(t.properties))if(o in a){let c=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],l,c,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let l of Object.keys(a))if(!o.has(l))n.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(i.push(...o),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}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 n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))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 n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,a]=i;t.push({path:n,required:!s,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:ph},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ph,gh=jt(()=>{bi(),Lr(),ph=/^https?:\/\//});function z0(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 jo{fileLoader=new Qn;envProcessor=new Zn;validator=new Lo;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...a}=e;try{if(r?.enabled){let l=this.checkCache(a.name||"",a);if(l)return l}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(l){let c=a.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(c)throw l;o={...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(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),f=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),h=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(c&&(h||u))throw l;if(f&&(!c||!h))o={...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)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(n||s)await this.validateConfiguration(o.config,n,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(i?.enabled){let l={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(l);if(i.slowThreshold&&l.duration>i.slowThreshold)Ye.warn(`Slow configuration loading detected: ${l.duration}ms for ${a.name}`);o.metrics=l}return o}catch(o){let l=Date.now()-t;throw Ye.error(`Configuration loading failed after ${l}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:a,defaultConfig:o,checkEnv:l=!0,arrayStrategy:c="replace",verbose:u=!1}=e,f=s||tr.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,a,o,c,u,l,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,a)),this.finalizeResult(d,h,l,i,u);let m=await this.loadHomeConfiguration(i,n,o,c,u,l);if(m)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(m,h,l,i,u);let p=await this.loadPackageJsonConfiguration(i,n,f,o,c,u,l);if(p)return h.push(Be(f,"package.json")),this.finalizeResult(p,h,l,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,a)),t)throw Vt.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,o,l,u),warnings:[`No configuration file found for "${i}"${z0(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,l){let c=o?Jr(e,n,a):n,u=this.getLocalDirectories(r,i);for(let f of u){if(a)Ye.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:s,verbose:a,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(d){if(a)Ye.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let a=s?Jr(e,r,n):r,o=[Be(mr(),".config",e),Be(mr(),".config"),mr()];for(let l of o){if(n)Ye.info(`Checking home directory: ${l}`);let c=this.fileLoader.generateConfigPaths(e,l,t),u=await this.fileLoader.tryLoadFromPaths(c,a,{arrayStrategy:i,verbose:n});if(u){if(n)Ye.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,a){let o=a?Jr(e,i,s):i;try{let l=Be(r,"package.json");if(!ys(l))return null;let c={};try{c=JSON.parse(pp(l,"utf8"))}catch(h){if(s)Ye.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=c[e],f=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(c[d]){u=c[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Ye.success(`Configuration loaded from package.json: ${f}`);return{config:Ro(o,u,n),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(s)Ye.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}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:Jr(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(n.length>0)throw Vt.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Dr.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Dr.set(n,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,Be(e,"config"),Be(e,".config"),t?Be(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Be(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let a of n)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Be(mr(),".config",e),Be(mr(),".config"),mr()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Bc(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 _0(e){return Pt.loadConfig({...e,__strictErrorHandling:!0})}async function yh(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 Pt.loadConfig(e);else i=await Pt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)Ye.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 Pt.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function U0(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Pt.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"&&Bc(r)))return(await Pt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Pt.loadConfig({...e,cwd:e.cwd||tr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Bc(t)))return(await Pt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function V0(e,t,r="replace"){let i=new Qn;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Jr(e,t,r=!1){let i=new Zn,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let l={...a};for(let[c,u]of Object.entries(a)){let f=[...o,c],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((p)=>p.toUpperCase()).join("")}`,`${n}_${f.map((p)=>p.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,m;for(let p of h)if(d=tr.env[p],d!==void 0){m=p;break}if(d!==void 0&&m)if(typeof u==="boolean")l[c]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let p=Number(d);if(!Number.isNaN(p))l[c]=p}else if(Array.isArray(u))try{l[c]=JSON.parse(d)}catch{l[c]=d.split(",").map((p)=>p.trim())}else l[c]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))l[c]=s(u,f)}return l}return s(t)}function G0(e){let t=Be(tr.cwd(),e.configDir),r=Be(tr.cwd(),e.generatedDir),i=Be(r,"config-types.ts");if(!ys(lc(i)))dp(lc(i),{recursive:!0,mode:511});let n=ys(t)?mp(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${P0}
55
+ export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
56
+ `;gp(i,s,{mode:438})}function W0(e){let t=null,r=null,i=()=>{if(!r)r=yh(e).then((s)=>(t=s,s),(s)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)Ye.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return a});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,a){if(t)return t[a];let o=n[a];return i(),o},has(s,a){return a in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,a){return Object.getOwnPropertyDescriptor(t||n,a)},set(s,a,o){if(!t)t={...n};return t[a]=o,!0}})}var Ye,Pt,wh,bh,q0=jt(()=>{N0(),F0(),bi(),Lr(),ch(),mh(),gh(),Do(),Ye=new Jn("bunfig",{showTags:!0}),Pt=new jo,wh=Be(tr.cwd(),"config"),bh=Be(tr.cwd(),"src/generated")});function K0(e){let t=cc(bp.cwd(),e?.configDir||"./config");function r(){if(!yp(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=wp(t).filter((l)=>n.has(ka(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),o=new Map;for(let{base:l,file:c}of a){let u=ka(c).toLowerCase(),f=o.get(l);if(!f){o.set(l,c);continue}let h=ka(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))o.set(l,c)}return Array.from(o.entries()).map(([l,c])=>({base:l,file:c})).sort((l,c)=>l.base.localeCompare(c.base))}function i(){let n=r(),s=n.map((l)=>l.base),a=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",o=n.length?`{
57
+ ${n.map((l)=>{let c=cc(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${c}').default`}).join(`,
58
+ `)}
59
+ }`:"Record<string, any>";return`export type ConfigNames = ${a}
60
+ export type ConfigByName = ${o}
61
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
62
+ export type ConfigOf = Config
63
+ `}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var Y0=()=>{},vh={};u0(vh,{withErrorRecovery:()=>oh,tryLoadConfig:()=>V0,loadConfigWithResult:()=>_0,loadConfig:()=>yh,isRetryableError:()=>R0,isConfigNotFoundError:()=>O0,isBunfigError:()=>lh,globalPerformanceMonitor:()=>wi,globalCache:()=>Dr,getEnvOrDefault:()=>D0,generateConfigTypes:()=>G0,defaultGeneratedDir:()=>bh,defaultConfigDir:()=>wh,deepMergeWithArrayStrategy:()=>Ro,deepMerge:()=>uh,createLibraryConfig:()=>W0,config:()=>U0,bunfigPlugin:()=>K0,applyEnvVarsToConfig:()=>Jr,TypeGenerationError:()=>Ps,SchemaValidationError:()=>ci,PluginError:()=>Os,PerformanceMonitor:()=>Oo,FileSystemError:()=>Ns,ErrorFactory:()=>Vt,EnvVarError:()=>kn,EnvProcessor:()=>Zn,ConfigValidator:()=>Lo,ConfigValidationError:()=>Ms,ConfigNotFoundError:()=>En,ConfigMergeError:()=>Ts,ConfigLoader:()=>jo,ConfigLoadError:()=>li,ConfigFileLoader:()=>Qn,ConfigCache:()=>Fo,CacheUtils:()=>nh,BunfigError:()=>We,BrowserConfigError:()=>Fs,ArrayMergeStrategies:()=>dh});var Sh=jt(()=>{q0(),Lr(),bi(),Lr(),Y0(),ch(),mh(),gh(),Do()});Sh();var Rt=Symbol("visitSkip");function wt(e,t,r){let i=t[e.type];if(i?.enter){if(i.enter(e,r??null)===Rt)return}let n=!1;if(e.type==="root")n=!0;else if(e.type==="element"&&r){let s=r.children;n=s[s.length-1]===e||s[0]===e||s.indexOf(e)>=0}if(n&&"children"in e){let s=e.children,a=s.length;if(a===0);else if(a===1)wt(s[0],t,e);else{let o=Array(a);for(let l=0;l<a;l++)o[l]=s[l];for(let l=0;l<a;l++)wt(o[l],t,e)}}if(i?.exit)i.exit(e,r??null)}var H0="cleanupEnableBackground",J0="remove or cleanup enable-background attribute when possible",Z0=/^new\s0\s0\s([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)\s([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)$/;function Ic(e,t,r,i){let n=Z0.exec(e);if(n!=null&&r===n[1]&&i===n[2])return t==="svg"?void 0:"new";return e}var Q0=(e)=>{let t=!1;return wt(e,{element:{enter:(r)=>{if(r.name==="filter")t=!0}}}),{element:{enter:(r)=>{let i=null,n=null;if(r.attributes.style!=null){if(i=G.parse(r.attributes.style,{context:"declarationList"}),i.type==="DeclarationList"){let a=[];G.walk(i,(o,l)=>{if(o.type==="Declaration"&&o.property==="enable-background")a.push(l),n=l});for(let o=0;o<a.length-1;o++)i.children.remove(a[o])}}if(!t){if(delete r.attributes["enable-background"],i?.type==="DeclarationList"){if(n)i.children.remove(n);if(i.children.isEmpty)delete r.attributes.style;else r.attributes.style=G.generate(i)}return}let s=r.attributes.width!=null&&r.attributes.height!=null;if((r.name==="svg"||r.name==="mask"||r.name==="pattern")&&s){let a=r.attributes["enable-background"],o=Ic(a,r.name,r.attributes.width,r.attributes.height);if(o)r.attributes["enable-background"]=o;else delete r.attributes["enable-background"];if(i?.type==="DeclarationList"&&n){let l=G.generate(n.data.value),c=Ic(l,r.name,r.attributes.width,r.attributes.height);if(c)n.data.value={type:"Raw",value:c};else i.children.remove(n)}}if(i?.type==="DeclarationList")if(i.children.isEmpty)delete r.attributes.style;else r.attributes.style=G.generate(i)}}}},Bo={};D(Bo,{name:()=>aw,fn:()=>uw,description:()=>sw});var Kt={animation:new Set(["animate","animateColor","animateMotion","animateTransform","set"]),descriptive:new Set(["desc","metadata","title"]),shape:new Set(["circle","ellipse","line","path","polygon","polyline","rect"]),structural:new Set(["defs","g","svg","symbol","use"]),paintServer:new Set(["hatch","linearGradient","meshGradient","pattern","radialGradient","solidColor"]),nonRendering:new Set(["clipPath","filter","linearGradient","marker","mask","pattern","radialGradient","solidColor","symbol"]),container:new Set(["a","defs","foreignObject","g","marker","mask","missing-glyph","pattern","svg","switch","symbol"]),textContent:new Set(["a","altGlyph","altGlyphDef","altGlyphItem","glyph","glyphRef","text","textPath","tref","tspan"]),textContentChild:new Set(["altGlyph","textPath","tref","tspan"]),lightSource:new Set(["feDiffuseLighting","feDistantLight","fePointLight","feSpecularLighting","feSpotLight"]),filterPrimitive:new Set(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence"])},xh=new Set([...Kt.textContent,"pre","title"]),Io=new Set(["glyph","missing-glyph","path"]),Oe={animationAddition:new Set(["additive","accumulate"]),animationAttributeTarget:new Set(["attributeType","attributeName"]),animationEvent:new Set(["onbegin","onend","onrepeat","onload"]),animationTiming:new Set(["begin","dur","end","fill","max","min","repeatCount","repeatDur","restart"]),animationValue:new Set(["by","calcMode","from","keySplines","keyTimes","to","values"]),conditionalProcessing:new Set(["requiredExtensions","requiredFeatures","systemLanguage"]),core:new Set(["id","tabindex","xml:base","xml:lang","xml:space"]),graphicalEvent:new Set(["onactivate","onclick","onfocusin","onfocusout","onload","onmousedown","onmousemove","onmouseout","onmouseover","onmouseup"]),presentation:new Set(["alignment-baseline","baseline-shift","clip-path","clip-rule","clip","color-interpolation-filters","color-interpolation","color-profile","color-rendering","color","cursor","direction","display","dominant-baseline","enable-background","fill-opacity","fill-rule","fill","filter","flood-color","flood-opacity","font-family","font-size-adjust","font-size","font-stretch","font-style","font-variant","font-weight","glyph-orientation-horizontal","glyph-orientation-vertical","image-rendering","letter-spacing","lighting-color","marker-end","marker-mid","marker-start","mask","opacity","overflow","paint-order","pointer-events","shape-rendering","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","stroke","text-anchor","text-decoration","text-overflow","text-rendering","transform-origin","transform","unicode-bidi","vector-effect","visibility","word-spacing","writing-mode"]),xlink:new Set(["xlink:actuate","xlink:arcrole","xlink:href","xlink:role","xlink:show","xlink:title","xlink:type"]),documentEvent:new Set(["onabort","onerror","onresize","onscroll","onunload","onzoom"]),documentElementEvent:new Set(["oncopy","oncut","onpaste"]),globalEvent:new Set(["oncancel","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onmousewheel","onpause","onplay","onplaying","onprogress","onratechange","onreset","onresize","onscroll","onseeked","onseeking","onselect","onshow","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","onvolumechange","onwaiting"]),filterPrimitive:new Set(["x","y","width","height","result"]),transferFunction:new Set(["amplitude","exponent","intercept","offset","slope","tableValues","type"])},zo={core:{"xml:space":"default"},presentation:{clip:"auto","clip-path":"none","clip-rule":"nonzero",mask:"none",opacity:"1","stop-color":"#000","stop-opacity":"1","fill-opacity":"1","fill-rule":"nonzero",fill:"#000",stroke:"none","stroke-width":"1","stroke-linecap":"butt","stroke-linejoin":"miter","stroke-miterlimit":"4","stroke-dasharray":"none","stroke-dashoffset":"0","stroke-opacity":"1","paint-order":"normal","vector-effect":"none",display:"inline",visibility:"visible","marker-start":"none","marker-mid":"none","marker-end":"none","color-interpolation":"sRGB","color-interpolation-filters":"linearRGB","color-rendering":"auto","shape-rendering":"auto","text-rendering":"auto","image-rendering":"auto","font-style":"normal","font-variant":"normal","font-weight":"normal","font-stretch":"normal","font-size":"medium","font-size-adjust":"none",kerning:"auto","letter-spacing":"normal","word-spacing":"normal","text-decoration":"none","text-anchor":"start","text-overflow":"clip","writing-mode":"lr-tb","glyph-orientation-vertical":"auto","glyph-orientation-horizontal":"0deg",direction:"ltr","unicode-bidi":"normal","dominant-baseline":"auto","alignment-baseline":"baseline","baseline-shift":"baseline"},transferFunction:{slope:"1",intercept:"0",amplitude:"1",exponent:"1",offset:"0"}},X0={animationAttributeTarget:{unsafe:new Set(["attributeType"])},conditionalProcessing:{unsafe:new Set(["requiredFeatures"])},core:{unsafe:new Set(["xml:base","xml:lang","xml:space"])},presentation:{unsafe:new Set(["clip","color-profile","enable-background","glyph-orientation-horizontal","glyph-orientation-vertical","kerning"])}},_o={a:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation","xlink"]),attrs:new Set(["class","externalResourcesRequired","style","target","transform"]),defaults:{target:"_self"},contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view","tspan"])},altGlyph:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation","xlink"]),attrs:new Set(["class","dx","dy","externalResourcesRequired","format","glyphRef","rotate","style","x","y"])},altGlyphDef:{attrsGroups:new Set(["core"]),content:new Set(["glyphRef"])},altGlyphItem:{attrsGroups:new Set(["core"]),content:new Set(["glyphRef","altGlyphItem"])},animate:{attrsGroups:new Set(["animationAddition","animationAttributeTarget","animationEvent","animationTiming","animationValue","conditionalProcessing","core","presentation","xlink"]),attrs:new Set(["externalResourcesRequired"]),contentGroups:new Set(["descriptive"])},animateColor:{attrsGroups:new Set(["animationAddition","animationAttributeTarget","animationEvent","animationTiming","animationValue","conditionalProcessing","core","presentation","xlink"]),attrs:new Set(["externalResourcesRequired"]),contentGroups:new Set(["descriptive"])},animateMotion:{attrsGroups:new Set(["animationAddition","animationEvent","animationTiming","animationValue","conditionalProcessing","core","xlink"]),attrs:new Set(["externalResourcesRequired","keyPoints","origin","path","rotate"]),defaults:{rotate:"0"},contentGroups:new Set(["descriptive"]),content:new Set(["mpath"])},animateTransform:{attrsGroups:new Set(["animationAddition","animationAttributeTarget","animationEvent","animationTiming","animationValue","conditionalProcessing","core","xlink"]),attrs:new Set(["externalResourcesRequired","type"]),contentGroups:new Set(["descriptive"])},circle:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","cx","cy","externalResourcesRequired","r","style","transform"]),defaults:{cx:"0",cy:"0"},contentGroups:new Set(["animation","descriptive"])},clipPath:{attrsGroups:new Set(["conditionalProcessing","core","presentation"]),attrs:new Set(["class","clipPathUnits","externalResourcesRequired","style","transform"]),defaults:{clipPathUnits:"userSpaceOnUse"},contentGroups:new Set(["animation","descriptive","shape"]),content:new Set(["text","use"])},"color-profile":{attrsGroups:new Set(["core","xlink"]),attrs:new Set(["local","name","rendering-intent"]),defaults:{name:"sRGB","rendering-intent":"auto"},deprecated:{unsafe:new Set(["name"])},contentGroups:new Set(["descriptive"])},cursor:{attrsGroups:new Set(["core","conditionalProcessing","xlink"]),attrs:new Set(["externalResourcesRequired","x","y"]),defaults:{x:"0",y:"0"},contentGroups:new Set(["descriptive"])},defs:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","externalResourcesRequired","style","transform"]),contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view"])},desc:{attrsGroups:new Set(["core"]),attrs:new Set(["class","style"])},ellipse:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","cx","cy","externalResourcesRequired","rx","ry","style","transform"]),defaults:{cx:"0",cy:"0"},contentGroups:new Set(["animation","descriptive"])},feBlend:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","style","in","in2","mode"]),defaults:{mode:"normal"},content:new Set(["animate","set"])},feColorMatrix:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","style","in","type","values"]),defaults:{type:"matrix"},content:new Set(["animate","set"])},feComponentTransfer:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","style","in"]),content:new Set(["feFuncA","feFuncB","feFuncG","feFuncR"])},feComposite:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","in","in2","k1","k2","k3","k4","operator","style"]),defaults:{operator:"over",k1:"0",k2:"0",k3:"0",k4:"0"},content:new Set(["animate","set"])},feConvolveMatrix:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","in","kernelMatrix","order","style","bias","divisor","edgeMode","targetX","targetY","kernelUnitLength","preserveAlpha"]),defaults:{order:"3",bias:"0",edgeMode:"duplicate",preserveAlpha:"false"},content:new Set(["animate","set"])},feDiffuseLighting:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","diffuseConstant","in","kernelUnitLength","style","surfaceScale"]),defaults:{surfaceScale:"1",diffuseConstant:"1"},contentGroups:new Set(["descriptive"]),content:new Set(["feDistantLight","fePointLight","feSpotLight"])},feDisplacementMap:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","in","in2","scale","style","xChannelSelector","yChannelSelector"]),defaults:{scale:"0",xChannelSelector:"A",yChannelSelector:"A"},content:new Set(["animate","set"])},feDistantLight:{attrsGroups:new Set(["core"]),attrs:new Set(["azimuth","elevation"]),defaults:{azimuth:"0",elevation:"0"},content:new Set(["animate","set"])},feFlood:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","style"]),content:new Set(["animate","animateColor","set"])},feFuncA:{attrsGroups:new Set(["core","transferFunction"]),content:new Set(["set","animate"])},feFuncB:{attrsGroups:new Set(["core","transferFunction"]),content:new Set(["set","animate"])},feFuncG:{attrsGroups:new Set(["core","transferFunction"]),content:new Set(["set","animate"])},feFuncR:{attrsGroups:new Set(["core","transferFunction"]),content:new Set(["set","animate"])},feGaussianBlur:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","style","in","stdDeviation"]),defaults:{stdDeviation:"0"},content:new Set(["set","animate"])},feImage:{attrsGroups:new Set(["core","presentation","filterPrimitive","xlink"]),attrs:new Set(["class","externalResourcesRequired","href","preserveAspectRatio","style","xlink:href"]),defaults:{preserveAspectRatio:"xMidYMid meet"},content:new Set(["animate","animateTransform","set"])},feMerge:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","style"]),content:new Set(["feMergeNode"])},feMergeNode:{attrsGroups:new Set(["core"]),attrs:new Set(["in"]),content:new Set(["animate","set"])},feMorphology:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","style","in","operator","radius"]),defaults:{operator:"erode",radius:"0"},content:new Set(["animate","set"])},feOffset:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","style","in","dx","dy"]),defaults:{dx:"0",dy:"0"},content:new Set(["animate","set"])},fePointLight:{attrsGroups:new Set(["core"]),attrs:new Set(["x","y","z"]),defaults:{x:"0",y:"0",z:"0"},content:new Set(["animate","set"])},feSpecularLighting:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","in","kernelUnitLength","specularConstant","specularExponent","style","surfaceScale"]),defaults:{surfaceScale:"1",specularConstant:"1",specularExponent:"1"},contentGroups:new Set(["descriptive","lightSource"])},feSpotLight:{attrsGroups:new Set(["core"]),attrs:new Set(["limitingConeAngle","pointsAtX","pointsAtY","pointsAtZ","specularExponent","x","y","z"]),defaults:{x:"0",y:"0",z:"0",pointsAtX:"0",pointsAtY:"0",pointsAtZ:"0",specularExponent:"1"},content:new Set(["animate","set"])},feTile:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["class","style","in"]),content:new Set(["animate","set"])},feTurbulence:{attrsGroups:new Set(["core","presentation","filterPrimitive"]),attrs:new Set(["baseFrequency","class","numOctaves","seed","stitchTiles","style","type"]),defaults:{baseFrequency:"0",numOctaves:"1",seed:"0",stitchTiles:"noStitch",type:"turbulence"},content:new Set(["animate","set"])},filter:{attrsGroups:new Set(["core","presentation","xlink"]),attrs:new Set(["class","externalResourcesRequired","filterRes","filterUnits","height","href","primitiveUnits","style","width","x","xlink:href","y"]),defaults:{primitiveUnits:"userSpaceOnUse",x:"-10%",y:"-10%",width:"120%",height:"120%"},deprecated:{unsafe:new Set(["filterRes"])},contentGroups:new Set(["descriptive","filterPrimitive"]),content:new Set(["animate","set"])},font:{attrsGroups:new Set(["core","presentation"]),attrs:new Set(["class","externalResourcesRequired","horiz-adv-x","horiz-origin-x","horiz-origin-y","style","vert-adv-y","vert-origin-x","vert-origin-y"]),defaults:{"horiz-origin-x":"0","horiz-origin-y":"0"},deprecated:{unsafe:new Set(["horiz-origin-x","horiz-origin-y","vert-adv-y","vert-origin-x","vert-origin-y"])},contentGroups:new Set(["descriptive"]),content:new Set(["font-face","glyph","hkern","missing-glyph","vkern"])},"font-face":{attrsGroups:new Set(["core"]),attrs:new Set(["font-family","font-style","font-variant","font-weight","font-stretch","font-size","unicode-range","units-per-em","panose-1","stemv","stemh","slope","cap-height","x-height","accent-height","ascent","descent","widths","bbox","ideographic","alphabetic","mathematical","hanging","v-ideographic","v-alphabetic","v-mathematical","v-hanging","underline-position","underline-thickness","strikethrough-position","strikethrough-thickness","overline-position","overline-thickness"]),defaults:{"font-style":"all","font-variant":"normal","font-weight":"all","font-stretch":"normal","unicode-range":"U+0-10FFFF","units-per-em":"1000","panose-1":"0 0 0 0 0 0 0 0 0 0",slope:"0"},deprecated:{unsafe:new Set(["accent-height","alphabetic","ascent","bbox","cap-height","descent","hanging","ideographic","mathematical","panose-1","slope","stemh","stemv","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","widths","x-height"])},contentGroups:new Set(["descriptive"]),content:new Set(["font-face-src"])},"font-face-format":{attrsGroups:new Set(["core"]),attrs:new Set(["string"]),deprecated:{unsafe:new Set(["string"])}},"font-face-name":{attrsGroups:new Set(["core"]),attrs:new Set(["name"]),deprecated:{unsafe:new Set(["name"])}},"font-face-src":{attrsGroups:new Set(["core"]),content:new Set(["font-face-name","font-face-uri"])},"font-face-uri":{attrsGroups:new Set(["core","xlink"]),attrs:new Set(["href","xlink:href"]),content:new Set(["font-face-format"])},foreignObject:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","externalResourcesRequired","height","style","transform","width","x","y"]),defaults:{x:"0",y:"0"}},g:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","externalResourcesRequired","style","transform"]),contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view"])},glyph:{attrsGroups:new Set(["core","presentation"]),attrs:new Set(["arabic-form","class","d","glyph-name","horiz-adv-x","lang","orientation","style","unicode","vert-adv-y","vert-origin-x","vert-origin-y"]),defaults:{"arabic-form":"initial"},deprecated:{unsafe:new Set(["arabic-form","glyph-name","horiz-adv-x","orientation","unicode","vert-adv-y","vert-origin-x","vert-origin-y"])},contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view"])},glyphRef:{attrsGroups:new Set(["core","presentation"]),attrs:new Set(["class","d","horiz-adv-x","style","vert-adv-y","vert-origin-x","vert-origin-y"]),deprecated:{unsafe:new Set(["horiz-adv-x","vert-adv-y","vert-origin-x","vert-origin-y"])},contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view"])},hatch:{attrsGroups:new Set(["core","presentation","xlink"]),attrs:new Set(["class","hatchContentUnits","hatchUnits","pitch","rotate","style","transform","x","y"]),defaults:{hatchUnits:"objectBoundingBox",hatchContentUnits:"userSpaceOnUse",x:"0",y:"0",pitch:"0",rotate:"0"},contentGroups:new Set(["animation","descriptive"]),content:new Set(["hatchPath"])},hatchPath:{attrsGroups:new Set(["core","presentation","xlink"]),attrs:new Set(["class","style","d","offset"]),defaults:{offset:"0"},contentGroups:new Set(["animation","descriptive"])},hkern:{attrsGroups:new Set(["core"]),attrs:new Set(["u1","g1","u2","g2","k"]),deprecated:{unsafe:new Set(["g1","g2","k","u1","u2"])}},image:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation","xlink"]),attrs:new Set(["class","externalResourcesRequired","height","href","preserveAspectRatio","style","transform","width","x","xlink:href","y"]),defaults:{x:"0",y:"0",preserveAspectRatio:"xMidYMid meet"},contentGroups:new Set(["animation","descriptive"])},line:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","externalResourcesRequired","style","transform","x1","x2","y1","y2"]),defaults:{x1:"0",y1:"0",x2:"0",y2:"0"},contentGroups:new Set(["animation","descriptive"])},linearGradient:{attrsGroups:new Set(["core","presentation","xlink"]),attrs:new Set(["class","externalResourcesRequired","gradientTransform","gradientUnits","href","spreadMethod","style","x1","x2","xlink:href","y1","y2"]),defaults:{x1:"0",y1:"0",x2:"100%",y2:"0",spreadMethod:"pad"},contentGroups:new Set(["descriptive"]),content:new Set(["animate","animateTransform","set","stop"])},marker:{attrsGroups:new Set(["core","presentation"]),attrs:new Set(["class","externalResourcesRequired","markerHeight","markerUnits","markerWidth","orient","preserveAspectRatio","refX","refY","style","viewBox"]),defaults:{markerUnits:"strokeWidth",refX:"0",refY:"0",markerWidth:"3",markerHeight:"3"},contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view"])},mask:{attrsGroups:new Set(["conditionalProcessing","core","presentation"]),attrs:new Set(["class","externalResourcesRequired","height","mask-type","maskContentUnits","maskUnits","style","width","x","y"]),defaults:{maskUnits:"objectBoundingBox",maskContentUnits:"userSpaceOnUse",x:"-10%",y:"-10%",width:"120%",height:"120%"},contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view"])},metadata:{attrsGroups:new Set(["core"])},"missing-glyph":{attrsGroups:new Set(["core","presentation"]),attrs:new Set(["class","d","horiz-adv-x","style","vert-adv-y","vert-origin-x","vert-origin-y"]),deprecated:{unsafe:new Set(["horiz-adv-x","vert-adv-y","vert-origin-x","vert-origin-y"])},contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view"])},mpath:{attrsGroups:new Set(["core","xlink"]),attrs:new Set(["externalResourcesRequired","href","xlink:href"]),contentGroups:new Set(["descriptive"])},path:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","d","externalResourcesRequired","pathLength","style","transform"]),contentGroups:new Set(["animation","descriptive"])},pattern:{attrsGroups:new Set(["conditionalProcessing","core","presentation","xlink"]),attrs:new Set(["class","externalResourcesRequired","height","href","patternContentUnits","patternTransform","patternUnits","preserveAspectRatio","style","viewBox","width","x","xlink:href","y"]),defaults:{patternUnits:"objectBoundingBox",patternContentUnits:"userSpaceOnUse",x:"0",y:"0",width:"0",height:"0",preserveAspectRatio:"xMidYMid meet"},contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view"])},polygon:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","externalResourcesRequired","points","style","transform"]),contentGroups:new Set(["animation","descriptive"])},polyline:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","externalResourcesRequired","points","style","transform"]),contentGroups:new Set(["animation","descriptive"])},radialGradient:{attrsGroups:new Set(["core","presentation","xlink"]),attrs:new Set(["class","cx","cy","externalResourcesRequired","fr","fx","fy","gradientTransform","gradientUnits","href","r","spreadMethod","style","xlink:href"]),defaults:{gradientUnits:"objectBoundingBox",cx:"50%",cy:"50%",r:"50%"},contentGroups:new Set(["descriptive"]),content:new Set(["animate","animateTransform","set","stop"])},meshGradient:{attrsGroups:new Set(["core","presentation","xlink"]),attrs:new Set(["class","style","x","y","gradientUnits","transform"]),contentGroups:new Set(["descriptive","paintServer","animation"]),content:new Set(["meshRow"])},meshRow:{attrsGroups:new Set(["core","presentation"]),attrs:new Set(["class","style"]),contentGroups:new Set(["descriptive"]),content:new Set(["meshPatch"])},meshPatch:{attrsGroups:new Set(["core","presentation"]),attrs:new Set(["class","style"]),contentGroups:new Set(["descriptive"]),content:new Set(["stop"])},rect:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","externalResourcesRequired","height","rx","ry","style","transform","width","x","y"]),defaults:{x:"0",y:"0"},contentGroups:new Set(["animation","descriptive"])},script:{attrsGroups:new Set(["core","xlink"]),attrs:new Set(["externalResourcesRequired","type","href","xlink:href"])},set:{attrsGroups:new Set(["animation","animationAttributeTarget","animationTiming","conditionalProcessing","core","xlink"]),attrs:new Set(["externalResourcesRequired","to"]),contentGroups:new Set(["descriptive"])},solidColor:{attrsGroups:new Set(["core","presentation"]),attrs:new Set(["class","style"]),contentGroups:new Set(["paintServer"])},stop:{attrsGroups:new Set(["core","presentation"]),attrs:new Set(["class","style","offset","path"]),content:new Set(["animate","animateColor","set"])},style:{attrsGroups:new Set(["core"]),attrs:new Set(["type","media","title"]),defaults:{type:"text/css"}},svg:{attrsGroups:new Set(["conditionalProcessing","core","documentEvent","graphicalEvent","presentation"]),attrs:new Set(["baseProfile","class","contentScriptType","contentStyleType","height","preserveAspectRatio","style","version","viewBox","width","x","y","zoomAndPan"]),defaults:{x:"0",y:"0",width:"100%",height:"100%",preserveAspectRatio:"xMidYMid meet",zoomAndPan:"magnify",version:"1.1",baseProfile:"none",contentScriptType:"application/ecmascript",contentStyleType:"text/css"},deprecated:{safe:new Set(["version"]),unsafe:new Set(["baseProfile","contentScriptType","contentStyleType","zoomAndPan"])},contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view"])},switch:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","externalResourcesRequired","style","transform"]),contentGroups:new Set(["animation","descriptive","shape"]),content:new Set(["a","foreignObject","g","image","svg","switch","text","use"])},symbol:{attrsGroups:new Set(["core","graphicalEvent","presentation"]),attrs:new Set(["class","externalResourcesRequired","preserveAspectRatio","refX","refY","style","viewBox"]),defaults:{refX:"0",refY:"0"},contentGroups:new Set(["animation","descriptive","paintServer","shape","structural"]),content:new Set(["a","altGlyphDef","clipPath","color-profile","cursor","filter","font-face","font","foreignObject","image","marker","mask","pattern","script","style","switch","text","view"])},text:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","dx","dy","externalResourcesRequired","lengthAdjust","rotate","style","textLength","transform","x","y"]),defaults:{x:"0",y:"0",lengthAdjust:"spacing"},contentGroups:new Set(["animation","descriptive","textContentChild"]),content:new Set(["a"])},textPath:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation","xlink"]),attrs:new Set(["class","d","externalResourcesRequired","href","method","spacing","startOffset","style","xlink:href"]),defaults:{startOffset:"0",method:"align",spacing:"exact"},contentGroups:new Set(["descriptive"]),content:new Set(["a","altGlyph","animate","animateColor","set","tref","tspan"])},title:{attrsGroups:new Set(["core"]),attrs:new Set(["class","style"])},tref:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation","xlink"]),attrs:new Set(["class","externalResourcesRequired","href","style","xlink:href"]),contentGroups:new Set(["descriptive"]),content:new Set(["animate","animateColor","set"])},tspan:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation"]),attrs:new Set(["class","dx","dy","externalResourcesRequired","lengthAdjust","rotate","style","textLength","x","y"]),contentGroups:new Set(["descriptive"]),content:new Set(["a","altGlyph","animate","animateColor","set","tref","tspan"])},use:{attrsGroups:new Set(["conditionalProcessing","core","graphicalEvent","presentation","xlink"]),attrs:new Set(["class","externalResourcesRequired","height","href","style","transform","width","x","xlink:href","y"]),defaults:{x:"0",y:"0"},contentGroups:new Set(["animation","descriptive"])},view:{attrsGroups:new Set(["core"]),attrs:new Set(["externalResourcesRequired","preserveAspectRatio","viewBox","viewTarget","zoomAndPan"]),deprecated:{unsafe:new Set(["viewTarget","zoomAndPan"])},contentGroups:new Set(["descriptive"])},vkern:{attrsGroups:new Set(["core"]),attrs:new Set(["u1","g1","u2","g2","k"]),deprecated:{unsafe:new Set(["g1","g2","k","u1","u2"])}}},zc=new Set(["http://creativecommons.org/ns#","http://inkscape.sourceforge.net/DTD/sodipodi-0.dtd","http://krita.org/namespaces/svg/krita","http://ns.adobe.com/AdobeIllustrator/10.0/","http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/","http://ns.adobe.com/Extensibility/1.0/","http://ns.adobe.com/Flows/1.0/","http://ns.adobe.com/GenericCustomNamespace/1.0/","http://ns.adobe.com/Graphs/1.0/","http://ns.adobe.com/ImageReplacement/1.0/","http://ns.adobe.com/SaveForWeb/1.0/","http://ns.adobe.com/Variables/1.0/","http://ns.adobe.com/XPath/1.0/","http://purl.org/dc/elements/1.1/","http://schemas.microsoft.com/visio/2003/SVGExtensions/","http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd","http://taptrix.com/vectorillustrator/svg_extensions","http://www.bohemiancoding.com/sketch/ns","http://www.figma.com/figma/ns","http://www.inkscape.org/namespaces/inkscape","http://www.serif.com/","http://www.vector.evaxdesign.sk","http://www.w3.org/1999/02/22-rdf-syntax-ns#","https://boxy-svg.com"]),Xn=new Set(["clip-path","color-profile","fill","filter","marker-end","marker-mid","marker-start","mask","stroke","style"]),ea=new Set(["clip-rule","color-interpolation-filters","color-interpolation","color-profile","color-rendering","color","cursor","direction","dominant-baseline","fill-opacity","fill-rule","fill","font-family","font-size-adjust","font-size","font-stretch","font-style","font-variant","font-weight","font","glyph-orientation-horizontal","glyph-orientation-vertical","image-rendering","letter-spacing","marker-end","marker-mid","marker-start","marker","paint-order","pointer-events","shape-rendering","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","stroke","text-anchor","text-rendering","transform","visibility","word-spacing","writing-mode"]),Uo=new Set(["clip-path","display","filter","mask","opacity","text-decoration","transform","unicode-bidi"]),_c={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#0ff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000",blanchedalmond:"#ffebcd",blue:"#00f",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#0ff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#f0f",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#789",lightslategrey:"#789",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#0f0",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#f0f",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#639",red:"#f00",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#fff",whitesmoke:"#f5f5f5",yellow:"#ff0",yellowgreen:"#9acd32"},Uc={"#f0ffff":"azure","#f5f5dc":"beige","#ffe4c4":"bisque","#a52a2a":"brown","#ff7f50":"coral","#ffd700":"gold","#808080":"gray","#008000":"green","#4b0082":"indigo","#fffff0":"ivory","#f0e68c":"khaki","#faf0e6":"linen","#800000":"maroon","#000080":"navy","#808000":"olive","#ffa500":"orange","#da70d6":"orchid","#cd853f":"peru","#ffc0cb":"pink","#dda0dd":"plum","#800080":"purple","#f00":"red","#ff0000":"red","#fa8072":"salmon","#a0522d":"sienna","#c0c0c0":"silver","#fffafa":"snow","#d2b48c":"tan","#008080":"teal","#ff6347":"tomato","#ee82ee":"violet","#f5deb3":"wheat"},Ds=new Set(["color","fill","flood-color","lighting-color","stop-color","stroke"]),Vc={displayState:new Set(["fullscreen","modal","picture-in-picture"]),input:new Set(["autofill","blank","checked","default","disabled","enabled","in-range","indeterminate","invalid","optional","out-of-range","placeholder-shown","read-only","read-write","required","user-invalid","valid"]),linguistic:new Set(["dir","lang"]),location:new Set(["any-link","link","local-link","scope","target-within","target","visited"]),resourceState:new Set(["playing","paused"]),timeDimensional:new Set(["current","past","future"]),treeStructural:new Set(["empty","first-child","first-of-type","last-child","last-of-type","nth-child","nth-last-child","nth-last-of-type","nth-of-type","only-child","only-of-type","root"]),userAction:new Set(["active","focus-visible","focus-within","focus","hover"]),functional:new Set(["is","not","where","has"])},$h=/\burl\((["'])?#(.+?)\1\)/g,ew=/^#(.+?)$/,tw=/(\w+)\.[a-z]/i;function rw(e,t){let r="data:image/svg+xml";if(!t||t==="base64")return r+=";base64,",r+vp.from(e).toString("base64");if(t==="enc")return`${r},${encodeURIComponent(e)}`;if(t==="unenc")return`${r},${e}`;return e}function jr(e,t,r){let i="",n,s=0;for(let a=0;a<e.length;a++){let o=e[a];if(n=" ",a===0)n="";if(t.noSpaceAfterFlags&&(r==="A"||r==="a")){let c=a%7;if(c===4||c===5)n=""}let l=t.leadingZero?Qt(o):o.toString();if(t.negativeExtraSpace&&n!==""&&(o<0||l.charAt(0)==="."&&s%1!==0))n="";s=o,i+=n+l}return i}function Qt(e){if(e===0||e<=-1||e>=1)return e.toString();let t=e.toString();if(t.charCodeAt(0)===48&&t.charCodeAt(1)===46)return t.slice(1);if(t.charCodeAt(0)===45&&t.charCodeAt(1)===48&&t.charCodeAt(2)===46)return`-${t.slice(2)}`;return t}var iw=[...Oe.animationEvent??new Set,...Oe.documentEvent??new Set,...Oe.documentElementEvent??new Set,...Oe.globalEvent??new Set,...Oe.graphicalEvent??new Set];function ta(e){if(e.name==="script"&&e.children.length!==0)return!0;if(e.name==="a"){if(Object.entries(e.attributes).some(([t,r])=>(t==="href"||t.endsWith(":href"))&&r!=null&&r.trimStart().startsWith("javascript:")))return!0}return iw.some((t)=>e.attributes[t]!=null)}function ra(e){return new RegExp($h).test(e)}function nw(e){return/var\s*\(\s*--/.test(e)}function Vo(e,t){let r=[];if(Xn.has(e)){let i=t.matchAll($h);for(let n of i)r.push(n[2])}if(e==="href"||e.endsWith(":href")){let i=ew.exec(t);if(i!=null)r.push(i[1])}if(e==="begin"){let i=tw.exec(t);if(i!=null)r.push(i[1])}return r.map((i)=>decodeURI(i))}function Ot(e,t){let r=10**t;return Math.round(e*r)/r}var aw="cleanupIds",sw="removes unused IDs and minifies used",Ch=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"],Gc=Ch.length-1;function ow(e,t){for(let r of t)if(e.startsWith(r))return!0;return!1}function lw(e){if(e==null)return[0];e[e.length-1]+=1;for(let t=e.length-1;t>0;t--)if(e[t]>Gc){if(e[t]=0,e[t-1]!==void 0)e[t-1]++}if(e[0]>Gc)e[0]=0,e.unshift(0);return e}function cw(e){return e.map((t)=>Ch[t]).join("")}var uw=(e,t)=>{let{remove:r=!0,minify:i=!0,preserve:n=[],preservePrefixes:s=[],force:a=!1}=t||{},o=new Set(Array.isArray(n)?n:n?[n]:[]),l=Array.isArray(s)?s:s?[s]:[],c=new Map,u=new Map,f=!1;return{element:{enter:(h)=>{if(!a){if(h.name==="style"&&h.children.length!==0||ta(h)){f=!0;return}if(h.name==="svg"){let m=!0;for(let p of h.children)if(p.type!=="element"||p.name!=="defs"){m=!1;break}if(m)return Rt}}let d=h.attributes;for(let m in d){let p=d[m];if(m==="id"){let y=p;if(c.has(y))delete h.attributes.id;else c.set(y,h)}else{let y=Vo(m,p);for(let g of y){let w=u.get(g);if(w==null)w=[],u.set(g,w);w.push({element:h,name:m})}}}}},root:{exit:()=>{if(f)return;let h=(m)=>o.has(m)||ow(m,l),d=null;for(let[m,p]of u){let y=c.get(m);if(y!=null){if(i&&!h(m)){let g;do d=lw(d),g=cw(d);while(h(g)||u.has(g)&&c.get(g)==null);y.attributes.id=g;for(let{element:w,name:b}of p){let v=w.attributes[b];if(v.includes("#"))w.attributes[b]=v.replace(`#${encodeURI(m)}`,`#${g}`).replace(`#${m}`,`#${g}`);else w.attributes[b]=v.replace(`${m}.`,`${g}.`)}}c.delete(m)}}if(r){for(let[m,p]of c)if(!h(m))delete p.attributes.id}}}}},Ah={};D(Ah,{name:()=>fw,fn:()=>pw,description:()=>hw});var fw="cleanupListOfValues",hw="rounds list of values to the fixed precision",dw=/^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/,mw=/\s+,?\s*|,\s*/,Wc={cm:37.79527559055118,mm:3.7795275590551185,in:96,pt:1.3333333333333333,pc:16,px:1},pw=(e,t)=>{let{floatPrecision:r=3,leadingZero:i=!0,defaultPx:n=!0,convertToPx:s=!0}=t||{},a=(o)=>{let l=[];for(let c of o.split(mw)){let u=c.match(dw),f=c.match(/new/);if(u){let h=Number(Number(u[1]).toFixed(r)),d=u[2]||"";if(s&&d&&d in Wc){let p=Number((Wc[d]*Number(u[1])).toFixed(r));if(p.toString().length<u[0].length)h=p,d="px"}let m;if(i)m=Qt(h);else m=h.toString();if(n&&d==="px")d="";l.push(m+d)}else if(f)l.push("new");else if(c)l.push(c)}return l.join(" ")};return{element:{enter:(o)=>{if(o.attributes.points!=null)o.attributes.points=a(o.attributes.points);if(o.attributes["enable-background"]!=null)o.attributes["enable-background"]=a(o.attributes["enable-background"]);if(o.attributes.viewBox!=null)o.attributes.viewBox=a(o.attributes.viewBox);if(o.attributes["stroke-dasharray"]!=null)o.attributes["stroke-dasharray"]=a(o.attributes["stroke-dasharray"]);if(o.attributes.dx!=null)o.attributes.dx=a(o.attributes.dx);if(o.attributes.dy!=null)o.attributes.dy=a(o.attributes.dy);if(o.attributes.x!=null)o.attributes.x=a(o.attributes.x);if(o.attributes.y!=null)o.attributes.y=a(o.attributes.y)}}}},Go={};D(Go,{name:()=>gw,fn:()=>bw,description:()=>yw});var gw="cleanupNumericValues",yw='rounds numeric values to the fixed precision, removes default "px" units',ww=/^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/,qc={cm:37.79527559055118,mm:3.7795275590551185,in:96,pt:1.3333333333333333,pc:16,px:1},bw=(e,t)=>{let{floatPrecision:r=3,leadingZero:i=!0,defaultPx:n=!0,convertToPx:s=!0}=t||{};return{element:{enter:(a)=>{if(a.attributes.viewBox!=null){let l=a.attributes.viewBox.trim().split(/(?:\s,?|,)\s*/g);a.attributes.viewBox=l.map((c)=>{let u=Number(c);return Number.isNaN(u)?c:Number(u.toFixed(r))}).join(" ")}let o=a.attributes;for(let l in o){if(l==="version")continue;let c=o[l],u=ww.exec(c);if(u){let f=Number(Number(u[1]).toFixed(r)),h=u[2]||"";if(s&&h!==""&&h in qc){let m=Number((qc[h]*Number(u[1])).toFixed(r));if(m.toString().length<u[0].length)f=m,h="px"}let d;if(i)d=Qt(f);else d=f.toString();if(n&&h==="px")h="";a.attributes[l]=d+h}}}}}},Wo={};D(Wo,{name:()=>Nw,fn:()=>Fw,description:()=>Pw});function vw(e){let t=new Map;for(let r of e.children)t.set(r,e),wt(r,{element:{enter:(i,n)=>{t.set(i,n)}}},e);return t}function ia(e){return e.type==="element"}function Dt(e){return e.children??[]}function qo(e){return e.type==="element"||e.type==="root"}function Ls(e,t){return t.some((r)=>{if(ia(r))return e(r)||Ls(e,Dt(r));if(qo(r))return Ls(e,Dt(r));return!1})}function Sw(e,t){return e.attributes[t]}function xw(e){return e.name}function $w(e){let t=Dt(e);if(t[0]&&(t[0].type==="text"||t[0].type==="cdata"))return t[0].value;return""}function Cw(e,t){return e.attributes[t]!==void 0}function js(e,t){let r=[];for(let i of t)if(ia(i)){if(e(i))r.push(i);r.push(...js(e,Dt(i)))}else if(qo(i))r.push(...js(e,Dt(i)));return r}function Bs(e,t){for(let r of t)if(ia(r)){if(e(r))return r;let i=Bs(e,Dt(r));if(i)return i}else if(qo(r)){let i=Bs(e,Dt(r));if(i)return i}return null}function Aw(e,t){let r=(i)=>{if(!t)t=vw(e);return t.get(i)??null};return{isTag:ia,existsOne:Ls,getAttributeValue:Sw,getChildren:Dt,getName:xw,getParent:r,getSiblings:(i)=>{let n=r(i);return n?Dt(n):[]},getText:$w,hasAttrib:Cw,removeSubsets:(i)=>{let n=i.length;while(--n>-1){let s=i[n],a=s;i[n]=null;let o=!0;while(a){if(i.includes(a)){o=!1,i.splice(n,1);break}a=r(a)}if(o)i[n]=s}return i},findAll:js,findOne:Bs}}function Ko(e,t){return{xmlMode:!0,adapter:Aw(e,t)}}function ui(e,t,r){return Hf(t,e,Ko(e,r))}function Eh(e,t,r){return Jf(t,e,Ko(e,r))}function Ew(e,t,r){return Zf(e,t,Ko(e,r))}function V(e,t){t.children=t.children.filter((r)=>r!==e)}var{syntax:kw}=oi,Di=G.walk.skip;function Kc(e,t){let r=[];e.block.children.forEach((n)=>{if(n.type==="Declaration")r.push({name:n.property,value:G.generate(n.value),important:n.important===!0})});let i=[];return G.walk(e.prelude,(n)=>{if(n.type==="Selector"){let s=G.clone(n),a=!1;G.walk(s,(o,l,c)=>{if(o.type==="PseudoClassSelector"){if(a=!0,c&&l)c.remove(l)}}),i.push({specificity:kw.specificity(n),dynamic:a||t,selector:G.generate(s),declarations:r})}}),i}function Mw(e,t){let r=[],i=G.parse(e,{parseValue:!1,parseAtrulePrelude:!1});return G.walk(i,(n)=>{if(n.type==="Rule")return r.push(...Kc(n,t||!1)),Di;if(n.type==="Atrule"){if(["keyframes","-webkit-keyframes","-o-keyframes","-moz-keyframes"].includes(n.name))return Di;return G.walk(n,(s)=>{if(s.type==="Rule")return r.push(...Kc(s,t||!0)),Di}),Di}}),r}function Tw(e){let t=[],r=G.parse(e,{context:"declarationList",parseValue:!1});return G.walk(r,(i)=>{if(i.type==="Declaration")t.push({name:i.property,value:G.generate(i.value),important:i.important===!0})}),t}function Yc(e,t,r){let i={},n=new Map,s=t.attributes,a=Oe.presentation;for(let l in s)if(a.has(l))i[l]={type:"static",inherited:!1,value:s[l]},n.set(l,!1);for(let{selector:l,declarations:c,dynamic:u}of e.rules)if(Ew(t,l,r))for(let{name:f,value:h,important:d}of c){let m=i[f];if(m&&m.type==="dynamic")continue;if(u){i[f]={type:"dynamic",inherited:!1};continue}if(m==null||d===!0||n.get(f)===!1)i[f]={type:"static",inherited:!1,value:h},n.set(f,d)}let o=t.attributes.style==null?[]:Tw(t.attributes.style);for(let{name:l,value:c,important:u}of o){let f=i[l];if(f&&f.type==="dynamic")continue;if(f==null||u===!0||n.get(l)===!1)i[l]={type:"static",inherited:!1,value:c},n.set(l,u)}return i}function kh(e,t){for(let r=0;r<4;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return 0}function ht(e){let t=[],r=new Map;return wt(e,{element:{enter:(i,n)=>{if(r.set(i,n),i.name!=="style")return;if(i.attributes.type==null||i.attributes.type===""||i.attributes.type==="text/css"){let s=i.attributes.media!=null&&i.attributes.media!=="all";for(let a of i.children)if(a.type==="text"||a.type==="cdata")t.push(...Mw(a.value,s))}}}}),t.sort((i,n)=>kh(i.specificity,n.specificity)),{rules:t,parents:r}}function ft(e,t){let{parents:r}=e,i=Yc(e,t,r),n=r.get(t);while(n!=null&&n.type!=="root"){let s=Yc(e,n,r);for(let a in s)if(i[a]==null&&ea.has(a)&&!Uo.has(a))i[a]={...s[a],inherited:!0};n=r.get(n)}return i}function nn(e,t,r=null,i=!1){let n=typeof e==="string"?ti.parse(e,{xmlMode:!0}):ti.parse(G.generate(e.data),{xmlMode:!0});for(let s of n)if(s.some((a,o)=>{if(i){if(o===s.length-1)return!1;if(!ti.isTraversal(s[o+1]))return!1}if(a.type!=="attribute"||a.name!==t)return!1;return r==null?!0:a.value===r}))return!0;return!1}var Nw="collapseGroups",Pw="collapses useless groups";function Mh(e,t){if(e.type==="element"){if(Kt.animation.has(e.name)&&e.attributes.attributeName===t)return!0;for(let r of e.children)if(Mh(r,t))return!0}return!1}var Fw=(e)=>{let t=ht(e);return{element:{exit:(r,i)=>{if(i.type==="root"||i.name==="switch")return;if(r.name!=="g"||r.children.length===0)return;if(Object.keys(r.attributes).length!==0&&r.children.length===1){let n=r.children[0],s=!!(r.attributes.filter||ft(t,r).filter);if(n.type==="element"&&n.attributes.id==null&&!s&&(r.attributes.class==null||n.attributes.class==null)&&(r.attributes["clip-path"]==null&&r.attributes.mask==null||n.name==="g"&&r.attributes.transform==null&&n.attributes.transform==null)){let a={...n.attributes};for(let[o,l]of Object.entries(r.attributes)){if(Mh(n,o))return;if(a[o]==null)a[o]=l;else if(o==="transform")a[o]=`${l} ${a[o]}`;else if(a[o]==="inherit")a[o]=l;else if(!ea.has(o)&&a[o]!==l)return}r.attributes={},n.attributes=a}}if(Object.keys(r.attributes).length===0){for(let s of r.children)if(s.type==="element"&&Kt.animation.has(s.name))return;let n=i.children.indexOf(r);i.children.splice(n,1,...r.children)}}}}},Yo={};D(Yo,{name:()=>Ow,fn:()=>Bw,description:()=>Rw});var Ow="convertColors",Rw="converts colors: rgb() to #rrggbb and #rrggbb to #rgb",Ba="([+-]?(?:\\d*\\.\\d+|\\d+\\.?)%?)",Hc="(?:\\s*,\\s*|\\s+)",Dw=new RegExp(`^rgb\\(\\s*${Ba}${Hc}${Ba}${Hc}${Ba}\\s*\\)$`),Lw=/^#(([a-f0-9])\2){3}$/i;function jw([e,t,r]){return`#${((256+e<<8|t)<<8|r).toString(16).slice(1).toUpperCase()}`}var Bw=(e,t)=>{let{currentColor:r=!1,names2hex:i=!0,rgb2hex:n=!0,convertCase:s="lower",shorthex:a=!0,shortname:o=!0}=t||{},l=0;return{element:{enter:(c)=>{if(c.name==="mask")l++;let u=c.attributes;for(let f in u)if(Ds.has(f)){let h=u[f];if(r&&l===0){let d;if(typeof r==="string")d=h===r;else if(r instanceof RegExp)d=r.exec(h)!=null;else d=h!=="none";if(d)h="currentColor"}if(i){let d=h.toLowerCase();if(_c[d]!=null)h=_c[d]}if(n){let d=h.match(Dw);if(d!=null){let m=d.slice(1,4).map((p)=>{let y;if(p.includes("%"))y=Math.round(Number.parseFloat(p)*2.55);else y=Number(p);return Math.max(0,Math.min(y,255))});h=jw(m)}}if(s&&!ra(h)&&!nw(h)&&h!=="currentColor"){if(s==="lower")h=h.toLowerCase();else if(s==="upper")h=h.toUpperCase()}if(a){let d=Lw.exec(h);if(d!=null)h=`#${d[0][1]}${d[0][3]}${d[0][5]}`}if(o){let d=h.toLowerCase();if(Uc[d]!=null)h=Uc[d]}c.attributes[f]=h}},exit:(c)=>{if(c.name==="mask")l--}}}},Ho={};D(Ho,{name:()=>Iw,fn:()=>_w,description:()=>zw});var Iw="convertEllipseToCircle",zw="converts non-eccentric <ellipse>s to <circle>s",_w=()=>({element:{enter:(e)=>{if(e.name==="ellipse"){let t=e.attributes.rx||"0",r=e.attributes.ry||"0";if(t===r||t==="auto"||r==="auto"){e.name="circle";let i=t==="auto"?r:t;delete e.attributes.rx,delete e.attributes.ry,e.attributes.r=i}}}}}),Th={};D(Th,{name:()=>Uw,fn:()=>Gw,description:()=>Vw});var Uw="convertOneStopGradients",Vw="converts one-stop (single color) gradients to a plain color",Gw=(e)=>{let t=ht(e),r=new Set,i=new Map,n=new Map,s=0;return{element:{enter:(a,o)=>{if(a.attributes["xlink:href"]!=null)s++;if(a.name==="defs"){i.set(a,o);return}if(a.name!=="linearGradient"&&a.name!=="radialGradient")return;let l=a.children.filter((w)=>w.type==="element"&&w.name==="stop"),c=a.attributes["xlink:href"]||a.attributes.href,u=l.length===0&&c!=null&&c.startsWith("#")?Eh(e,c):a;if(u==null||u.type!=="element"){n.set(a,o);return}let f=u.children.filter((w)=>w.type==="element"&&w.name==="stop");if(f.length!==1||f[0].type!=="element")return;if(o.type==="element"&&o.name==="defs")r.add(o);n.set(a,o);let h,d=ft(t,f[0])["stop-color"];if(d!=null&&d.type==="static")h=d.value;let m=`url(#${a.attributes.id})`,p=[...Ds].map((w)=>`[${w}="${m}"]`).join(","),y=ui(e,p);for(let w of y){if(w.type!=="element")continue;for(let b of Ds){if(w.attributes[b]!==m)continue;if(h!=null)w.attributes[b]=h;else delete w.attributes[b]}}let g=ui(e,`[style*="${m}"]`);for(let w of g){if(w.type!=="element")continue;w.attributes.style=w.attributes.style.replace(m,h||zo.presentation["stop-color"])}},exit:(a)=>{if(a.name==="svg"){for(let[o,l]of n.entries()){if(o.attributes["xlink:href"]!=null)s--;V(o,l)}if(s===0)delete a.attributes["xmlns:xlink"];for(let[o,l]of i.entries())if(r.has(o)&&o.children.length===0)V(o,l)}}}}},Jo={};D(Jo,{name:()=>s1,fn:()=>l1,description:()=>o1});var Nh={M:2,m:2,Z:0,z:0,L:2,l:2,H:1,h:1,V:1,v:1,C:6,c:6,S:4,s:4,Q:4,q:4,T:2,t:2,A:7,a:7};function Ww(e){return e in Nh}function qw(e){return e===" "||e==="\t"||e==="\r"||e===`
64
+ `}function Jc(e,t){let r=e.length,i=t;if(i<r){let o=e.charCodeAt(i);if(o===43||o===45)i++}let n=!1,s=!1;while(i<r){let o=e.charCodeAt(i);if(o>=48&&o<=57)n=!0,i++;else if(o===46&&!s)s=!0,i++;else break}if(n&&i<r){let o=e.charCodeAt(i);if(o===101||o===69){let l=i;if(i++,i<r){let u=e.charCodeAt(i);if(u===43||u===45)i++}let c=!1;while(i<r){let u=e.charCodeAt(i);if(u>=48&&u<=57)c=!0,i++;else break}if(!c)i=l}}if(!n)return[t,null];let a=Number.parseFloat(e.slice(t,i));if(Number.isNaN(a))return[t,null];return[i-1,a]}function Zo(e){let t=[],r=null,i=[],n=0,s=!1,a=!1;for(let o=0;o<e.length;o++){let l=e.charAt(o);if(qw(l))continue;if(s&&l===","){if(a)break;a=!0;continue}if(Ww(l)){if(a)return t;if(r==null){if(l!=="M"&&l!=="m")return t}else if(i.length!==0)return t;if(r=l,i=[],n=Nh[r],s=!1,n===0)t.push({command:r,args:i});continue}if(r==null)return t;let c=o,u=null;if(r==="A"||r==="a"){let f=i.length;if(f===0||f===1||f===2||f===5||f===6)[c,u]=Jc(e,o);if(f===3||f===4){if(l==="0")u=0;if(l==="1")u=1}}else[c,u]=Jc(e,o);if(u==null)return t;if(i.push(u),s=!0,a=!1,o=c,i.length===n){if(r==="A"||r==="a")i[0]=Math.abs(i[0]),i[1]=Math.abs(i[1]);if(t.push({command:r,args:i}),r==="M")r="L";if(r==="m")r="l";i=[]}}return t}function Li(e,t,r,i){let n=!!i&&(e==="A"||e==="a"),s="",a,o=t.length;for(let l=0;l<o;l++){let c=t[l];if(r!=null)c=Ot(c,r);let u=Qt(c);if(n){let f=l%7;if(f===4||f===5){s+=u,a=c;continue}}if(l===0||c<0)s+=u;else if(a!==void 0&&!Number.isInteger(a)){let f=u.charCodeAt(0);if(f<48||f>57)s+=u;else s+=` ${u}`}else s+=` ${u}`;a=c}return s}function Mr({pathData:e,precision:t,disableSpaceAfterFlags:r}){if(e.length===1){let{command:s,args:a}=e[0];return s+Li(s,a,t,r)}let i="",n={...e[0]};if(e[1].command==="L")n.command="M";else if(e[1].command==="l")n.command="m";for(let s=1;s<e.length;s++){let{command:a,args:o}=e[s];if(n.command===a&&n.command!=="M"&&n.command!=="m"||n.command==="M"&&a==="L"||n.command==="m"&&a==="l"){if(n.args=[...n.args,...o],s===e.length-1)i+=n.command+Li(n.command,n.args,t,r)}else if(i+=n.command+Li(n.command,n.args,t,r),s===e.length-1)i+=a+Li(a,o,t,r);else n={command:a,args:o}}return i}var pt=[0,0];function Mn(e){let t=e.pathJS;if(t)return t;let r=[],i=Zo(e.attributes.d??"");for(let{command:n,args:s}of i)r.push({command:n,args:s});if(r.length&&r[0].command==="m")r[0].command="M";return e.pathJS=r,r}function Zc(e){let t=[],r=[0,0],i=[0,0];for(let n of e){let s=n.command,a=n.args.slice();if(s==="m")a[0]+=i[0],a[1]+=i[1],s="M";if(s==="M")i[0]=a[0],i[1]=a[1],r[0]=i[0],r[1]=i[1];if(s==="h")a[0]+=i[0],s="H";if(s==="H")i[0]=a[0];if(s==="v")a[0]+=i[1],s="V";if(s==="V")i[1]=a[0];if(s==="l")a[0]+=i[0],a[1]+=i[1],s="L";if(s==="L")i[0]=a[0],i[1]=a[1];if(s==="c")a[0]+=i[0],a[1]+=i[1],a[2]+=i[0],a[3]+=i[1],a[4]+=i[0],a[5]+=i[1],s="C";if(s==="C")i[0]=a[4],i[1]=a[5];if(s==="s")a[0]+=i[0],a[1]+=i[1],a[2]+=i[0],a[3]+=i[1],s="S";if(s==="S")i[0]=a[2],i[1]=a[3];if(s==="q")a[0]+=i[0],a[1]+=i[1],a[2]+=i[0],a[3]+=i[1],s="Q";if(s==="Q")i[0]=a[2],i[1]=a[3];if(s==="t")a[0]+=i[0],a[1]+=i[1],s="T";if(s==="T")i[0]=a[0],i[1]=a[1];if(s==="a")a[5]+=i[0],a[6]+=i[1],s="A";if(s==="A")i[0]=a[5],i[1]=a[6];if(s==="z"||s==="Z")i[0]=r[0],i[1]=r[1],s="z",a=[];t.push({command:s,args:a})}return t}function Ph(e,t,r){e.pathJS=t;let i=[];for(let n of t){if(i.length!==0&&(n.command==="M"||n.command==="m")){let s=i[i.length-1];if(s.command==="M"||s.command==="m")i.pop()}i.push({command:n.command,args:n.args})}e.attributes.d=Mr({pathData:i,precision:r.floatPrecision,disableSpaceAfterFlags:r.noSpaceAfterFlags})}function gr(e,t){return e[0]=t[t.length-2],e[1]=t[t.length-1],e}function Fh(e,t){let r=Qc(Zc(e)),i=Qc(Zc(t));if(r.maxX<=i.minX||i.maxX<=r.minX||r.maxY<=i.minY||i.maxY<=r.minY||r.list.every((l)=>i.list.every((c)=>l.list[l.maxX][0]<=c.list[c.minX][0]||c.list[c.maxX][0]<=l.list[l.minX][0]||l.list[l.maxY][1]<=c.list[c.minY][1]||c.list[c.maxY][1]<=l.list[l.minY][1])))return!1;let n=r.list.map(Xc),s=i.list.map(Xc);return n.some((l)=>{if(l.list.length<3)return!1;return s.some((c)=>{if(c.list.length<3)return!1;let u=[a(l,c,[1,0])],f=Br(u[0]),h=1e4;while(!0){if(h--===0)return console.error("Error: infinite loop while processing mergePaths plugin."),!0;if(u.push(a(l,c,f)),zt(f,u[u.length-1])<=0)return!1;if(Kw(u,f))return!0}})});function a(l,c,u){return an(o(l,u),o(c,Br(u)))}function o(l,c){let u=c[1]>=0?c[0]<0?l.maxY:l.maxX:c[0]<0?l.minX:l.minY,f=-1/0,h;while((h=zt(l.list[u],c))>f)f=h,u=++u%l.list.length;return l.list[(u||l.list.length)-1]}}function Kw(e,t){if(e.length===2){let r=e[1],i=e[0],n=Br(e[1]),s=an(i,r);if(zt(n,s)>0)gr(t,Ia(s,r));else gr(t,n),e.shift()}else{let r=e[2],i=e[1],n=e[0],s=an(i,r),a=an(n,r),o=Br(r),l=Ia(s,a),c=Ia(a,s);if(zt(l,o)>0)if(zt(s,o)>0)gr(t,l),e.shift();else gr(t,o),e.splice(0,2);else if(zt(c,o)>0)if(zt(a,o)>0)gr(t,c),e.splice(1,1);else gr(t,o),e.splice(0,2);else return!0}return!1}function Br(e){return[-e[0],-e[1]]}function an(e,t){return[e[0]-t[0],e[1]-t[1]]}function zt(e,t){return e[0]*t[0]+e[1]*t[1]}function Ia(e,t){let r=[-e[1],e[0]];return zt(r,Br(t))<0?Br(r):r}function Qc(e){let t={list:[],minX:0,minY:0,maxX:0,maxY:0},r=(i,n)=>{if(!i.list.length||n[1]>i.list[i.maxY][1])i.maxY=i.list.length,t.maxY=t.list.length?Math.max(n[1],t.maxY):n[1];if(!i.list.length||n[0]>i.list[i.maxX][0])i.maxX=i.list.length,t.maxX=t.list.length?Math.max(n[0],t.maxX):n[0];if(!i.list.length||n[1]<i.list[i.minY][1])i.minY=i.list.length,t.minY=t.list.length?Math.min(n[1],t.minY):n[1];if(!i.list.length||n[0]<i.list[i.minX][0])i.minX=i.list.length,t.minX=t.list.length?Math.min(n[0],t.minX):n[0];i.list.push(n)};for(let i=0;i<e.length;i++){let n=e[i],s=t.list.length===0?{list:[],minX:0,minY:0,maxX:0,maxY:0}:t.list[t.list.length-1],a=i===0?null:e[i-1],o=s.list.length===0?null:s.list[s.list.length-1],l=n.args,c=o,u=(f,h)=>f+(o==null?0:o[h%2]);switch(n.command){case"M":s={list:[],minX:0,minY:0,maxX:0,maxY:0},t.list.push(s);break;case"H":if(o!=null)r(s,[l[0],o[1]]);break;case"V":if(o!=null)r(s,[o[0],l[0]]);break;case"Q":r(s,l.slice(0,2)),pt=[l[2]-l[0],l[3]-l[1]];break;case"T":if(o!=null&&a!=null&&(a.command==="Q"||a.command==="T"))c=[o[0]+pt[0],o[1]+pt[1]],r(s,c),pt=[l[0]-c[0],l[1]-c[1]];break;case"C":if(o!=null)r(s,[0.5*(o[0]+l[0]),0.5*(o[1]+l[1])]);r(s,[0.5*(l[0]+l[2]),0.5*(l[1]+l[3])]),r(s,[0.5*(l[2]+l[4]),0.5*(l[3]+l[5])]),pt=[l[4]-l[2],l[5]-l[3]];break;case"S":if(o!=null&&a!=null&&(a.command==="C"||a.command==="S"))r(s,[o[0]+0.5*pt[0],o[1]+0.5*pt[1]]),c=[o[0]+pt[0],o[1]+pt[1]];if(c!=null)r(s,[0.5*(c[0]+l[0]),0.5*(c[1]+l[1])]);r(s,[0.5*(l[0]+l[2]),0.5*(l[1]+l[3])]),pt=[l[2]-l[0],l[3]-l[1]];break;case"A":if(o!=null){let f=Oh(o[0],o[1],l[0],l[1],l[2],l[3],l[4],l[5],l[6]),h;while((h=f.splice(0,6).map(u)).length){if(o!=null)r(s,[0.5*(o[0]+h[0]),0.5*(o[1]+h[1])]);if(r(s,[0.5*(h[0]+h[2]),0.5*(h[1]+h[3])]),r(s,[0.5*(h[2]+h[4]),0.5*(h[3]+h[5])]),f.length)r(s,o=h.slice(-2))}}break}if(l.length>=2)r(s,l.slice(-2))}return t}function Xc(e){e.list.sort((l,c)=>l[0]===c[0]?l[1]-c[1]:l[0]-c[0]);let t=[],r=0,i=0;for(let l=0;l<e.list.length;l++){while(t.length>=2&&eu(t[t.length-2],t[t.length-1],e.list[l])<=0)t.pop();if(e.list[l][1]<e.list[r][1])r=l,i=t.length;t.push(e.list[l])}let n=[],s=e.list.length-1,a=0;for(let l=e.list.length;l--;){while(n.length>=2&&eu(n[n.length-2],n[n.length-1],e.list[l])<=0)n.pop();if(e.list[l][1]>e.list[s][1])s=l,a=n.length;n.push(e.list[l])}n.pop(),t.pop();let o=t.concat(n);return{list:o,minX:0,maxX:t.length,minY:i,maxY:(t.length+a)%o.length}}function eu(e,t,r){return(t[0]-e[0])*(r[1]-e[1])-(t[1]-e[1])*(r[0]-e[0])}function Oh(e,t,r,i,n,s,a,o,l,c){let u=Math.PI*120/180,f=Math.PI/180*(+n||0),h=[],d=(k,P,T)=>k*Math.cos(T)-P*Math.sin(T),m=(k,P,T)=>k*Math.sin(T)+P*Math.cos(T),p,y,g,w;if(!c){e=d(e,t,-f),t=m(e,t,-f),o=d(o,l,-f),l=m(o,l,-f);let k=(e-o)/2,P=(t-l)/2,T=k*k/(r*r)+P*P/(i*i);if(T>1)T=Math.sqrt(T),r=T*r,i=T*i;let O=r*r,W=i*i,X=(s===a?-1:1)*Math.sqrt(Math.abs((O*W-O*P*P-W*k*k)/(O*P*P+W*k*k)));if(p=X*r*P/i+(e+o)/2,y=X*-i*k/r+(t+l)/2,g=Math.asin(Number(((t-y)/i).toFixed(9))),w=Math.asin(Number(((l-y)/i).toFixed(9))),g=e<p?Math.PI-g:g,w=o<p?Math.PI-w:w,g<0)g=Math.PI*2+g;if(w<0)w=Math.PI*2+w;if(a&&g>w)g=g-Math.PI*2;if(!a&&w>g)w=w-Math.PI*2}else g=c[0],w=c[1],p=c[2],y=c[3];let b=w-g;if(Math.abs(b)>u){let k=w,P=o,T=l;w=g+u*(a&&w>g?1:-1),o=p+r*Math.cos(w),l=y+i*Math.sin(w),h=Oh(o,l,r,i,n,0,a,P,T,[w,k,p,y])}b=w-g;let v=Math.cos(g),S=Math.sin(g),E=Math.cos(w),C=Math.sin(w),F=Math.tan(b/4),R=1.3333333333333333*r*F,x=1.3333333333333333*i*F,A=[-R*S,x*v,o+R*C-e,l-x*E-t,o-e,l-t];if(c)return A.concat(h);h=A.concat(h);let M=[];for(let k=0;k<h.length;k++)M[k]=k%2?m(h[k-1],h[k],f):d(h[k],h[k+1],f);return M}var Yw=new Set(["matrix","rotate","scale","skewX","skewY","translate"]),Hw=/\s*(matrix|translate|scale|rotate|skewX|skewY)\s*\(\s*(.+?)\s*\)[\s,]*/,tu=/[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;function Rh(e){let t=[],r=null;for(let i of e.split(Hw)){if(!i)continue;if(Yw.has(i))r={name:i,data:[]},t.push(r);else{let n;tu.lastIndex=0;while((n=tu.exec(i))!=null){let s=Number(n[0]);if(r!=null)r.data.push(s)}}}return r==null||r.data.length===0?[]:t}function Dh(e){let t=e.map((r)=>r.name==="matrix"?r.data:i1(r));return{name:"matrix",data:t.length>0?t.reduce(Lh):[]}}var ze={rad:(e)=>e*Math.PI/180,deg:(e)=>e*180/Math.PI,cos:(e)=>Math.cos(ze.rad(e)),acos:(e,t)=>Ot(ze.deg(Math.acos(e)),t),sin:(e)=>Math.sin(ze.rad(e)),asin:(e,t)=>Ot(ze.deg(Math.asin(e)),t),tan:(e)=>Math.tan(ze.rad(e)),atan:(e,t)=>Ot(ze.deg(Math.atan(e)),t)};function Jw(e){let t=[],r=Zw(e),i=Qw(e);if(r)t.push(r);if(i)t.push(i);return t}function Zw(e){let t=e.data,r=t[0],i=t[1],n=t[2],s=t[3],a=t[4],o=t[5],l=r*s-i*n;if(l===0)return;let c=Math.hypot(r,i);if(c===0)return;let u=[],f=r/c;if(a||o)u.push({name:"translate",data:[a,o]});if(f!==1){let p=Math.acos(f);u.push({name:"rotate",data:[ze.deg(i<0?-p:p),0,0]})}let h=c,d=l/h;if(h!==1||d!==1)u.push({name:"scale",data:[h,d]});let m=r*n+i*s;if(m)u.push({name:"skewX",data:[ze.deg(Math.atan(m/(r*r+i*i)))]});return u}function Qw(e){let t=e.data,r=t[0],i=t[1],n=t[2],s=t[3],a=t[4],o=t[5],l=r*s-i*n;if(l===0)return;let c=Math.hypot(n,s);if(c===0)return;let u=[];if(a||o)u.push({name:"translate",data:[a,o]});let f=Math.PI/2-(s<0?-1:1)*Math.acos(-n/c);u.push({name:"rotate",data:[ze.deg(f),0,0]});let h=l/c,d=c;if(h!==1||d!==1)u.push({name:"scale",data:[h,d]});let m=r*n+i*s;if(m)u.push({name:"skewY",data:[ze.deg(Math.atan(m/(n*n+s*s)))]});return u}function Xw(e,t,r){let i=ze.rad(r),n=1-Math.cos(i),s=Math.sin(i),a=(n*t+s*e)/(n*n+s*s),o=(e-s*a)/n;return{name:"rotate",data:[r,o,a]}}function e1(e){switch(e.name){case"rotate":case"skewX":case"skewY":return e.data[0]===0;case"scale":return e.data[0]===1&&e.data[1]===1;case"translate":return e.data[0]===0&&e.data[1]===0}return!1}function t1(e,t){let r=[];for(let i=0;i<e.length;i++){let n=e[i];if(e1(n))continue;let s=n.data;switch(n.name){case"rotate":switch(s[0]){case 180:case-180:{let a=e[i+1];if(a&&a.name==="scale")r.push(ru(a.data.map((o)=>-o))),i++;else r.push({name:"scale",data:[-1]});continue}}r.push({name:"rotate",data:s.slice(0,s[1]||s[2]?3:1)});break;case"scale":r.push(ru(s));break;case"skewX":case"skewY":r.push({name:n.name,data:[s[0]]});break;case"translate":{let a=e[i+1];if(a&&a.name==="rotate"&&a.data[0]!==180&&a.data[0]!==-180&&a.data[0]!==0&&a.data[1]===0&&a.data[2]===0){let o=t[i].data;r.push(Xw(o[0],o[1],t[i+1].data[0])),i++;continue}r.push({name:"translate",data:s.slice(0,s[1]?2:1)});break}}}return r.length?r:[{name:"scale",data:[1]}]}function ru(e){return{name:"scale",data:e.slice(0,e[0]===e[1]?1:2)}}function r1(e,t){let r=Jw(e),i,n=Number.MAX_VALUE;for(let s of r){let a=s.map((c)=>{let u={name:c.name,data:[...c.data]};return na(u,t)}),o=t1(a,s),l=Tn(o,t).length;if(l<n)i=o,n=l}return i??[e]}function i1(e){if(e.name==="matrix")return e.data;switch(e.name){case"translate":return[1,0,0,1,e.data[0],e.data[1]||0];case"scale":return[e.data[0],0,0,e.data[1]??e.data[0],0,0];case"rotate":{let t=ze.cos(e.data[0]),r=ze.sin(e.data[0]),i=e.data[1]||0,n=e.data[2]||0;return[t,r,-r,t,(1-t)*i+r*n,(1-t)*n-r*i]}case"skewX":return[1,0,ze.tan(e.data[0]),1,0,0];case"skewY":return[1,ze.tan(e.data[0]),0,1,0,0];default:throw Error(`Unknown transform ${e.name}`)}}function iu(e,t,r){let i=t[5]-e[0],n=t[6]-e[1],s=t[0],a=t[1],o=t[2]*Math.PI/180,l=Math.cos(o),c=Math.sin(o);if(s>0&&a>0){let p=(i*l+n*c)**2/(4*s*s)+(n*l-i*c)**2/(4*a*a);if(p>1)p=Math.sqrt(p),s*=p,a*=p}let u=[s*l,s*c,-a*c,a*l,0,0],f=Lh(r,u),h=f[2]*f[2]+f[3]*f[3],d=f[0]*f[0]+f[1]*f[1]+h,m=Math.hypot(f[0]-f[3],f[1]+f[2])*Math.hypot(f[0]+f[3],f[1]-f[2]);if(!m)t[0]=t[1]=Math.sqrt(d/2),t[2]=0;else{let p=(d+m)/2,y=(d-m)/2,g=Math.abs(p-h)>0.000001,w=(g?p:y)-h,b=f[0]*f[2]+f[1]*f[3],v=f[0]*w+f[2]*b,S=f[1]*w+f[3]*b;t[0]=Math.sqrt(p),t[1]=Math.sqrt(y),t[2]=((g?S<0:v>0)?-1:1)*Math.acos((g?v:S)/Math.hypot(v,S))*180/Math.PI}if(r[0]<0!==r[3]<0)t[4]=1-t[4];return t}function Lh(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}function na(e,t){switch(e.name){case"translate":e.data=za(e.data,t);break;case"rotate":e.data=[...nu(e.data.slice(0,1),t),...za(e.data.slice(1),t)];break;case"skewX":case"skewY":e.data=nu(e.data,t);break;case"scale":e.data=au(e.data,t);break;case"matrix":e.data=[...au(e.data.slice(0,4),t),...za(e.data.slice(4),t)];break}return e}function nu(e,t){if(t.degPrecision!=null&&t.degPrecision>=1&&t.floatPrecision<20)return Xo(t.degPrecision,e);return Qo(e)}function za(e,t){if(t.floatPrecision>=1&&t.floatPrecision<20)return Xo(t.floatPrecision,e);return Qo(e)}function au(e,t){if(t.transformPrecision>=1&&t.floatPrecision<20)return Xo(t.transformPrecision,e);return Qo(e)}function Qo(e){return e.map(Math.round)}function Xo(e,t){let r=+(0.1**e).toFixed(e);for(let i=t.length;i--;)if(Ot(t[i],e)!==t[i]){let n=+t[i].toFixed(e-1);t[i]=+Math.abs(n-t[i]).toFixed(e+1)>=r?+t[i].toFixed(e):n}return t}function Tn(e,t){return e.map((r)=>(na(r,t),`${r.name}(${jr(r.data,t)})`)).join("")}var _a=/[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;function rt(e,t,r){return[e[0]*t+e[2]*r+e[4],e[1]*t+e[3]*r+e[5]]}function it(e,t,r){return[e[0]*t+e[2]*r,e[1]*t+e[3]*r]}function n1(e,t){let r=[0,0],i=[0,0];for(let n of e){let{command:s,args:a}=n;if(s==="M"){i[0]=a[0],i[1]=a[1],r[0]=i[0],r[1]=i[1];let[o,l]=rt(t,a[0],a[1]);a[0]=o,a[1]=l}if(s==="m"){i[0]+=a[0],i[1]+=a[1],r[0]=i[0],r[1]=i[1];let[o,l]=it(t,a[0],a[1]);a[0]=o,a[1]=l}if(s==="H")s="L",a=[a[0],i[1]];if(s==="h")s="l",a=[a[0],0];if(s==="V")s="L",a=[i[0],a[0]];if(s==="v")s="l",a=[0,a[0]];if(s==="L"){i[0]=a[0],i[1]=a[1];let[o,l]=rt(t,a[0],a[1]);a[0]=o,a[1]=l}if(s==="l"){i[0]+=a[0],i[1]+=a[1];let[o,l]=it(t,a[0],a[1]);a[0]=o,a[1]=l}if(s==="C"){i[0]=a[4],i[1]=a[5];let[o,l]=rt(t,a[0],a[1]),[c,u]=rt(t,a[2],a[3]),[f,h]=rt(t,a[4],a[5]);a[0]=o,a[1]=l,a[2]=c,a[3]=u,a[4]=f,a[5]=h}if(s==="c"){i[0]+=a[4],i[1]+=a[5];let[o,l]=it(t,a[0],a[1]),[c,u]=it(t,a[2],a[3]),[f,h]=it(t,a[4],a[5]);a[0]=o,a[1]=l,a[2]=c,a[3]=u,a[4]=f,a[5]=h}if(s==="S"){i[0]=a[2],i[1]=a[3];let[o,l]=rt(t,a[0],a[1]),[c,u]=rt(t,a[2],a[3]);a[0]=o,a[1]=l,a[2]=c,a[3]=u}if(s==="s"){i[0]+=a[2],i[1]+=a[3];let[o,l]=it(t,a[0],a[1]),[c,u]=it(t,a[2],a[3]);a[0]=o,a[1]=l,a[2]=c,a[3]=u}if(s==="Q"){i[0]=a[2],i[1]=a[3];let[o,l]=rt(t,a[0],a[1]),[c,u]=rt(t,a[2],a[3]);a[0]=o,a[1]=l,a[2]=c,a[3]=u}if(s==="q"){i[0]+=a[2],i[1]+=a[3];let[o,l]=it(t,a[0],a[1]),[c,u]=it(t,a[2],a[3]);a[0]=o,a[1]=l,a[2]=c,a[3]=u}if(s==="T"){i[0]=a[0],i[1]=a[1];let[o,l]=rt(t,a[0],a[1]);a[0]=o,a[1]=l}if(s==="t"){i[0]+=a[0],i[1]+=a[1];let[o,l]=it(t,a[0],a[1]);a[0]=o,a[1]=l}if(s==="A"){if(iu(i,a,t),i[0]=a[5],i[1]=a[6],Math.abs(a[2])>80){let c=a[0],u=a[2];a[0]=a[1],a[1]=c,a[2]=u+(u>0?-90:90)}let[o,l]=rt(t,a[5],a[6]);a[5]=o,a[6]=l}if(s==="a"){if(iu([0,0],a,t),i[0]+=a[5],i[1]+=a[6],Math.abs(a[2])>80){let c=a[0],u=a[2];a[0]=a[1],a[1]=c,a[2]=u+(u>0?-90:90)}let[o,l]=it(t,a[5],a[6]);a[5]=o,a[6]=l}if(s==="z"||s==="Z")i[0]=r[0],i[1]=r[1];n.command=s,n.args=a}}var a1=(e,t)=>{let r=ht(e);return{element:{enter:(i)=>{if(i.attributes.d==null)return;if(i.attributes.id!=null)return;if(i.attributes.transform==null||i.attributes.transform===""||i.attributes.style!=null||Object.entries(i.attributes).some(([h,d])=>Xn.has(h)&&ra(d)))return;let n=ft(r,i),s=n.transform;if(s&&s.type==="static"&&s.value!==i.attributes.transform)return;let a=Dh(Rh(i.attributes.transform)),o=n.stroke?.type==="static"?n.stroke.value:null,l=n["stroke-width"]?.type==="static"?n["stroke-width"].value:null,c=t.transformPrecision;if(n.stroke?.type==="dynamic"||n["stroke-width"]?.type==="dynamic")return;let u=Number(Math.hypot(a.data[0],a.data[1]).toFixed(c));if(o&&o!=="none"){if(!t.applyTransformsStroked)return;if((a.data[0]!==a.data[3]||a.data[1]!==-a.data[2])&&(a.data[0]!==-a.data[3]||a.data[1]!==a.data[2]))return;if(u!==1){if(i.attributes["vector-effect"]!=="non-scaling-stroke"){if(i.attributes["stroke-width"]=(l||zo.presentation["stroke-width"]).trim().replace(_a,(h)=>Qt(Number(h)*u)),i.attributes["stroke-dashoffset"]!=null)i.attributes["stroke-dashoffset"]=i.attributes["stroke-dashoffset"].trim().replace(_a,(h)=>Qt(Number(h)*u));if(i.attributes["stroke-dasharray"]!=null)i.attributes["stroke-dasharray"]=i.attributes["stroke-dasharray"].trim().replace(_a,(h)=>Qt(Number(h)*u))}}}let f=Mn(i);n1(f,a.data),delete i.attributes.transform}}}},s1="convertPathData",o1="optimizes path data: writes in shorter form, applies transformations",Tt,st,fe,el,tl,l1=(e,t)=>{let{applyTransforms:r=!0,applyTransformsStroked:i=!0,makeArcs:n={threshold:2.5,tolerance:0.5},straightCurves:s=!0,convertToQ:a=!0,lineShorthands:o=!0,convertToZ:l=!0,curveSmoothShorthands:c=!0,floatPrecision:u=3,transformPrecision:f=5,smartArcRounding:h=!0,removeUseless:d=!0,collapseRepeated:m=!0,utilizeAbsolute:p=!0,leadingZero:y=!0,negativeExtraSpace:g=!0,noSpaceAfterFlags:w=!1,forceAbsolutePath:b=!1}=t||{},v={applyTransforms:r,applyTransformsStroked:i,makeArcs:n,straightCurves:s,convertToQ:a,lineShorthands:o,convertToZ:l,curveSmoothShorthands:c,floatPrecision:u,transformPrecision:f,smartArcRounding:h,removeUseless:d,collapseRepeated:m,utilizeAbsolute:p,leadingZero:y,negativeExtraSpace:g,noSpaceAfterFlags:w,forceAbsolutePath:b};if(r)wt(e,a1(e,{transformPrecision:f,applyTransformsStroked:i},{multipassCount:0}));let S=ht(e);return{element:{enter:(E)=>{if(Io.has(E.name)&&E.attributes.d!=null){let C=ft(S,E);if(st=u,fe=st!==!1?+(0.1**st).toFixed(st):0.01,Tt=st!==!1&&st>0&&st<20?h1:d1,n)el=n.threshold,tl=n.tolerance;let F=C["marker-mid"]!=null,R=C.stroke&&(C.stroke.type==="dynamic"||C.stroke.value!=="none"),x=C["stroke-linecap"]&&(C["stroke-linecap"].type==="dynamic"||C["stroke-linecap"].value!=="butt"),A=R?C["stroke-linecap"]?.type==="static"&&C["stroke-linecap"].value==="round"&&C["stroke-linejoin"]?.type==="static"&&C["stroke-linejoin"].value==="round":!0,M=(P,T)=>{if(!R)return!0;if(P)return!x;return T},k=Mn(E);if(k.length){let P=k.some((T)=>T.command!=="m"&&T.command!=="M");if(c1(k),k=u1(k,v,{isSafeToUseZ:A,isSafeToRemove:M,hasMarkerMid:F}),p)k=f1(k,v);if((E.attributes["marker-start"]!=null||E.attributes["marker-end"]!=null)&&P&&k.every((T)=>T.command==="m"||T.command==="M"))k.push({command:"z",args:[]});Ph(E,k,{floatPrecision:typeof v.floatPrecision==="number"?v.floatPrecision:void 0,noSpaceAfterFlags:v.noSpaceAfterFlags})}}}}}};function c1(e){let t=[0,0],r=[0,0],i=[0,0];for(let n=0;n<e.length;n++){let s=e[n],{command:a,args:o}=s;if(a==="m")r[0]+=o[0],r[1]+=o[1],t[0]=r[0],t[1]=r[1];else if(a==="M"){if(n!==0)a="m";o[0]-=r[0],o[1]-=r[1],r[0]+=o[0],r[1]+=o[1],t[0]=r[0],t[1]=r[1]}else if(a==="l")r[0]+=o[0],r[1]+=o[1];else if(a==="L")a="l",o[0]-=r[0],o[1]-=r[1],r[0]+=o[0],r[1]+=o[1];else if(a==="h")r[0]+=o[0];else if(a==="H")a="h",o[0]-=r[0],r[0]+=o[0];else if(a==="v")r[1]+=o[0];else if(a==="V")a="v",o[0]-=r[1],r[1]+=o[0];else if(a==="c")r[0]+=o[4],r[1]+=o[5];else if(a==="C")a="c",o[0]-=r[0],o[1]-=r[1],o[2]-=r[0],o[3]-=r[1],o[4]-=r[0],o[5]-=r[1],r[0]+=o[4],r[1]+=o[5];else if(a==="s")r[0]+=o[2],r[1]+=o[3];else if(a==="S")a="s",o[0]-=r[0],o[1]-=r[1],o[2]-=r[0],o[3]-=r[1],r[0]+=o[2],r[1]+=o[3];else if(a==="q")r[0]+=o[2],r[1]+=o[3];else if(a==="Q")a="q",o[0]-=r[0],o[1]-=r[1],o[2]-=r[0],o[3]-=r[1],r[0]+=o[2],r[1]+=o[3];else if(a==="t")r[0]+=o[0],r[1]+=o[1];else if(a==="T")a="t",o[0]-=r[0],o[1]-=r[1],r[0]+=o[0],r[1]+=o[1];else if(a==="a")r[0]+=o[5],r[1]+=o[6];else if(a==="A")a="a",o[5]-=r[0],o[6]-=r[1],r[0]+=o[5],r[1]+=o[6];else if(a==="Z"||a==="z")r[0]=t[0],r[1]=t[1];s.command=a,s.args=o,s.base=i,s.coords=[r[0],r[1]],i=s.coords}return e}function u1(e,t,{isSafeToUseZ:r,isSafeToRemove:i,hasMarkerMid:n}){let s=p1.bind(null,t),a=[0,0],o=[0,0],l={},c;return e=e.filter(function(u,f,h){let d=c,m=u.command,p=u.args,y=h[f+1];if(m!=="Z"&&m!=="z"){let g=p,w;if(m==="s"){g=[0,0].concat(p);let v=l.args,S=v.length;g[0]=v[S-2]-v[S-4],g[1]=v[S-1]-v[S-3]}if(t.makeArcs&&(m==="c"||m==="s")&&Ua(g)&&(w=m1(g))){let v=Tt([w.radius])[0],S=Ga(g,w),E=g[5]*g[0]-g[4]*g[1]>0?1:0,C={command:"a",args:[v,v,0,0,E,g[4],g[5]],coords:u.coords.slice(),base:u.base},F=[C],R=[w.center[0]-g[4],w.center[1]-g[5]],x={center:R,radius:w.radius},A=[u],M=0,k="",P;if(l.command==="c"&&Ua(l.args)&&lu(l.args,w)||l.command==="a"&&l.sdata&&lu(l.sdata,w)){A.unshift(l),C.base=l.base,C.args[5]=C.coords[0]-C.base[0],C.args[6]=C.coords[1]-C.base[1];let T=l.command==="a"?l.sdata:l.args,O=Ga(T,{center:[T[4]+w.center[0],T[5]+w.center[1]],radius:w.radius});if(S+=O,S>Math.PI)C.args[3]=1;M=1}for(let T=f;(y=h[++T])&&(y.command==="c"||y.command==="s");){let O=y.args;if(y.command==="s")P=ji({command:"s",args:y.args.slice()},h[T-1].args),O=P.args,P.args=O.slice(0,2),k=s([P]);if(Ua(O)&&Bh(O,x)){if(S+=Ga(O,x),S-2*Math.PI>0.001)break;if(S>Math.PI)C.args[3]=1;if(A.push(y),2*Math.PI-S>0.001)C.coords=y.coords,C.args[5]=C.coords[0]-C.base[0],C.args[6]=C.coords[1]-C.base[1];else{C.args[5]=2*(x.center[0]-O[4]),C.args[6]=2*(x.center[1]-O[5]),C.coords=[C.base[0]+C.args[5],C.base[1]+C.args[6]],C={command:"a",args:[v,v,0,0,E,y.coords[0]-C.coords[0],y.coords[1]-C.coords[1]],coords:y.coords,base:C.coords},F.push(C),T++;break}R[0]-=O[4],R[1]-=O[5]}else break}if((s(F)+k).length<s(A).length){if(h[y?y.command==="s"?e.indexOf(y):-1:-1]);if(M){let T=F.shift();Tt(T.args),a[0]+=T.args[5]-l.args[l.args.length-2],a[1]+=T.args[6]-l.args[l.args.length-1],l.command="a",l.args=T.args,u.base=l.coords=T.coords}if(C=F.shift(),A.length===1)u.sdata=g.slice();else if(A.length-1-M>0)e.splice(f+1,A.length-1-M,...F);if(!C)return!1;m="a",p=C.args,u.coords=C.coords}}if(st!==!1){if(m==="m"||m==="l"||m==="t"||m==="q"||m==="s"||m==="c")for(let v=p.length;v--;)p[v]+=u.base[v%2]-a[v%2];else if(m==="h")p[0]+=u.base[0]-a[0];else if(m==="v")p[0]+=u.base[1]-a[1];else if(m==="a")p[5]+=u.base[0]-a[0],p[6]+=u.base[1]-a[1];if(Tt(p),m==="h")a[0]+=p[0];else if(m==="v")a[1]+=p[0];else a[0]+=p[p.length-2],a[1]+=p[p.length-1];if(Tt(a),m==="M"||m==="m")o[0]=a[0],o[1]=a[1]}let b=m==="a"?su(p):void 0;if(t.smartArcRounding&&b!==void 0&&st)for(let v=st;v>=0;v--){let S=Ot(p[0],v),E=su([S,S,...p.slice(2)]);if(Math.abs(b-E)<fe)p[0]=S,p[1]=S;else break}if(t.straightCurves){if(m==="c"&&Va(p)||m==="s"&&Va(g)){if(y&&y.command==="s")ji(y,p);m="l",p=p.slice(-2)}else if(m==="q"&&Va(p)||m==="t"&&l.command!=="q"&&l.command!=="t"){if(m==="q"&&y&&y.command==="t")ji(y,p);if(m==="t"&&y&&y.command==="t")y.command="q",y.args.unshift(2*u.coords[0]-u.base[0]-u.coords[0],2*u.coords[1]-u.base[1]-u.coords[1]);m="l",p=p.slice(-2)}else if(m==="a"&&(p[0]===0||p[1]===0||b!==void 0&&b<fe))m="l",p=p.slice(-2)}if(t.convertToQ&&m==="c"){let v=0.75*(u.base[0]+p[0])-0.25*u.base[0],S=0.75*(u.base[0]+p[2])-0.25*(u.base[0]+p[4]);if(Math.abs(v-S)<fe*2){let E=0.75*(u.base[1]+p[1])-0.25*u.base[1],C=0.75*(u.base[1]+p[3])-0.25*(u.base[1]+p[5]);if(Math.abs(E-C)<fe*2){let F=p.slice();F.splice(0,4,v+S-u.base[0],E+C-u.base[1]),Tt(F);let R=jr(p,t).length;if(jr(F,t).length<R){if(m="q",p=F,y&&y.command==="s")ji(y,p)}}}}if(t.lineShorthands&&m==="l"){if(p[1]===0)m="h",p.pop();else if(p[0]===0)m="v",p.shift()}if(t.collapseRepeated&&!n&&(m==="m"||m==="h"||m==="v")&&l.command&&m===l.command.toLowerCase()&&(m!=="h"&&m!=="v"||l.args[0]>=0===p[0]>=0)){if(l.args[0]+=p[0],m!=="h"&&m!=="v")l.args[1]+=p[1];return l.coords=u.coords,e[f]=l,!1}if(t.curveSmoothShorthands&&l.command){if(m==="c"){if(l.command==="c"&&Math.abs(p[0]- -(l.args[2]-l.args[4]))<fe&&Math.abs(p[1]- -(l.args[3]-l.args[5]))<fe)m="s",p=p.slice(2);else if(l.command==="s"&&Math.abs(p[0]- -(l.args[0]-l.args[2]))<fe&&Math.abs(p[1]- -(l.args[1]-l.args[3]))<fe)m="s",p=p.slice(2);else if(l.command!=="c"&&l.command!=="s"&&Math.abs(p[0])<fe&&Math.abs(p[1])<fe)m="s",p=p.slice(2)}else if(m==="q"){if(l.command==="q"&&Math.abs(p[0]-(l.args[2]-l.args[0]))<fe&&Math.abs(p[1]-(l.args[3]-l.args[1]))<fe)m="t",p=p.slice(2);else if(l.command==="t"){let v=ou(d,u.base),S=[p[0]+u.base[0],p[1]+u.base[1]];if(Math.abs(v[0]-S[0])<fe&&Math.abs(v[1]-S[1])<fe)m="t",p=p.slice(2)}}}if(t.removeUseless&&i(l.command==="m"||l.command==="M",!0)){if((m==="l"||m==="h"||m==="v"||m==="q"||m==="t"||m==="c"||m==="s")&&p.every((v)=>v===0))return e[f]=l,!1;if(m==="a"&&p[5]===0&&p[6]===0)return e[f]=l,!1}if(t.convertToZ&&(r||y?.command==="Z"||y?.command==="z")&&(m==="l"||m==="h"||m==="v")){if(Math.abs(o[0]-u.coords[0])<fe&&Math.abs(o[1]-u.coords[1])<fe)m="z",p=[]}u.command=m,u.args=p}else if(a[0]=o[0],a[1]=o[1],l.command==="Z"||l.command==="z")return!1;if((m==="Z"||m==="z")&&t.removeUseless&&i(l.command==="m"||l.command==="M",r)&&Math.abs(u.base[0]-u.coords[0])<fe/10&&Math.abs(u.base[1]-u.coords[1])<fe/10)return!1;if(m==="q")c=[p[0]+u.base[0],p[1]+u.base[1]];else if(m==="t")if(d)c=ou(d,u.base);else c=u.coords;else c=void 0;return l=u,!0}),e}function f1(e,t){let r=e[0];return e=e.filter(function(i,n){if(n===0)return!0;if(i.command==="Z"||i.command==="z")return r=i,!0;let{command:s,args:a}=i,o=a.slice(),l=a.slice();if(s==="m"||s==="l"||s==="t"||s==="q"||s==="s"||s==="c")for(let f=o.length;f--;)o[f]+=i.base[f%2];else if(s==="h")o[0]+=i.base[0];else if(s==="v")o[0]+=i.base[1];else if(s==="a")o[5]+=i.base[0],o[6]+=i.base[1];Tt(o),Tt(l);let c=jr(o,t),u=jr(l,t);if(t.forceAbsolutePath||c.length<u.length&&!(t.negativeExtraSpace&&s===r.command&&r.command.charCodeAt(0)>96&&c.length===u.length-1&&(a[0]<0||Math.floor(a[0])===0&&!Number.isInteger(a[0])&&r.args[r.args.length-1]%1)))i.command=s.toUpperCase(),i.args=o;return r=i,!0}),e}function Ua(e){let t=jh([0,0,e[2],e[3],e[0],e[1],e[4],e[5]]);return t!=null&&e[2]<t[0]===t[0]<0&&e[3]<t[1]===t[1]<0&&e[4]<t[0]===t[0]<e[0]&&e[5]<t[1]===t[1]<e[1]}function jh(e){let t=e[1]-e[3],r=e[2]-e[0],i=e[0]*e[3]-e[2]*e[1],n=e[5]-e[7],s=e[6]-e[4],a=e[4]*e[7]-e[5]*e[6],o=t*s-n*r;if(!o)return;let l=[(r*a-s*i)/o,(t*a-n*i)/-o];if(!Number.isNaN(l[0])&&!Number.isNaN(l[1])&&Number.isFinite(l[0])&&Number.isFinite(l[1]))return l}function h1(e){let t=st||0;for(let r=e.length;r-- >0;){let i=Ot(e[r],t);if(i!==e[r]){let n=Ot(e[r],t-1);e[r]=Ot(Math.abs(n-e[r]),t+1)>=fe?i:n}}return e}function d1(e){for(let t=e.length;t-- >0;)e[t]=Math.round(e[t]);return e}function Va(e){let t=e.length-2,r=-e[t+1],i=e[t],n=1/(r*r+i*i);if(t<=1||!Number.isFinite(n))return!1;while((t-=2)>=0)if(Math.sqrt((r*e[t]+i*e[t+1])**2*n)>fe)return!1;return!0}function su(e){if(e[3]===1)return;let t=e[0],r=e[1];if(Math.abs(t-r)>fe)return;let i=Math.hypot(e[5],e[6]);if(i>t*2)return;return t-Math.sqrt(t**2-0.25*i**2)}function ji(e,t){switch(e.command){case"s":e.command="c";break;case"t":e.command="q";break}return e.args.unshift(t[t.length-2]-t[t.length-4],t[t.length-1]-t[t.length-3]),e}function Is(e,t){return Math.hypot(e[0]-t[0],e[1]-t[1])}function ou(e,t){return[2*t[0]-e[0],2*t[1]-e[1]]}function zs(e,t){let r=t*t,i=r*t,n=1-t,s=n*n;return[3*s*t*e[0]+3*n*r*e[2]+i*e[4],3*s*t*e[1]+3*n*r*e[3]+i*e[5]]}function m1(e){let t=zs(e,0.5),r=[t[0]/2,t[1]/2],i=[(t[0]+e[4])/2,(t[1]+e[5])/2],n=jh([r[0],r[1],r[0]+r[1],r[1]-r[0],i[0],i[1],i[0]+(i[1]-t[1]),i[1]-(i[0]-t[0])]),s=n&&Is([0,0],n),a=Math.min(el*fe,tl*(s||0)/100);if(n&&s<1000000000000000&&[0.25,0.75].every((o)=>Math.abs(Is(zs(e,o),n)-s)<=a))return{center:n,radius:s}}function Bh(e,t){let r=Math.min(el*fe,tl*t.radius/100);return[0,0.25,0.5,0.75,1].every((i)=>Math.abs(Is(zs(e,i),t.center)-t.radius)<=r)}function lu(e,t){return Bh(e,{center:[t.center[0]+e[4],t.center[1]+e[5]],radius:t.radius})}function Ga(e,t){let r=-t.center[0],i=-t.center[1],n=e[4]-t.center[0],s=e[5]-t.center[1];return Math.acos((r*n+i*s)/Math.sqrt((r*r+i*i)*(n*n+s*s)))}function p1(e,t){return t.reduce((r,i)=>{let n="";if(i.args)n=jr(Tt(i.args.slice()),e);return r+i.command+n},"")}var rl={};D(rl,{name:()=>g1,fn:()=>b1,description:()=>y1});var g1="convertShapeToPath",y1="converts basic shapes to more compact path form",w1=/[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g,b1=(e,t)=>{let{convertArcs:r=!1,floatPrecision:i}=t||{};return{element:{enter:(n,s)=>{if(n.name==="rect"&&n.attributes.width!=null&&n.attributes.height!=null&&n.attributes.rx==null&&n.attributes.ry==null){let a=Number(n.attributes.x||"0"),o=Number(n.attributes.y||"0"),l=Number(n.attributes.width),c=Number(n.attributes.height);if(Number.isNaN(a-o+l-c))return;let u=[{command:"M",args:[a,o]},{command:"H",args:[a+l]},{command:"V",args:[o+c]},{command:"H",args:[a]},{command:"z",args:[]}];n.name="path",n.attributes.d=Mr({pathData:u,precision:i}),delete n.attributes.x,delete n.attributes.y,delete n.attributes.width,delete n.attributes.height}if(n.name==="line"){let a=Number(n.attributes.x1||"0"),o=Number(n.attributes.y1||"0"),l=Number(n.attributes.x2||"0"),c=Number(n.attributes.y2||"0");if(Number.isNaN(a-o+l-c))return;let u=[{command:"M",args:[a,o]},{command:"L",args:[l,c]}];n.name="path",n.attributes.d=Mr({pathData:u,precision:i}),delete n.attributes.x1,delete n.attributes.y1,delete n.attributes.x2,delete n.attributes.y2}if((n.name==="polyline"||n.name==="polygon")&&n.attributes.points!=null){let a=(n.attributes.points.match(w1)||[]).map(Number);if(a.length<4){V(n,s);return}let o=[];for(let l=0;l<a.length;l+=2)o.push({command:l===0?"M":"L",args:a.slice(l,l+2)});if(n.name==="polygon")o.push({command:"z",args:[]});n.name="path",n.attributes.d=Mr({pathData:o,precision:i}),delete n.attributes.points}if(n.name==="circle"&&r){let a=Number(n.attributes.cx||"0"),o=Number(n.attributes.cy||"0"),l=Number(n.attributes.r||"0");if(Number.isNaN(a-o+l))return;let c=[{command:"M",args:[a,o-l]},{command:"A",args:[l,l,0,1,0,a,o+l]},{command:"A",args:[l,l,0,1,0,a,o-l]},{command:"z",args:[]}];n.name="path",n.attributes.d=Mr({pathData:c,precision:i}),delete n.attributes.cx,delete n.attributes.cy,delete n.attributes.r}if(n.name==="ellipse"&&r){let a=Number(n.attributes.cx||"0"),o=Number(n.attributes.cy||"0"),l=Number(n.attributes.rx||"0"),c=Number(n.attributes.ry||"0");if(Number.isNaN(a-o+l-c))return;let u=[{command:"M",args:[a,o-c]},{command:"A",args:[l,c,0,1,0,a,o+c]},{command:"A",args:[l,c,0,1,0,a,o-c]},{command:"z",args:[]}];n.name="path",n.attributes.d=Mr({pathData:u,precision:i}),delete n.attributes.cx,delete n.attributes.cy,delete n.attributes.rx,delete n.attributes.ry}}}}},Ih={};D(Ih,{name:()=>v1,fn:()=>N1,description:()=>S1});var v1="convertStyleToAttrs",S1="converts style to attributes",vi=(...e)=>`(?:${e.join("|")})`,x1=Oe.presentation,Gr="\\\\(?:[0-9a-f]{1,6}\\s?|\\r\\n|.)",$1=`\\s*(${vi("[^:;\\\\]",Gr)}*?)\\s*`,aa=`'(?:[^'\\n\\r\\\\]|${Gr})*?(?:'|$)`,sa=`"(?:[^"\\n\\r\\\\]|${Gr})*?(?:"|$)`,C1=new RegExp(`^${vi(aa,sa)}$`),A1=`\\(${vi(`[^'"()\\\\]+`,Gr,aa,sa)}*?\\)`,E1=`\\s*(${vi(`[^!'"();\\\\]+?`,Gr,aa,sa,A1,"[^;]*?")}*?)`,k1="\\s*(?:;\\s*|$)",M1="(\\s*!important(?![-(\\w]))?",cu=new RegExp(`${$1}:${E1}${M1}${k1}`,"ig"),T1=new RegExp(vi(Gr,aa,sa,"/\\*[^]*?\\*/"),"ig"),N1=(e,t)=>{let{keepImportant:r=!1}=t||{};return{element:{enter:(i)=>{if(i.attributes.style!=null){let n=[],s={},a=i.attributes.style.replace(T1,(l)=>l[0]==="/"?"":l[0]==="\\"&&/[-g-z]/i.test(l[1])?l[1]:l);cu.lastIndex=0;let o;while((o=cu.exec(a))!=null)if(!r||!o[3])n.push([o[1],o[2]]);if(n.length)if(n=n.filter((l)=>{if(l[0]){let c=l[0].toLowerCase(),u=l[1];if(C1.test(u))u=u.slice(1,-1);if(x1.has(c))return s[c]=u,!1}return!0}),Object.assign(i.attributes,s),n.length)i.attributes.style=n.map((l)=>l.join(":")).join(";");else delete i.attributes.style}}}}},il={};D(il,{name:()=>P1,fn:()=>O1,description:()=>F1});var P1="convertTransform",F1="collapses multiple transformations and optimizes it",O1=(e,t)=>{let{convertToShorts:r=!0,degPrecision:i,floatPrecision:n=3,transformPrecision:s=5,matrixToTransform:a=!0,shortTranslate:o=!0,shortScale:l=!0,shortRotate:c=!0,removeUseless:u=!0,collapseIntoOne:f=!0,leadingZero:h=!0,negativeExtraSpace:d=!1}=t||{},m={convertToShorts:r,degPrecision:i,floatPrecision:n,transformPrecision:s,matrixToTransform:a,shortTranslate:o,shortScale:l,shortRotate:c,removeUseless:u,collapseIntoOne:f,leadingZero:h,negativeExtraSpace:d};return{element:{enter:(p)=>{if(p.attributes.transform!=null)Wa(p,"transform",m);if(p.attributes.gradientTransform!=null)Wa(p,"gradientTransform",m);if(p.attributes.patternTransform!=null)Wa(p,"patternTransform",m)}}}};function Wa(e,t,r){let i=Rh(e.attributes[t]);if(r=R1(i,r),r.collapseIntoOne&&i.length>1)i=[Dh(i)];if(r.convertToShorts)i=L1(i,r);else i.forEach((n)=>na(n,r));if(r.removeUseless)i=j1(i);if(i.length)e.attributes[t]=Tn(i,r);else delete e.attributes[t]}function R1(e,t){let r={...t},i=[];for(let s of e)if(s.name==="matrix")i.push(...s.data.slice(0,4));let n=r.transformPrecision;if(i.length)r.transformPrecision=Math.min(r.transformPrecision,Math.max(...i.map(D1))||r.transformPrecision),n=Math.max(...i.map((s)=>s.toString().replace(/\D+/g,"").length));if(r.degPrecision==null)r.degPrecision=Math.max(0,Math.min(r.floatPrecision,n-2));return r}function D1(e){let t=e.toString();return t.slice(t.indexOf(".")).length-1}function L1(e,t){for(let r=0;r<e.length;r++){let i=e[r];if(t.matrixToTransform&&i.name==="matrix"){let n=r1(i,t);if(Tn(n,t).length<=Tn([i],t).length)e.splice(r,1,...n);i=e[r]}if(na(i,t),t.shortTranslate&&i.name==="translate"&&i.data.length===2&&!i.data[1])i.data.pop();if(t.shortScale&&i.name==="scale"&&i.data.length===2&&i.data[0]===i.data[1])i.data.pop();if(t.shortRotate&&e[r-2]?.name==="translate"&&e[r-1]?.name==="rotate"&&e[r]?.name==="translate"&&e[r-2].data[0]===-e[r].data[0]&&e[r-2].data[1]===-e[r].data[1])e.splice(r-2,3,{name:"rotate",data:[e[r-1].data[0],e[r-2].data[0],e[r-2].data[1]]}),r-=2}return e}function j1(e){return e.filter((t)=>{if(["translate","rotate","skewX","skewY"].includes(t.name)&&(t.data.length===1||t.name==="rotate")&&!t.data[0]||t.name==="translate"&&!t.data[0]&&!t.data[1]||t.name==="scale"&&t.data[0]===1&&(t.data.length<2||t.data[1]===1)||t.name==="matrix"&&t.data[0]===1&&t.data[3]===1&&!(t.data[1]||t.data[2]||t.data[4]||t.data[5]))return!1;return!0})}var nl={};D(nl,{name:()=>B1,fn:()=>_1,description:()=>I1});var{syntax:uu}=oi,B1="inlineStyles",I1="inline styles (additional options)",z1=[...Vc.functional??new Set,...Vc.treeStructural??new Set],_1=(e,t)=>{let{onlyMatchedOnce:r=!0,removeMatchedSelectors:i=!0,useMqs:n=["","screen"],usePseudos:s=[""]}=t||{},a=[],o=[];return{element:{enter:(l,c)=>{if(l.name==="foreignObject")return Rt;if(l.name!=="style"||l.children.length===0)return;if(l.attributes.type!=null&&l.attributes.type!==""&&l.attributes.type!=="text/css")return;let u=l.children.filter((h)=>h.type==="text"||h.type==="cdata").map((h)=>h.value).join(""),f=null;try{f=G.parse(u,{parseValue:!1,parseCustomProperty:!1})}catch{return}if(f.type==="StyleSheet")a.push({node:l,parentNode:c,cssAst:f});G.walk(f,{visit:"Rule",enter(h){let d=this.atrule,m="";if(d!=null){if(m=d.name,d.prelude!=null)m+=` ${G.generate(d.prelude)}`}if(!n.includes(m))return;if(h.prelude.type==="SelectorList")h.prelude.children.forEach((p,y)=>{if(p.type==="Selector"){let g=[];p.children.forEach((b,v,S)=>{if((b.type==="PseudoClassSelector"||b.type==="PseudoElementSelector")&&!z1.includes(b.name))g.push({item:v,list:S})});let w=G.generate({type:"Selector",children:new G.List().fromArray(g.map((b)=>b.item.data))});if(s.includes(w))for(let b of g)b.list.remove(b.item);o.push({node:p,rule:h,item:y})}})}})}},root:{exit:()=>{if(a.length===0)return;let l=o.slice().sort((c,u)=>{let f=uu.specificity(c.item.data),h=uu.specificity(u.item.data);return kh(f,h)}).reverse();for(let c of l){let u=G.generate(c.item.data),f=[];try{for(let h of ui(e,u))if(h.type==="element")f.push(h)}catch{continue}if(f.length===0)continue;if(r&&f.length>1)continue;for(let h of f){let d=G.parse(h.attributes.style??"",{context:"declarationList",parseValue:!1});if(d.type!=="DeclarationList")continue;let m=new Map,p=null;G.walk(d,{visit:"Declaration",enter(g,w){if(w==null)return;if(p==null)p=w;m.set(g.property.toLowerCase(),w)}}),G.walk(c.rule,{visit:"Declaration",enter(g){let w=g.property;if(Oe.presentation.has(w)&&!o.some((S)=>nn(S.item,w)))delete h.attributes[w];let b=m.get(w),v=d.children.createItem(g);if(b==null)d.children.insert(v,p);else if(b.data.important!==!0&&g.important===!0)d.children.replace(b,v),m.set(w,v)}});let y=G.generate(d);if(y.length!==0)h.attributes.style=y}if(i&&f.length!==0&&c.rule.prelude.type==="SelectorList")c.rule.prelude.children.remove(c.item);c.matchedElements=f}if(!i)return;for(let c of l){if(c.matchedElements==null)continue;if(r&&c.matchedElements.length>1)continue;for(let u of c.matchedElements){let f=new Set(u.attributes.class==null?null:u.attributes.class.split(" "));if(c.node.children.forEach((d)=>{if(d.type==="ClassSelector"&&!o.some((m)=>nn(m.item,"class",d.name,!0)))f.delete(d.name)}),f.size===0)delete u.attributes.class;else u.attributes.class=Array.from(f).join(" ");let h=c.node.children.first;if(h?.type==="IdSelector"&&u.attributes.id===h.name&&!o.some((d)=>nn(d.item,"id",h.name,!0)))delete u.attributes.id}}for(let c of a)if(G.walk(c.cssAst,{visit:"Rule",enter(u,f,h){if(u.type==="Rule"&&u.prelude.type==="SelectorList"&&u.prelude.children.isEmpty){if(h&&f)h.remove(f)}}}),c.cssAst.children.isEmpty)V(c.node,c.parentNode);else{let u=c.node.children[0];if(u&&(u.type==="text"||u.type==="cdata"))u.value=G.generate(c.cssAst)}}}}},al={};D(al,{name:()=>U1,fn:()=>W1,description:()=>V1});var U1="mergePaths",V1="merges multiple paths in one if possible";function G1(e,t){let r=e[t];if(r?.type==="static")return ra(r.value);return!1}var W1=(e,t)=>{let{force:r=!1,floatPrecision:i=3,noSpaceAfterFlags:n=!1}=t||{},s=ht(e);return{element:{enter:(a)=>{if(a.children.length<=1)return;let o=new Set,l=a.children[0],c=null,u=(f,h)=>{Ph(f,h,{floatPrecision:i,noSpaceAfterFlags:n}),c=null};for(let f=1;f<a.children.length;f++){let h=a.children[f];if(l.type!=="element"||l.name!=="path"||l.children.length!==0||l.attributes.d==null){if(c&&l.type==="element")u(l,c);l=h;continue}if(h.type!=="element"||h.name!=="path"||h.children.length!==0||h.attributes.d==null){if(c)u(l,c);l=h;continue}let d=ft(s,h);if(d["marker-start"]||d["marker-mid"]||d["marker-end"]||d["clip-path"]||d.mask||d["mask-image"]||["fill","filter","stroke"].some((g)=>G1(d,g))){if(c)u(l,c);l=h;continue}let m=Object.keys(h.attributes);if(m.length!==Object.keys(l.attributes).length){if(c)u(l,c);l=h;continue}if(m.some((g)=>g!=="d"&&l.type==="element"&&l.attributes[g]!==h.attributes[g])){if(c)u(l,c);l=h;continue}let p=c!=null,y=Mn(h);if(c=c??Mn(l),r||!Fh(c,y)){c.push(...y),o.add(h);continue}if(p)u(l,c);l=h,c=null}if(c&&l.type==="element")u(l,c);a.children=a.children.filter((f)=>!o.has(f))}}}},sl={};D(sl,{name:()=>q1,fn:()=>Y1,description:()=>K1});var q1="mergeStyles",K1="merge multiple style elements into one",Y1=()=>{let e=null,t="",r="text";return{element:{enter:(i,n)=>{if(i.name==="foreignObject")return Rt;if(i.name!=="style")return;if(i.attributes.type!=null&&i.attributes.type!==""&&i.attributes.type!=="text/css")return;let s="";for(let a of i.children){if(a.type==="text")s+=a.value;if(a.type==="cdata")r="cdata",s+=a.value}if(s.trim().length===0){V(i,n);return}if(i.attributes.media==null)t+=s;else t+=`@media ${i.attributes.media}{${s}}`,delete i.attributes.media;if(e==null)e=i;else{V(i,n);let a={type:r,value:t};e.children=[a]}}}}},ol={};D(ol,{name:()=>H1,fn:()=>Z1,description:()=>J1});var H1="minifyStyles",J1="minifies styles and removes unused styles",Z1=(e,t)=>{let{usage:r,...i}=t||{},n=new Map,s=[],a=new Set,o=new Set,l=new Set,c=!0,u=!0,f=!0,h=!1;if(typeof r==="boolean")c=r,u=r,f=r;else if(r)c=r.tags==null?!0:r.tags,u=r.ids==null?!0:r.ids,f=r.classes==null?!0:r.classes,h=r.force==null?!1:r.force;let d=!1;return{element:{enter:(m,p)=>{if(ta(m))d=!0;if(a.add(m.name),m.attributes.id!=null)o.add(m.attributes.id);if(m.attributes.class!=null)for(let y of m.attributes.class.split(/\s+/))l.add(y);if(m.name==="style"&&m.children.length!==0)n.set(m,p);else if(m.attributes.style!=null)s.push(m)}},root:{exit:()=>{let m={};if(!d||h){if(c)m.tags=Array.from(a);if(u)m.ids=Array.from(o);if(f)m.classes=Array.from(l)}for(let[p,y]of n.entries()){let g=p.children[0];if(g&&(g.type==="text"||g.type==="cdata")){let w=g.value,b=oi.minify(w,{...i,usage:m}).css;if(b.length===0){V(p,y);continue}if(w.includes(">")||w.includes("<"))g.type="cdata",g.value=b;else g.type="text",g.value=b}}for(let p of s){let y=p.attributes.style;p.attributes.style=oi.minifyBlock(y,{...i}).css}}}}},ll={};D(ll,{name:()=>Q1,fn:()=>eb,description:()=>X1});var Q1="moveElemsAttrsToGroup",X1="Move common attributes of group children to the group",eb=(e)=>{let t=!1;return wt(e,{element:{enter:(r)=>{if(r.name==="style")t=!0}}}),{element:{exit:(r)=>{if(r.name!=="g"||r.children.length<=1)return;if(t)return;let i=new Map,n=!0,s=!0;for(let a of r.children)if(a.type==="element"){if(!Io.has(a.name))s=!1;if(n){n=!1;let o=a.attributes;for(let l in o)if(ea.has(l))i.set(l,o[l])}else for(let[o,l]of i)if(a.attributes[o]!==l)i.delete(o)}if(r.attributes.filter!=null||r.attributes["clip-path"]!=null||r.attributes.mask!=null)i.delete("transform");if(s)i.delete("transform");for(let[a,o]of i)if(a==="transform")if(r.attributes.transform!=null)r.attributes.transform=`${r.attributes.transform} ${o}`;else r.attributes.transform=o;else r.attributes[a]=o;for(let a of r.children)if(a.type==="element")for(let[o]of i)delete a.attributes[o]}}}},cl={};D(cl,{name:()=>tb,fn:()=>nb,description:()=>rb});var tb="moveGroupAttrsToElems",rb="moves some group attributes to the content elements",ib=[...Io,"g","text"],nb=()=>({element:{enter:(e)=>{if(e.name==="g"&&e.children.length!==0&&e.attributes.transform!=null&&!Object.entries(e.attributes).some(([t,r])=>Xn.has(t)&&ra(r))&&e.children.every((t)=>t.type==="element"&&ib.includes(t.name)&&t.attributes.id==null)){for(let t of e.children){let r=e.attributes.transform;if(t.type==="element")if(t.attributes.transform!=null)t.attributes.transform=`${r} ${t.attributes.transform}`;else t.attributes.transform=r}delete e.attributes.transform}}}}),zh={};D(zh,{name:()=>ab,fn:()=>fb,description:()=>sb});var ab="prefixIds",sb="prefix IDs";function ob(e){let t=/[/\\]?([^/\\]+)$/.exec(e);if(t)return t[1];return""}function lb(e){return e.replace(/[. ]/g,"_")}function cb(e){if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);return e}function Zr(e,t){let r=e(t);if(t.startsWith(r))return t;return r+t}function qa(e,t){if(t.startsWith("#"))return`#${Zr(e,t.slice(1))}`;return null}function ub(e,t,r,i,n,s){if(typeof i==="function"){let a=s.get(e);if(a!=null)return a;return a=i(t,r)+n,s.set(e,a),a}if(typeof i==="string")return i+n;if(i===!1)return"";if(r.path!=null&&r.path.length>0)return lb(ob(r.path))+n;return`prefix${n}`}var fb=(e,t,r)=>{let{delim:i="__",prefix:n,prefixIds:s=!0,prefixClassNames:a=!0}=t||{},o=new Map;return{element:{enter:(l)=>{let c=(u)=>ub(u,l,r,n,i,o);if(l.name==="style"){if(l.children.length===0)return;for(let u of l.children){if(u.type!=="text"&&u.type!=="cdata")continue;let f=u.value,h;try{h=G.parse(f,{parseValue:!0,parseCustomProperty:!1})}catch{return}G.walk(h,(d)=>{if(s&&d.type==="IdSelector"||a&&d.type==="ClassSelector"){d.name=Zr(c,d.name);return}if(d.type==="Url"&&d.value.length>0){let m=qa(c,cb(d.value));if(m!=null)d.value=m}}),u.value=G.generate(h)}}if(s&&l.attributes.id!=null&&l.attributes.id.length!==0)l.attributes.id=Zr(c,l.attributes.id);if(a&&l.attributes.class!=null&&l.attributes.class.length!==0)l.attributes.class=l.attributes.class.split(/\s+/).map((u)=>Zr(c,u)).join(" ");for(let u of["href","xlink:href"])if(l.attributes[u]!=null&&l.attributes[u].length!==0){let f=qa(c,l.attributes[u]);if(f!=null)l.attributes[u]=f}for(let u of Xn)if(l.attributes[u]!=null&&l.attributes[u].length!==0)l.attributes[u]=l.attributes[u].replace(/\burl\((["'])?(#.+?)\1\)/gi,(f,h,d)=>{let m=qa(c,d);if(m==null)return f;return`url(${m})`});for(let u of["begin","end"])if(l.attributes[u]!=null&&l.attributes[u].length!==0){let f=l.attributes[u].split(/\s*;\s+/).map((h)=>{if(h.endsWith(".end")||h.endsWith(".start")){let[d,m]=h.split(".");return`${Zr(c,d)}.${m}`}return h});l.attributes[u]=f.join("; ")}}}}},ul={};D(ul,{name:()=>hb,fn:()=>pb,description:()=>db});var hb="removeComments",db="removes comments",mb=[/^!/],pb=(e,t)=>{let{preservePatterns:r=mb}=t||{};return{comment:{enter:(i,n)=>{if(r){if(!Array.isArray(r))throw Error(`Expected array in removeComments preservePatterns parameter but received ${r}`);if(r.some((s)=>new RegExp(s).test(i.value)))return}V(i,n)}}}},fl={};D(fl,{name:()=>gb,fn:()=>bb,description:()=>yb});var gb="removeDeprecatedAttrs",yb="removes deprecated attributes";function wb(e){let t=new Set;return e.rules.forEach((r)=>{ti.parse(r.selector).forEach((i)=>{i.forEach((n)=>{if(n.type!=="attribute")return;t.add(n.name)})})}),t}function fu(e,t,r,i){if(!t)return;if(t.safe)t.safe.forEach((n)=>{if(i.has(n))return;delete e.attributes[n]});if(r.removeUnsafe&&t.unsafe)t.unsafe.forEach((n)=>{if(i.has(n))return;delete e.attributes[n]})}var bb=(e,t)=>{let r=ht(e),i=wb(r);return{element:{enter:(n)=>{let s=_o[n.name];if(!s)return;if(s.attrsGroups.has("core")&&n.attributes["xml:lang"]&&!i.has("xml:lang")&&n.attributes.lang)delete n.attributes["xml:lang"];s.attrsGroups.forEach((a)=>{fu(n,X0[a],t||{},i)}),fu(n,s.deprecated,t||{},i)}}}},hl={};D(hl,{name:()=>vb,fn:()=>$b,description:()=>Sb});var vb="removeDesc",Sb="removes <desc>",xb=/^(?:Created with|Created using)/,$b=(e,t)=>{let{removeAny:r=!1}=t||{};return{element:{enter:(i,n)=>{if(i.name==="desc"){if(r||i.children.length===0||i.children[0].type==="text"&&xb.test(i.children[0].value))V(i,n)}}}}},dl={};D(dl,{name:()=>Cb,fn:()=>Eb,description:()=>Ab});var Cb="removeDoctype",Ab="removes doctype declaration",Eb=()=>({doctype:{enter:(e,t)=>{V(e,t)}}}),ml={};D(ml,{name:()=>kb,fn:()=>Tb,description:()=>Mb});var kb="removeEditorsNSData",Mb="removes editors namespaces, elements and attributes",Tb=(e,t)=>{let r=[...zc];if(t&&Array.isArray(t.additionalNamespaces))r=[...zc,...t.additionalNamespaces];let i=[];return{element:{enter:(n,s)=>{if(n.name==="svg"){let a=n.attributes;for(let o in a)if(o.startsWith("xmlns:")&&r.includes(a[o]))i.push(o.slice(6)),delete a[o]}for(let a of Object.keys(n.attributes))if(a.includes(":")){let[o]=a.split(":");if(i.includes(o))delete n.attributes[a]}if(n.name.includes(":")){let[a]=n.name.split(":");if(i.includes(a))V(n,s)}}}}},pl={};D(pl,{name:()=>Nb,fn:()=>Fb,description:()=>Pb});var Nb="removeEmptyAttrs",Pb="removes empty attributes",Fb=()=>({element:{enter:(e)=>{let t=e.attributes;for(let r in t)if(t[r]===""&&!Oe.conditionalProcessing.has(r))delete t[r]}}}),gl={};D(gl,{name:()=>Ob,fn:()=>Db,description:()=>Rb});var Ob="removeEmptyContainers",Rb="removes empty container elements",Db=(e)=>{let t=ht(e),r=new Set,i=new Map;return{element:{enter:(n,s)=>{if(n.name==="use"){let a=n.attributes;for(let o in a){let l=a[o],c=Vo(o,l);for(let u of c){let f=i.get(u);if(f===void 0)f=[],i.set(u,f);f.push({node:n,parent:s})}}}},exit:(n,s)=>{if(n.name==="svg"||!Kt.container.has(n.name)||n.children.length!==0)return;if(n.name==="pattern"&&Object.keys(n.attributes).length!==0)return;if(n.name==="mask"&&n.attributes.id!=null)return;if(s.type==="element"&&s.name==="switch")return;if(n.name==="g"&&(n.attributes.filter!=null||ft(t,n).filter))return;if(V(n,s),n.attributes.id)r.add(n.attributes.id)}},root:{exit:()=>{for(let n of r){let s=i.get(n);if(s)for(let a of s)V(a.node,a.parent)}}}}},yl={};D(yl,{name:()=>Lb,fn:()=>Bb,description:()=>jb});var Lb="removeEmptyText",jb="removes empty <text> elements",Bb=(e,t)=>{let{text:r=!0,tspan:i=!0,tref:n=!0}=t||{};return{element:{enter:(s,a)=>{if(r&&s.name==="text"&&s.children.length===0)V(s,a);if(i&&s.name==="tspan"&&s.children.length===0)V(s,a);if(n&&s.name==="tref"&&s.attributes["xlink:href"]==null)V(s,a)}}}},wl={};D(wl,{name:()=>zb,fn:()=>Ub,description:()=>_b});var Ib=Kt.nonRendering,zb="removeHiddenElems",_b="removes hidden elements (zero sized, with absent attributes)",Ub=(e,t)=>{let{isHidden:r=!0,displayNone:i=!0,opacity0:n=!0,circleR0:s=!0,ellipseRX0:a=!0,ellipseRY0:o=!0,rectWidth0:l=!0,rectHeight0:c=!0,patternWidth0:u=!0,patternHeight0:f=!0,imageWidth0:h=!0,imageHeight0:d=!0,pathEmptyD:m=!0,polylineEmptyPoints:p=!0,polygonEmptyPoints:y=!0}=t||{},g=ht(e),w=new Map,b=new Set,v=new Map,S=new Set,E=new Map,C=!1;function F(x){if(S.has(x.attributes.id))return!1;for(let A of x.children)if(A.type==="element"&&!F(A))return!1;return!0}function R(x,A){if(x.type==="element"&&x.attributes.id!=null&&A.type==="element"&&A.name==="defs")b.add(x.attributes.id);V(x,A)}return wt(e,{element:{enter:(x,A)=>{if(Ib.has(x.name))return w.set(x,A),Rt;let M=ft(g,x);if(n&&M.opacity&&M.opacity.type==="static"&&M.opacity.value==="0"){if(x.name==="path")return w.set(x,A),Rt;R(x,A)}}}}),{element:{enter:(x,A)=>{if(x.name==="style"&&x.children.length!==0||ta(x)){C=!0;return}if(x.name==="defs")v.set(x,A);if(x.name==="use")for(let P of Object.keys(x.attributes)){if(P!=="href"&&!P.endsWith(":href"))continue;let T=x.attributes[P].slice(1),O=E.get(T);if(!O)O=[],E.set(T,O);O.push({node:x,parentNode:A})}if(s&&x.name==="circle"&&x.children.length===0&&x.attributes.r==="0"){R(x,A);return}if(a&&x.name==="ellipse"&&x.children.length===0&&x.attributes.rx==="0"){R(x,A);return}if(o&&x.name==="ellipse"&&x.children.length===0&&x.attributes.ry==="0"){R(x,A);return}if(l&&x.name==="rect"&&x.children.length===0&&x.attributes.width==="0"){R(x,A);return}if(c&&l&&x.name==="rect"&&x.children.length===0&&x.attributes.height==="0"){R(x,A);return}if(u&&x.name==="pattern"&&x.attributes.width==="0"){R(x,A);return}if(f&&x.name==="pattern"&&x.attributes.height==="0"){R(x,A);return}if(h&&x.name==="image"&&x.attributes.width==="0"){R(x,A);return}if(d&&x.name==="image"&&x.attributes.height==="0"){R(x,A);return}if(p&&x.name==="polyline"&&x.attributes.points==null){R(x,A);return}if(y&&x.name==="polygon"&&x.attributes.points==null){R(x,A);return}let M=ft(g,x);if(r&&M.visibility&&M.visibility.type==="static"&&M.visibility.value==="hidden"&&Eh(x,"[visibility=visible]")==null){R(x,A);return}if(i&&M.display&&M.display.type==="static"&&M.display.value==="none"&&x.name!=="marker"){R(x,A);return}if(m&&x.name==="path"){if(x.attributes.d==null){R(x,A);return}let P=Zo(x.attributes.d);if(P.length===0){R(x,A);return}if(P.length===1&&M["marker-start"]==null&&M["marker-end"]==null){R(x,A);return}}let k=x.attributes;for(let P in k){let T=Vo(P,k[P]);for(let O of T)S.add(O)}}},root:{exit:()=>{for(let x of b){let A=E.get(x);if(A)for(let{node:M,parentNode:k}of A)V(M,k)}if(!C){for(let[x,A]of w.entries())if(F(x))V(x,A)}for(let[x,A]of v.entries())if(x.children.length===0)V(x,A)}}}},bl={};D(bl,{name:()=>Vb,fn:()=>Wb,description:()=>Gb});var Vb="removeMetadata",Gb="removes <metadata>",Wb=()=>({element:{enter:(e,t)=>{if(e.name==="metadata")V(e,t)}}}),vl={};D(vl,{name:()=>qb,fn:()=>Yb,description:()=>Kb});var qb="removeNonInheritableGroupAttrs",Kb="removes non-inheritable group's presentational attributes",Yb=()=>({element:{enter:(e)=>{if(e.name==="g"){for(let t of Object.keys(e.attributes))if(Oe.presentation.has(t)&&!ea.has(t)&&!Uo.has(t))delete e.attributes[t]}}}}),Sl={};D(Sl,{name:()=>Hb,fn:()=>Zb,description:()=>Jb});var Hb="removeUnknownsAndDefaults",Jb="removes unknown elements content and attributes, removes attrs with default values",_s=new Map,_h=new Map,Uh=new Map;for(let[e,t]of Object.entries(_o)){let r=new Set;if(t.content)for(let s of t.content)r.add(s);if(t.contentGroups)for(let s of t.contentGroups){let a=Kt[s];if(a)for(let o of a)r.add(o)}let i=new Set;if(t.attrs)for(let s of t.attrs)i.add(s);let n=new Map;if(t.defaults)for(let[s,a]of Object.entries(t.defaults))n.set(s,a);for(let s of t.attrsGroups){let a=Oe[s];if(a)for(let l of a)i.add(l);let o=zo[s];if(o)for(let[l,c]of Object.entries(o))n.set(l,c)}_s.set(e,r),_h.set(e,i),Uh.set(e,n)}var Zb=(e,t)=>{let{unknownContent:r=!0,unknownAttrs:i=!0,defaultAttrs:n=!0,defaultMarkupDeclarations:s=!0,uselessOverrides:a=!0,keepDataAttrs:o=!0,keepAriaAttrs:l=!0,keepRoleAttr:c=!1}=t||{},u=ht(e);return{instruction:{enter:(f)=>{if(s)f.value=f.value.replace(/\s*standalone\s*=\s*(["'])no\1/,"")}},element:{enter:(f,h)=>{if(f.name.includes(":"))return;if(f.name==="foreignObject")return Rt;if(r&&h.type==="element"){let g=_s.get(h.name);if(g==null||g.size===0){if(_s.get(f.name)==null){V(f,h);return}}else if(!g.has(f.name)){V(f,h);return}}let d=_h.get(f.name),m=Uh.get(f.name),p=h.type==="element"?ft(u,h):null,y=f.attributes;for(let g in y){let w=y[g];if(o&&g.startsWith("data-"))continue;if(l&&g.startsWith("aria-"))continue;if(c&&g==="role")continue;if(g==="xmlns")continue;if(g.includes(":")){let[b]=g.split(":");if(b!=="xml"&&b!=="xlink")continue}if(i&&d&&!d.has(g))delete f.attributes[g];if(n&&f.attributes.id==null&&m&&m.get(g)===w){if(p?.[g]==null&&!u.rules.some((b)=>nn(b.selector,g)))delete f.attributes[g]}if(a&&f.attributes.id==null){let b=p?.[g];if(!Uo.has(g)&&b!=null&&b.type==="static"&&b.value===w)delete f.attributes[g]}}}}}},xl={};D(xl,{name:()=>Qb,fn:()=>ev,description:()=>Xb});var Qb="removeUnusedNS",Xb="removes unused namespaces declaration",ev=()=>{let e=new Set;return{element:{enter:(t,r)=>{if(t.name==="svg"&&r.type==="root"){for(let i of Object.keys(t.attributes))if(i.startsWith("xmlns:"))e.add(i.slice(6))}if(e.size!==0){if(t.name.includes(":")){let[i]=t.name.split(":");if(e.has(i))e.delete(i)}for(let i of Object.keys(t.attributes))if(i.includes(":")){let[n]=i.split(":");e.delete(n)}}},exit:(t,r)=>{if(t.name==="svg"&&r.type==="root")for(let i of e)delete t.attributes[`xmlns:${i}`]}}}},$l={};D($l,{name:()=>tv,fn:()=>iv,description:()=>rv});var tv="removeUselessDefs",rv="removes elements in <defs> without id";function Vh(e,t){for(let r of e.children)if(r.type==="element")if(r.attributes.id!=null||r.name==="style")t.push(r);else Vh(r,t)}var iv=()=>({element:{enter:(e,t)=>{if(e.name==="defs"||Kt.nonRendering.has(e.name)&&e.attributes.id==null){let r=[];if(Vh(e,r),r.length===0)V(e,t);e.children=r}}}}),Cl={};D(Cl,{name:()=>nv,fn:()=>sv,description:()=>av});var nv="removeUselessStrokeAndFill",av="removes useless stroke and fill attributes",sv=(e,t)=>{let{stroke:r=!0,fill:i=!0,removeNone:n=!1}=t||{},s=!1;if(wt(e,{element:{enter:(o)=>{if(o.name==="style"||ta(o))s=!0}}}),s)return null;let a=ht(e);return{element:{enter:(o,l)=>{if(o.attributes.id!=null)return Rt;if(!Kt.shape.has(o.name))return;let c=ft(a,o),u=c.stroke,f=c["stroke-opacity"],h=c["stroke-width"],d=c["marker-end"],m=c.fill,p=c["fill-opacity"],y=l.type==="element"?ft(a,l):null,g=y==null?null:y.stroke;if(r){if(u==null||u.type==="static"&&u.value==="none"||f!=null&&f.type==="static"&&f.value==="0"||h!=null&&h.type==="static"&&h.value==="0"){if(h!=null&&h.type==="static"&&h.value==="0"||d==null){for(let w of Object.keys(o.attributes))if(w.startsWith("stroke"))delete o.attributes[w];if(g!=null&&g.type==="static"&&g.value!=="none")o.attributes.stroke="none"}}}if(i){if(m!=null&&m.type==="static"&&m.value==="none"||p!=null&&p.type==="static"&&p.value==="0"){for(let w of Object.keys(o.attributes))if(w.startsWith("fill-"))delete o.attributes[w];if(m==null||m.type==="static"&&m.value!=="none")o.attributes.fill="none"}}if(n){if((u==null||o.attributes.stroke==="none")&&(m!=null&&m.type==="static"&&m.value==="none"||o.attributes.fill==="none"))V(o,l)}}}}},Al={};D(Al,{name:()=>ov,fn:()=>cv,description:()=>lv});var ov="removeXMLProcInst",lv="removes XML processing instructions",cv=()=>({instruction:{enter:(e,t)=>{if(e.name==="xml")V(e,t)}}}),El={};D(El,{name:()=>uv,fn:()=>hv,description:()=>fv});var uv="sortAttrs",fv="Sort element attributes for better compression",hv=(e,t)=>{let{order:r=["id","width","height","x","x1","x2","y","y1","y2","cx","cy","r","fill","stroke","marker","d","points"],xmlnsOrder:i="front"}=t||{},n=(a)=>{if(i==="front"){if(a==="xmlns")return 3;if(a.startsWith("xmlns:"))return 2}if(a.includes(":"))return 1;return 0},s=([a],[o])=>{let l=n(a),c=n(o)-l;if(c!==0)return c;let[u]=a.split("-"),[f]=o.split("-");if(u!==f){let h=r.includes(u)?1:0,d=r.includes(f)?1:0;if(h===1&&d===1)return r.indexOf(u)-r.indexOf(f);let m=d-h;if(m!==0)return m}return a<o?-1:1};return{element:{enter:(a)=>{let o=Object.entries(a.attributes);o.sort(s);let l={};for(let[c,u]of o)l[c]=u;a.attributes=l}}}},kl={};D(kl,{name:()=>dv,fn:()=>pv,description:()=>mv});var dv="sortDefsChildren",mv="Sorts children of <defs> to improve compression",pv=()=>({element:{enter:(e)=>{if(e.name==="defs"){let t=new Map;for(let r of e.children)if(r.type==="element")t.set(r.name,(t.get(r.name)??0)+1);e.children.sort((r,i)=>{if(r.type!=="element"||i.type!=="element")return 0;let n=t.get(r.name),s=t.get(i.name);if(n!=null&&s!=null){let o=s-n;if(o!==0)return o}let a=i.name.length-r.name.length;if(a!==0)return a;if(r.name!==i.name)return r.name>i.name?-1:1;return 0})}}}});function Gh(e,t,r,i,n){let s=i==null,a=!0;for(let l in n){a=!1;break}let o=r.length;for(let l=0;l<o;l++){let c=r[l],u=s?void 0:i[c.name];if(u===!1)continue;let f;if(s&&a)f=c.params??{};else if(u===void 0)f=a?c.params??{}:{...c.params,...n};else f={...c.params,...n,...u};let h=c.fn(e,f,t);if(h!=null)wt(e,h)}}function gv({name:e,plugins:t}){return{name:e,isPreset:!0,plugins:Object.freeze(t),fn:(r,i,n)=>{let{floatPrecision:s,overrides:a}=i||{},o={};if(s!=null)o.floatPrecision=s;if(a){let l=t.map((c)=>c.name);for(let c of Object.keys(a))if(!l.includes(c))console.warn(`You are trying to configure ${c} which is not part of ${e}.
65
+ Try to put it before or after, for example
66
+
67
+ plugins: [
68
+ {
69
+ name: '${e}',
70
+ },
71
+ '${c}'
72
+ ]
73
+ `)}Gh(r,n,t,a,o)}}}var yv=gv({name:"preset-default",plugins:[dl,Al,ul,fl,bl,ml,wo,sl,nl,ol,Bo,$l,Go,Yo,Sl,vl,Cl,bo,wl,yl,rl,Ho,ll,cl,Wo,Jo,il,pl,gl,al,xl,El,kl,hl]}),wv=yv,Wh={};D(Wh,{name:()=>bv,fn:()=>xv,description:()=>vv});var bv="removeAttributesBySelector",vv="removes attributes of elements that match a css selector",Sv=`Warning: The plugin "removeAttributesBySelector" is missing parameters.
74
+ It should have a list of "selectors", or one "selector" and one "attributes".`,xv=(e,t)=>{if(!Array.isArray(t?.selectors)&&(!t?.selector||!t?.attributes))return console.warn(Sv),null;let r=Array.isArray(t.selectors)?t.selectors:[t];for(let{selector:i,attributes:n}of r){let s=ui(e,i);for(let a of s)if(a.type==="element")if(Array.isArray(n))for(let o of n)delete a.attributes[o];else delete a.attributes[n]}return{}},qh={};D(qh,{name:()=>$v,fn:()=>Av,description:()=>Cv});var $v="removeAttrs",Cv="removes specified attributes",Av=(e,t)=>{if(!t||typeof t.attrs>"u")return console.warn(`Warning: The plugin "removeAttrs" requires the "attrs" parameter.
75
+ It should have a pattern to remove, otherwise the plugin is a noop.`),null;let r=typeof t.elemSeparator==="string"?t.elemSeparator:":",i=typeof t.preserveCurrentColor==="boolean"?t.preserveCurrentColor:!1,n=Array.isArray(t.attrs)?t.attrs:[t.attrs];return{element:{enter:(s)=>{for(let a of n){if(!a.includes(r))a=[".*",a,".*"].join(r);else if(a.split(r).length<3)a=[a,".*"].join(r);let o=a.split(r).map((l)=>{if(l==="*")l=".*";return new RegExp(["^",l,"$"].join(""),"i")});if(o[0].test(s.name)){let l=s.attributes;for(let c in l){let u=l[c],f=u.toLowerCase()==="currentcolor";if(!(i&&c==="fill"&&f)&&!(i&&c==="stroke"&&f)&&o[1].test(c)&&o[2].test(u))delete s.attributes[c]}}}}}}},Kh={};D(Kh,{name:()=>Ev,fn:()=>Mv,description:()=>kv});var Ev="removeDimensions",kv="removes width and height in presence of viewBox (opposite to removeViewBox)",Mv=()=>({element:{enter:(e)=>{if(e.name==="svg"){if(e.attributes.viewBox!=null)delete e.attributes.width,delete e.attributes.height;else if(e.attributes.width!=null&&e.attributes.height!=null&&!Number.isNaN(Number(e.attributes.width))&&!Number.isNaN(Number(e.attributes.height))){let t=Number(e.attributes.width),r=Number(e.attributes.height);e.attributes.viewBox=`0 0 ${t} ${r}`,delete e.attributes.width,delete e.attributes.height}}}}}),Yh={};D(Yh,{name:()=>Tv,fn:()=>Pv,description:()=>Nv});var Tv="removeElementsByAttr",Nv="removes arbitrary elements by ID or className",Pv=(e,t)=>{let r=t?.id==null?[]:Array.isArray(t.id)?t.id:[t.id],i=t?.class==null?[]:Array.isArray(t.class)?t.class:[t.class];return{element:{enter:(n,s)=>{if(n.attributes.id!=null&&r.length!==0){if(r.includes(n.attributes.id))V(n,s)}if(n.attributes.class&&i.length!==0){let a=n.attributes.class.split(" ");for(let o of i)if(a.includes(o)){V(n,s);break}}}}}},Hh={};D(Hh,{name:()=>Fv,fn:()=>Rv,description:()=>Ov});var Fv="removeOffCanvasPaths",Ov="removes elements that are drawn outside of the viewBox",Rv=()=>{let e=null;return{element:{enter:(t,r)=>{if(t.name==="svg"&&r.type==="root"){let i="";if(t.attributes.viewBox!=null)i=t.attributes.viewBox;else if(t.attributes.height!=null&&t.attributes.width!=null)i=`0 0 ${t.attributes.width} ${t.attributes.height}`;i=i.replace(/[,+]|px/g," ").replace(/\s+/g," ").replace(/^\s*|\s*$/g,"");let n=/^(-?\d*\.?\d+) (-?\d*\.?\d+) (\d*\.?\d+) (\d*\.?\d+)$/.exec(i);if(n==null)return;let s=Number.parseFloat(n[1]),a=Number.parseFloat(n[2]),o=Number.parseFloat(n[3]),l=Number.parseFloat(n[4]);e={left:s,top:a,right:s+o,bottom:a+l,width:o,height:l}}if(t.attributes.transform!=null)return Rt;if(t.name==="path"&&t.attributes.d!=null&&e!=null){let i=Zo(t.attributes.d),n=!1;for(let c of i)if(c.command==="M"){let[u,f]=c.args;if(u>=e.left&&u<=e.right&&f>=e.top&&f<=e.bottom)n=!0}if(n)return;if(i.length===2)i.push({command:"z",args:[]});let{left:s,top:a,width:o,height:l}=e;if(!Fh([{command:"M",args:[s,a]},{command:"h",args:[o]},{command:"v",args:[l]},{command:"H",args:[s]},{command:"z",args:[]}],i))V(t,r)}}}}},Jh={};D(Jh,{name:()=>Dv,fn:()=>jv,description:()=>Lv});var Dv="removeRasterImages",Lv="removes raster images",jv=()=>({element:{enter:(e,t)=>{if(e.name==="image"&&e.attributes["xlink:href"]!=null&&/(?:\.|image\/)(?:jpe?g|png|gif)/.test(e.attributes["xlink:href"]))V(e,t)}}}),Zh={};D(Zh,{name:()=>Bv,fn:()=>_v,description:()=>Iv});var Bv="removeScripts",Iv="removes scripts",zv=[...Oe.animationEvent??new Set,...Oe.documentEvent??new Set,...Oe.documentElementEvent??new Set,...Oe.globalEvent??new Set,...Oe.graphicalEvent??new Set],_v=()=>({element:{enter:(e,t)=>{if(e.name==="script"){V(e,t);return}for(let r of zv)if(e.attributes[r]!=null)delete e.attributes[r]},exit:(e,t)=>{if(e.name!=="a")return;for(let r of Object.keys(e.attributes))if(r==="href"||r.endsWith(":href")){if(e.attributes[r]==null||!e.attributes[r].trimStart().startsWith("javascript:"))continue;let i=t.children.indexOf(e),n=e.children.filter((s)=>s.type!=="text");t.children.splice(i,1,...n)}}}}),Qh={};D(Qh,{name:()=>Uv,fn:()=>Gv,description:()=>Vv});var Uv="removeStyleElement",Vv="removes <style> element",Gv=()=>({element:{enter:(e,t)=>{if(e.name==="style")V(e,t)}}}),Xh={};D(Xh,{name:()=>Wv,fn:()=>Kv,description:()=>qv});var Wv="removeTitle",qv="removes <title>",Kv=()=>({element:{enter:(e,t)=>{if(e.name==="title")V(e,t)}}}),ed={};D(ed,{name:()=>Yv,fn:()=>Zv,description:()=>Hv});var Yv="removeViewBox",Hv="removes viewBox attribute when possible",Jv=new Set(["pattern","svg","symbol"]),Zv=()=>({element:{enter:(e,t)=>{if(Jv.has(e.name)&&e.attributes.viewBox!=null&&e.attributes.width!=null&&e.attributes.height!=null){if(e.name==="svg"&&t.type!=="root")return;let r=e.attributes.viewBox.split(/[ ,]+/g);if(r[0]==="0"&&r[1]==="0"&&e.attributes.width.replace(/px$/,"")===r[2]&&e.attributes.height.replace(/px$/,"")===r[3])delete e.attributes.viewBox}}}}),td={};D(td,{name:()=>Qv,fn:()=>r2,description:()=>Xv});var Qv="removeXlink",Xv="remove xlink namespace and replaces attributes with the SVG 2 equivalent where applicable",hu="http://www.w3.org/1999/xlink",e2={new:"_blank",replace:"_self"},t2=new Set(["cursor","filter","font-face-uri","glyphRef","tref"]);function Ka(e,t,r){return t.map((i)=>`${i}:${r}`).filter((i)=>e.attributes[i]!=null)}var r2=(e,t)=>{let{includeLegacy:r}=t||{},i=[],n=[],s=[];return{element:{enter:(a)=>{for(let[f,h]of Object.entries(a.attributes))if(f.startsWith("xmlns:")){let d=f.split(":",2)[1];if(h===hu){i.push(d);continue}if(i.includes(d))n.push(d)}if(n.some((f)=>i.includes(f)))return;let o=Ka(a,i,"show"),l=a.attributes.target!=null;for(let f=o.length-1;f>=0;f--){let h=o[f],d=a.attributes[h],m=e2[d];if(l||m==null){delete a.attributes[h];continue}if(m!==_o[a.name]?.defaults?.target)a.attributes.target=m;delete a.attributes[h],l=!0}let c=Ka(a,i,"title");for(let f=c.length-1;f>=0;f--){let h=c[f],d=a.attributes[h];if(a.children.filter((p)=>p.type==="element"&&p.name==="title").length>0){delete a.attributes[h];continue}let m={type:"element",name:"title",attributes:{},children:[{type:"text",value:d}]};a.children.unshift(m),delete a.attributes[h]}let u=Ka(a,i,"href");if(u.length>0&&t2.has(a.name)&&!r){u.map((f)=>f.split(":",1)[0]).forEach((f)=>s.push(f));return}for(let f=u.length-1;f>=0;f--){let h=u[f],d=a.attributes[h];if(a.attributes.href!=null){delete a.attributes[h];continue}a.attributes.href=d,delete a.attributes[h]}},exit:(a)=>{for(let[o,l]of Object.entries(a.attributes)){let[c,u]=o.split(":",2);if(i.includes(c)&&!n.includes(c)&&!s.includes(c)&&!r){delete a.attributes[o];continue}if(o.startsWith("xmlns:")&&!s.includes(u)){if(l===hu){let f=i.indexOf(u);if(f>=0)i.splice(f,1);delete a.attributes[o];continue}if(n.includes(c)){let f=n.indexOf(u);if(f>=0)n.splice(f,1)}}}}}}},rd={};D(rd,{name:()=>i2,fn:()=>a2,description:()=>n2});var i2="removeXMLNS",n2="removes xmlns attribute (for inline svg)",a2=()=>({element:{enter:(e)=>{if(e.name==="svg")delete e.attributes.xmlns}}}),id={};D(id,{name:()=>s2,fn:()=>l2,description:()=>o2});var s2="reusePaths",o2="Finds <path> elements with the same d, fill, and stroke, and converts them to <use> elements referencing a single <path> def.",l2=(e)=>{let t=ht(e),r=new Map,i,n=new Set;return{element:{enter:(s,a)=>{if(s.name==="path"&&s.attributes.d!=null){let o=s.attributes.d,l=s.attributes.fill||"",c=s.attributes.stroke||"",u=`${o};s:${c};f:${l}`,f=r.get(u);if(f==null)f=[],r.set(u,f);f.push(s)}if(i==null&&s.name==="defs"&&a.type==="element"&&a.name==="svg")i=s;if(s.name==="use")for(let o of["href","xlink:href"]){let l=s.attributes[o];if(l!=null&&l.startsWith("#")&&l.length>1)n.add(l.slice(1))}},exit:(s,a)=>{if(s.name==="svg"&&a.type==="root"){let o=i;if(o==null)o={type:"element",name:"defs",attributes:{},children:[]};let l=0;for(let c of r.values())if(c.length>1){let u={type:"element",name:"path",attributes:{},children:[]};for(let h of["fill","stroke","d"])if(c[0].attributes[h]!=null)u.attributes[h]=c[0].attributes[h];let f=c[0].attributes.id;if(f==null||n.has(f)||t.rules.some((h)=>h.selector===`#${f}`))u.attributes.id=`reuse-${l++}`;else u.attributes.id=f,delete c[0].attributes.id;o.children.push(u);for(let h of c){if(delete h.attributes.d,delete h.attributes.stroke,delete h.attributes.fill,o.children.includes(h)&&h.children.length===0){if(Object.keys(h.attributes).length===0){V(h,o);continue}if(Object.keys(h.attributes).length===1&&h.attributes.id!=null){V(h,o);let d=`[xlink\\:href="#${h.attributes.id}"], [href="#${h.attributes.id}"]`;for(let m of ui(s,d)){if(m.type!=="element")continue;for(let p of["href","xlink:href"])if(m.attributes[p]!=null)m.attributes[p]=`#${u.attributes.id}`}continue}}h.name="use",h.attributes["xlink:href"]=`#${u.attributes.id}`}}if(o.children.length!==0){if(s.attributes["xmlns:xlink"]==null)s.attributes["xmlns:xlink"]="http://www.w3.org/1999/xlink";if(i==null)s.children.unshift(o)}}}}}},c2=Object.freeze([wv,Pf,Ff,wo,bo,Bo,Ah,Go,Wo,Yo,Ho,Th,Jo,rl,Ih,il,nl,al,sl,ol,ll,cl,zh,Wh,qh,ul,fl,hl,Kh,dl,ml,Yh,pl,gl,yl,wl,bl,vl,Hh,Jh,Zh,Qh,Xh,Sl,xl,$l,Cl,ed,td,rd,Al,id,El,kl]);class nd extends Error{reason;line;column;source;file;constructor(e,t,r,i,n){super(e);this.name="SvgParserError",this.message=`${n||"<input>"}:${t}:${r}: ${e}`,this.reason=e,this.line=t,this.column=r,this.source=i,this.file=n}toString(){let e=this.source.split(/\r?\n/),t=Math.max(this.line-3,0),r=Math.min(this.line+2,e.length),i=String(r).length,n=Math.max(this.column-54,0),s=Math.max(this.column+20,80),a=e.slice(t,r).map((o,l)=>{let c=o.slice(n,s),u="",f="";if(n!==0)u=n>o.length-1?" ":"\u2026";if(s<o.length-1)f="\u2026";let h=t+1+l,d=` ${h.toString().padStart(i)} | `;if(h===this.line){let m=d.replace(/[^|]/g," "),p=(u+o.slice(n,this.column-1)).replace(/[^\t]/g," "),y=m+p;return`>${d}${u}${c}${f}
76
+ ${y}^`}return` ${d}${u}${c}${f}`}).join(`
77
+ `);return`${this.name}: ${this.message}
78
+
79
+ ${a}
80
+ `}}var du={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function mu(e,t){if(e.indexOf("&")<0)return e;return e.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z][a-z0-9]*);/gi,(r,i)=>{if(i.charCodeAt(0)===35){if(i.charCodeAt(1)===120||i.charCodeAt(1)===88){let a=Number.parseInt(i.slice(2),16);return Number.isFinite(a)?String.fromCodePoint(a):r}let s=Number.parseInt(i.slice(1),10);return Number.isFinite(s)?String.fromCodePoint(s):r}let n=i.toLowerCase();if(n in du)return du[n];if(t&&i in t)return t[i];return r})}var pu=/<!ENTITY\s+(\S+)\s+(?:'([^']+)'|"([^"]+)")\s*>/g;function u2(e,t){let r=1,i=0;for(let n=0;n<t;n++)if(e.charCodeAt(n)===10)r++,i=n+1;return{line:r,column:t-i+1}}function f2(e,t){let r={type:"root",children:[]},i=r,n=[r],s={},a=!1,o=e.length,l=0,c=(f,h)=>{let{line:d,column:m}=u2(e,h);throw new nd(f,d,m,e,t)},u=(f)=>{i.children.push(f)};while(l<o){let f=e.charCodeAt(l);if(f!==60){let b=l,v=f===32||f===9||f===10||f===13;l++;while(l<o){let S=e.charCodeAt(l);if(S===60)break;if(v&&S!==32&&S!==9&&S!==10&&S!==13)v=!1;l++}if(i.type==="element"){let S=xh.has(i.name);if(v&&!S)continue;let E=e.slice(b,l),C=mu(E,a?s:null);if(S)u({type:"text",value:C});else{let F=C.trim();if(F.length>0)u({type:"text",value:F})}}continue}let h=e.charCodeAt(l+1);if(h===33){if(e.startsWith("<!--",l)){let b=e.indexOf("-->",l+4);if(b<0)c("Unterminated comment",l);let v={type:"comment",value:e.slice(l+4,b).trim()};u(v),l=b+3;continue}if(e.startsWith("<![CDATA[",l)){let b=e.indexOf("]]>",l+9);if(b<0)c("Unterminated CDATA",l);let v={type:"cdata",value:e.slice(l+9,b)};u(v),l=b+3;continue}if(e.startsWith("<!DOCTYPE",l)){let b=l+9,v=!1;while(b<o){let E=e.charCodeAt(b);if(E===91)v=!0;else if(E===93)v=!1;else if(E===62&&!v)break;b++}if(b>=o)c("Unterminated doctype",l);let S=e.slice(l+9,b);if(u({type:"doctype",name:"svg",data:{doctype:S}}),S.indexOf("[")>=0){pu.lastIndex=0;let E;while((E=pu.exec(S))!=null)s[E[1]]=E[2]??E[3]??"",a=!0}l=b+1;continue}c("Unrecognised <! declaration",l)}if(h===63){let b=e.indexOf("?>",l+2);if(b<0)c("Unterminated processing instruction",l);let v=e.slice(l+2,b),S=v.search(/\s/),E=S<0?v:v.slice(0,S),C=S<0?"":v.slice(S+1);u({type:"instruction",name:E,value:C}),l=b+2;continue}if(h===47){let b=e.indexOf(">",l+2);if(b<0)c("Unterminated end tag",l);n.pop(),i=n[n.length-1],l=b+1;continue}let d=l+1,m=d;while(m<o){let b=e.charCodeAt(m);if(b===32||b===9||b===10||b===13||b===47||b===62)break;m++}if(m===d)c("Empty tag name",l);let p=e.slice(d,m),y={},g=!1;while(m<o){let b=e.charCodeAt(m);while(b===32||b===9||b===10||b===13){if(m++,m>=o)break;b=e.charCodeAt(m)}if(m>=o)c("Unterminated open tag",l);if(b===62){m++;break}if(b===47){if(e.charCodeAt(m+1)!==62)c("Expected `>` after `/`",m);g=!0,m+=2;break}let v=m;while(m<o){let F=e.charCodeAt(m);if(F===61||F===32||F===9||F===10||F===13||F===47||F===62)break;m++}let S=e.slice(v,m);while(m<o){let F=e.charCodeAt(m);if(F!==32&&F!==9&&F!==10&&F!==13)break;m++}if(e.charCodeAt(m)!==61){y[S]="";continue}m++;while(m<o){let F=e.charCodeAt(m);if(F!==32&&F!==9&&F!==10&&F!==13)break;m++}let E=e.charCodeAt(m),C;if(E===34||E===39){let F=e.indexOf(E===34?'"':"'",m+1);if(F<0)c("Unterminated attribute value",m);C=e.slice(m+1,F),m=F+1}else{let F=m;while(m<o){let R=e.charCodeAt(m);if(R===32||R===9||R===10||R===13||R===47||R===62)break;m++}C=e.slice(F,m)}y[S]=mu(C,a?s:null)}let w={type:"element",name:p,attributes:y,children:[]};if(u(w),!g)n.push(w),i=w;l=m}if(n.length>1);return r}var h2={"&":"&amp;","'":"&apos;",'"':"&quot;",">":"&gt;","<":"&lt;"};function Si(e){return h2[e]}var ot={doctypeStart:"<!DOCTYPE",doctypeEnd:">",procInstStart:"<?",procInstEnd:"?>",tagOpenStart:"<",tagOpenEnd:">",tagCloseStart:"</",tagCloseEnd:">",tagShortStart:"<",tagShortEnd:"/>",attrStart:'="',attrEnd:'"',commentStart:"<!--",commentEnd:"-->",cdataStart:"<![CDATA[",cdataEnd:"]]>",textStart:"",textEnd:"",indent:4,regEntities:/[&'"<>]/g,regValEntities:/[&"<>]/g,encodeEntity:Si,pretty:!1,useShortTags:!0,eol:"lf",finalNewline:!1};function d2(e,t={}){let r={...ot,...t},i=r.indent,n=" ";if(typeof i==="number"&&!Number.isNaN(i))n=i<0?"\t":" ".repeat(i);else if(typeof i==="string")n=i;let s={indent:n,textContext:null,indentLevel:0},a=r.eol==="crlf"?`\r
81
+ `:`
82
+ `;if(r.pretty)r.doctypeEnd+=a,r.procInstEnd+=a,r.commentEnd+=a,r.cdataEnd+=a,r.tagShortEnd+=a,r.tagOpenEnd+=a,r.tagCloseEnd+=a,r.textEnd+=a;let o=ad(e,r,s);if(r.finalNewline&&o.length>0&&!o.endsWith(`
83
+ `))o+=a;return o}function ad(e,t,r){let i="";r.indentLevel++;for(let n of e.children)switch(n.type){case"element":i+=w2(n,t,r);break;case"text":i+=S2(n,t,r);break;case"doctype":i+=m2(n,t);break;case"instruction":i+=p2(n,t);break;case"comment":i+=g2(n,t);break;case"cdata":i+=y2(n,t,r);break}return r.indentLevel--,i}function Tr(e,t){if(e.pretty&&t.textContext==null)return t.indent.repeat(t.indentLevel-1);return""}function m2(e,t){return t.doctypeStart+e.data.doctype+t.doctypeEnd}function p2(e,t){return`${t.procInstStart+e.name} ${e.value}${t.procInstEnd}`}function g2(e,t){return t.commentStart+e.value+t.commentEnd}function y2(e,t,r){return Tr(t,r)+t.cdataStart+e.value+t.cdataEnd}function w2(e,t,r){if(e.children.length===0){if(t.useShortTags)return Tr(t,r)+t.tagShortStart+e.name+Ya(e,t)+t.tagShortEnd;return Tr(t,r)+t.tagShortStart+e.name+Ya(e,t)+t.tagOpenEnd+t.tagCloseStart+e.name+t.tagCloseEnd}let{tagOpenStart:i,tagOpenEnd:n,tagCloseStart:s,tagCloseEnd:a}=t,o=Tr(t,r),l=Tr(t,r);if(r.textContext)i=ot.tagOpenStart,n=ot.tagOpenEnd,s=ot.tagCloseStart,a=ot.tagCloseEnd,o="";else if(xh.has(e.name))n=ot.tagOpenEnd,s=ot.tagCloseStart,l="",r.textContext=e;let c=ad(e,t,r);if(r.textContext===e)r.textContext=null;return o+i+e.name+Ya(e,t)+n+c+l+s+e.name+a}function b2(e){if(e.indexOf("&")<0&&e.indexOf('"')<0&&e.indexOf("<")<0&&e.indexOf(">")<0)return e;return e.replace(ot.regValEntities,Si)}function v2(e){if(e.indexOf("&")<0&&e.indexOf("'")<0&&e.indexOf('"')<0&&e.indexOf("<")<0&&e.indexOf(">")<0)return e;return e.replace(ot.regEntities,Si)}function Ya(e,t){let r="",i=t.encodeEntity===Si&&t.regValEntities===ot.regValEntities,n=e.attributes;for(let s in n){let a=n[s];if(r+=` ${s}`,a!==void 0){let o=typeof a==="string"?a:String(a),l=i?b2(o):o.replace(t.regValEntities,t.encodeEntity);r+=t.attrStart+l+t.attrEnd}}return r}function S2(e,t,r){let i=t.encodeEntity===Si&&t.regEntities===ot.regEntities?v2(e.value):e.value.replace(t.regEntities,t.encodeEntity);return Tr(t,r)+t.textStart+i+(r.textContext?"":t.textEnd)}var Us=new Map;for(let e of c2)Us.set(e.name,e);function gu(e){if(e==="removeScriptElement")return console.warn("Warning: removeScriptElement has been renamed to removeScripts, please update your config"),Us.get("removeScripts");return Us.get(e)}function x2(e){if(typeof e==="string"){let t=gu(e);if(t==null)throw Error(`Unknown builtin plugin "${e}" specified.`);return{name:e,params:{},fn:t.fn}}if(typeof e==="object"&&e!=null){let t=e;if(t.name==null)throw Error("Plugin name must be specified");let r=t.fn;if(r==null){let i=gu(t.name);if(i==null)throw Error(`Unknown builtin plugin "${t.name}" specified.`);r=i.fn}return{name:t.name,params:t.params,fn:r}}return null}function sd(e,t){if(t==null)t={};if(typeof t!=="object")throw Error("Config should be an object");let r=t.multipass?10:1,i=Number.POSITIVE_INFINITY,n="",s={multipassCount:0};if(t.path!=null)s.path=t.path;for(let a=0;a<r;a++){s.multipassCount=a;let o=f2(e,t.path),l=t.plugins||["preset-default"];if(!Array.isArray(l))throw Error("malformed config, `plugins` property must be an array.");let c=l.filter((f)=>f!=null).map(x2).filter((f)=>f!=null);if(c.length<l.length)console.warn("Warning: plugins list includes null or undefined elements, these will be ignored.");let u={};if(t.floatPrecision!=null)u.floatPrecision=t.floatPrecision;if(Gh(o,s,c,null,u),n=d2(o,t.js2svg),n.length<i)e=n,i=n.length;else break}if(t.datauri)n=rw(n,t.datauri);return{data:n}}var uS=Object.defineProperty,fS=(e)=>e;function hS(e,t){this[e]=fS.bind(null,t)}var dS=(e,t)=>{for(var r in t)uS(e,r,{get:t[r],enumerable:!0,configurable:!0,set:hS.bind(t,r)})},mS=(e,t)=>()=>(e&&(t=e(e=0)),t),cd={};dS(cd,{withErrorRecovery:()=>hd,tryLoadConfig:()=>jS,loadConfigWithResult:()=>DS,loadConfig:()=>yd,isRetryableError:()=>TS,isConfigNotFoundError:()=>MS,isBunfigError:()=>dd,globalPerformanceMonitor:()=>xi,globalCache:()=>Ir,getEnvOrDefault:()=>NS,generateConfigTypes:()=>BS,defaultGeneratedDir:()=>Ad,defaultConfigDir:()=>Cd,deepMergeWithArrayStrategy:()=>Fl,deepMerge:()=>md,createLibraryConfig:()=>IS,config:()=>LS,bunfigPlugin:()=>zS,applyEnvVarsToConfig:()=>Qr,TypeGenerationError:()=>Zs,SchemaValidationError:()=>di,PluginError:()=>Xs,PerformanceMonitor:()=>Tl,FileSystemError:()=>Js,ErrorFactory:()=>Gt,EnvVarError:()=>In,EnvProcessor:()=>oa,ConfigValidator:()=>Ol,ConfigValidationError:()=>Ys,ConfigNotFoundError:()=>Bn,ConfigMergeError:()=>Hs,ConfigLoader:()=>Rl,ConfigLoadError:()=>hi,ConfigFileLoader:()=>la,ConfigCache:()=>Ml,CacheUtils:()=>bd,BunfigError:()=>qe,BrowserConfigError:()=>Qs,ArrayMergeStrategies:()=>xd});class Ml{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 n=this.generateKey(e,r),s=i??this.options.ttl,a=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,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(!yu(e))return!0;return wu(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 n=yu(r)?wu(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},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,n)=>i+n.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 Tl{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),a=performance.now()-i;return this.recordMetric({operation:e,duration:a,timestamp:n,...r}),s}catch(s){let a=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:a,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,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 pS(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function gS(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function yS(e){return e.getStats().size*2}function Nl(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ue(t[0])&&"id"in t[0]&&t[0].id===3&&ue(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ue(t)&&ue(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(ue(e)&&"arr"in e&&Array.isArray(e.arr)&&ue(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ue(t[0])&&ue(e[0])){let i=[...t];for(let n of e)if(ue(n)&&"name"in n){if(!i.find((s)=>ue(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(ue(n)&&"path"in n){if(!i.find((s)=>ue(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>Rn(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!ue(t)||!ue(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(ue(n)&&ue(r[i]))r[i]=Nl(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&ue(n[0])&&ue(r[i][0])){let s=[...n];for(let a of r[i])if(ue(a)&&"name"in a){if(!s.find((o)=>ue(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(ue(a)&&"path"in a){if(!s.find((o)=>ue(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>Rn(o,a)))s.push(a);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let a of r[i])if(!s.includes(a))s.push(a);r[i]=s}else r[i]=n;else r[i]=n}return r}function Rn(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(!Rn(e[r],t[r]))return!1;return!0}if(ue(e)&&ue(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Rn(e[n],t[n]))return!1}return!0}return!1}function ue(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function wS(e,t){if(!ld(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 Nl(t,i)}catch{return null}}catch{return null}}async function bS({name:e="",cwd:t,defaultConfig:r}){let i=t||Gs.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let a of s)for(let o of n){let l=Fn(i,`${a}${o}`),c=await wS(l,r);if(c!==null)return c}try{let a=Fn(i,"package.json");if(ld(a)){let o=(await import(a))[e];if(o&&typeof o==="object"&&!Array.isArray(o))try{return Nl(r,o)}catch{}}}catch{}return r}function vS(e,t={}){let r=Pn.cwd();while(r.includes("storage"))r=Su(r,"..");let i=Su(r,e||"");if(t?.relative)return F2(Pn.cwd(),i);return i}async function SS(){try{let e=await bS({name:"clarity",defaultConfig:on,cwd:Pn.cwd(),endpoint:"",headers:{}});return{...on,...e}}catch{return on}}function me(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xS(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Et<"u"){let e=Et.type;if(e==="renderer"||e==="worker")return!1;return!!(Et.versions&&(Et.versions.node||Et.versions.bun))}return!1}class ud{async format(e){let t=await xS(),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:vr.pid,hostname:t(),environment:vr.env.NODE_ENV||"development",platform:vr.platform,version:vr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:vr.env.NODE_ENV||vr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Dn{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={...qs},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ud,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??Te.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 n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ln,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ln};return{...ln,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:qs.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,n=0,s=3,a=1000;while(n<s)try{try{try{await j2(this.config.logDirectory,Au.F_OK|Au.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await B2(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:It.from(e);try{if(!Qa(this.currentLogFile))await Xa(this.currentLogFile,"",{mode:420});if(i=Cu(this.currentLogFile,"a",420),L2(i,o,{flag:"a"}),$u(i),i!==void 0)Za(i),i=void 0;if((await wr(this.currentLogFile)).size===0){if(await Xa(this.currentLogFile,o,{flag:"w",mode:420}),(await wr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let c=l;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(n<s-1){let u=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=a*2**n;await new Promise((h)=>setTimeout(h,f)),n++;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{Za(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(o){if(n===s-1){let c=o,u=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let l=a*2**(n-1);await new Promise((c)=>setTimeout(c,l))}})();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 br(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 br(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return br(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(me())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],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return Ja(16).toString("hex")}generateKey(){return Ja(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=Ja(16),i=O2("aes-256-gcm",t,r),n=It.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:It.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=ku(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(It.from(It.concat(n)))),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(me())return;let e=await wr(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 n=await Bi(this.config.logDirectory),s=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,c)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await wr(r).catch(()=>null))try{if(await Eu(r,o),t.compress)try{let l=`${o}.gz`;await this.compressLogFile(o,l),await Ii(o)}catch(l){console.error("Error compressing rotated file:",l)}if(s.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Xa(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await wr(r).catch(()=>null))await Eu(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Bi(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Ii(br(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=xu(e),i=D2(t),n=ku();await I2(r,n,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()})),Qa(this.currentLogFile))try{let e=Cu(this.currentLogFile,"r+");$u(e),Za(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(!me()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Bi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ii(br(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?ce.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let l=Te.stdout.columns||120,c="";if(s==="warning"||s==="error")c=`${r} ${n}`;else if(s==="info"||s==="success")c=`${r} ${i} ${n}`;else c=`${r} ${i} ${ce.cyan(n)}`;if(!a)return c.trim();let u=o(c).trim().length,f=o(t).length,h=Math.max(1,l-2-u-f);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);if(this.fancy&&!me()){let c=vd[e],u=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:n,icon:c,tag:u,message:ce.gray(a),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:n,icon:c,tag:u,message:a,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:n,icon:c,tag:u,message:ce.green(a),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:n,icon:c,tag:u,message:a,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:n,icon:c,tag:u,message:a,level:e}),console.error(f),o){let h=o.split(`
84
+ `);for(let d of h)if(d.trim()&&!d.includes(a))console.error(this.formatConsoleMessage({timestamp:n,message:ce.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!me()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}if(!this.shouldLog(e))return;let l=`${s} ${this.environment}.${e.toUpperCase()}: ${a}
85
+ `;if(o)l+=`${o}
86
+ `;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(e){let t=performance.now();if(this.fancy&&!me()){let r=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:ce.blue("\u25D0"),tag:r,message:`${ce.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,a=new Date,o=this.formatConsoleTimestamp(a),l=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
87
+ `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!me()){let c=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:ce.green("\u2713"),tag:c,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!me())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Dn(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(me())throw Error("createReadStream is not supported in browser environments");if(!Qa(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return xu(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=It.isBuffer(e)?e:It.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),a=i.slice(16,-16),o=R2("aes-256-gcm",r,n);return o.setAuthTag(s),It.concat([o.update(a),o.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 me()}isServerMode(){return!me()}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&&!me()){let s=e.split(`
88
+ `),a=Math.max(...s.map((u)=>u.length))+2,o=`\u250C${"\u2500".repeat(a)}\u2510`,l=`\u2514${"\u2500".repeat(a)}\u2518`,c=s.map((u)=>{let f=" ".repeat(a-u.length-2);return`\u2502 ${u}${f} \u2502`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:ce.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ce.cyan(o)})),c.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:ce.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:ce.cyan(l),showTimestamp:!1}))}else if(!me())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let n=`${i} ${this.environment}.INFO: [BOX] ${e}
89
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(me())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ce.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();Te.stdin.removeListener("data",r);try{if(typeof Te.stdin.setRawMode==="function")Te.stdin.setRawMode(!1)}catch{}Te.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof Te.stdin.setRawMode==="function")Te.stdin.setRawMode(!0)}catch{}Te.stdin.resume(),Te.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 n=/%([sdijfo%])/g,s=0;if(r=e.replace(n,(a,o)=>{if(o==="%")return"%";if(s>=t.length)return a;let l=t[s++];switch(o){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 a}}),s<t.length)r+=` ${t.slice(s).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!me()){let n=this.options.showTags!==!1&&this.name?ce.gray(this.formatTag(this.name)):"",s=ce.blue("\u25D0");console.error(`${s} ${n} ${ce.cyan(r)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
90
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||me()||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,n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||me())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,i)),n!==void 0)this.activeProgressBar.message=n;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||me())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,n="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||me())return;Te.stdout.write(`${"\r".padEnd(Te.stdout.columns||80)}\r`),this.log(n,i),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||me()||!Te.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),n=e.barLength-i,s=ce.green("\u2501".repeat(i)),a=ce.gray("\u2501".repeat(n)),o=`[${s}${a}]`,l=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",u=t||r===100?ce.green("\u2713"):ce.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${ce.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${o} ${l}${c}`,d=Te.stdout.columns||80,m=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,Te.stdout.write(e.lastRenderedLine),t)Te.stdout.write(`
91
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||me()||!Te.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(me()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Bi(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 n=br(this.config.logDirectory,i);if(e.before)try{if((await wr(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 Ii(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function sn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ae(t[0])&&"id"in t[0]&&t[0].id===3&&ae(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ae(t)&&ae(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(ae(e)&&"arr"in e&&Array.isArray(e.arr)&&ae(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ae(t[0])&&ae(e[0])){let i=[...t];for(let n of e)if(ae(n)&&"name"in n){if(!i.find((s)=>ae(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(ae(n)&&"path"in n){if(!i.find((s)=>ae(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>Ln(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!ae(t)||!ae(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(ae(n)&&ae(r[i]))r[i]=sn(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&ae(n[0])&&ae(r[i][0])){let s=[...n];for(let a of r[i])if(ae(a)&&"name"in a){if(!s.find((o)=>ae(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(ae(a)&&"path"in a){if(!s.find((o)=>ae(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>Ln(o,a)))s.push(a);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let a of r[i])if(!s.includes(a))s.push(a);r[i]=s}else r[i]=n;else r[i]=n}return r}function Pl(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:sn(e,t);if(Array.isArray(e))return r==="replace"?t:sn(e,t);if(!ae(t)||!ae(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],a=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(a))if(r==="replace")i[n]=s;else i[n]=sn(a,s);else if(ae(s)&&ae(a))i[n]=Pl(a,s,r);else i[n]=s}return i}function Ln(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(!Ln(e[r],t[r]))return!1;return!0}if(ae(e)&&ae(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Ln(e[n],t[n]))return!1}return!0}return!1}function ae(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Yi(e,t,r="replace"){if(!od(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Pl(t,n,r)}catch{return null}}catch{return null}}function $S(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(a,o=[]){let l={...a};for(let[c,u]of Object.entries(a)){let f=[...o,c],h=(p)=>p.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${f.map(h).join("_")}`,m=`${i}_${f.map((p)=>p.toUpperCase()).join("_")}`;if(r)Pe.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[c]=s(u,f);else{let p=fi.env[d]||fi.env[m];if(p!==void 0){if(r)Pe.info(`Using environment variable ${p?d:m} for config ${e}.${f.join(".")}`);if(typeof u==="number")l[c]=Number(p);else if(typeof u==="boolean")l[c]=p.toLowerCase()==="true";else if(Array.isArray(u))try{let y=JSON.parse(p);if(Array.isArray(y))l[c]=y;else l[c]=p.split(",").map((g)=>g.trim())}catch{l[c]=p.split(",").map((y)=>y.trim())}else l[c]=p}}}return l}return s(n)}async function CS({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:a=!0,arrayStrategy:o="replace"}){let l=a&&typeof n==="object"&&n!==null&&!Array.isArray(n)?$S(e,n,s):n,c=r||fi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Pe.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${c}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],m=t?[`${t}.config`,`.${t}.config`]:[],p=Array.from(new Set([c,Le(c,"config"),Le(c,".config"),i?Le(c,i):void 0].filter(Boolean)));for(let y of p){if(s)Pe.info(`Searching for configuration in: ${y}`);let g=[Le(c,"config"),Le(c,".config")].concat(i?[Le(c,i)]:[]).includes(y)?[...f,...h,...d,...m]:[...h,...f,...m,...d];for(let w of g)for(let b of u){let v=Le(y,`${w}${b}`),S=await Yi(v,l,o);if(S!==null){if(s)Pe.success(`Configuration loaded from: ${v}`);return S}}}if(e){let y=Le(Ha(),".config",e),g=["config",`${e}.config`];if(t)g.push(`${t}.config`);if(s)Pe.info(`Checking user config directory: ${y}`);for(let w of g)for(let b of u){let v=Le(y,`${w}${b}`),S=await Yi(v,l,o);if(S!==null){if(s)Pe.success(`Configuration loaded from user config directory: ${v}`);return S}}}if(e){let y=Le(Ha(),".config"),g=[`.${e}.config`];if(t)g.push(`.${t}.config`);if(s)Pe.info(`Checking user config directory for dotfile configs: ${y}`);for(let w of g)for(let b of u){let v=Le(y,`${w}${b}`),S=await Yi(v,l,o);if(S!==null){if(s)Pe.success(`Configuration loaded from user config directory dotfile: ${v}`);return S}}}if(e){let y=Ha(),g=[`.${e}.config`,`.${e}`];if(t)g.push(`.${t}.config`),g.push(`.${t}`);if(s)Pe.info(`Checking user home directory for dotfile configs: ${y}`);for(let w of g)for(let b of u){let v=Le(y,`${w}${b}`),S=await Yi(v,l,o);if(S!==null){if(s)Pe.success(`Configuration loaded from user home directory: ${v}`);return S}}}try{let y=Le(c,"package.json");if(od(y)){let g=await import(y),w=g[e];if(!w&&t){if(w=g[t],w&&s)Pe.success(`Using alias "${t}" configuration from package.json`)}if(w&&typeof w==="object"&&!Array.isArray(w))try{if(s)Pe.success(`Configuration loaded from package.json: ${w===g[e]?e:t}`);return Pl(l,w,o)}catch(b){if(s)Pe.warn("Failed to merge package.json config:",b)}}}catch(y){if(s)Pe.warn("Failed to load package.json:",y)}if(s)Pe.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return l}function AS(e,t={}){let r=Nn.cwd();while(r.includes("storage"))r=vu(r,"..");let i=vu(r,e||"");if(t?.relative)return N2(Nn.cwd(),i);return i}async function ES(){try{let e=await CS({name:"clarity",alias:"logging",defaultConfig:cn,cwd:Nn.cwd()});return{...cn,...e||{}}}catch{return cn}}function Se(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function kS(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof kt<"u"){let e=kt.type;if(e==="renderer"||e==="worker")return!1;return!!(kt.versions&&(kt.versions.node||kt.versions.bun))}return!1}class fd{async format(e){let t=await kS(),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:$r.pid,hostname:t(),environment:$r.env.NODE_ENV||"development",platform:$r.platform,version:$r.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$r.env.NODE_ENV||$r.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class jn{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={...Ks},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new fd,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??ie.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 n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,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{...un,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...un};return{...un,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ks.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!Se()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await G2(this.config.logDirectory,Pu.F_OK|Pu.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await W2(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:St.from(e);try{if(!zi(this.currentLogFile))await rs(this.currentLogFile,"",{mode:420});if(i=Nu(this.currentLogFile,"a",420),V2(i,o,{flag:"a"}),Tu(i),i!==void 0)ts(i),i=void 0;if((await Sr(this.currentLogFile)).size===0){if(await rs(this.currentLogFile,o,{flag:"w",mode:420}),(await Sr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let c=l;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(n<s-1){let u=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=a*2**n;await new Promise((h)=>setTimeout(h,f)),n++;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{ts(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(o){if(n===s-1){let c=o,u=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let l=a*2**(n-1);await new Promise((c)=>setTimeout(c,l))}})();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 xr(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 xr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return xr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Se())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],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return es(16).toString("hex")}generateKey(){return es(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=es(16),i=z2("aes-256-gcm",t,r),n=St.isBuffer(e)?e:St.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,l=i.getAuthTag(),c=St.allocUnsafe(16+o+16);return r.copy(c,0),s.copy(c,16),a.copy(c,16+s.length),l.copy(c,16+o),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Ou(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(St.from(St.concat(n)))),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(Se())return;if(!this.shouldWriteToFile())return;let e=await Sr(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 n=await _i(this.config.logDirectory),s=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,c)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Sr(r).catch(()=>null))try{if(await Fu(r,o),t.compress)try{let l=`${o}.gz`;await this.compressLogFile(o,l),await Ui(o)}catch(l){console.error("Error compressing rotated file:",l)}if(s.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await rs(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Sr(r).catch(()=>null))await Fu(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await _i(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Ui(xr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Mu(e),i=U2(t),n=Ou();await Y2(r,n,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()})),zi(this.currentLogFile))try{let e=Nu(this.currentLogFile,"r+");Tu(e),ts(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(!Se()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await _i(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ui(xr(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()?Z.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Se())return!1;let e=typeof ie.env.NO_COLOR<"u",t=ie.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ie.stderr<"u"&&ie.stderr.isTTY||typeof ie.stdout<"u"&&ie.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let l=ie.stdout.columns||120,c="";if(s==="warning"||s==="error")c=`${r} ${n}`;else if(s==="info"||s==="success")c=`${r} ${i} ${n}`;else c=`${r} ${i} ${Z.cyan(n)}`;if(!a)return c.trim();let u=o(c).trim().length,f=o(t).length,h=Math.max(1,l-2-u-f);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=Z.underline(Z.blue(i)),a=this.toAbsoluteFilePath(n);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,l="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${o}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>Z.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>Z.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>Z.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>Z.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>Z.strikethrough(i)),t}supportsHyperlinks(){if(Se())return!1;let e=ie.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=ie.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(q2(t)||t.startsWith("./")||t.startsWith("../"))t=K2(t);else return null;return zi(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,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:l,fileText:c}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Sd[e],h=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:Z.gray(l),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:Z.green(l),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.error(d),o){let m=o.split(`
92
+ `);for(let p of m)if(p.trim()&&!p.includes(a))console.error(this.formatConsoleMessage({timestamp:n,message:Z.gray(` ${p}`),level:e,showTimestamp:!1}))}break}}else if(!Se()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${c}
93
+ `;if(o)u+=`${o}
94
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};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()&&!Se()&&ie.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!Se()&&ie.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!Se()&&ie.stdout.isTTY)ie.stdout.write(`
95
+ `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!Se()&&ie.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":Z.blue("\u25D0"),tag:r,message:`${Z.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,a=new Date,o=this.formatConsoleTimestamp(a),l=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
96
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":Z.green("\u2713"),tag:c,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Se())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new jn(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(Se())throw Error("createReadStream is not supported in browser environments");if(!zi(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Mu(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=St.isBuffer(e)?e:St.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),a=i.subarray(16,i.length-16),o=_2("aes-256-gcm",r,n);o.setAuthTag(s);let l=o.update(a),c=o.final(),u=l.length+c.length,f=St.allocUnsafe(u);return l.copy(f,0),c.copy(f,l.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 Se()}isServerMode(){return!Se()}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:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let o=n.split(`
97
+ `),l=Math.max(...o.map((h)=>h.length))+2,c=`\u250C${"\u2500".repeat(l)}\u2510`,u=`\u2514${"\u2500".repeat(l)}\u2518`,f=o.map((h)=>this.formatConsoleMessage({timestamp:r,message:Z.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(c),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(u),showTimestamp:!1}))}else if(!Se())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let a=`${i} ${this.environment}.INFO: [BOX] ${s}
98
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if(Se())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Z.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();ie.stdin.removeListener("data",r);try{if(typeof ie.stdin.setRawMode==="function")ie.stdin.setRawMode(!1)}catch{}ie.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof ie.stdin.setRawMode==="function")ie.stdin.setRawMode(!0)}catch{}ie.stdin.resume(),ie.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,o=0;if(r=e.replace(a,(l,c)=>{if(c==="%")return"%";if(o>=t.length)return l;let u=t[o++];switch(c){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),o<t.length)r+=` ${t.slice(o).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${Z.blue("\u25D0")} `;console.error(`${o}${a} ${Z.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
99
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ie.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),n=e.barLength-i,s=Z.green("\u2501".repeat(i)),a=Z.gray("\u2501".repeat(n)),o=`[${s}${a}]`,l=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?Z.green("\u2713"):Z.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${Z.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${o} ${l}${c}`,d=ie.stdout.columns||80,m=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,ie.stdout.write(e.lastRenderedLine),t)ie.stdout.write(`
100
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Se()||!ie.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(Se()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await _i(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 n=xr(this.config.logDirectory,i);if(e.before)try{if((await Sr(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 Ui(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function hd(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,a=Error("Unknown error occurred");for(let o=0;o<=r;o++)try{return await e()}catch(l){if(a=l instanceof Error?l:Error(String(l)),o===r||!n(a))break;if(i>0)await new Promise((c)=>setTimeout(c,i))}if(s!==void 0)return s;throw a instanceof Error?a:Error(`Unknown error: ${String(a)}`)}function dd(e){return e instanceof qe}function MS(e){return e instanceof Bn}function TS(e){if(dd(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 oa{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:n=!0,useBackwardCompatibility:s=!0,customParsers:a={},verbose:o=!1,trackPerformance:l=!0}=r,c=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:a,verbose:o,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return xi.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[n,s]of Object.entries(e)){let a=[...t,n],o=a.map((u)=>this.formatEnvKey(u,i.useCamelCase)),l=`${r}_${o.join("_")}`,c=i.useBackwardCompatibility?`${r}_${a.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,a,r,i);else{let u=Vi.env[l]||(c?Vi.env[c]:void 0);if(u!==void 0){if(i.verbose){let f=Vi.env[l]?l:c}try{e[n]=this.parseEnvironmentValue(u,typeof s,l,i.customParsers,i.configName)}catch(f){if(f instanceof In)throw f;throw Gt.envVar(l,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,a]of Object.entries(i))try{return a(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Gt.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(Vi.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;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(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),a=[];switch(this.extractEnvVarInfo(t,[],s,a),n){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[n,s]of Object.entries(e)){let a=[...t,n],o=`${r}_${a.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,a,r,i);else i.push({key:o,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${a.join(".")}`,example:this.generateExample(s)})}}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}:
101
+
102
+ `;for(let i of e)r+=`${i.key}
103
+ `,r+=` Type: ${i.type}
104
+ `,r+=` Description: ${i.description}
105
+ `,r+=` Example: ${i.example}
106
+
107
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
108
+
109
+ `;r+=`| Variable | Type | Description | Example |
110
+ `,r+=`|----------|------|-------------|----------|
111
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
112
+ `;return r}}function NS(e,t){let r=wd("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function md(e,t,r={}){return pd(e,t,r,new WeakMap)}function pd(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:a}=r;if(t===null||t===void 0)return s?e:t;if(a){let o=a(e,t);if(o!==void 0)return o}if(Array.isArray(t)||Array.isArray(e))return gd(e,t,n,i);if(!Xe(t)||!Xe(e))return t;return RS(e,t,r,i)}function gd(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 PS(e,t);case"smart":return FS(e,t,i);default:return t}return t}function PS(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Ws(n,i)))r.push(i);return r}function FS(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Xe(t[0])&&Xe(e[0]))return OS(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function OS(e,t,r){let i=[...t];for(let n of e){if(!Xe(n)){i.push(n);continue}let s=["id","name","key","path","type"],a=!1;for(let o of s)if(o in n){if(i.find((l)=>Xe(l)&&(o in l)&&l[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function RS(e,t,r,i){let n=t;if(Xe(n)&&i.has(n))return i.get(n);let s={...e};if(Xe(n))i.set(n,s);for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;let o=n[a],l=s[a];if(r.skipNullish&&(o===null||o===void 0))continue;if(o===null||o===void 0){s[a]=o;continue}if(Xe(o)&&Xe(l))s[a]=pd(l,o,r,i);else if(Array.isArray(o)||Array.isArray(l))s[a]=gd(l,o,r.arrayMergeMode||"smart",i);else s[a]=o}return s}function Fl(e,t,r="replace"){return md(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Ws(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(!Ws(e[r],t[r]))return!1;return!0}if(Xe(e)&&Xe(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Ws(e[n],t[n]))return!1}return!0}return!1}function Xe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class la{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:a=!0,verbose:o=!1}=r;if(n){let c=Ir.getWithFileCheck("file",e);if(c){if(o)console.log(`Configuration loaded from cache: ${e}`);return c}}let l=async()=>{if(!Gi(e))return null;try{let c=`?t=${Date.now()}`,u=await import(e+c),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new hi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new hi(e,Error("Configuration must export a valid object"),"unknown");let m={config:Fl(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Ir.setWithFileCheck("file",m,e,s);return m}catch(c){throw c instanceof Error?Gt.configLoad(e,c):Gt.configLoad(e,Error(String(c)))}};if(a)return xi.track("loadFromPath",l,{path:e});return l()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let a of this.extensions)n.push(is(t,`${s}${a}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return hd(async()=>Gi(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Gi(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let a of this.extensions){let o=is(e,`${s}${a}`);if(await this.checkFileAccess(o))i.push(o)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let a of s)if(this.looksLikeConfigFile(a)){let o=is(e,a);if(await this.checkFileAccess(o))i.push(o)}}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(!Gi(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:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Ol{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:a=[],trackPerformance:o=!0,verbose:l=!1}=r,c=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:a,trackPerformance:o,verbose:l};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...a],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(o)return await xi.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!H2(t))throw new di(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new di(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let a=Array.isArray(e)?"array":typeof e,o=Array.isArray(t.type)?t.type:[t.type];if(!o.includes(a)){if(i.push({path:r,message:`Expected type ${o.join(" or ")}, got ${a}`,expected:o.join(" or "),actual:a,rule:"type"}),s.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"}),s.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 o=r?`${r}[${a}]`:`[${a}]`;if(this.validateObjectAgainstSchema(e[a],t.items,o,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let a=e;if(s.validateRequired&&t.required){for(let o of t.required)if(!(o in a)){if(i.push({path:r?`${r}.${o}`:o,message:`Missing required property '${o}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[o,l]of Object.entries(t.properties))if(o in a){let c=r?`${r}.${o}`:o;if(this.validateObjectAgainstSchema(a[o],l,c,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let o=new Set(Object.keys(t.properties||{}));for(let l of Object.keys(a))if(!o.has(l))n.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let a=this.getValueByPath(e,s.path),o=this.validateWithRule(a,s,s.path);if(i.push(...o),r.stopOnFirstError&&i.length>0)break}catch(a){i.push({path:s.path,message:`Rule validation failed: ${a}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}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 n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))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 n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,a]=i;t.push({path:n,required:!s,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:$d},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Rl{fileLoader=new la;envProcessor=new oa;validator=new Ol;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...a}=e;try{if(r?.enabled){let l=this.checkCache(a.name||"",a);if(l)return l}let o;try{o=await this.loadConfigurationStrategies(a,!0,r)}catch(l){let c=a.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(c)throw l;o={...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(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),f=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),h=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(c&&(h||u))throw l;if(f&&(!c||!h))o={...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)o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else o={...await this.applyEnvironmentVariables(a.name||"",a.defaultConfig,a.checkEnv!==!1,a.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(n||s)await this.validateConfiguration(o.config,n,s,a.name);if(r?.enabled&&o)this.cacheResult(a.name||"",o,r,a);if(i?.enabled){let l={operation:"loadConfig",duration:Date.now()-t,configName:a.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(l);if(i.slowThreshold&&l.duration>i.slowThreshold)nt.warn(`Slow configuration loading detected: ${l.duration}ms for ${a.name}`);o.metrics=l}return o}catch(o){let l=Date.now()-t;throw nt.error(`Configuration loading failed after ${l}ms:`,[o instanceof Error?o:Error(String(o))]),o}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:a,defaultConfig:o,checkEnv:l=!0,arrayStrategy:c="replace",verbose:u=!1}=e,f=s||rr.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,a,o,c,u,l,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,a)),this.finalizeResult(d,h,l,i,u);let m=await this.loadHomeConfiguration(i,n,o,c,u,l);if(m)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(m,h,l,i,u);let p=await this.loadPackageJsonConfiguration(i,n,f,o,c,u,l);if(p)return h.push(Ie(f,"package.json")),this.finalizeResult(p,h,l,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,a)),t)throw Gt.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,o,l,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,l){let c=o?Qr(e,n,a):n,u=this.getLocalDirectories(r,i);for(let f of u){if(a)nt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:s,verbose:a,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(d){if(a)nt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let a=s?Qr(e,r,n):r,o=[Ie(yr(),".config",e),Ie(yr(),".config"),yr()];for(let l of o){if(n)nt.info(`Checking home directory: ${l}`);let c=this.fileLoader.generateConfigPaths(e,l,t),u=await this.fileLoader.tryLoadFromPaths(c,a,{arrayStrategy:i,verbose:n});if(u){if(n)nt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,a){let o=a?Qr(e,i,s):i;try{let l=Ie(r,"package.json");if(!Vs(l))return null;let c=await import(l),u=c[e],f=e;if(!u&&t)u=c[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)nt.success(`Configuration loaded from package.json: ${f}`);return{config:Fl(o,u,n),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(s)nt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}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:Qr(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((a)=>a.path?`${a.path}: ${a.message}`:a.message))}if(n.length>0)throw Gt.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Ir.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Ir.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ie(e,"config"),Ie(e,".config"),t?Ie(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Ie(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let a of n)s.push(...this.fileLoader.generateConfigPaths(e,a,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ie(yr(),".config",e),Ie(yr(),".config"),yr()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Uu(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 DS(e){return Ft.loadConfig({...e,__strictErrorHandling:!0})}async function yd(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 Ft.loadConfig(e);else i=await Ft.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)nt.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 Ft.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function LS(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Ft.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"&&Uu(r)))return(await Ft.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Ft.loadConfig({...e,cwd:e.cwd||rr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Uu(t)))return(await Ft.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function jS(e,t,r="replace"){let i=new la;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Qr(e,t,r=!1){let i=new oa,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(a,o=[]){let l={...a};for(let[c,u]of Object.entries(a)){let f=[...o,c],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((p)=>p.toUpperCase()).join("")}`,`${n}_${f.map((p)=>p.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,m;for(let p of h)if(d=rr.env[p],d!==void 0){m=p;break}if(d!==void 0&&m)if(typeof u==="boolean")l[c]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let p=Number(d);if(!Number.isNaN(p))l[c]=p}else if(Array.isArray(u))try{l[c]=JSON.parse(d)}catch{l[c]=d.split(",").map((p)=>p.trim())}else l[c]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))l[c]=s(u,f)}return l}return s(t)}function BS(e){let t=Ie(rr.cwd(),e.configDir),r=Ie(rr.cwd(),e.generatedDir),i=Ie(r,"config-types.ts");if(!Vs(bu(i)))E2(bu(i),{recursive:!0,mode:511});let n=Vs(t)?k2(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${dx}
113
+ export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
114
+ `;M2(i,s,{mode:438})}function IS(e){let t=null,r=null,i=()=>{if(!r)r=yd(e).then((s)=>(t=s,s),(s)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)nt.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return a});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,a){if(t)return t[a];let o=n[a];return i(),o},has(s,a){return a in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,a){return Object.getOwnPropertyDescriptor(t||n,a)},set(s,a,o){if(!t)t={...n};return t[a]=o,!0}})}function zS(e){let t=Ru(Q2.cwd(),e?.configDir||"./config");function r(){if(!J2(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=Z2(t).filter((l)=>n.has(ns(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),o=new Map;for(let{base:l,file:c}of a){let u=ns(c).toLowerCase(),f=o.get(l);if(!f){o.set(l,c);continue}let h=ns(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))o.set(l,c)}return Array.from(o.entries()).map(([l,c])=>({base:l,file:c})).sort((l,c)=>l.base.localeCompare(c.base))}function i(){let n=r(),s=n.map((l)=>l.base),a=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",o=n.length?`{
115
+ ${n.map((l)=>{let c=Ru(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${c}').default`}).join(`,
116
+ `)}
117
+ }`:"Record<string, any>";return`export type ConfigNames = ${a}
118
+ export type ConfigByName = ${o}
119
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
120
+ export type ConfigOf = Config
121
+ `}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var wd,Ir,xi,bd,_S,US,Vu,on,qs,Ne,ce,VS,Gu,GS,Wu,WS,qS,ls,KS,qu,Ku,cs,YS,HS,JS,ZS,ln,vd,QS,Pe,XS,ex,Yu,cn,Ks,xe,Z,tx,Hu,rx,Ju,ix,nx,us,ax,Zu,Qu,sx,fs,ox,lx,cx,ux,fx,un,Sd,hx,dx="0.15.6",qe,Bn,hi,Ys,Hs,In,Js,Zs,di,Qs,Xs,Gt,xd,$d,nt,Ft,Cd,Ad,mx=mS(async()=>{wd=import.meta.require,Ir=new Ml,xi=new Tl,bd={createKey:pS,isEquivalent:gS,estimateMemoryUsage:yS},_S=Fn(Gs.cwd(),"config"),US=Fn(Gs.cwd(),"src/generated"),Vu=Pn.env.CLARITY_LOG_DIR||P2(vS(),"logs"),on={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Vu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},qs=await SS(),Ne={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"},ce=Ne,VS=Ne.red,Gu=Ne.green,GS=Ne.yellow,Wu=Ne.blue,WS=Ne.magenta,qS=Ne.cyan,ls=Ne.white,KS=Ne.gray,qu=Ne.bgRed,Ku=Ne.bgYellow,cs=Ne.bold,YS=Ne.dim,HS=Ne.italic,JS=Ne.underline,ZS=Ne.reset,ln={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},vd={debug:"\uD83D\uDD0D",info:Wu("\u2139"),success:Gu("\u2713"),warning:Ku(ls(cs(" WARN "))),error:qu(ls(cs(" ERROR ")))},QS=new Dn("stacks"),Pe=new Dn("bunfig",{showTags:!0}),XS=Le(fi.cwd(),"config"),ex=Le(fi.cwd(),"src/generated"),Yu=Nn.env.CLARITY_LOG_DIR||T2(AS(),"logs"),cn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Yu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ks=await ES(),xe={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"},Z=xe,tx=xe.red,Hu=xe.green,rx=xe.yellow,Ju=xe.blue,ix=xe.magenta,nx=xe.cyan,us=xe.white,ax=xe.gray,Zu=xe.bgRed,Qu=xe.bgYellow,sx=xe.bgGray,fs=xe.bold,ox=xe.dim,lx=xe.italic,cx=xe.underline,ux=xe.strikethrough,fx=xe.reset,un={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Sd={debug:"\uD83D\uDD0D",info:Ju("\u2139"),success:Hu("\u2713"),warning:Qu(us(fs(" WARN "))),error:Zu(us(fs(" ERROR ")))},hx=new jn("stacks"),qe=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}`}},Bn=class extends qe{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})}},hi=class extends qe{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}},Ys=class extends qe{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Hs=class extends qe{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}},In=class extends qe{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})}},Js=class extends qe{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}},Zs=class extends qe{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}},di=class extends qe{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})}},Qs=class extends qe{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})}},Xs=class extends qe{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}},Gt={configNotFound(e,t,r){return new Bn(e,t,r)},configLoad(e,t,r){return new hi(e,t,r)},configValidation(e,t,r){return new Ys(e,t,r)},configMerge(e,t,r,i){return new Hs(e,t,r,i)},envVar(e,t,r,i){return new In(e,t,r,i)},fileSystem(e,t,r){return new Js(e,t,r)},typeGeneration(e,t,r){return new Zs(e,t,r)},schemaValidation(e,t,r){return new di(e,t,r)},browserConfig(e,t,r,i){return new Qs(e,t,r,i)},plugin(e,t,r){return new Xs(e,t,r)}},xd={replace:"replace",concat:"concat",smart:"smart"},$d=/^https?:\/\//,nt=new jn("bunfig",{showTags:!0}),Ft=new Rl,Cd=Ie(rr.cwd(),"config"),Ad=Ie(rr.cwd(),"src/generated")});function px(e,t={}){let r=On.cwd();while(r.includes("storage"))r=Du(r,"..");let i=Du(r,e||"");if(t?.relative)return eS(On.cwd(),i);return i}var gx=On.env.CLARITY_LOG_DIR||X2(px(),"logs"),Ed={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gx,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},zn={...Ed},pE=(async()=>{try{let{loadConfig:e}=await mx().then(()=>cd),t=await e({name:"clarity",alias:"logging",defaultConfig:Ed,cwd:On.cwd()});if(t)Object.assign(zn,t)}catch{}return zn})();function $e(){if(Mt.env.NODE_ENV==="test"||Mt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function yx(){if(Mt.env.NODE_ENV==="test"||Mt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Mt<"u"){let e=Mt.type;if(e==="renderer"||e==="worker")return!1;return!!(Mt.versions&&(Mt.versions.node||Mt.versions.bun))}return!1}class kd{async format(e){let t=await yx(),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:Er.pid,hostname:t(),environment:Er.env.NODE_ENV||"development",platform:Er.platform,version:Er.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Er.env.NODE_ENV||Er.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ke={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"},Q=ke,gE=ke.red,wx=ke.green,yE=ke.yellow,bx=ke.blue,wE=ke.magenta,bE=ke.cyan,Xu=ke.white,vE=ke.gray,vx=ke.bgRed,Sx=ke.bgYellow,SE=ke.bgGray,ef=ke.bold,xE=ke.dim,$E=ke.italic,CE=ke.underline,AE=ke.strikethrough,EE=ke.reset,hs={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xx={debug:"\uD83D\uDD0D",info:bx("\u2139"),success:wx("\u2713"),warning:Sx(Xu(ef(" WARN "))),error:vx(Xu(ef(" ERROR ")))};class ca{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={...zn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new kd,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??ne.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 n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,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{...hs,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...hs};return{...hs,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:zn.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!$e()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,a=1000;while(n<s)try{try{try{await aS(this.config.logDirectory,Iu.F_OK|Iu.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await sS(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let o=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:xt.from(e);try{if(!Wi(this.currentLogFile))await os(this.currentLogFile,"",{mode:420});if(i=Bu(this.currentLogFile,"a",420),nS(i,o,{flag:"a"}),ju(i),i!==void 0)ss(i),i=void 0;if((await Cr(this.currentLogFile)).size===0){if(await os(this.currentLogFile,o,{flag:"w",mode:420}),(await Cr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let c=l;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(n<s-1){let u=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=a*2**n;await new Promise((h)=>setTimeout(h,f)),n++;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{ss(i)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(o){if(n===s-1){let c=o,u=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),o}n++;let l=a*2**(n-1);await new Promise((c)=>setTimeout(c,l))}})();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 Ar(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 Ar(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ar(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if($e())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],[,o])=>o.createdAt.getTime()-a.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[a]of i.slice(s))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return as(16).toString("hex")}generateKey(){return as(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=as(16),i=tS("aes-256-gcm",t,r),n=xt.isBuffer(e)?e:xt.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,l=i.getAuthTag(),c=xt.allocUnsafe(16+o+16);return r.copy(c,0),s.copy(c,16),a.copy(c,16+s.length),l.copy(c,16+o),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=_u(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(xt.from(xt.concat(n)))),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($e())return;if(!this.shouldWriteToFile())return;let e=await Cr(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 n=await qi(this.config.logDirectory),s=n.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,c)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),a=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,o=`${r}.${a}`;if(await Cr(r).catch(()=>null))try{if(await zu(r,o),t.compress)try{let l=`${o}.gz`;await this.compressLogFile(o,l),await Ki(o)}catch(l){console.error("Error compressing rotated file:",l)}if(s.length===0&&!n.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await os(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Cr(r).catch(()=>null))await zu(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await qi(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Ki(Ar(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Lu(e),i=iS(t),n=_u();await cS(r,n,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()})),Wi(this.currentLogFile))try{let e=Bu(this.currentLogFile,"r+");ju(e),ss(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(!$e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await qi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ki(Ar(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()?Q.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||$e())return!1;let e=typeof ne.env.NO_COLOR<"u",t=ne.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ne.stderr<"u"&&ne.stderr.isTTY||typeof ne.stdout<"u"&&ne.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:a=!0}=e,o=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(a)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let l=ne.stdout.columns||120,c="";if(s==="warning"||s==="error")c=`${r} ${n}`;else if(s==="info"||s==="success")c=`${r} ${i} ${n}`;else c=`${r} ${i} ${Q.cyan(n)}`;if(!a)return c.trim();let u=o(c).trim().length,f=o(t).length,h=Math.max(1,l-2-u-f);return`${c.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,a)=>{let o=Number.parseInt(a,10);return o<t[0].length?String(t[0][o]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,a)=>{if(a==="%")return"%";if(i>=t.length)return s;let o=t[i++];switch(a){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 s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=Q.underline(Q.blue(i)),a=this.toAbsoluteFilePath(n);if(a&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let o=`file://${encodeURI(a)}`,l="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${o}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>Q.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>Q.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>Q.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>Q.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>Q.strikethrough(i)),t}supportsHyperlinks(){if($e())return!1;let e=ne.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=ne.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(oS(t)||t.startsWith("./")||t.startsWith("../"))t=lS(t);else return null;return Wi(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,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),a,o;if(t instanceof Error)a=t.message,o=t.stack;else a=this.formatMessage(t,r);let{consoleText:l,fileText:c}=this.buildOutputTexts(a);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":xx[e],h=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:Q.gray(l),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:Q.green(l),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:l,level:e}),console.error(d),o){let m=o.split(`
122
+ `);for(let p of m)if(p.trim()&&!p.includes(a))console.error(this.formatConsoleMessage({timestamp:n,message:Q.gray(` ${p}`),level:e,showTimestamp:!1}))}break}}else if(!$e()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${a}`),o)console.error(o)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${c}
123
+ `;if(o)u+=`${o}
124
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};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()&&!$e()&&ne.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!$e()&&ne.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!$e()&&ne.stdout.isTTY)ne.stdout.write(`
125
+ `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!$e()&&ne.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":Q.blue("\u25D0"),tag:r,message:`${Q.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,a=new Date,o=this.formatConsoleTimestamp(a),l=`${this.formatFileTimestamp(a)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
126
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":Q.green("\u2713"),tag:c,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!$e())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ca(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($e())throw Error("createReadStream is not supported in browser environments");if(!Wi(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Lu(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=xt.isBuffer(e)?e:xt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),a=i.subarray(16,i.length-16),o=rS("aes-256-gcm",r,n);o.setAuthTag(s);let l=o.update(a),c=o.final(),u=l.length+c.length,f=xt.allocUnsafe(u);return l.copy(f,0),c.copy(f,l.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 $e()}isServerMode(){return!$e()}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:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let o=n.split(`
127
+ `),l=Math.max(...o.map((h)=>h.length))+2,c=`\u250C${"\u2500".repeat(l)}\u2510`,u=`\u2514${"\u2500".repeat(l)}\u2518`,f=o.map((h)=>this.formatConsoleMessage({timestamp:r,message:Q.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Q.cyan(c),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:Q.cyan(u),showTimestamp:!1}))}else if(!$e())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let a=`${i} ${this.environment}.INFO: [BOX] ${s}
128
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}async prompt(e){if($e())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Q.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();ne.stdin.removeListener("data",r);try{if(typeof ne.stdin.setRawMode==="function")ne.stdin.setRawMode(!1)}catch{}ne.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof ne.stdin.setRawMode==="function")ne.stdin.setRawMode(!0)}catch{}ne.stdin.resume(),ne.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,o=0;if(r=e.replace(a,(l,c)=>{if(c==="%")return"%";if(o>=t.length)return l;let u=t[o++];switch(c){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),o<t.length)r+=` ${t.slice(o).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${Q.blue("\u25D0")} `;console.error(`${o}${a} ${Q.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
129
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!ne.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),n=e.barLength-i,s=Q.green("\u2501".repeat(i)),a=Q.gray("\u2501".repeat(n)),o=`[${s}${a}]`,l=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?Q.green("\u2713"):Q.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${Q.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${o} ${l}${c}`,d=ne.stdout.columns||80,m=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,ne.stdout.write(e.lastRenderedLine),t)ne.stdout.write(`
130
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||$e()||!ne.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($e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await qi(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 n=Ar(this.config.logDirectory,i);if(e.before)try{if((await Cr(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 Ki(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var kE=new ca("stacks"),Pr=new ca("imgx",{showTags:!1});async function Md(e,t={}){let{patterns:r=["**/*.{jpg,jpeg,png,webp,avif,svg}"],ignore:i=["**/node_modules/**"],maxDepth:n,...s}=t;try{if(!(await $2(e)).isDirectory())return[A2(e)];let a=new Set;for(let o of r){let l=new Bun.Glob(o);for await(let c of l.scan({...s,cwd:e,absolute:!0,onlyFiles:!0}))a.add(c)}if(i.length>0)for(let o of i){let l=new Bun.Glob(o);for await(let c of l.scan({...s,cwd:e,absolute:!0,onlyFiles:!0}))a.delete(c)}if(typeof n==="number")return Array.from(a).filter((o)=>C2(e,o).split("/").filter(Boolean).length<=n);return Array.from(a)}catch(a){let o=a instanceof Error?a.message:String(a);throw Error(`Failed to get files: ${o}`)}}async function $x(e,t,r,i={}){let n=await Md(e,{...i,patterns:t}),s=new AbortController;for(let a of n)q("watch",`Would watch file: ${a}`,!0);return()=>s.abort()}function Cx(e,t){return t.some((r)=>new Bun.Glob(r).match(e))}function Ax(e,t,r=[]){return e.filter((i)=>t.some((n)=>new Bun.Glob(n).match(i))&&!r.some((n)=>new Bun.Glob(n).match(i)))}function q(e,t,r){if(r===!1)return;if(r===!0||N.verbose===!0)Pr.debug(`[imgx:${e}] ${t}`);if(Array.isArray(r)){if(r.some((i)=>e.startsWith(i)))Pr.info(`[imgx:${e}] ${t}`)}if(Array.isArray(N.verbose)){if(N.verbose.some((i)=>e.startsWith(i)))Pr.debug(`[imgx:${e}] ${t}`)}}function Ex(e){let t={b:1,kb:1024,mb:1048576,gb:1073741824},r=e.toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)$/);if(!r)throw Error(`Invalid file size format: ${e}`);let[,i,n]=r;return Number.parseFloat(i)*t[n]}function fn(e){let t=["B","KB","MB","GB"],r=e,i=0;while(r>=1024&&i<t.length-1)r/=1024,i++;return`${r.toFixed(2)} ${t[i]}`}function kx(e){let t=e.filter(Boolean),r=e.filter((i)=>i?.error);if(t.length>0){let i=t.reduce((o,l)=>o+l.inputSize,0),n=t.reduce((o,l)=>o+l.outputSize,0),s=i-n,a=s/i*100;Pr.box(`
131
+ Successfully processed ${t.length} files:
132
+ - Total input size: ${fn(i)}
133
+ - Total output size: ${fn(n)}
134
+ - Total saved: ${fn(s)} (${a.toFixed(2)}%)
135
+ `)}if(r.length>0)Pr.error(`
136
+ Failed to process ${r.length} files:`),r.forEach((i)=>{Pr.error(`- ${i?.inputPath}: ${i?.error?.message}`)})}function Mx(e){if(typeof e==="string"){let t=e.match(/^(\d+)%$/);if(t){let r=Number.parseInt(t[1],10);return{width:r,height:r}}return null}return e}async function Wt(e){let t=ff(e);await uf(t,{recursive:!0})}async function qt(e){let t,r;if(typeof e==="string")t=new Uint8Array(await pi(e)),r=(await ut(e)).size;else t=new Uint8Array(e),r=e.length;return{imageData:await Re(t),originalSize:r}}async function ir(e,t,r,i={}){let n=await tt(e,t,i);if(r)await Wt(r),await Xt(r,n);return n}async function eo(e){let{input:t,output:r,quality:i=80,resize:n,format:s,progressive:a=!0}=e;q("process",`Processing image with options: ${JSON.stringify(e)}`);try{let{imageData:o,originalSize:l}=await qt(t),c=o;if(n){let m=Mx(n);if(m)c=Ee(c,{width:m.width,height:m.height})}let u=s||Vr(typeof t==="string"?new Uint8Array(await pi(t)):new Uint8Array(t))||"png",f=(await ir(c,u,r,{quality:i,progressive:a})).length,h=l-f,d=h/l*100;return q("process",`Processed image: saved ${d.toFixed(2)}% (${h} bytes)`),{inputPath:typeof t==="string"?t:"buffer",outputPath:r||"buffer",inputSize:l,outputSize:f,saved:h,savedPercentage:d}}catch(o){throw q("error",`Failed to process image: ${o instanceof Error?o.message:String(o)}`),o}}async function to(e){let{input:t,output:r,prettify:i=!1}=e;q("process",`Processing SVG with options: ${JSON.stringify(e)}`);try{let n,s;if(typeof t==="string")n=await pi(t,"utf-8"),s=(await ut(t)).size;else n=t.toString("utf-8"),s=t.length;let a=sd(n,{plugins:["preset-default"],js2svg:{pretty:i,indent:2}}).data;if(r)await Wt(r),await Xt(r,a);let o=wn.from(a).length,l=s-o,c=l/s*100;return q("process",`Processed SVG: saved ${c.toFixed(2)}% (${l} bytes)`),{inputPath:typeof t==="string"?t:"buffer",outputPath:r||"buffer",inputSize:s,outputSize:o,saved:l,savedPercentage:c}}catch(n){let s=n instanceof Error?n:Error(typeof n==="string"?n:"Unknown error processing SVG");throw q("error",`Failed to process SVG: ${s.message}`),s}}async function Td(e,t={}){let{output:r,prettify:i=N.svg?.prettify||!1,precision:n=N.svg?.precision||3,multipass:s=N.svg?.multipass||!1,removeComments:a=N.svg?.removeComments||!0,removeMetadata:o=N.svg?.removeMetadata||!0,removeViewBox:l=N.svg?.removeViewBox||!1,removeDimensions:c=N.svg?.removeDimensions||!0,removeHiddenElements:u=N.svg?.removeHiddenElements||!0,removeEmptyAttrs:f=N.svg?.removeEmptyAttrs||!0,removeEmptyContainers:h=N.svg?.removeEmptyContainers||!0,removeUnusedNS:d=N.svg?.removeUnusedNS||!0,cleanupIDs:m=N.svg?.cleanupIDs||!0,cleanupNumericValues:p=N.svg?.cleanupNumericValues||!0,cleanupListOfValues:y=N.svg?.cleanupListOfValues||!0,collapseGroups:g=N.svg?.collapseGroups||!0,convertColors:w=N.svg?.convertColors||!0,convertPathData:b=N.svg?.convertPathData||!0,convertShapeToPath:v=N.svg?.convertShapeToPath||!0,convertStyleToAttrs:S=N.svg?.convertStyleToAttrs||!0,convertTransform:E=N.svg?.convertTransform||!0,inlineStyles:C=N.svg?.inlineStyles||!0,minifyStyles:F=N.svg?.minifyStyles||!0,mergePaths:R=N.svg?.mergePaths||!0,prefixIds:x=N.svg?.prefixIds||!1,prefixClassNames:A=N.svg?.prefixClassNames||!1,removeXMLNS:M=N.svg?.removeXMLNS||!1,removeOffCanvasPaths:k=N.svg?.removeOffCanvasPaths||!1,reusePaths:P=N.svg?.reusePaths||!1,sortAttrs:T=N.svg?.sortAttrs||!0,sortDefsChildren:O=N.svg?.sortDefsChildren||!0,removeDoctype:W=N.svg?.removeDoctype||!0,removeXMLProcInst:X=N.svg?.removeXMLProcInst||!0,removeTitle:ee=N.svg?.removeTitle||!1,removeDesc:he=N.svg?.removeDesc||!1,removeScriptElement:Y=N.svg?.removeScriptElement||!1,removeStyleElement:le=N.svg?.removeStyleElement||!1,stats:K=!1}=t;q("processor",`Optimizing SVG with ${s?"multipass":"single pass"} mode`);try{let _,se=typeof e==="string"&&!e.trim().startsWith("<")?e:"buffer",Ce;if(typeof e==="string")if(e.trim().startsWith("<"))_=e,Ce=wn.from(e).length;else _=await pi(e,"utf-8"),Ce=(await ut(e)).size;else _=e.toString("utf-8"),Ce=e.length;let L={multipass:s,plugins:[{name:"preset-default",params:{overrides:{removeViewBox:l,removeComments:a,removeMetadata:o,removeDoctype:W,removeXMLProcInst:X,removeTitle:ee,removeDesc:he,convertPathData:b,convertTransform:E,inlineStyles:C,mergePaths:R,minifyStyles:F,cleanupNumericValues:p,collapseGroups:g,convertColors:w,removeEmptyAttrs:f,removeEmptyContainers:h,removeUnusedNS:d,sortAttrs:T,sortDefsChildren:O}}}],js2svg:{pretty:i,indent:2,precision:n}};if(m)L.plugins.push({name:"cleanupIds"});if(y)L.plugins.push({name:"cleanupListOfValues"});if(v)L.plugins.push({name:"convertShapeToPath"});if(S)L.plugins.push({name:"convertStyleToAttrs"});if(u)L.plugins.push({name:"removeHiddenElems"});if(c)L.plugins.push({name:"removeDimensions"});if(x)L.plugins.push({name:"prefixIds",params:{prefix:typeof x==="string"?x:"id-",delim:"-"}});if(A)L.plugins.push({name:"prefixClassNames",params:{prefix:typeof A==="string"?A:"class-",delim:"-"}});if(M)L.plugins.push({name:"removeXMLNS"});if(P)L.plugins.push({name:"reusePaths"});if(k)L.plugins.push({name:"removeOffCanvasPaths"});if(Y)L.plugins.push({name:"removeScriptElems"});if(le)L.plugins.push({name:"removeStyleElems"});let oe=sd(_,L).data,Me=wn.from(oe).length,ge=Ce-Me,dt=ge/Ce*100,Yt=K?{}:null,Ae=r;if(Ae)await Wt(Ae),await Xt(Ae,oe);else if(typeof e==="string"&&!e.trim().startsWith("<")){let Ht=ii(e);Ae=e.replace(new RegExp(`${Ht}$`),`.optimized${Ht}`),await Wt(Ae),await Xt(Ae,oe)}else Ae="buffer";return q("processor",`Optimized SVG: saved ${dt.toFixed(2)}% (${ge} bytes)`),{inputPath:se,outputPath:Ae,inputSize:Ce,outputSize:Me,saved:ge,savedPercentage:dt,content:oe,prettified:i,multipass:s,stats:Yt}}catch(_){let se=_ instanceof Error?_:Error(typeof _==="string"?_:"Unknown error optimizing SVG");throw q("error",`Failed to optimize SVG: ${se.message}`),se}}async function Tx(e,t={}){let{output:r,mode:i="color",background:n,colorCount:s=16,steps:a=4,threshold:o=128,tolerance:l=3,optionsSvg:c={}}=t;q("processor",`Converting image to SVG using ${i} mode`);try{let{imageData:u}=await qt(e),f=typeof e==="string"?e:"buffer",h=u.width,d=u.height,m=vg({data:u.data,width:h,height:d},{mode:i,threshold:o,colorCount:s,steps:a,background:n}).svg;if(Object.keys(c).length>0)m=(await Td(m,c)).content;let p=r;if(p)await Wt(p),await Xt(p,m);else if(typeof e==="string"){let y=ii(e);p=e.replace(new RegExp(`${y}$`),".svg"),await Wt(p),await Xt(p,m)}else p="buffer";return{inputPath:f,outputPath:p,svgContent:m,dimensions:{width:h,height:d}}}catch(u){let f=u instanceof Error?u:Error(typeof u==="string"?u:"Unknown error converting image to SVG");throw q("error",`Failed to convert image to SVG: ${f.message}`),f}}async function Nx(e,t={}){let{width:r=N.placeholders?.width||20,height:i=N.placeholders?.height,quality:n=N.placeholders?.quality||50,format:s=N.placeholders?.format||"webp",blurLevel:a=N.placeholders?.blurLevel||40,base64Encode:o=N.placeholders?.base64Encode!==void 0?N.placeholders.base64Encode:!0,thumbhash:l=N.placeholders?.useThumbhash||!1,outputPath:c,strategy:u=l?"thumbhash":"blur",saturation:f=1.2,cssFilter:h=!1}=t;q("processor",`Generating placeholder for ${e} using strategy: ${u}`);let{imageData:d}=await qt(e),m=d.width,p=d.height,y=(m||1)/(p||1);if(u==="thumbhash"||l){let{dataUrl:v}=await Wd(e);return{dataURL:v,width:r||Math.round(i?i*y:m),height:i||Math.round(r?r/y:p),aspectRatio:y,originalWidth:m,originalHeight:p,strategy:"thumbhash"}}if(u==="dominant-color"){let v=Ld(d),S=`rgb(${v.r}, ${v.g}, ${v.b})`;return{dataURL:`data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${m}' height='${p}' style='background-color:${S}'/%3E`,width:m,height:p,aspectRatio:y,originalWidth:m,originalHeight:p,strategy:"dominant-color",dominantColor:S}}let g=Ee(d,{width:r,height:i,fit:"inside"});if(u==="blur"){let v=a/10;g=ua(g,v)}else if(u==="pixelate"){let v=Math.max(8,Math.floor(r/8)),S=Ee(d,{width:v,fit:"inside"});g=Ee(S,{width:r,height:i,kernel:"nearest"})}if(f!==1)g=Dd(g,{saturation:f});let w,b;if(o){w=await tt(g,s,{quality:n});let v=wn.from(w).toString("base64"),S=`data:${`image/${s==="jpeg"?"jpeg":s}`};base64,${v}`,E={dataURL:S,width:m,height:p,aspectRatio:y,originalWidth:m,originalHeight:p,strategy:u};if(h){let C=`
137
+ .placeholder-image {
138
+ background-size: cover;
139
+ background-position: center;
140
+ background-image: url(${S});
141
+ filter: blur(20px);
142
+ transform: scale(1.1);
143
+ }`.trim();return{...E,css:C}}return E}else return b=c||e.replace(/\.[^/.]+$/,`.placeholder.${s}`),await ir(g,s,b,{quality:n}),{dataURL:b,width:m,height:p,aspectRatio:y,originalWidth:m,originalHeight:p,strategy:u}}async function Px(e,t,r={}){let{outputDir:i,quality:n=N.conversion?.quality||80,lossless:s=N.conversion?.lossless||!1,progressive:a=N.conversion?.progressive!==void 0?N.conversion.progressive:!0,filenamePrefix:o="",filenameSuffix:l="",resize:c,preserveMetadata:u=!1,effort:f=6}=r;q("processor",`Converting ${e} to ${t}`);let h=(await ut(e)).size,d=ii(e),m=e.slice(0,-d.length),p=m.split("/").pop()||"image",y=`${o}${p}${l}.${t}`,g=i?Zi(i,y):`${m}.${t}`;if(i)await Wt(g);let{imageData:w}=await qt(e),b=w;if(c)b=Ee(b,{width:c.width,height:c.height,fit:c.fit||"contain"});await ir(b,t,g,{quality:n,lossless:s,progressive:a,effort:f});let v=(await ut(g)).size,S=h-v,E=S/h*100;return{inputPath:e,outputPath:g,format:t,width:b.width,height:b.height,originalSize:h,convertedSize:v,saved:S,savedPercentage:E}}async function Fx(e,t={}){let{outputDir:r=e,formats:i=N.batch?.formats||["webp"],quality:n=N.batch?.quality||80,resize:s=N.batch?.resize,recursive:a=N.batch?.recursive||!1,filter:o=N.batch?.filter?new RegExp(N.batch.filter,"i"):/\.(jpe?g|png|gif|bmp|tiff?)$/i,skipExisting:l=N.batch?.skipExisting!==void 0?N.batch.skipExisting:!0,concurrency:c=N.concurrent||4,preserveStructure:u=!0,filenameTemplate:f="[name].[format]",preserveMetadata:h=!1,optimizationPreset:d="web",transformations:m=[],progressCallback:p}=t;q("processor",`Batch processing images in ${e}`);let y=[],g={totalFiles:0,successCount:0,errorCount:0,originalSize:0,optimizedSize:0,saved:0,savedPercentage:0,timeElapsed:0},w=Date.now(),b=[],v=new Map,S=(A)=>{if(typeof n==="number")return n;if(n[A])return n[A];switch(A){case"webp":return 80;case"avif":return 70;case"jpeg":return 85;case"png":return 90;default:return 80}},E=(A,M)=>{let k=S(A);switch(d){case"web":return{quality:k,effort:6,lossless:!1,progressive:A==="jpeg"||A==="png"};case"quality":return{quality:Math.min(k+10,100),effort:9,lossless:A==="png"||M<102400,progressive:A==="jpeg"||A==="png"};case"performance":return{quality:Math.max(k-10,60),effort:3,lossless:!1,progressive:!1};default:return{quality:k}}},C=(A)=>{let M=A;for(let k of m)switch(k.type){case"resize":M=Ee(M,k.options??{});break;case"rotate":M=so(M,k.options?.angle||0,k.options);break;case"flip":M=Xr(M);break;case"flop":M=lo(M);break;case"blur":M=ua(M,k.options?.sigma||1);break;case"sharpen":M=Od(M,k.options);break;case"grayscale":M=Rd(M);break}return M};async function F(A){let M=await Dm(A,{withFileTypes:!0});for(let k of M){let P=Zi(A,k.name);if(k.isDirectory()&&a){await F(P);continue}if(!k.isFile()||!o.test(k.name))continue;b.push(P),g.totalFiles++}}async function R(A){if(v.get(A))return;v.set(A,!0);try{let M=[],k=A.replace(e,"").replace(/^\//,""),P=r;if(u){let ee=ff(k);if(ee!==".")P=Zi(r,ee),await uf(P,{recursive:!0})}let T=(A.split("/").pop()||"image").replace(/\.[^/.]+$/,""),O=await ut(A);g.originalSize+=O.size;let{imageData:W}=await qt(A);for(let ee of i){let he=f.replace(/\[name\]/g,T).replace(/\[format\]/g,ee).replace(/\[width\]/g,W.width.toString()).replace(/\[height\]/g,W.height.toString()).replace(/\[quality\]/g,S(ee).toString()),Y=Zi(P,he);if(l)try{await ut(Y);let Ce=await ut(Y);M.push({path:Y,format:ee,size:Ce.size,saved:O.size-Ce.size});continue}catch{}let le=E(ee,O.size),K=C(W);if(s)K=Ee(K,{width:s.width,height:s.height});await ir(K,ee,Y,le);let _=await ut(Y),se=O.size-_.size;M.push({path:Y,format:ee,size:_.size,saved:se}),g.optimizedSize+=_.size,g.saved+=se}let X={input:A,outputs:M,success:!0};if(y.push(X),g.successCount++,p)p({completed:g.successCount+g.errorCount,total:g.totalFiles,percentage:(g.successCount+g.errorCount)/g.totalFiles*100,currentFile:A,success:!0})}catch(M){let k=M instanceof Error?M.message:String(M);if(y.push({input:A,outputs:[],success:!1,error:k}),g.errorCount++,p)p({completed:g.successCount+g.errorCount,total:g.totalFiles,percentage:(g.successCount+g.errorCount)/g.totalFiles*100,currentFile:A,success:!1})}v.delete(A)}await F(e);while(b.length>0){let A=b.splice(0,Math.min(c,b.length));await Promise.all(A.map((M)=>R(M)))}let x=Date.now();if(g.timeElapsed=x-w,g.originalSize>0)g.savedPercentage=g.saved/g.originalSize*100;return{summary:g,results:y}}async function Ox(e,t,r={}){let{quality:i=N.optimization?.quality||80,lossless:n=N.optimization?.lossless||!1,progressive:s=N.optimization?.progressive!==void 0?N.optimization.progressive:!0,effort:a=N.optimization?.effort||7,metadata:o=N.optimization?.preserveMetadata||!1}=r;q("processor",`Optimizing image: ${e}`);try{let l=(await ut(e)).size,c=await pi(e),u=Vr(new Uint8Array(c))||"png",{imageData:f}=await qt(e),h=i;switch(u){case"jpeg":h=r.quality||N.optimization?.jpeg?.quality||i;break;case"png":h=r.quality||N.optimization?.png?.quality||i;break;case"webp":h=r.quality||N.optimization?.webp?.quality||i;break;case"avif":h=r.quality||N.optimization?.avif?.quality||i;break}await ir(f,u,t,{quality:h,lossless:n,progressive:s,effort:a});let d=(await ut(t)).size;if(d>=l)return await Xt(t,new Uint8Array(c)),d=l,q("processor","Optimization complete: saved 0.00% (0 bytes) - original was already optimal"),{originalSize:l,optimizedSize:l,saved:0,savedPercentage:0,success:!0,outputPath:t};let m=l-d,p=m/l*100;return q("processor",`Optimization complete: saved ${p.toFixed(2)}% (${m} bytes)`),{originalSize:l,optimizedSize:d,saved:m,savedPercentage:p,success:!0,outputPath:t}}catch(l){let c=l instanceof Error?l.message:String(l);return q("error",`Failed to optimize image: ${c}`),{originalSize:0,optimizedSize:0,saved:0,savedPercentage:0,success:!1,outputPath:t}}}async function Rx(e,t={}){let{output:r,text:i,image:n,position:s=N.watermark?.position||"bottom-right",margin:a=N.watermark?.margin||20,opacity:o=N.watermark?.opacity||0.5,scale:l=N.watermark?.scale||0.2,rotate:c=0,tiled:u=!1,textOptions:f={}}=t;if(!i&&!n)throw Error("Either text or image must be provided for watermarking");let h=i?"text":"image";q("processor",`Applying ${h} watermark to ${typeof e==="string"?e:"buffer"}`);let{imageData:d}=await qt(e),m=typeof e==="string"?e:"buffer",p=d.width,y=d.height,g=(v,S)=>{let E={center:{left:Math.floor((p-v)/2),top:Math.floor((y-S)/2)},top:{left:Math.floor((p-v)/2),top:a},bottom:{left:Math.floor((p-v)/2),top:y-S-a},left:{left:a,top:Math.floor((y-S)/2)},right:{left:p-v-a,top:Math.floor((y-S)/2)},"top-left":{left:a,top:a},"top-right":{left:p-v-a,top:a},"bottom-left":{left:a,top:y-S-a},"bottom-right":{left:p-v-a,top:y-S-a}};return E[s]||E["bottom-right"]},w=d;if(i){let v=N.watermark?.textOptions||{},{fontSize:S=v.fontSize||24,color:E=v.color||"rgba(255, 255, 255, 0.5)"}=f,C=E.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/),F=C?parseInt(C[1]):255,R=C?parseInt(C[2]):255,x=C?parseInt(C[3]):255,A=C&&C[4]?Math.floor(parseFloat(C[4])*255):128,M=Math.min(Math.floor(p*0.3),i.length*S*0.6),k=S+20,P=U(M,k,{fill:{r:F,g:R,b:x,a:Math.floor(A*o)}}),{left:T,top:O}=g(M,k);w=Fr(d,P,{left:T,top:O,blend:"normal"})}else if(n){let{imageData:v}=await qt(n),S=Math.floor(p*l),E=Math.floor(S*(v.height/v.width)),C=Ee(v,{width:S,height:E});if(c!==0)C=so(C,c);if(o<1){let x=Math.floor(o*255);for(let A=3;A<C.data.length;A+=4)C.data[A]=Math.floor(C.data[A]*o)}let{left:F,top:R}=g(C.width,C.height);if(u){let x=d;for(let A=0;A<y;A+=C.height+a*2)for(let M=0;M<p;M+=C.width+a*2)x=Fr(x,C,{left:M,top:A,blend:"normal"});w=x}else w=Fr(d,C,{left:F,top:R,blend:"normal"})}let b=r;if(b){await Wt(b);let v=ii(b).slice(1)||"png";await ir(w,v,b)}else if(typeof e==="string"){let v=ii(e);b=e.replace(new RegExp(`${v}$`),`.watermarked${v}`);let S=v.slice(1)||"png";await ir(w,S,b)}else b="buffer";return{inputPath:m,outputPath:b,watermarkType:h,dimensions:{width:p,height:y}}}function Nd(e,t,r){let i=U(t,r,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}),n=e.width/t,s=e.height/r;for(let a=0;a<r;a++)for(let o=0;o<t;o++){let l=o*n,c=a*s,u=Math.floor(l),f=Math.floor(c),h=l-u,d=c-f,m=[];for(let b=-1;b<=2;b++){m[b+1]=[];for(let v=-1;v<=2;v++){let S=kr(u+v,0,e.width-1),E=kr(f+b,0,e.height-1);m[b+1][v+1]=He(e,S,E)}}let p=Hi(m,h,d,"r"),y=Hi(m,h,d,"g"),g=Hi(m,h,d,"b"),w=Hi(m,h,d,"a");_r(i,o,a,{r:kr(Math.round(p),0,255),g:kr(Math.round(y),0,255),b:kr(Math.round(g),0,255),a:kr(Math.round(w),0,255)})}return i}function tf(e){let t=Math.abs(e);if(t<=1)return 1.5*t*t*t-2.5*t*t+1;else if(t<2)return-0.5*t*t*t+2.5*t*t-4*t+2;return 0}function Hi(e,t,r,i){let n=0;for(let s=0;s<4;s++){let a=0;for(let o=0;o<4;o++)a+=e[s][o][i]*tf(t-(o-1));n+=a*tf(r-(s-1))}return n}function kr(e,t,r){return Math.min(r,Math.max(t,e))}function Pd(e,t,r){let i=U(t,r,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}),n=e.width/t,s=e.height/r;for(let a=0;a<r;a++)for(let o=0;o<t;o++){let l=o*n,c=a*s,u=Math.floor(l),f=Math.floor(c),h=Math.min(u+1,e.width-1),d=Math.min(f+1,e.height-1),m=l-u,p=c-f,y=He(e,u,f),g=He(e,h,f),w=He(e,u,d),b=He(e,h,d),v=Ji(y.r,g.r,w.r,b.r,m,p),S=Ji(y.g,g.g,w.g,b.g,m,p),E=Ji(y.b,g.b,w.b,b.b,m,p),C=Ji(y.a,g.a,w.a,b.a,m,p);_r(i,o,a,{r:v,g:S,b:E,a:C})}return i}function Ji(e,t,r,i,n,s){let a=e+(t-e)*n,o=r+(i-r)*n;return Math.round(a+(o-a)*s)}function ro(e,t,r,i=3){let n=Dx(e,t,i);return Lx(n,r,i)}function Fd(e,t){if(e===0)return 1;if(Math.abs(e)>=t)return 0;let r=Math.PI*e;return t*Math.sin(r)*Math.sin(r/t)/(r*r)}function Dx(e,t,r){let i=U(t,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}),n=e.width/t,s=r;for(let a=0;a<e.height;a++)for(let o=0;o<t;o++){let l=(o+0.5)*n-0.5,c=Math.floor(l)-s+1,u=Math.floor(l)+s,f=0,h=0,d=0,m=0,p=0;for(let y=c;y<=u;y++){let g=Fd(l-y,r),w=yt(y,0,e.width-1),b=He(e,w,a);f+=b.r*g,h+=b.g*g,d+=b.b*g,m+=b.a*g,p+=g}if(p>0)f/=p,h/=p,d/=p,m/=p;_r(i,o,a,{r:yt(Math.round(f),0,255),g:yt(Math.round(h),0,255),b:yt(Math.round(d),0,255),a:yt(Math.round(m),0,255)})}return i}function Lx(e,t,r){let i=U(e.width,t,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}),n=e.height/t,s=r;for(let a=0;a<e.width;a++)for(let o=0;o<t;o++){let l=(o+0.5)*n-0.5,c=Math.floor(l)-s+1,u=Math.floor(l)+s,f=0,h=0,d=0,m=0,p=0;for(let y=c;y<=u;y++){let g=Fd(l-y,r),w=yt(y,0,e.height-1),b=He(e,a,w);f+=b.r*g,h+=b.g*g,d+=b.b*g,m+=b.a*g,p+=g}if(p>0)f/=p,h/=p,d/=p,m/=p;_r(i,a,o,{r:yt(Math.round(f),0,255),g:yt(Math.round(h),0,255),b:yt(Math.round(d),0,255),a:yt(Math.round(m),0,255)})}return i}function yt(e,t,r){return Math.min(r,Math.max(t,e))}function Ee(e,t){let{width:r,height:i,kernel:n="lanczos3",fit:s="cover",position:a="center"}=t;if(!r&&!i)return{...e,data:new Uint8ClampedArray(e.data)};let{targetWidth:o,targetHeight:l,needsCrop:c,finalWidth:u,finalHeight:f}=io(e.width,e.height,r,i,s),h=Bx(e,o,l,n);if(c&&u&&f)h=jx(h,u,f,a);return h}function jx(e,t,r,i){let n=Math.floor((e.width-t)/2),s=Math.floor((e.height-r)/2);switch(i){case"top":s=0;break;case"bottom":s=e.height-r;break;case"left":n=0;break;case"right":n=e.width-t;break;case"top-left":s=0,n=0;break;case"top-right":s=0,n=e.width-t;break;case"bottom-left":s=e.height-r,n=0;break;case"bottom-right":s=e.height-r,n=e.width-t;break}n=Math.max(0,n),s=Math.max(0,s);let a=new Uint8ClampedArray(t*r*4);for(let o=0;o<r;o++)for(let l=0;l<t;l++){let c=((s+o)*e.width+(n+l))*4,u=(o*t+l)*4;a[u]=e.data[c],a[u+1]=e.data[c+1],a[u+2]=e.data[c+2],a[u+3]=e.data[c+3]}return{data:a,width:t,height:r,colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}}function io(e,t,r,i,n="cover"){if(!r&&!i)return{targetWidth:e,targetHeight:t,needsCrop:!1};let s=e/t;if(!r)return{targetWidth:Math.round(i*s),targetHeight:i,needsCrop:!1};if(!i)return{targetWidth:r,targetHeight:Math.round(r/s),needsCrop:!1};let a=r/i;switch(n){case"fill":return{targetWidth:r,targetHeight:i,needsCrop:!1};case"contain":if(s>a)return{targetWidth:r,targetHeight:Math.round(r/s),needsCrop:!1};return{targetWidth:Math.round(i*s),targetHeight:i,needsCrop:!1};case"cover":if(s>a)return{targetWidth:Math.round(i*s),targetHeight:i,needsCrop:!0,finalWidth:r,finalHeight:i};return{targetWidth:r,targetHeight:Math.round(r/s),needsCrop:!0,finalWidth:r,finalHeight:i};case"inside":if(e<=r&&t<=i)return{targetWidth:e,targetHeight:t,needsCrop:!1};return io(e,t,r,i,"contain");case"outside":if(e>=r&&t>=i)return{targetWidth:e,targetHeight:t,needsCrop:!1};return io(e,t,r,i,"cover");default:return{targetWidth:r,targetHeight:i,needsCrop:!1}}}function Bx(e,t,r,i){switch(i){case"nearest":return Ix(e,t,r);case"bilinear":return Pd(e,t,r);case"bicubic":return Nd(e,t,r);case"lanczos2":return ro(e,t,r,2);case"lanczos3":default:return ro(e,t,r,3)}}function Ix(e,t,r){let i=new Uint8ClampedArray(t*r*4),n=e.width/t,s=e.height/r;for(let a=0;a<r;a++)for(let o=0;o<t;o++){let l=Math.floor(o*n),c=(Math.floor(a*s)*e.width+l)*4,u=(a*t+o)*4;i[u]=e.data[c],i[u+1]=e.data[c+1],i[u+2]=e.data[c+2],i[u+3]=e.data[c+3]}return{data:i,width:t,height:r,colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}}function ua(e,t){if(t<=0)return{...e,data:new Uint8ClampedArray(e.data)};let r=zx(t),i=Math.floor(r.length/2),n=_x(e,r,i);return Ux(n,r,i)}function zx(e){let t=Math.max(1,Math.ceil(e*3)),r=t*2+1,i=[],n=0;for(let s=0;s<r;s++){let a=s-t,o=Math.exp(-(a*a)/(2*e*e));i.push(o),n+=o}for(let s=0;s<r;s++)i[s]/=n;return i}function _x(e,t,r){let i=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let n=0;n<e.height;n++)for(let s=0;s<e.width;s++){let a=0,o=0,l=0,c=0;for(let f=-r;f<=r;f++){let h=Math.min(e.width-1,Math.max(0,s+f)),d=(n*e.width+h)*4,m=t[f+r];a+=e.data[d]*m,o+=e.data[d+1]*m,l+=e.data[d+2]*m,c+=e.data[d+3]*m}let u=(n*e.width+s)*4;i.data[u]=Math.round(a),i.data[u+1]=Math.round(o),i.data[u+2]=Math.round(l),i.data[u+3]=Math.round(c)}return i}function Ux(e,t,r){let i=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let n=0;n<e.height;n++)for(let s=0;s<e.width;s++){let a=0,o=0,l=0,c=0;for(let f=-r;f<=r;f++){let h=(Math.min(e.height-1,Math.max(0,n+f))*e.width+s)*4,d=t[f+r];a+=e.data[h]*d,o+=e.data[h+1]*d,l+=e.data[h+2]*d,c+=e.data[h+3]*d}let u=(n*e.width+s)*4;i.data[u]=Math.round(a),i.data[u+1]=Math.round(o),i.data[u+2]=Math.round(l),i.data[u+3]=Math.round(c)}return i}function Vx(e,t){if(t<=0)return{...e,data:new Uint8ClampedArray(e.data)};let r=Math.floor(t),i=r*2+1,n=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let a=0;a<e.height;a++){let o=0,l=0,c=0,u=0;for(let f=-r;f<=r;f++){let h=Math.max(0,Math.min(e.width-1,f)),d=(a*e.width+h)*4;o+=e.data[d],l+=e.data[d+1],c+=e.data[d+2],u+=e.data[d+3]}for(let f=0;f<e.width;f++){let h=(a*e.width+f)*4;n.data[h]=Math.round(o/i),n.data[h+1]=Math.round(l/i),n.data[h+2]=Math.round(c/i),n.data[h+3]=Math.round(u/i);let d=Math.max(0,f-r),m=Math.min(e.width-1,f+r+1),p=(a*e.width+d)*4,y=(a*e.width+m)*4;o+=e.data[y]-e.data[p],l+=e.data[y+1]-e.data[p+1],c+=e.data[y+2]-e.data[p+2],u+=e.data[y+3]-e.data[p+3]}}let s=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let a=0;a<e.width;a++){let o=0,l=0,c=0,u=0;for(let f=-r;f<=r;f++){let h=(Math.max(0,Math.min(e.height-1,f))*e.width+a)*4;o+=n.data[h],l+=n.data[h+1],c+=n.data[h+2],u+=n.data[h+3]}for(let f=0;f<e.height;f++){let h=(f*e.width+a)*4;s.data[h]=Math.round(o/i),s.data[h+1]=Math.round(l/i),s.data[h+2]=Math.round(c/i),s.data[h+3]=Math.round(u/i);let d=Math.max(0,f-r),m=Math.min(e.height-1,f+r+1),p=(d*e.width+a)*4,y=(m*e.width+a)*4;o+=n.data[y]-n.data[p],l+=n.data[y+1]-n.data[p+1],c+=n.data[y+2]-n.data[p+2],u+=n.data[y+3]-n.data[p+3]}}return s}function Od(e,t={}){let{sigma:r=1,amount:i=1,threshold:n=0}=t;if(i<=0)return{...e,data:new Uint8ClampedArray(e.data)};let s=ua(e,r),a=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let o=0;o<e.data.length;o+=4){let l=e.data[o]-s.data[o],c=e.data[o+1]-s.data[o+1],u=e.data[o+2]-s.data[o+2];if(n>0){if(Math.abs(l*0.299+c*0.587+u*0.114)<n){a.data[o]=e.data[o],a.data[o+1]=e.data[o+1],a.data[o+2]=e.data[o+2],a.data[o+3]=e.data[o+3];continue}}a.data[o]=hn(e.data[o]+l*i),a.data[o+1]=hn(e.data[o+1]+c*i),a.data[o+2]=hn(e.data[o+2]+u*i),a.data[o+3]=e.data[o+3]}return a}function Gx(e,t=1){let r=1+4*t,i=-t,n=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let s=0;s<e.height;s++)for(let a=0;a<e.width;a++){let o=(s*e.width+a)*4,l=Math.max(0,s-1),c=Math.min(e.height-1,s+1),u=Math.max(0,a-1),f=Math.min(e.width-1,a+1),h=(l*e.width+a)*4,d=(c*e.width+a)*4,m=(s*e.width+u)*4,p=(s*e.width+f)*4;for(let y=0;y<3;y++){let g=e.data[h+y]*i+e.data[m+y]*i+e.data[o+y]*r+e.data[p+y]*i+e.data[d+y]*i;n.data[o+y]=hn(g)}n.data[o+3]=e.data[o+3]}return n}function hn(e){return Math.min(255,Math.max(0,Math.round(e)))}function _n(e,t,r,i=0){let n=t.length,s=Math.floor(n/2);if(r===void 0){r=0;for(let o=0;o<n;o++)for(let l=0;l<n;l++)r+=t[o][l];if(r===0)r=1}let a=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let o=0;o<e.height;o++)for(let l=0;l<e.width;l++){let c=0,u=0,f=0;for(let d=0;d<n;d++)for(let m=0;m<n;m++){let p=Math.min(e.width-1,Math.max(0,l+m-s)),y=(Math.min(e.height-1,Math.max(0,o+d-s))*e.width+p)*4,g=t[d][m];c+=e.data[y]*g,u+=e.data[y+1]*g,f+=e.data[y+2]*g}let h=(o*e.width+l)*4;a.data[h]=dn(c/r+i),a.data[h+1]=dn(u/r+i),a.data[h+2]=dn(f/r+i),a.data[h+3]=e.data[(o*e.width+l)*4+3]}return a}function Wx(e){let t=[[-1,0,1],[-2,0,2],[-1,0,1]],r=[[-1,-2,-1],[0,0,0],[1,2,1]],i=_n(e,t,1,0),n=_n(e,r,1,0),s=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let a=0;a<e.data.length;a+=4){for(let o=0;o<3;o++){let l=i.data[a+o]-128,c=n.data[a+o]-128;s.data[a+o]=dn(Math.sqrt(l*l+c*c))}s.data[a+3]=e.data[a+3]}return s}function qx(e,t=1){let r=[[-2*t,-t,0],[-t,1,t],[0,t,2*t]];return _n(e,r,1,128)}var Kx={identity:[[0,0,0],[0,1,0],[0,0,0]],boxBlur3x3:[[1,1,1],[1,1,1],[1,1,1]],gaussian5x5:[[1,4,6,4,1],[4,16,24,16,4],[6,24,36,24,6],[4,16,24,16,4],[1,4,6,4,1]],sharpen:[[0,-1,0],[-1,5,-1],[0,-1,0]],laplacian:[[0,1,0],[1,-4,1],[0,1,0]],emboss:[[-2,-1,0],[-1,1,1],[0,1,2]]};function dn(e){return Math.min(255,Math.max(0,Math.round(e)))}function Rd(e){let t=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let r=0;r<e.data.length;r+=4){let i=Math.round(e.data[r]*0.2126+e.data[r+1]*0.7152+e.data[r+2]*0.0722);t.data[r]=i,t.data[r+1]=i,t.data[r+2]=i,t.data[r+3]=e.data[r+3]}return t}function Yx(e,t=128,r={}){let{grayscale:i=!0}=r,n=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let s=0;s<e.data.length;s+=4){let a=e.data[s]*0.2126+e.data[s+1]*0.7152+e.data[s+2]*0.0722>=t?255:0;if(i)n.data[s]=a,n.data[s+1]=a,n.data[s+2]=a;else{let o=a/255;n.data[s]=Math.round(e.data[s]*o),n.data[s+1]=Math.round(e.data[s+1]*o),n.data[s+2]=Math.round(e.data[s+2]*o)}n.data[s+3]=e.data[s+3]}return n}function Dd(e,t){let{brightness:r=1,saturation:i=1,hue:n=0,lightness:s=1}=t,a=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let o=0;o<e.data.length;o+=4){let[l,c,u]=jd(e.data[o],e.data[o+1],e.data[o+2]);l=(l+n)%360,c=Math.min(1,Math.max(0,c*i)),u=Math.min(1,Math.max(0,u*s*r));let[f,h,d]=Bd(l,c,u);a.data[o]=f,a.data[o+1]=h,a.data[o+2]=d,a.data[o+3]=e.data[o+3]}return a}function Hx(e){let t=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let r=0;r<e.data.length;r+=4)t.data[r]=255-e.data[r],t.data[r+1]=255-e.data[r+1],t.data[r+2]=255-e.data[r+2],t.data[r+3]=e.data[r+3];return t}function Jx(e,t=1){let r=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let i=0;i<e.data.length;i+=4){let n=e.data[i],s=e.data[i+1],a=e.data[i+2],o=Math.min(255,n*0.393+s*0.769+a*0.189),l=Math.min(255,n*0.349+s*0.686+a*0.168),c=Math.min(255,n*0.272+s*0.534+a*0.131);r.data[i]=Math.round(n+(o-n)*t),r.data[i+1]=Math.round(s+(l-s)*t),r.data[i+2]=Math.round(a+(c-a)*t),r.data[i+3]=e.data[i+3]}return r}function Zx(e,t=1){let r=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}),i=128*(1-t);for(let n=0;n<e.data.length;n+=4)r.data[n]=ds(e.data[n]*t+i),r.data[n+1]=ds(e.data[n+1]*t+i),r.data[n+2]=ds(e.data[n+2]*t+i),r.data[n+3]=e.data[n+3];return r}function Qx(e,t=1){let r=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}),i=1/t,n=new Uint8Array(256);for(let s=0;s<256;s++)n[s]=Math.round(255*(s/255)**i);for(let s=0;s<e.data.length;s+=4)r.data[s]=n[e.data[s]],r.data[s+1]=n[e.data[s+1]],r.data[s+2]=n[e.data[s+2]],r.data[s+3]=e.data[s+3];return r}function Xx(e){let t=255,r=0,i=255,n=0,s=255,a=0;for(let f=0;f<e.data.length;f+=4)t=Math.min(t,e.data[f]),r=Math.max(r,e.data[f]),i=Math.min(i,e.data[f+1]),n=Math.max(n,e.data[f+1]),s=Math.min(s,e.data[f+2]),a=Math.max(a,e.data[f+2]);let o=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth}),l=r-t||1,c=n-i||1,u=a-s||1;for(let f=0;f<e.data.length;f+=4)o.data[f]=Math.round((e.data[f]-t)/l*255),o.data[f+1]=Math.round((e.data[f+1]-i)/c*255),o.data[f+2]=Math.round((e.data[f+2]-s)/u*255),o.data[f+3]=e.data[f+3];return o}function e$(e,t,r=0.5){let i=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});for(let n=0;n<e.data.length;n+=4){let s=e.data[n]*0.2126+e.data[n+1]*0.7152+e.data[n+2]*0.0722,a=s*t.r/255,o=s*t.g/255,l=s*t.b/255;i.data[n]=Math.round(e.data[n]+(a-e.data[n])*r),i.data[n+1]=Math.round(e.data[n+1]+(o-e.data[n+1])*r),i.data[n+2]=Math.round(e.data[n+2]+(l-e.data[n+2])*r),i.data[n+3]=e.data[n+3]}return i}function Ld(e){let t=0,r=0,i=0,n=0;for(let s=0;s<e.data.length;s+=4){if(e.data[s+3]<128)continue;t+=e.data[s],r+=e.data[s+1],i+=e.data[s+2],n++}if(n===0)return{r:0,g:0,b:0};return{r:Math.round(t/n),g:Math.round(r/n),b:Math.round(i/n)}}function jd(e,t,r){e/=255,t/=255,r/=255;let i=Math.max(e,t,r),n=Math.min(e,t,r),s=(i+n)/2;if(i===n)return[0,0,s];let a=i-n,o=s>0.5?a/(2-i-n):a/(i+n),l=0;switch(i){case e:l=((t-r)/a+(t<r?6:0))/6;break;case t:l=((r-e)/a+2)/6;break;case r:l=((e-t)/a+4)/6;break}return[l*360,o,s]}function Bd(e,t,r){if(e=e/360,t===0){let c=Math.round(r*255);return[c,c,c]}let i=(c,u,f)=>{if(f<0)f+=1;if(f>1)f-=1;if(f<0.16666666666666666)return c+(u-c)*6*f;if(f<0.5)return u;if(f<0.6666666666666666)return c+(u-c)*(0.6666666666666666-f)*6;return c},n=r<0.5?r*(1+t):r+t-r*t,s=2*r-n,a=i(s,n,e+0.3333333333333333),o=i(s,n,e),l=i(s,n,e-0.3333333333333333);return[Math.round(a*255),Math.round(o*255),Math.round(l*255)]}function mn(e){if(e=e/255,e<=0.04045)return e/12.92;return((e+0.055)/1.055)**2.4}function pn(e){if(e<=0.0031308)return Math.round(e*12.92*255);return Math.round((1.055*e**0.4166666666666667-0.055)*255)}function t$(e,t){if(e.colorSpace===t)return{...e,data:new Uint8ClampedArray(e.data)};let r=U(e.width,e.height,{colorSpace:t,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});if(t==="linear-srgb")for(let i=0;i<e.data.length;i+=4)r.data[i]=Math.round(mn(e.data[i])*255),r.data[i+1]=Math.round(mn(e.data[i+1])*255),r.data[i+2]=Math.round(mn(e.data[i+2])*255),r.data[i+3]=e.data[i+3];else for(let i=0;i<e.data.length;i+=4)r.data[i]=pn(e.data[i]/255),r.data[i+1]=pn(e.data[i+1]/255),r.data[i+2]=pn(e.data[i+2]/255),r.data[i+3]=e.data[i+3];return r}function ds(e){return Math.min(255,Math.max(0,Math.round(e)))}function Fr(e,t,r={}){let{blend:i="normal",opacity:n=1,left:s=0,top:a=0,tile:o=!1}=r,l=U(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});l.data.set(e.data);let c=i$(i);for(let u=0;u<e.height;u++)for(let f=0;f<e.width;f++){let h,d;if(o)h=((f-s)%t.width+t.width)%t.width,d=((u-a)%t.height+t.height)%t.height;else if(h=f-s,d=u-a,h<0||h>=t.width||d<0||d>=t.height)continue;let m=(u*e.width+f)*4,p=(d*t.width+h)*4,y=l.data[m]/255,g=l.data[m+1]/255,w=l.data[m+2]/255,b=l.data[m+3]/255,v=t.data[p]/255,S=t.data[p+1]/255,E=t.data[p+2]/255,C=t.data[p+3]/255*n,F=c(y,v),R=c(g,S),x=c(w,E),A=C+b*(1-C);if(A>0){let M=(v*C+y*b*(1-C))/A,k=(S*C+g*b*(1-C))/A,P=(E*C+w*b*(1-C))/A,T=y+(F-y)*C,O=g+(R-g)*C,W=w+(x-w)*C;if(i==="normal"||i==="source-over")l.data[m]=Math.round(M*255),l.data[m+1]=Math.round(k*255),l.data[m+2]=Math.round(P*255);else l.data[m]=Math.round(T*255),l.data[m+1]=Math.round(O*255),l.data[m+2]=Math.round(W*255);l.data[m+3]=Math.round(A*255)}}return l}function r$(e,t){let r=e;for(let i of t)r=Fr(r,i.input,i.options);return r}function i$(e){switch(e){case"normal":case"source-over":return(t,r)=>r;case"multiply":return(t,r)=>t*r;case"screen":return(t,r)=>1-(1-t)*(1-r);case"overlay":return(t,r)=>{if(t<0.5)return 2*t*r;return 1-2*(1-t)*(1-r)};case"darken":return(t,r)=>Math.min(t,r);case"lighten":return(t,r)=>Math.max(t,r);case"color-dodge":return(t,r)=>{if(r>=1)return 1;return Math.min(1,t/(1-r))};case"color-burn":return(t,r)=>{if(r<=0)return 0;return 1-Math.min(1,(1-t)/r)};case"hard-light":return(t,r)=>{if(r<0.5)return 2*t*r;return 1-2*(1-t)*(1-r)};case"soft-light":return(t,r)=>{if(r<0.5)return t-(1-2*r)*t*(1-t);let i=t<=0.25?((16*t-12)*t+4)*t:Math.sqrt(t);return t+(2*r-1)*(i-t)};case"difference":return(t,r)=>Math.abs(t-r);case"exclusion":return(t,r)=>t+r-2*t*r;case"dest-in":return(t,r)=>t;case"dest-out":return(t,r)=>t;case"source-atop":return(t,r)=>r;default:return(t,r)=>r}}function n$(e,t,r){return U(e,t,{colorSpace:"srgb",hasAlpha:!0,bitDepth:8,fill:r})}function a$(e,t,r,i,n="horizontal"){let s=U(e,t,{colorSpace:"srgb",hasAlpha:!0,bitDepth:8}),a=r.a??255,o=i.a??255;for(let l=0;l<t;l++)for(let c=0;c<e;c++){let u;switch(n){case"horizontal":u=c/(e-1||1);break;case"vertical":u=l/(t-1||1);break;case"diagonal":u=(c+l)/(e-1+(t-1)||1);break}let f=(l*e+c)*4;s.data[f]=Math.round(r.r+(i.r-r.r)*u),s.data[f+1]=Math.round(r.g+(i.g-r.g)*u),s.data[f+2]=Math.round(r.b+(i.b-r.b)*u),s.data[f+3]=Math.round(a+(o-a)*u)}return s}var s$=new Set([".svg"]),o$=new Set([".jpg",".jpeg",".png",".webp",".avif"]);async function Id(e){let{input:t}=e;if(typeof t==="string"){let r=Rm(t).toLowerCase(),i=s$.has(r),n=o$.has(r);if(!i&&!n)throw Error(`Unsupported file extension: ${r}`);return q("process",`Processing ${i?"SVG":"image"}: ${t}`),i?to(e):eo(e)}return e.isSvg??!1?to(e):eo(e)}async function l$(e,t){q("process",`Processing ${e.length} files`);let r=await Promise.all(e.map(async(o)=>{try{return await Id({...t,input:o,output:o})}catch(l){let c=l instanceof Error?l:Error(String(l));return q("error",`Failed to process ${o}: ${c.message}`),{inputPath:o,outputPath:o,inputSize:0,outputSize:0,saved:0,savedPercentage:0,error:c}}})),i=r.filter((o)=>!o.error),n=r.filter((o)=>o.error),s=i.reduce((o,l)=>o+l.saved,0),a=s/i.reduce((o,l)=>o+l.inputSize,0)*100;return q("process",`
144
+ Processed ${r.length} files:
145
+ - Successful: ${i.length}
146
+ - Failed: ${n.length}
147
+ - Total saved: ${s} bytes (${a.toFixed(2)}%)
148
+ `),r}function zd(e,t,r){if(e>100||t>100)throw Error(`${e}x${t} doesn't fit in 100x100`);let{PI:i,round:n,max:s,cos:a,abs:o}=Math,l=0,c=0,u=0,f=0;for(let K=0,_=0;K<e*t;K++,_+=4){let se=r[_+3]/255;l+=se/255*r[_],c+=se/255*r[_+1],u+=se/255*r[_+2],f+=se}if(f)l/=f,c/=f,u/=f;let h=f<e*t,d=h?5:7,m=s(1,n(d*e/s(e,t))),p=s(1,n(d*t/s(e,t))),y=[],g=[],w=[],b=[];for(let K=0,_=0;K<e*t;K++,_+=4){let se=r[_+3]/255,Ce=l*(1-se)+se/255*r[_],L=c*(1-se)+se/255*r[_+1],oe=u*(1-se)+se/255*r[_+2];y[K]=(Ce+L+oe)/3,g[K]=(Ce+L)/2-oe,w[K]=Ce-L,b[K]=se}let v=(K,_,se)=>{let Ce=0,L=[],oe=0,Me=[];for(let ge=0;ge<se;ge++)for(let dt=0;dt*se<_*(se-ge);dt++){let Yt=0;for(let Ae=0;Ae<e;Ae++)Me[Ae]=a(i/e*dt*(Ae+0.5));for(let Ae=0;Ae<t;Ae++)for(let Ht=0,um=a(i/t*ge*(Ae+0.5));Ht<e;Ht++)Yt+=K[Ht+Ae*e]*Me[Ht]*um;if(Yt/=e*t,dt||ge)L.push(Yt),oe=s(oe,o(Yt));else Ce=Yt}if(oe)for(let ge=0;ge<L.length;ge++)L[ge]=0.5+0.5/oe*L[ge];return[Ce,L,oe]},[S,E,C]=v(y,s(3,m),s(3,p)),[F,R,x]=v(g,3,3),[A,M,k]=v(w,3,3),[P,T,O]=h?v(b,5,5):[0,[],0],W=e>t,X=n(63*S)|n(31.5+31.5*F)<<6|n(31.5+31.5*A)<<12|n(31*C)<<18|Number(h)<<23,ee=(W?p:m)|n(63*x)<<3|n(63*k)<<9|Number(W)<<15,he=[X&255,X>>8&255,X>>16,ee&255,ee>>8],Y=h?6:5,le=0;if(h)he.push(n(15*P)|n(15*O)<<4);for(let K of h?[E,R,M,T]:[E,R,M])for(let _ of K)he[Y+(le>>1)]|=n(15*_)<<((le++&1)<<2);return new Uint8Array(he)}function _d(e){let{PI:t,min:r,max:i,cos:n,round:s}=Math,a=e[0]|e[1]<<8|e[2]<<16,o=e[3]|e[4]<<8,l=(a&63)/63,c=(a>>6&63)/31.5-1,u=(a>>12&63)/31.5-1,f=(a>>18&31)/31,h=a>>23,d=(o>>3&63)/63,m=(o>>9&63)/63,p=o>>15,y=i(3,p?h?5:7:o&7),g=i(3,p?o&7:h?5:7),w=h?(e[5]&15)/15:1,b=(e[5]>>4)/15,v=h?6:5,S=0,E=(W,X,ee)=>{let he=[];for(let Y=0;Y<X;Y++)for(let le=Y?0:1;le*X<W*(X-Y);le++)he.push(((e[v+(S>>1)]>>((S++&1)<<2)&15)/7.5-1)*ee);return he},C=E(y,g,f),F=E(3,3,d*1.25),R=E(3,3,m*1.25),x=h?E(5,5,b):!1,A=Ud(e),M=s(A>1?32:32*A),k=s(A>1?32/A:32),P=new Uint8Array(M*k*4),T=[],O=[];for(let W=0,X=0;W<k;W++)for(let ee=0;ee<M;ee++,X+=4){let he=l,Y=c,le=u,K=w;for(let L=0,oe=i(y,h?5:3);L<oe;L++)T[L]=n(t/M*(ee+0.5)*L);for(let L=0,oe=i(g,h?5:3);L<oe;L++)O[L]=n(t/k*(W+0.5)*L);for(let L=0,oe=0;L<g;L++)for(let Me=L?0:1,ge=O[L]*2;Me*g<y*(g-L);Me++,oe++)he+=C[oe]*T[Me]*ge;for(let L=0,oe=0;L<3;L++)for(let Me=L?0:1,ge=O[L]*2;Me<3-L;Me++,oe++){let dt=T[Me]*ge;Y+=F[oe]*dt,le+=R[oe]*dt}if(h&&x)for(let L=0,oe=0;L<5;L++)for(let Me=L?0:1,ge=O[L]*2;Me<5-L;Me++,oe++)K+=x[oe]*T[Me]*ge;let _=he-0.6666666666666666*Y,se=(3*he-_+le)/2,Ce=se-le;P[X]=i(0,255*r(1,se)),P[X+1]=i(0,255*r(1,Ce)),P[X+2]=i(0,255*r(1,_)),P[X+3]=i(0,255*r(1,K))}return{w:M,h:k,rgba:P}}function c$(e){let{min:t,max:r}=Math,i=e[0]|e[1]<<8|e[2]<<16,n=(i&63)/63,s=(i>>6&63)/31.5-1,a=(i>>12&63)/31.5-1,o=i>>23?(e[5]&15)/15:1,l=n-0.6666666666666666*s,c=(3*n-l+a)/2,u=c-a;return{r:r(0,t(1,c)),g:r(0,t(1,u)),b:r(0,t(1,l)),a:o}}function Ud(e){let t=e[3]|e[4]<<8,r=(e[2]&128)!==0,i=(t&32768)!==0,n=i?r?5:7:t&7,s=i?t&7:r?5:7;return n/s}function Vd(e,t,r){let i=e*4+1,n=6+t*(5+i),s=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,e>>8,e&255,0,0,t>>8,t&255,8,6,0,0,0,0,0,0,0,n>>>24,n>>16&255,n>>8&255,n&255,73,68,65,84,120,1],a=[0,498536548,997073096,651767980,1994146192,1802195444,1303535960,1342533948,-306674912,-267414716,-690576408,-882789492,-1687895376,-2032938284,-1609899400,-1111625188],o=1,l=0;for(let c=0,u=0,f=i-1;c<t;c++,f+=i-1){s.push(c+1<t?0:1,i&255,i>>8,~i&255,i>>8^255,0);for(l=(l+o)%65521;u<f;u++){let h=r[u]&255;s.push(h),o=(o+h)%65521,l=(l+o)%65521}}s.push(l>>8,l&255,o>>8,o&255,0,0,0,0,0,0,0,0,73,69,78,68,174,66,96,130);for(let[c,u]of[[12,29],[37,41+n]]){let f=-1;for(let h=c;h<u;h++)f^=s[h],f=f>>>4^a[f&15],f=f>>>4^a[f&15];f=~f,s[u++]=f>>>24,s[u++]=f>>16&255,s[u++]=f>>8&255,s[u++]=f&255}return`data:image/png;base64,${btoa(String.fromCharCode(...s))}`}function Gd(e){let t=_d(e);return Vd(t.w,t.h,t.rgba)}async function Wd(e){let t=new Uint8Array(await Om(e)),r=await Re(t),i=Ee(r,{width:100,height:100,fit:"inside"}),n=zd(i.width,i.height,i.data),s=Gd(n);return{hash:n,dataUrl:s}}var no=[{size:16,scale:1,idiom:"mac",filename:"AppIcon-16.png"},{size:16,scale:2,idiom:"mac",filename:"AppIcon-16@2x.png"},{size:32,scale:1,idiom:"mac",filename:"AppIcon-32.png"},{size:32,scale:2,idiom:"mac",filename:"AppIcon-32@2x.png"},{size:128,scale:1,idiom:"mac",filename:"AppIcon-128.png"},{size:128,scale:2,idiom:"mac",filename:"AppIcon-128@2x.png"},{size:256,scale:1,idiom:"mac",filename:"AppIcon-256.png"},{size:256,scale:2,idiom:"mac",filename:"AppIcon-256@2x.png"},{size:512,scale:1,idiom:"mac",filename:"AppIcon-512.png"},{size:512,scale:2,idiom:"mac",filename:"AppIcon-512@2x.png"}],ao=[{size:20,scale:1,idiom:"iphone",filename:"AppIcon-20.png"},{size:20,scale:2,idiom:"iphone",filename:"AppIcon-20@2x.png"},{size:20,scale:3,idiom:"iphone",filename:"AppIcon-20@3x.png"},{size:29,scale:1,idiom:"iphone",filename:"AppIcon-29.png"},{size:29,scale:2,idiom:"iphone",filename:"AppIcon-29@2x.png"},{size:29,scale:3,idiom:"iphone",filename:"AppIcon-29@3x.png"},{size:40,scale:2,idiom:"iphone",filename:"AppIcon-40@2x.png"},{size:40,scale:3,idiom:"iphone",filename:"AppIcon-40@3x.png"},{size:60,scale:2,idiom:"iphone",filename:"AppIcon-60@2x.png"},{size:60,scale:3,idiom:"iphone",filename:"AppIcon-60@3x.png"},{size:20,scale:1,idiom:"ipad",filename:"AppIcon-20-ipad.png"},{size:20,scale:2,idiom:"ipad",filename:"AppIcon-20@2x-ipad.png"},{size:29,scale:1,idiom:"ipad",filename:"AppIcon-29-ipad.png"},{size:29,scale:2,idiom:"ipad",filename:"AppIcon-29@2x-ipad.png"},{size:40,scale:1,idiom:"ipad",filename:"AppIcon-40.png"},{size:40,scale:2,idiom:"ipad",filename:"AppIcon-40@2x-ipad.png"},{size:76,scale:1,idiom:"ipad",filename:"AppIcon-76.png"},{size:76,scale:2,idiom:"ipad",filename:"AppIcon-76@2x.png"},{size:83.5,scale:2,idiom:"ipad",filename:"AppIcon-83.5@2x.png"},{size:1024,scale:1,idiom:"ios-marketing",filename:"AppIcon-1024.png"}];async function Yd(e){await rf(e,{recursive:!0}),await rf(zr(e,"AppIcon.appiconset"),{recursive:!0})}async function Hd(e,t=N.appIcon?.outputDir||"assets/app-icons"){let r=Kd(t,"AppIcon.appiconset");await Yd(t),q("app-icon",`Generating macOS app icons from ${e} to ${r}`);let i=[],n=new Uint8Array(await qd(e)),s=await Re(n);for(let{size:l,scale:c,filename:u}of no){let f=l*c,h=zr(r,u),d=Ee(s,{width:f,height:f}),m=await tt(d,"png");await mi(h,m),i.push({size:f,path:h,filename:u})}let a=Zd("macos",no),o=zr(r,"Contents.json");return await mi(o,a),await Qd(t,"macos"),{platform:"macos",sizes:i,contentsJson:a}}async function Jd(e,t=N.appIcon?.outputDir||"assets/app-icons"){let r=Kd(t,"AppIcon.appiconset");await Yd(t),q("app-icon",`Generating iOS app icons from ${e} to ${r}`);let i=[],n=new Uint8Array(await qd(e)),s=await Re(n);for(let{size:l,scale:c,filename:u}of ao){let f=Math.round(l*c),h=zr(r,u),d=Ee(s,{width:f,height:f}),m=await tt(d,"png");await mi(h,m),i.push({size:f,path:h,filename:u})}let a=Zd("ios",ao),o=zr(r,"Contents.json");return await mi(o,a),await Qd(t,"ios"),{platform:"ios",sizes:i,contentsJson:a}}async function u$(e,t={}){let r=t.platform||N.appIcon?.platform||"all",i=t.outputDir||N.appIcon?.outputDir||"assets/app-icons",n=[];if(r==="macos"||r==="all")n.push(await Hd(e,i));if(r==="ios"||r==="all")n.push(await Jd(e,i));return n}function Zd(e,t){let r={images:t.map(({size:i,scale:n,idiom:s,filename:a})=>({size:`${i}x${i}`,idiom:s,filename:a,scale:`${n}x`})),info:{version:1,author:"imgx"}};return JSON.stringify(r,null,2)}async function Qd(e,t){let r=Array.isArray(t)?t:[t],i=zr(e,"README.md"),n=`# App Icons Generated with imgx
149
+
150
+ `;if(r.includes("macos"))n+=`## macOS App Icons
151
+
152
+ `,n+=`To use these icons in your macOS app:
153
+
154
+ `,n+=`1. In Xcode, open your project
155
+ `,n+=`2. In the Project Navigator, find your Assets.xcassets folder
156
+ `,n+="3. Drag the entire `AppIcon.appiconset` folder into the Assets.xcassets folder\n",n+=`4. Ensure the "AppIcon" is set as the app icon in your target's settings
157
+
158
+ `;if(r.includes("ios"))n+=`## iOS App Icons
159
+
160
+ `,n+=`To use these icons in your iOS app:
161
+
162
+ `,n+=`1. In Xcode, open your project
163
+ `,n+=`2. In the Project Navigator, find your Assets.xcassets folder
164
+ `,n+="3. Drag the entire `AppIcon.appiconset` folder into the Assets.xcassets folder\n",n+=`4. Ensure the "AppIcon" is set as the app icon in your target's settings
165
+
166
+ `;if(n+=`## Icon Sizes
167
+
168
+ `,r.includes("macos")){n+=`### macOS
169
+
170
+ `,n+=`| Size | Scale | Filename |
171
+ `,n+=`| --- | --- | --- |
172
+ `;for(let{size:s,scale:a,filename:o}of no)n+=`| ${s}x${s} | ${a}x | ${o} |
173
+ `;n+=`
174
+ `}if(r.includes("ios")){n+=`### iOS
175
+
176
+ `,n+=`| Size | Scale | Idiom | Filename |
177
+ `,n+=`| --- | --- | --- | --- |
178
+ `;for(let{size:s,scale:a,idiom:o,filename:l}of ao)n+=`| ${s}x${s} | ${a}x | ${o} | ${l} |
179
+ `}await mi(i,n)}async function h$(e,t,r={}){let{padding:i=2,maxWidth:n=2048,prefix:s="sprite",format:a="png",quality:o=90,scale:l=1}=r;q("sprite",`Generating sprite sheet from ${e.length} images`);let c=await Promise.all(e.map(async({path:F,name:R})=>{let x=new Uint8Array(await f$(F)),A=await Re(x),M=A;if(l!==1){let k=Math.ceil(A.width*l),P=Math.ceil(A.height*l);M=Ee(A,{width:k,height:P})}return{name:R,imageData:M,width:M.width,height:M.height}})),u=0,f=0,h=0,d=0,m=0,p=c.map((F)=>{if(u+F.width+i>n)u=0,f+=h+i,h=0;let R={x:u,y:f,width:F.width,height:F.height};return u+=F.width+i,h=Math.max(h,F.height),d=Math.max(d,u),m=Math.max(m,f+F.height),R}),y=U(d,m,{fill:{r:0,g:0,b:0,a:0}});for(let F=0;F<c.length;F++){let R=c[F],x=p[F];y=Fr(y,R.imageData,{left:x.x,top:x.y,blend:"normal"})}let g=ps(t,`${s}-sprite.${a}`),w=await tt(y,a,{quality:o});await ms(g,w);let b=p.map((F,R)=>({name:c[R].name,...F})),v=d$(s,b,a),S=ps(t,`${s}-sprite.css`);await ms(S,v);let E=m$(s,b,a),C=ps(t,`${s}-sprite.scss`);return await ms(C,E),{imagePath:g,cssPath:S,width:d,height:m,sprites:b}}function d$(e,t,r){return`
180
+ .${e} {
181
+ background-image: url('./${e}-sprite.${r}');
182
+ background-repeat: no-repeat;
183
+ display: inline-block;
184
+ }
185
+
186
+ ${t.map((i)=>`
187
+ .${e}-${i.name} {
188
+ width: ${i.width}px;
189
+ height: ${i.height}px;
190
+ background-position: -${i.x}px -${i.y}px;
191
+ }
192
+ `).join(`
193
+ `)}
194
+
195
+ /* Retina support */
196
+ @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
197
+ .${e} {
198
+ background-size: ${t[0].width*2}px ${t[0].height*2}px;
199
+ }
200
+ }
201
+ `}function m$(e,t,r){return`
202
+ $${e}-sprites: (
203
+ ${t.map((i)=>`
204
+ '${i.name}': (
205
+ x: -${i.x}px,
206
+ y: -${i.y}px,
207
+ width: ${i.width}px,
208
+ height: ${i.height}px
209
+ )`).join(`,
210
+ `)}
211
+ );
212
+
213
+ @mixin ${e}-sprite($name) {
214
+ $sprite: map-get($${e}-sprites, $name);
215
+
216
+ width: map-get($sprite, 'width');
217
+ height: map-get($sprite, 'height');
218
+ background-position: map-get($sprite, 'x') map-get($sprite, 'y');
219
+ background-image: url('./${e}-sprite.${r}');
220
+ background-repeat: no-repeat;
221
+ display: inline-block;
222
+
223
+ @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
224
+ $w: map-get($sprite, 'width');
225
+ $h: map-get($sprite, 'height');
226
+ background-size: $w * 2 $h * 2;
227
+ }
228
+ }
229
+ `}import{mkdir as p$,readFile as g$,writeFile as fa}from"fs/promises";import{join as ha}from"path";import{readFile as w$,writeFile as b$}from"fs/promises";import{join as v$}from"path";import{readFile as tm,writeFile as rm}from"fs/promises";import{join as im}from"path";import{mkdir as S$,writeFile as x$}from"fs/promises";import{readFile as $$}from"fs/promises";import{join as C$}from"path";var y$=[16,32,48,96,144,180,192,384,512],Dl=[16,32,48];async function pk(e,t,r={}){q("favicon",`Generating favicons from ${e} \u2192 ${t}`),await p$(t,{recursive:!0});let i=r.sizes&&r.sizes.length>0?Array.from(new Set([...r.sizes,...Dl])).sort((f,h)=>f-h):Array.from(new Set([...y$,...Dl])).sort((f,h)=>f-h),n=new Uint8Array(await g$(e)),s=await Re(n),a=[],o=new Map;for(let f of i){let h=Ee(s,{width:f,height:f}),d=await tt(h,"png");o.set(f,d);let m=ha(t,`favicon-${f}x${f}.png`);await fa(m,d),a.push({size:f,path:m,type:"png"})}let l=o.get(180);if(l){let f=ha(t,"apple-touch-icon.png");await fa(f,l),a.push({size:180,path:f,type:"png"})}let c=em(Dl.map((f)=>({size:f,png:o.get(f)}))),u=ha(t,"favicon.ico");if(await fa(u,c),a.push({size:32,path:u,type:"ico"}),r.manifest!==!1){let f=typeof r.manifest==="object"?r.manifest:{},h=(f.pathPrefix||"/").replace(/\/?$/,"/"),d={name:f.name||"App",short_name:f.shortName||f.name||"App",icons:[192,512].filter((p)=>i.includes(p)).map((p)=>({src:`${h}favicon-${p}x${p}.png`,sizes:`${p}x${p}`,type:"image/png",purpose:"any maskable"})),theme_color:f.themeColor||"#1c1917",background_color:f.backgroundColor||"#ffffff",display:"standalone",start_url:"/"},m=ha(t,"site.webmanifest");await fa(m,JSON.stringify(d,null,2)),a.push({size:0,path:m,type:"manifest"})}return a}function em(e){let t=6+e.length*16,r=t+e.reduce((a,o)=>a+o.png.byteLength,0),i=new Uint8Array(r),n=new DataView(i.buffer);n.setUint16(0,0,!0),n.setUint16(2,1,!0),n.setUint16(4,e.length,!0);let s=t;for(let a=0;a<e.length;a++){let o=e[a],l=6+a*16;n.setUint8(l+0,o.size===256?0:o.size),n.setUint8(l+1,o.size===256?0:o.size),n.setUint8(l+2,0),n.setUint8(l+3,0),n.setUint16(l+4,1,!0),n.setUint16(l+6,32,!0),n.setUint32(l+8,o.png.byteLength,!0),n.setUint32(l+12,s,!0),i.set(o.png,s),s+=o.png.byteLength}return i}var gk={encodeIco:em};async function bk(e,t,r={}){q("social",`Generating social media images from ${e}`);let i={"og-github":{width:1280,height:640},"og-facebook":{width:1200,height:630},"og-twitter":{width:1200,height:600},"og-linkedin":{width:1104,height:736},"og-instagram":{width:1080,height:1080}},n={},s=new Uint8Array(await w$(e)),a=await Re(s);for(let[o,l]of Object.entries(i)){let c=v$(t,`${o}.png`),u=Ee(a,{width:l.width,height:l.height,fit:"cover"}),f=await tt(u,"png",{quality:r.quality||80});await b$(c,f),n[o]=c}return n}async function xk(e){let{input:t,breakpoints:r,formats:i,outputDir:n="dist",quality:s=80,filenameTemplate:a="[name]-[width].[ext]",generateSrcset:o=!0}=e;if(typeof t!=="string")throw TypeError("Input must be a string path");q("responsive",`Generating responsive images for ${t}`);let l=new Uint8Array(await tm(t)),c=await Re(l),u=c.width,f=c.height,h=[],d={};for(let p of i){d[p]=[];for(let y of r){if(y>u)continue;let g=t.split("/").pop()?.split(".")[0]||"image",w=a.replace("[name]",g).replace("[width]",y.toString()).replace("[ext]",p),b=im(n,w),v=Ee(c,{width:y}),S=await tt(v,p,{quality:s});if(await rm(b,S),h.push({path:b,width:y,format:p,size:S.length}),o)d[p].push(`${b} ${y}w`)}}let m=`
230
+ <picture>
231
+ ${i.map((p)=>`
232
+ <source
233
+ type='image/${p}'
234
+ srcset='${d[p].join(", ")}'
235
+ sizes='(max-width: ${Math.max(...r)}px) 100vw, ${Math.max(...r)}px'
236
+ />`).join(`
237
+ `)}
238
+ <img
239
+ src='${h[0]?.path||""}'
240
+ alt=''
241
+ loading='lazy'
242
+ decoding='async'
243
+ width='${h[0]?.width||0}'
244
+ height='${Math.round((h[0]?.width||0)*(f/(u||1)))}'
245
+ />
246
+ </picture>`.trim();return{original:t,variants:h,srcset:d,htmlMarkup:m}}async function $k(e){let{input:t,name:r,sizes:i,outputDir:n,format:s="png",quality:a=80}=e;q("imageset",`Generating image set for ${t}`);let o=new Uint8Array(await tm(t)),l=await Re(o),c=[];for(let u of i){let f=u.suffix||`${u.width}x${u.height||u.width}`,h=im(n,`${r}-${f}.${s}`),d=Ee(l,{width:u.width,height:u.height,fit:u.height?"fill":"cover"}),m=await tt(d,s,{quality:a});await rm(h,m),c.push({size:u,path:h})}return c}var kk=32,qr=[0.025,0.1,0.2,0.35],Wr=[new Float64Array(1923),new Float64Array(1923),new Float64Array(1923),new Float64Array(1923)],Il=Array.from({length:4}),$i=[0,0,0,0],zl=[0,0,0,0],nm=new Float64Array(1024),pa=new Float64Array(256),_l=new Float64Array(1025);function A$(e){if(e<=0.0031308)return 12.92*e;if(e<0)return 0;return 1.055*e**0.4166666666666667-0.055}(function(){for(let e=0;e<4;e++){let t=qr[e],r=2*t*t*1024;for(let a=0;a<1923;a++){let o=Math.exp(-a/r);if(o<0.0000001)o=0;Wr[e][a]=o}let i=0;for(let a=0;a<32;a++){if(Wr[e][a*a]<0.0000001)break;i=a}$i[e]=i;let n=new Float64Array(i+1);for(let a=0;a<=i;a++)n[a]=Wr[e][a*a];Il[e]=n;let s=0;for(let a=-i;a<=i;a++){let o=n[Math.abs(a)];s+=o*o}zl[e]=s*s}for(let e=0;e<256;e++){let t=e/255;pa[e]=t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}for(let e=0;e<1024;e++)nm[e]=A$(e/1023);for(let e=0;e<=1024;e++)_l[e]=Math.cbrt(e/1024)})();function Ll(e){if(e<=0)return 0;if(e>=1)return _l[1024];return _l[Math.round(e*1024)]}function jl(e){if(e<=0)return 0;if(e>=1)return 1;return nm[Math.round(e*1023)]}function ga(e){let t=0,r=Math.abs(qr[0]-e);for(let i=1;i<4;i++){let n=Math.abs(qr[i]-e);if(n<r)r=n,t=i}return t}function E$(e,t,r){let i=I$(e,t,r,32,32),n=0,s=0,a=0,o=1024;for(let p=0;p<o;p++)n+=i[p*3],s+=i[p*3+1],a+=i[p*3+2];n/=o,s/=o,a/=o;let l=j$(n,s,a),c=lm(l);n=c.l,s=c.a,a=c.b;let u=new Float64Array(o),f=new Float64Array(o),h=new Float64Array(o);for(let p=0;p<o;p++)u[p]=i[p*3]-n,f[p]=i[p*3+1]-s,h[p]=i[p*3+2]-a;let d=new am,m=R$(u,f,h,32,32,d,6);if(m.length>0)m=P$(m,i,n,s,a,32,32);return D$(l,m)}function k$(e){return E$(e.data,e.width,e.height)}function M$(e){if(e.length!==16)throw Error("ts-images: invalid SplatHash \u2014 must be 16 bytes");let{meanL:t,meanA:r,meanB:i,splats:n}=L$(e),s=32,a=32,o=new Float64Array(s*a*3);for(let c=0;c<o.length;c+=3)o[c]=t,o[c+1]=r,o[c+2]=i;for(let c of n)B$(o,c,s,a);let l=new Uint8ClampedArray(s*a*4);for(let c=0;c<a;c++)for(let u=0;u<s;u++){let f=(c*s+u)*3,{r:h,g:d,b:m}=_$(o[f],o[f+1],o[f+2]),p=(c*s+u)*4;l[p]=de(Math.round(h*255+0.5),0,255),l[p+1]=de(Math.round(d*255+0.5),0,255),l[p+2]=de(Math.round(m*255+0.5),0,255),l[p+3]=255}return{width:s,height:a,rgba:l}}var Bt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function T$(e){let t="";for(let r=0;r<e.length;r+=3){let i=e[r],n=r+1<e.length?e[r+1]:0,s=r+2<e.length?e[r+2]:0;t+=Bt[i>>2],t+=Bt[(i&3)<<4|n>>4],t+=r+1<e.length?Bt[(n&15)<<2|s>>6]:"=",t+=r+2<e.length?Bt[s&63]:"="}return t}function Mk(e){let t=e.replace(/=+$/,""),r=[],i=0,n=0;for(let s of t){let a=Bt.indexOf(s);if(a<0)continue;if(n=n<<6|a,i+=6,i>=8)i-=8,r.push(n>>i&255)}return new Uint8Array(r)}function N$(e){let{width:t,height:r,rgba:i}=M$(e);return`data:image/bmp;base64,${U$(t,r,i)}`}function P$(e,t,r,i,n,s,a){let o=e.length,l=s*a,c=new Float64Array(l),u=new Float64Array(l),f=new Float64Array(l);for(let w=0;w<l;w++)c[w]=t[w*3]-r,u[w]=t[w*3+1]-i,f[w]=t[w*3+2]-n;let h=e.map((w)=>O$(w,s,a)),d=Math.min(o,3),m=Bl(h,c,o,0.001),p=Bl(h.slice(0,d),u,d,0.001),y=Bl(h.slice(0,d),f,d,0.001),g=[];for(let w=0;w<o;w++)g.push({...e[w],l:m[w],a:w<3?p[w]:0,b:w<3?y[w]:0});return g}function Bl(e,t,r,i){if(r===0)return new Float64Array(0);let n=t.length,s=new Float64Array(r*r),a=new Float64Array(r);for(let o=0;o<r;o++){let l=e[o];for(let u=o;u<r;u++){let f=0,h=e[u];for(let d=0;d<n;d++)f+=l[d]*h[d];s[o*r+u]=f,s[u*r+o]=f}let c=0;for(let u=0;u<n;u++)c+=l[u]*t[u];a[o]=c}for(let o=0;o<r;o++)s[o*r+o]+=i;return F$(s,a,r)}function F$(e,t,r){let i=new Float64Array(e),n=new Float64Array(t);for(let a=0;a<r-1;a++)for(let o=a+1;o<r;o++){let l=i[o*r+a]/i[a*r+a];for(let c=a;c<r;c++)i[o*r+c]-=l*i[a*r+c];n[o]-=l*n[a]}let s=new Float64Array(r);for(let a=r-1;a>=0;a--){let o=0;for(let l=a+1;l<r;l++)o+=i[a*r+l]*s[l];s[a]=(n[a]-o)/i[a*r+a]}return s}function O$(e,t,r){let i=new Float64Array(t*r),n=ga(e.sigma),s=$i[n],a=Math.floor(e.x*t),o=Math.floor(e.y*r),l=de(o-s,0,r-1),c=de(o+s,0,r-1),u=de(a-s,0,t-1),f=de(a+s,0,t-1);for(let h=l;h<=c;h++){let d=h-o,m=h*t;for(let p=u;p<=f;p++){let y=p-a,g=y*y+d*d;if(g<1923)i[m+p]=Wr[n][g]}}return i}class am{tmpL=new Float64Array(1024);tmpA=new Float64Array(1024);tmpB=new Float64Array(1024);scoreMap=new Float64Array(1024);sigmaMap=new Int8Array(1024)}function R$(e,t,r,i,n,s,a){let o=[];while(o.length<a){let l=o.length<3;s.scoreMap.fill(-1),s.sigmaMap.fill(-1);for(let x=0;x<4;x++){let A=Il[x],M=$i[x],k=1/zl[x];for(let P=0;P<n;P++){let T=P*i;for(let O=0;O<i;O++){let W=A[0]*e[T+O],X=A[0]*t[T+O],ee=A[0]*r[T+O];for(let he=1;he<=M;he++){let Y=A[he],le=O-he;if(le>=0){if(W+=Y*e[T+le],l)X+=Y*t[T+le],ee+=Y*r[T+le]}let K=O+he;if(K<i){if(W+=Y*e[T+K],l)X+=Y*t[T+K],ee+=Y*r[T+K]}}if(s.tmpL[T+O]=W,l)s.tmpA[T+O]=X,s.tmpB[T+O]=ee}}for(let P=0;P<i;P++)for(let T=0;T<n;T++){let O=A[0]*s.tmpL[T*i+P],W=A[0]*s.tmpA[T*i+P],X=A[0]*s.tmpB[T*i+P];for(let Y=1;Y<=M;Y++){let le=A[Y],K=T-Y;if(K>=0){if(O+=le*s.tmpL[K*i+P],l)W+=le*s.tmpA[K*i+P],X+=le*s.tmpB[K*i+P]}let _=T+Y;if(_<n){if(O+=le*s.tmpL[_*i+P],l)W+=le*s.tmpA[_*i+P],X+=le*s.tmpB[_*i+P]}}let ee=T*i+P,he=l?(O*O+W*W+X*X)*k:O*O*k;if(he>s.scoreMap[ee])s.scoreMap[ee]=he,s.sigmaMap[ee]=x}}let c=-1,u=-1;for(let x=0;x<i*n;x++)if(s.scoreMap[x]>c)c=s.scoreMap[x],u=x;if(u<0||c<0.000000001)break;let f=u%i,h=Math.floor(u/i),d=s.sigmaMap[u],m=Il[d],p=$i[d],y=zl[d],g=0,w=0,b=0;for(let x=-p;x<=p;x++){let A=h+x;if(A<0||A>=n)continue;let M=m[Math.abs(x)];for(let k=-p;k<=p;k++){let P=f+k;if(P<0||P>=i)continue;let T=M*m[Math.abs(k)],O=A*i+P;g+=T*e[O],w+=T*t[O],b+=T*r[O]}}let v=1/y,S={x:f/i,y:h/n,sigma:qr[d],l:g*v,a:w*v,b:b*v,isLepton:!l};o.push(S);let E=de(h-p,0,n-1),C=de(h+p,0,n-1),F=de(f-p,0,i-1),R=de(f+p,0,i-1);for(let x=E;x<=C;x++){let A=x-h,M=x*i;for(let k=F;k<=R;k++){let P=k-f,T=P*P+A*A;if(T>=1923)continue;let O=Wr[d][T];if(O===0)continue;let W=M+k;e[W]-=S.l*O,t[W]-=S.a*O,r[W]-=S.b*O}}}return o}function D$(e,t){let r=new sm;r.write(e,16);let i=0;for(let n of t){if(n.isLepton)continue;if(i>=3)break;r.write(de(Math.floor(n.x*15+0.5),0,15),4),r.write(de(Math.floor(n.y*15+0.5),0,15),4),r.write(ga(n.sigma),2),r.write(da(n.l,-0.8,0.8,4),4),r.write(da(n.a,-0.4,0.4,4),4),r.write(da(n.b,-0.4,0.4,4),4),i++}while(i<3)r.write(0,22),i++;i=0;for(let n of t){if(!n.isLepton)continue;if(i>=3)break;r.write(de(Math.floor(n.x*15+0.5),0,15),4),r.write(de(Math.floor(n.y*15+0.5),0,15),4),r.write(ga(n.sigma),2),r.write(da(n.l,-0.8,0.8,5),5),i++}while(i<3)r.write(0,15),i++;return r.write(0,1),r.getBytes()}function L$(e){let t=new om(e),{l:r,a:i,b:n}=lm(t.read(16)),s=[];for(let a=0;a<3;a++){let o=t.read(4),l=t.read(4),c=t.read(2),u=t.read(4),f=t.read(4),h=t.read(4);if(o===0&&l===0&&u===0&&f===0&&h===0)continue;s.push({x:o/15,y:l/15,sigma:qr[c],l:ma(u,-0.8,0.8,4),a:ma(f,-0.4,0.4,4),b:ma(h,-0.4,0.4,4),isLepton:!1})}for(let a=0;a<3;a++){let o=t.read(4),l=t.read(4),c=t.read(2),u=t.read(5);if(o===0&&l===0&&u===0)continue;s.push({x:o/15,y:l/15,sigma:qr[c],l:ma(u,-0.8,0.8,5),a:0,b:0,isLepton:!0})}return{meanL:r,meanA:i,meanB:n,splats:s}}class sm{buf=[];acc=0n;n=0;write(e,t){this.acc=this.acc<<BigInt(t)|BigInt(e),this.n+=t;while(this.n>=8){let r=BigInt(this.n-8);this.buf.push(Number(this.acc>>r&0xFFn)),this.n-=8}}getBytes(){if(this.n>0)this.buf.push(Number(this.acc<<BigInt(8-this.n)&0xFFn));return new Uint8Array(this.buf)}}class om{data;pos=0;rem=0;curr=0;constructor(e){this.data=e}read(e){let t=0,r=e;while(r>0){if(this.rem===0){if(this.pos>=this.data.length)return t<<r;this.curr=this.data[this.pos++],this.rem=8}let i=Math.min(this.rem,r),n=this.rem-i,s=(1<<i)-1;t=t<<i|this.curr>>n&s,this.rem-=i,r-=i}return t}}function j$(e,t,r){let i=de(Math.floor(e*63.5),0,63),n=de(Math.floor((t+0.2)/0.4*31.5),0,31),s=de(Math.floor((r+0.2)/0.4*31.5),0,31);return i<<10|n<<5|s}function lm(e){let t=e>>10&63,r=e>>5&31,i=e&31;return{l:t/63,a:r/31*0.4-0.2,b:i/31*0.4-0.2}}function da(e,t,r,i){let n=(1<<i)-1;return de(Math.floor((e-t)/(r-t)*n+0.5),0,n)}function ma(e,t,r,i){let n=(1<<i)-1;return e/n*(r-t)+t}function B$(e,t,r,i){let n=ga(t.sigma),s=$i[n],a=Math.floor(t.x*r),o=Math.floor(t.y*i),l=de(o-s,0,i-1),c=de(o+s,0,i-1),u=de(a-s,0,r-1),f=de(a+s,0,r-1);for(let h=l;h<=c;h++){let d=h-o,m=h*r*3;for(let p=u;p<=f;p++){let y=p-a,g=y*y+d*d;if(g>=1923)continue;let w=Wr[n][g];if(w===0)continue;let b=m+p*3;e[b]+=t.l*w,e[b+1]+=t.a*w,e[b+2]+=t.b*w}}}function I$(e,t,r,i,n){let s=new Float64Array(i*n*3);for(let a=0;a<n;a++){let o=(a*r+Math.floor(r/2))/n|0;for(let l=0;l<i;l++){let c=(l*t+Math.floor(t/2))/i|0,u=(o*t+c)*4,f=pa[e[u]],h=pa[e[u+1]],d=pa[e[u+2]],{l:m,a:p,b:y}=z$(f,h,d),g=(a*i+l)*3;s[g]=m,s[g+1]=p,s[g+2]=y}}return s}function z$(e,t,r){let i=0.4122214708*e+0.5363325363*t+0.0514459929*r,n=0.2119034982*e+0.6806995451*t+0.1073969566*r,s=0.0883024619*e+0.2817188376*t+0.6299787005*r,a=Ll(i),o=Ll(n),l=Ll(s);return{l:0.2104542553*a+0.793617785*o-0.0040720468*l,a:1.9779984951*a-2.428592205*o+0.4505937099*l,b:0.0259040371*a+0.7827717662*o-0.808675766*l}}function _$(e,t,r){let i=e+0.3963377774*t+0.2158037573*r,n=e-0.1055613458*t-0.0638541728*r,s=e-0.0894841775*t-1.291485548*r,a=i*i*i,o=n*n*n,l=s*s*s,c=4.0767416621*a-3.3077115913*o+0.2309699292*l,u=-1.2684380046*a+2.6097574011*o-0.3413193965*l,f=-0.0041960863*a-0.7034186147*o+1.707614701*l;return{r:jl(c),g:jl(u),b:jl(f)}}function U$(e,t,r){let i=e*3+3&-4,n=i*t,s=54+n,a=new Uint8Array(s),o=new DataView(a.buffer);a[0]=66,a[1]=77,o.setUint32(2,s,!0),o.setUint32(10,54,!0),o.setUint32(14,40,!0),o.setInt32(18,e,!0),o.setInt32(22,t,!0),o.setUint16(26,1,!0),o.setUint16(28,24,!0),o.setUint32(34,n,!0);for(let c=0;c<t;c++){let u=54+(t-1-c)*i;for(let f=0;f<e;f++){let h=(c*e+f)*4,d=u+f*3;a[d]=r[h+2],a[d+1]=r[h+1],a[d+2]=r[h]}}let l="";for(let c=0;c<a.length;c+=3){let u=a[c],f=c+1<a.length?a[c+1]:0,h=c+2<a.length?a[c+2]:0;l+=Bt[u>>2],l+=Bt[(u&3)<<4|f>>4],l+=c+1<a.length?Bt[(f&15)<<2|h>>6]:"=",l+=c+2<a.length?Bt[h&63]:"="}return l}function de(e,t,r){return e<t?t:e>r?r:e}var Xd=99;function cm(e,t){if(e.length!==t.length||e.length===0)return 0;let r=0,i=0;for(let n=0;n<e.length;n++){if((n&3)===3)continue;let s=e[n]-t[n];r+=s*s,i++}if(r===0)return Xd;return Math.min(Xd,10*Math.log10(65025/(r/i)))}var V$={avif:"avif",webp:"webp",jpeg:"jpg",png:"png"};async function G$(e,t,r){try{let i=await tt(e,t,{quality:r});if(!i||i.length===0)return null;let n=await Re(i);if(n.width!==e.width||n.height!==e.height)return null;return{bytes:i,psnr:cm(e.data,n.data)}}catch(i){return q("picture-set",`${t} skipped: ${i.message}`),null}}async function Tk(e){let{input:t,outDir:r,name:i,widths:n,formats:s=["avif","webp"],quality:a=72,minPsnr:o=34,fallbackFormat:l="jpeg",fallbackQuality:c=82}=e;await S$(r,{recursive:!0});let u=typeof t==="string"?await Re(new Uint8Array(await $$(t))):await Re(t),f=k$(u),h=T$(f),d=N$(f),m=[];for(let{label:p,width:y}of n){let g=Math.min(y,u.width),w=g===u.width?u:Ee(u,{width:g}),b=null;for(let S of s){let E=await G$(w,S,a);if(!E||E.psnr<o)continue;if(!b||E.bytes.length<b.bytes.length)b={format:S,...E}}if(!b){let S=await tt(w,l,{quality:c}),E=await Re(S).catch(()=>null);b={format:l,bytes:S,psnr:E?cm(w.data,E.data):0}}let v=C$(r,`${i}-${p}.${V$[b.format]??b.format}`);await x$(v,b.bytes),m.push({label:p,path:v,width:w.width,height:w.height,format:b.format,size:b.bytes.length,psnr:b.psnr})}return{name:i,width:u.width,height:u.height,variants:m,splatHash:h,blurDataURL:d}}export{U as us,fm as vs,He as ws,_r as xs,nf as ys,nr as zs,Ur as As,so as Bs,gn as Cs,oo as Ds,yn as Es,Xr as Fs,lo as Gs,co as Hs,hm as Is,dm as Js,mm as Ks,af as Ls,sf as Ms,Re as Ns,tt as Os,lf as Ps,cf as Qs,Pm as Rs,N as Ss,Md as Ts,$x as Us,Cx as Vs,Ax as Ws,q as Xs,Ex as Ys,fn as Zs,kx as _s,eo as $s,to as at,Td as bt,Tx as ct,Nx as dt,Px as et,Fx as ft,Ox as gt,Rx as ht,Nd as it,Pd as jt,ro as kt,Ee as lt,ua as mt,Vx as nt,Od as ot,Gx as pt,_n as qt,Wx as rt,qx as st,Kx as tt,Rd as ut,Yx as vt,Dd as wt,Hx as xt,Jx as yt,Zx as zt,Qx as At,Xx as Bt,e$ as Ct,Ld as Dt,jd as Et,Bd as Ft,mn as Gt,pn as Ht,t$ as It,Fr as Jt,r$ as Kt,n$ as Lt,a$ as Mt,Id as Nt,l$ as Ot,zd as Pt,_d as Qt,c$ as Rt,Ud as St,Vd as Tt,Gd as Ut,Wd as Vt,Hd as Wt,Jd as Xt,u$ as Yt,h$ as Zt,pk as _t,gk as $t,bk as au,xk as bu,$k as cu,kk as du,E$ as eu,k$ as fu,M$ as gu,T$ as hu,Mk as iu,N$ as ju,Tk as ku};