@stacksjs/bun-router 0.0.26 → 0.1.0

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 (103) hide show
  1. package/dist/chunk-0gjq8ttx.js +14 -0
  2. package/dist/chunk-0t5vz87j.js +35 -0
  3. package/dist/chunk-30rkn2ym.js +2 -0
  4. package/dist/chunk-38cmrard.js +2 -0
  5. package/dist/chunk-3qna6dwd.js +2 -0
  6. package/dist/chunk-4d5fmta0.js +2 -0
  7. package/dist/chunk-4x3b4b4q.js +2 -0
  8. package/dist/chunk-5be9x5cq.js +3 -0
  9. package/dist/chunk-5mxby3fd.js +1654 -0
  10. package/dist/chunk-5n0ckcmc.js +3 -0
  11. package/dist/chunk-5ncn73tp.js +3 -0
  12. package/dist/chunk-5s0pnsd6.js +12 -0
  13. package/dist/chunk-5s1pr62n.js +3 -0
  14. package/dist/chunk-67wgad4f.js +60 -0
  15. package/dist/chunk-6bbmkwng.js +3 -0
  16. package/dist/chunk-6s1kbajm.js +7851 -0
  17. package/dist/chunk-6sjvhy5f.js +3 -0
  18. package/dist/chunk-6xed4va1.js +2 -0
  19. package/dist/chunk-73k79n7q.js +15413 -0
  20. package/dist/chunk-748n6ydj.js +2 -0
  21. package/dist/chunk-7qnxdedn.js +321 -0
  22. package/dist/chunk-7rsf8tes.js +898 -0
  23. package/dist/chunk-8aspmtf1.js +2 -0
  24. package/dist/chunk-8wpj3fqe.js +351 -0
  25. package/dist/chunk-8yfdg595.js +2 -0
  26. package/dist/chunk-90eze7av.js +3 -0
  27. package/dist/chunk-9805tt8n.js +341 -0
  28. package/dist/chunk-9dvwyej7.js +2 -0
  29. package/dist/chunk-9ght4n4r.js +216 -0
  30. package/dist/chunk-a2w45krb.js +2 -0
  31. package/dist/chunk-a3wahyg7.js +3 -0
  32. package/dist/chunk-a547f2ab.js +48 -0
  33. package/dist/chunk-bqdycvtc.js +2 -0
  34. package/dist/chunk-brpgjyqg.js +3 -0
  35. package/dist/chunk-cd03rk3x.js +2 -0
  36. package/dist/chunk-csfrpsp7.js +185 -0
  37. package/dist/chunk-ct0m17q5.js +2 -0
  38. package/dist/chunk-dhbvvr5h.js +2 -0
  39. package/dist/chunk-dhptcsya.js +943 -0
  40. package/dist/chunk-dq93zag9.js +2 -0
  41. package/dist/chunk-dxg045wj.js +5 -0
  42. package/dist/chunk-e3qej0jr.js +4 -0
  43. package/dist/chunk-edrtesh7.js +2 -0
  44. package/dist/chunk-ejcws37w.js +2 -0
  45. package/dist/chunk-ex5fkjah.js +397 -0
  46. package/dist/chunk-ex890p45.js +51 -0
  47. package/dist/chunk-f69cpnhw.js +2 -0
  48. package/dist/chunk-fjf53b44.js +2 -0
  49. package/dist/chunk-fjzye4qj.js +2 -0
  50. package/dist/chunk-gfd23b6t.js +2 -0
  51. package/dist/chunk-habv0vef.js +12 -0
  52. package/dist/chunk-hmgedrmr.js +11 -0
  53. package/dist/chunk-hz6fc788.js +2 -0
  54. package/dist/chunk-jff6j9y3.js +10 -0
  55. package/dist/chunk-jmeb7n8k.js +70 -0
  56. package/dist/chunk-jrf5a2ap.js +2 -0
  57. package/dist/chunk-jy2jhcpy.js +246 -0
  58. package/dist/chunk-kc659vhx.js +4 -0
  59. package/dist/chunk-kjtjbcq4.js +71 -0
  60. package/dist/chunk-krkchy8v.js +4 -0
  61. package/dist/chunk-kxp888dn.js +4540 -0
  62. package/dist/chunk-m249t3je.js +3 -0
  63. package/dist/chunk-m9yabnjx.js +2 -0
  64. package/dist/chunk-mekrq9wd.js +2 -0
  65. package/dist/chunk-mmxv535f.js +82 -0
  66. package/dist/chunk-mypn7jss.js +2 -0
  67. package/dist/chunk-n18x1k3c.js +2 -0
  68. package/dist/chunk-nkddjzsa.js +2 -0
  69. package/dist/chunk-pjmhqmr9.js +2 -0
  70. package/dist/chunk-qyrnsaq1.js +2 -0
  71. package/dist/chunk-r19ff2qm.js +62 -0
  72. package/dist/chunk-r338fssq.js +2 -0
  73. package/dist/chunk-s36z58x2.js +29 -0
  74. package/dist/chunk-s3dn1kwx.js +231 -0
  75. package/dist/chunk-s79dd325.js +471 -0
  76. package/dist/chunk-sw0chtw4.js +4 -0
  77. package/dist/chunk-ta38j9em.js +2 -0
  78. package/dist/chunk-tpfgntwj.js +4211 -0
  79. package/dist/chunk-vr10sbbh.js +3 -0
  80. package/dist/chunk-vsh4390q.js +358 -0
  81. package/dist/chunk-vv3gb1m5.js +84 -0
  82. package/dist/chunk-vw8rwv6e.js +2 -0
  83. package/dist/chunk-w4r464v5.js +288 -0
  84. package/dist/chunk-wcrqs5z9.js +2 -0
  85. package/dist/chunk-x6d1rmwa.js +2 -0
  86. package/dist/chunk-x7ft15zz.js +2 -0
  87. package/dist/chunk-x8trwn7j.js +3 -0
  88. package/dist/chunk-xg9xscqz.js +1 -0
  89. package/dist/chunk-xhepdj1f.js +2 -0
  90. package/dist/chunk-xv2em0q4.js +4 -0
  91. package/dist/chunk-ypw6g0te.js +2 -0
  92. package/dist/chunk-z8szsm21.js +2 -0
  93. package/dist/chunk-zetqzgf3.js +194 -0
  94. package/dist/chunk-zfbh14qe.js +2 -0
  95. package/dist/chunk-zhx0hxdd.js +28 -0
  96. package/dist/cli.js +67 -3240
  97. package/dist/container/index.js +1 -321
  98. package/dist/index.js +80 -13987
  99. package/dist/types.d.ts +12 -2
  100. package/package.json +1 -1
  101. package/dist/chunk-1ahs68ys.js +0 -18
  102. package/dist/chunk-cgptvjdf.js +0 -18131
  103. package/dist/chunk-g3ybefhg.js +0 -1923
@@ -0,0 +1,246 @@
1
+ // @bun
2
+ import{Zu as Pe}from"./chunk-a3wahyg7.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 yn}from"buffer";import{mkdir as uf,readdir as Dm,readFile as mi,stat as ct,writeFile as Qt}from"fs/promises";import{dirname as ff,extname as ri,join as Ji}from"path";import{existsSync as Ul,statSync as Vl}from"fs";import{join as Lm,relative as jm,resolve as Gl}from"path";import wn from"process";import{Buffer as wt}from"buffer";import{createCipheriv as Bm,createDecipheriv as Im,randomBytes as ya}from"crypto";import{closeSync as wa,createReadStream as Wl,createWriteStream as zm,existsSync as $i,fsyncSync as ql,openSync as Kl,writeFileSync as _m}from"fs";import{access as Um,constants as Yl,mkdir as Vm,readdir as Ci,rename as Hl,stat as sr,unlink as Ai,writeFile as ba}from"fs/promises";import{isAbsolute as Gm,join as or,resolve as Wm}from"path";import ee from"process";import{pipeline as qm}from"stream/promises";import{createGzip as Jl}from"zlib";import lr from"process";import xt from"process";import Ei from"process";import{existsSync as ki}from"fs";import{resolve as va}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 cr}from"os";import{dirname as Zl,resolve as Le}from"path";import Xt from"process";import{existsSync as Qm,readdirSync as Xm}from"fs";import{extname as Sa,resolve as Ql}from"path";import ep from"process";import{Buffer as xa}from"buffer";import tp from"process";import{Stream as rp}from"stream";import{existsSync as Xl,statSync as ec}from"fs";import{join as ip,relative as np,resolve as tc}from"path";import bn from"process";import{Buffer as bt}from"buffer";import{createCipheriv as ap,createDecipheriv as sp,randomBytes as $a}from"crypto";import{closeSync as Ca,createReadStream as rc,createWriteStream as op,existsSync as Mi,fsyncSync as ic,openSync as nc,writeFileSync as lp}from"fs";import{access as cp,constants as ac,mkdir as up,readdir as Ti,rename as sc,stat as ur,unlink as Ni,writeFile as Aa}from"fs/promises";import{isAbsolute as fp,join as fr,resolve as hp}from"path";import te from"process";import{pipeline as dp}from"stream/promises";import{createGzip as oc}from"zlib";import hr from"process";import $t from"process";import Pi from"process";import{existsSync as Fi}from"fs";import{resolve as Ea}from"path";import{existsSync as mp}from"fs";import{existsSync as ys,mkdirSync as pp,readdirSync as gp,readFileSync as yp,writeFileSync as wp}from"fs";import{homedir as dr}from"os";import{dirname as lc,resolve as je}from"path";import er from"process";import{existsSync as bp,readdirSync as vp}from"fs";import{extname as ka,resolve as cc}from"path";import Sp from"process";import{Buffer as xp}from"buffer";import{stat as E2}from"fs/promises";import{relative as k2,resolve as M2}from"path";import{existsSync as yu,statSync as wu}from"fs";import{existsSync as Vs,mkdirSync as T2,readdirSync as N2,writeFileSync as P2}from"fs";import{homedir as gr}from"os";import{dirname as bu,resolve as Be}from"path";import tr from"process";import{join as F2,relative as O2,resolve as vu}from"path";import Tn from"process";import{existsSync as od,mkdirSync as vA,readdirSync as SA,writeFileSync as xA}from"fs";import{homedir as Ha}from"os";import{dirname as AA,resolve as De}from"path";import ui from"process";import{join as R2,relative as D2,resolve as Su}from"path";import Nn from"process";import{existsSync as ld,mkdirSync as NA,readdirSync as PA,writeFileSync as FA}from"fs";import{dirname as RA,resolve as Pn}from"path";import Gs from"process";import{Buffer as Bt}from"buffer";import{createCipheriv as L2,createDecipheriv as j2,randomBytes as Ja}from"crypto";import{closeSync as Za,createReadStream as xu,createWriteStream as B2,existsSync as Qa,fsyncSync as $u,openSync as Cu,writeFileSync as I2}from"fs";import{access as z2,constants as Au,mkdir as _2,readdir as ji,rename as Eu,stat as yr,unlink as Bi,writeFile as Xa}from"fs/promises";import{join as wr}from"path";import Me from"process";import{pipeline as U2}from"stream/promises";import{createGzip as ku}from"zlib";import br from"process";import At from"process";import{Buffer as vt}from"buffer";import{createCipheriv as V2,createDecipheriv as G2,randomBytes as es}from"crypto";import{closeSync as ts,createReadStream as Mu,createWriteStream as W2,existsSync as Ii,fsyncSync as Tu,openSync as Nu,writeFileSync as q2}from"fs";import{access as K2,constants as Pu,mkdir as Y2,readdir as zi,rename as Fu,stat as vr,unlink as _i,writeFile as rs}from"fs/promises";import{isAbsolute as H2,join as Sr,resolve as J2}from"path";import re from"process";import{pipeline as Z2}from"stream/promises";import{createGzip as Ou}from"zlib";import xr from"process";import Et from"process";import Ui from"process";import{existsSync as Vi}from"fs";import{resolve as is}from"path";import{existsSync as Q2}from"fs";import{existsSync as X2,readdirSync as eS}from"fs";import{extname as ns,resolve as Ru}from"path";import tS from"process";import{join as rS,relative as iS,resolve as Du}from"path";import Fn from"process";import{Buffer as St}from"buffer";import{createCipheriv as nS,createDecipheriv as aS,randomBytes as as}from"crypto";import{closeSync as ss,createReadStream as Lu,createWriteStream as sS,existsSync as Gi,fsyncSync as ju,openSync as Bu,writeFileSync as oS}from"fs";import{access as lS,constants as Iu,mkdir as cS,readdir as Wi,rename as zu,stat as $r,unlink as qi,writeFile as os}from"fs/promises";import{isAbsolute as uS,join as Cr,resolve as fS}from"path";import ie from"process";import{pipeline as hS}from"stream/promises";import{createGzip as _u}from"zlib";import Ar from"process";import kt from"process";import{mkdir as rf,readFile as qd,writeFile as di}from"fs/promises";import{join as Ir,resolve as Kd}from"path";import{readFile as m$,writeFile as ms}from"fs/promises";import{join as ps}from"path";function _(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 Ye(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 zr(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=Ye(e,i,n),u=Ye(e,s,n),f=Ye(e,i,a),h=Ye(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 ir(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 _r(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 pn(e);if(t===180)return oo(e);if(t===270)return gn(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=_(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);zr(u,y,p,S)}}return u}function pn(e){let t=_(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=_(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 gn(e){let t=_(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 Qr(e){let t=_(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=_(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=_(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=_(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 _(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 Qr(e);case 5:return pn(Qr(e));case 6:return pn(e);case 7:return gn(Qr(e));case 8:return gn(e);default:return e}}var ga=Object.create(null);async function Xe(e){let t=ga[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 ga[e]={module:r,available:!0},r}catch(r){throw ga[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 Ur(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=Ur(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 Oe(e,t={}){let r=Ur(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 et(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=Ur(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 Oe(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 Xe("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=ir(r.data,r.width,r.height,{channels:n});return s.hasAlpha=!1,s}async function ym(e,t){let r=await Xe("ts-jpeg"),i=_r(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 Xe("@stacksjs/ts-png")).png.sync.read(Buffer.from(e));return ir(r.data,r.width,r.height,{channels:4})}async function bm(e,t){let r=await Xe("@stacksjs/ts-png"),i=Buffer.from(Uint8Array.from(_r(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 Xe("ts-gif")).Reader(Buffer.from(e)),i=r.frameInfo(0),n=new Uint8Array(i.width*i.height*4);return r.decodeAndBlitFrameRGBA(0,n),ir(n,i.width,i.height,{channels:4})}async function Sm(e,t){let r=await Xe("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 Xe("@stacksjs/ts-bmp")).decode(e);return ir(r.data,r.width,r.height,{channels:4})}async function $m(e,t){let r=await Xe("@stacksjs/ts-bmp"),i=_r(e,{channels:4});return r.encode({width:e.width,height:e.height,data:i})}async function Cm(e,t){let r=(await Xe("@stacksjs/ts-webp")).decode(e),i=4,n=ir(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 Xe("@stacksjs/ts-webp"),i=_r(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 Xe("@stacksjs/ts-avif")).decode(e);return ir(r.data,r.width,r.height,{channels:4})}async function km(e,t){let r=await Xe("@stacksjs/ts-avif"),i=_r(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=Ur(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 Oe(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)=>{return 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}}},T=Fm,$p=Object.defineProperty,Cp=(e)=>e;function Ap(e,t){this[e]=Cp.bind(null,t)}var R=(e,t)=>{for(var r in t)$p(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ap.bind(t,r)})},Ep=Object.defineProperty,kp=(e)=>e;function Mp(e,t){this[e]=kp.bind(null,t)}var Tp=(e,t)=>{for(var r in t)Ep(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Mp.bind(t,r)})},Dt=(e,t)=>()=>(e&&(t=e(e=0)),t),Np=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 Pp(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function Fp(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Op(e){return e.getStats().size*2}var Fr,pi,hf,gi=Dt(()=>{Fr=new uo,pi=new fo,hf={createKey:Pp,isEquivalent:Fp,estimateMemoryUsage:Op}});function Rp(e,t={}){let r=wn.cwd();while(r.includes("storage"))r=Gl(r,"..");let i=Gl(r,e||"");if(t?.relative)return jm(wn.cwd(),i);return i}function ge(){if(xt.env.NODE_ENV==="test"||xt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Dp(){if(xt.env.NODE_ENV==="test"||xt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof xt<"u"){let e=xt.type;if(e==="renderer"||e==="worker")return!1;return!!(xt.versions&&(xt.versions.node||xt.versions.bun))}return!1}class df{async format(e){let t=await Dp(),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:lr.pid,hostname:t(),environment:lr.env.NODE_ENV||"development",platform:lr.platform,version:lr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:lr.env.NODE_ENV||lr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class _n{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={...Xr},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??ee.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{...Zi,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Zi};return{...Zi,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Xr.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!ge()&&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:wt.from(e);try{if(!$i(this.currentLogFile))await ba(this.currentLogFile,"",{mode:420});if(i=Kl(this.currentLogFile,"a",420),_m(i,o,{flag:"a"}),ql(i),i!==void 0)wa(i),i=void 0;if((await sr(this.currentLogFile)).size===0){if(await ba(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{wa(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 or(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 or(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return or(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ge())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 ya(16).toString("hex")}generateKey(){return ya(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=ya(16),i=Bm("aes-256-gcm",t,r),n=wt.isBuffer(e)?e:wt.from(e,"utf8"),s=i.update(n),a=i.final(),o=s.length+a.length,l=i.getAuthTag(),c=wt.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(wt.from(wt.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(ge())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 Ci(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 Hl(r,o),t.compress)try{let l=`${o}.gz`;await this.compressLogFile(o,l),await Ai(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 ba(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 Hl(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Ci(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Ai(or(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()})),$i(this.currentLogFile))try{let e=Kl(this.currentLogFile,"r+");ql(e),wa(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(!ge()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ci(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ai(or(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?Y.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ge())return!1;let e=typeof ee.env.NO_COLOR<"u",t=ee.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof ee.stderr<"u"&&ee.stderr.isTTY||typeof ee.stdout<"u"&&ee.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=ee.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} ${Y.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=Y.underline(Y.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)=>Y.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>Y.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>Y.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>Y.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>Y.strikethrough(i)),t}supportsHyperlinks(){if(ge())return!1;let e=ee.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=ee.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Gm(t)||t.startsWith("./")||t.startsWith("../"))t=Wm(t);else return null;return $i(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?Y.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:Y.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:Y.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:Y.gray(` ${p}`),level:e,showTimestamp:!1}))}break}}else if(!ge()){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()&&!ge()&&ee.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()&&!ge()&&ee.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!ge()&&ee.stdout.isTTY)ee.stdout.write(`
6
+ `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!ge()&&ee.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?Y.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":Y.blue("\u25D0"),tag:r,message:`${Y.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),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?Y.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:this.options.showIcons===!1?"":Y.green("\u2713"),tag:c,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ge())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 _n(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(ge())throw Error("createReadStream is not supported in browser environments");if(!$i(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=wt.isBuffer(e)?e:wt.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=wt.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 ge()}isServerMode(){return!ge()}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)=>{return this.formatConsoleMessage({timestamp:r,message:Y.cyan(h),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:Y.cyan(c),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:Y.cyan(u),showTimestamp:!1}))}else if(!ge())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(ge())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Y.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();ee.stdin.removeListener("data",r);try{if(typeof ee.stdin.setRawMode==="function")ee.stdin.setRawMode(!1)}catch{}ee.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof ee.stdin.setRawMode==="function")ee.stdin.setRawMode(!0)}catch{}ee.stdin.resume(),ee.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?Y.gray(this.formatTag(this.name)):"",o=this.options.showIcons===!1?"":`${Y.blue("\u25D0")} `;console.error(`${o}${a} ${Y.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()||!ee.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=Y.green("\u2501".repeat(i)),a=Y.gray("\u2501".repeat(n)),o=`[${s}${a}]`,l=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?Y.green("\u2713"):Y.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${Y.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${o} ${l}${c}`,d=ee.stdout.columns||80,m=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,ee.stdout.write(e.lastRenderedLine),t)ee.stdout.write(`
11
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ge()||!ee.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(ge()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ci(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=or(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 Ai(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,Xr,Lp,ye,Y,jp,fc,Bp,hc,Ip,zp,Ta,_p,dc,mc,Up,Na,Vp,Gp,Wp,qp,Kp,Zi,mf,Yp,Hp=Dt(()=>{uc=wn.env.CLARITY_LOG_DIR||Lm(Rp(),"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},Xr={...Ma},Lp=(async()=>{try{let{loadConfig:e}=await Promise.resolve().then(()=>(Tf(),Mf)),t=await e({name:"clarity",alias:"logging",defaultConfig:Ma,cwd:wn.cwd()});if(t)Object.assign(Xr,t)}catch{}return Xr})(),ye={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},Y=ye,jp=ye.red,fc=ye.green,Bp=ye.yellow,hc=ye.blue,Ip=ye.magenta,zp=ye.cyan,Ta=ye.white,_p=ye.gray,dc=ye.bgRed,mc=ye.bgYellow,Up=ye.bgGray,Na=ye.bold,Vp=ye.dim,Gp=ye.italic,Wp=ye.underline,qp=ye.strikethrough,Kp=ye.reset,Zi={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 ")))},Yp=new _n("stacks")}),Jp="0.15.9",Zp=()=>{};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 Ve}function Qp(e){return e instanceof vn}function Xp(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 Ve,vn,ii,ws,bs,Sn,vs,Ss,ni,xs,$s,_t,Or=Dt(()=>{Ve=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}`}},vn=class extends Ve{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})}},ii=class extends Ve{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 Ve{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 Ve{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}},Sn=class extends Ve{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 Ve{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 Ve{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}},ni=class extends Ve{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 Ve{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 Ve{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}},_t={configNotFound(e,t,r){return new vn(e,t,r)},configLoad(e,t,r){return new ii(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 Sn(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 ni(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 Un{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 pi.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=Ei.env[l]||(c?Ei.env[c]:void 0);if(u!==void 0){if(i.verbose){let f=Ei.env[l]?l:c}try{e[n]=this.parseEnvironmentValue(u,typeof s,l,i.customParsers,i.configName)}catch(f){if(f instanceof Sn)throw f;throw _t.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 _t.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(Ei.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=Dt(()=>{gi(),Or()});function eg(e,t){let r=Np("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(!He(t)||!He(e))return t;return ng(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 tg(e,t);case"smart":return rg(e,t,i);default:return t}return t}function tg(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Cs(n,i)))r.push(i);return r}function rg(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(He(t[0])&&He(e[0]))return ig(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 ig(e,t,r){let i=[...t];for(let n of e){if(!He(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)=>He(l)&&(o in l)&&l[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function ng(e,t,r,i){let n=t;if(He(n)&&i.has(n))return i.get(n);let s={...e};if(He(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(He(o)&&He(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(He(e)&&He(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 He(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}var Sf,mo=Dt(()=>{Sf={replace:"replace",concat:"concat",smart:"smart"}});class Vn{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=Fr.getWithFileCheck("file",e);if(c){if(o)console.log(`Configuration loaded from cache: ${e}`);return c}}let l=async()=>{if(!ki(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 ii(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new ii(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)Fr.setWithFileCheck("file",m,e,s);return m}catch(c){throw c instanceof Error?_t.configLoad(e,c):_t.configLoad(e,Error(String(c)))}};if(a)return pi.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(va(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()=>{return ki(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!ki(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=va(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=va(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(!ki(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=Dt(()=>{gi(),Or(),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 pi.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!Km(t))throw new ni(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 ni(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=Dt(()=>{gi(),Or(),$f=/^https?:\/\//});function ag(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 Vn;envProcessor=new Un;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)qe.warn(`Slow configuration loading detected: ${l.duration}ms for ${a.name}`);o.metrics=l}return o}catch(o){let l=Date.now()-t;throw qe.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||Xt.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(Le(f,"package.json")),this.finalizeResult(p,h,l,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,a)),t)throw _t.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,o,l,u),warnings:[`No configuration file found for "${i}"${ag(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)qe.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)qe.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=[Le(cr(),".config",e),Le(cr(),".config"),cr()];for(let l of o){if(n)qe.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)qe.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=Le(r,"package.json");if(!gs(l))return null;let c={};try{c=JSON.parse(Jm(l,"utf8"))}catch(h){if(s)qe.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)qe.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)qe.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 _t.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Fr.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Fr.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,Le(e,"config"),Le(e,".config"),t?Le(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(Le(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=[Le(cr(),".config",e),Le(cr(),".config"),cr()],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 sg(e){return Tt.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 Tt.loadConfig(e);else i=await Tt.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)qe.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 Tt.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function og(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Tt.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 Tt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Tt.loadConfig({...e,cwd:e.cwd||Xt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&pc(t)))return(await Tt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function lg(e,t,r="replace"){let i=new Vn;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 Un,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=Xt.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 cg(e){let t=Le(Xt.cwd(),e.configDir),r=Le(Xt.cwd(),e.generatedDir),i=Le(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${Jp}
24
+ export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
25
+ `;Zm(i,s,{mode:438})}function ug(e){let t=null,r=null,i=()=>{if(!r)r=Af(e).then((s)=>{return t=s,s},(s)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)qe.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 qe,Tt,Ef,kf,fg=Dt(()=>{Hp(),Zp(),gi(),Or(),yf(),xf(),Cf(),mo(),qe=new _n("bunfig",{showTags:!0}),Tt=new go,Ef=Le(Xt.cwd(),"config"),kf=Le(Xt.cwd(),"src/generated")});function hg(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(Sa(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=Sa(c).toLowerCase(),f=o.get(l);if(!f){o.set(l,c);continue}let h=Sa(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)=>{return{path:s.path,namespace:"bunfig-virtual"}}),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:i(),loader:"ts"}})}}}var dg=()=>{},Mf={};Tp(Mf,{withErrorRecovery:()=>pf,tryLoadConfig:()=>lg,loadConfigWithResult:()=>sg,loadConfig:()=>Af,isRetryableError:()=>Xp,isConfigNotFoundError:()=>Qp,isBunfigError:()=>gf,globalPerformanceMonitor:()=>pi,globalCache:()=>Fr,getEnvOrDefault:()=>eg,generateConfigTypes:()=>cg,defaultGeneratedDir:()=>kf,defaultConfigDir:()=>Ef,deepMergeWithArrayStrategy:()=>ho,deepMerge:()=>wf,createLibraryConfig:()=>ug,config:()=>og,bunfigPlugin:()=>hg,applyEnvVarsToConfig:()=>qr,TypeGenerationError:()=>Ss,SchemaValidationError:()=>ni,PluginError:()=>$s,PerformanceMonitor:()=>fo,FileSystemError:()=>vs,ErrorFactory:()=>_t,EnvVarError:()=>Sn,EnvProcessor:()=>Un,ConfigValidator:()=>po,ConfigValidationError:()=>ws,ConfigNotFoundError:()=>vn,ConfigMergeError:()=>bs,ConfigLoader:()=>go,ConfigLoadError:()=>ii,ConfigFileLoader:()=>Vn,ConfigCache:()=>uo,CacheUtils:()=>hf,BunfigError:()=>Ve,BrowserConfigError:()=>xs,ArrayMergeStrategies:()=>Sf});var Tf=Dt(()=>{fg(),Or(),gi(),Or(),dg(),yf(),xf(),Cf(),mo()});Tf();var mg={verbose:!1,tolerance:0.25,background:"transparent",currentColor:"black",maxUseDepth:16},QC={...mg},pg={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]},XC=new Map(Object.entries(pg)),eA=new Uint8Array(0),tA=new Float32Array(0),rA=new Uint8Array([137,80,78,71,13,10,26,10]);var zt={GRAYSCALE:0,PALETTE:1,COLOR:2,ALPHA:4},xn={PALETTE_COLOR:3,COLOR_ALPHA:6},iA={[zt.GRAYSCALE]:1,[zt.COLOR]:3,[xn.PALETTE_COLOR]:1,[zt.GRAYSCALE|zt.ALPHA]:2,[xn.COLOR_ALPHA]:4};var{GRAYSCALE:nA,PALETTE:aA,COLOR:sA,ALPHA:oA}=zt,lA=xn.PALETTE_COLOR,cA=xn.COLOR_ALPHA,gg=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;gg[e]=t}})();class yg extends rp{_buffers=[];_buffered=0;_reads=[];_paused=!1;_encoding="utf-8";writable=!0;constructor(){super()}read(e,t){this._reads?.push({length:Math.abs(e),allowLess:e<0,func:t}),tp.nextTick(()=>{if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")})}write(e,t){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let r=xa.isBuffer(e)?e:xa.from(e,t||this._encoding);if(this._buffers?.push(r),this._buffered+=r.length,this._process(),this._reads?.length===0)this._paused=!0;return this.writable&&!this._paused}end(e,t){if(e)this.write(e,t);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()}destroySoon=this.end;_end(){if(this._reads&&this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()}destroy(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")}_processReadAllowingLess(e){if(this._reads?.shift(),!this._buffers)return;let t=this._buffers[0];if(!t)return;if(t.length>e.length)this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length));else this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t)}_processRead(e){this._reads?.shift();let t=0,r=0,i=xa.alloc(e.length);while(t<e.length){if(!this._buffers)break;let n=this._buffers[r++];if(!n)break;let s=Math.min(n.length,e.length-t);if(n.copy(i,t,0,s),t+=s,s!==n.length)this._buffers[--r]=n.slice(s)}if(r>0)this._buffers?.splice(0,r);this._buffered-=e.length,e.func.call(this,i)}_process(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}if(this._buffers&&!this.writable)this._end()}catch(e){this.emit("error",e instanceof Error?e:Error(String(e)))}}}function Nf(e,t,r){return Math.round(0.2126*e+0.7152*t+0.0722*r)}function wg(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 bg(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 vg(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 Sg(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 xg(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,A=b*b+v*v+S*S;if(A<g)g=A,y=l[w].key}u.get(y)[h]=1}return u}function $g(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=bg(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=vg(e,o);else if(n==="grayscale")d=Sg(e,Math.max(2,o));else d=xg(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="${wg(b,v,S)}" d="${w}"/>`)}return{svg:`${f}${u}${p.join("")}${h}`,width:r,height:i}}var Pf={};R(Pf,{name:()=>Cg,fn:()=>Eg,description:()=>Ag});var Cg="addAttributesToSVGElement",Ag="adds attributes to an outer <svg> element",Eg=(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={};R(Ff,{name:()=>kg,fn:()=>Tg,description:()=>Mg});var kg="addClassesToSVGElement",Mg="adds classnames to an outer <svg> element",Tg=(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={};R(wo,{name:()=>Ng,fn:()=>Dg,description:()=>Pg});var Ng="cleanupAttrs",Pg="cleanups attributes from newlines, trailing and repeating spaces",Fg=/(\S)\r?\n(\S)/g,Og=/\r?\n/g,Rg=/\s{2,}/g,Dg=(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(Fg,(o,l,c)=>`${l} ${c}`),s.attributes[a]=s.attributes[a].replace(Og,"");if(i)s.attributes[a]=s.attributes[a].trim();if(n)s.attributes[a]=s.attributes[a].replace(Rg," ")}}}}},bo={};R(bo,{name:()=>Qy,fn:()=>tw,description:()=>Xy});var Lg=Object.defineProperty,jg=(e)=>e;function Bg(e,t){this[e]=jg.bind(null,t)}var Gn=(e,t)=>{for(var r in t)Lg(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Bg.bind(t,r)})},V={};Gn(V,{walk:()=>qn,parse:()=>So,makeList:()=>Ig,generate:()=>_e,decodeName:()=>Df,clone:()=>zg,Tokenizer:()=>vo,TokenType:()=>Of,List:()=>Je});function dt(e){return{prev:null,next:null,data:e}}class Je{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 dt(e)}createItem(e){return dt(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=dt(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 Je,r=null,i=0;for(let n=this.head;n!=null;n=n.next){let s=dt(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 Je,r=null,i=0;for(let n=this.head;n!=null;n=n.next)if(e(n.data,i++,this)){let s=dt(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 Je,t=null;for(let r=this.head;r!=null;r=r.next){let i=dt(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(dt(e),this.head)}append(e){return this.insert(e,null)}appendData(e){return this.insert(dt(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(dt(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(dt(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 Je)this.insertList(t,e),this.remove(e);else this.insert(t,e),this.remove(e)}}function Ig(){return new Je}function zg(e){return Kr(e)}function Kr(e){if(e===null||typeof e!=="object")return e;if(e instanceof Je){let r=new Je;for(let i of e)r.appendData(Kr(i));return r}if(Array.isArray(e))return e.map(Kr);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]=Kr(e[i])}return r}let t={};for(let r of Object.keys(e))t[r]=Kr(e[r]);return t}function _e(e){switch(e.type){case"StyleSheet":return Ue(e.children,"");case"Rule":return`${_e(e.prelude)}{${_e(e.block)}}`;case"Block":return _g(e.children);case"Atrule":{let t=`@${e.name}`;if(e.prelude){let r=_e(e.prelude);if(r)t+=` ${r}`}if(e.block)t+=`{${_e(e.block)}}`;else t+=";";return t}case"AtrulePrelude":return Ue(e.children,"");case"SelectorList":return Ue(e.children,",");case"Selector":return Ue(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}(${Ue(e.children,"")})`:`:${e.name}`;case"PseudoElementSelector":return e.children?`::${e.name}(${Ue(e.children,"")})`:`::${e.name}`;case"Combinator":return e.name===" "?" ":e.name;case"Declaration":return`${e.property}:${_e(e.value)}${e.important?"!important":""}`;case"DeclarationList":return Ue(e.children,";");case"Value":return Ue(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}(${Ue(e.children,"")})`;case"Parentheses":return`(${Ue(e.children,"")})`;case"Brackets":return`[${Ue(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?`${_e(e.nth)} of ${_e(e.selector)}`:_e(e.nth);case"MediaQueryList":return Ue(e.children,",");case"MediaQuery":return Ue(e.children,"");case"MediaFeature":{let t=`(${e.name}`;if(e.value)t+=`:${_e(e.value)}`;return t+=")",t}}return""}function Ue(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=_e(a);if(!o){s=s.next;continue}if(!i&&t&&!Vg(n))r+=t;i=!1,r+=o,n=a,s=s.next}return r}function _g(e){let t="",r=null,i=e.head;while(i!=null){let n=i.data,s=_e(n);if(!s){i=i.next;continue}if(r&&Ug(r,n))t+=";";t+=s,r=n,i=i.next}return t}function Ug(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 Vg(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,nr=(()=>{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 nt(e){return e<128&&(nr[e]&2)!==0}function ai(e){return e<128&&(nr[e]&4)!==0}function wc(e){return e>=128||e<128&&(nr[e]&8)!==0}function Gg(e){return e===45||e>=128||e<128&&(nr[e]&10)!==0}function Wg(e){return e>=0&&e<=8||e===11||e>=14&&e<=31||e===127}function Es(e){return e<128&&(nr[e]&16)!==0}function Ct(e){return e<128&&(nr[e]&1)!==0}function Ht(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||Ht(t,r);if(wc(e))return!0;if(e===92)return Ht(e,t);return!1}function qg(e,t,r){if(e===43||e===45){if(nt(t))return!0;if(t===46&&nt(r))return!0;return!1}if(e===46)return nt(t);return nt(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=Kg(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(Ct(i)){let a=t;while(t<r&&Ct(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&&(Gg(e.charCodeAt(t+1))||Ht(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(qg(i,n,s)){t=this.consumeNumeric(t);continue}if(Fa(i,n,s)){t=this.consumeIdentLike(t);continue}if(i===92){if(Ht(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(ai(r)){let i=1;e++;while(i<6&&e<t.length&&ai(t.charCodeAt(e)))e++,i++;if(e<t.length&&Ct(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&&(nr[n]&10)!==0){i++;continue}if(n===45){i++;continue}if(n>=128){i++;continue}if(n===92&&Ht(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&&nt(t.charCodeAt(r)))r++;if(t.charCodeAt(r)===46&&nt(t.charCodeAt(r+1))){r+=2;while(r<t.length&&nt(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(nt(n)){r+=2;while(r<t.length&&nt(t.charCodeAt(r)))r++}else if((n===43||n===45)&&nt(s)){r+=3;while(r<t.length&&nt(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&&Ct(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&&Ct(r.charCodeAt(n)))n++;while(n<i){let s=r.charCodeAt(n);if(s===41)return n++,this.addToken(7,e,n),n;if(Ct(s)){let a=n;while(n<i&&Ct(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||Wg(s))return this.consumeBadUrl(e,n);if(s===92){if(Ht(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&&Ht(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 Kg(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 Yg(e,t,r,i);return e.slice(t,r)}function Yg(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(ai(a)){let o=s+1,l="";while(l.length<6&&o<r&&ai(e.charCodeAt(o)))l+=e[o],o++;let c=Number.parseInt(l,16);if(o<r&&Ct(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 Hg(e,t,r,i);return e.slice(t,r)}function Hg(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&&ai(e.charCodeAt(a)))o+=e[a],a++;if(o.length>0){let l=Number.parseInt(o,16);if(a<r&&Ct(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 L(e){return e.pos<e.end?e.types[e.pos]:0}function j(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 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 pt(e,t){return e.source.slice(t.start,t.end)}function ot(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 I(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=j(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 Qi(e,t,r,i){return{type:"Raw",value:e,loc:I(i,t,r)}}function ze(){return new Je}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 Wn(r)??vc(r);case"atrulePrelude":return Qg(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 t0(r);case"declaration":return Ao(r)??vc(r);case"value":return r0(r);case"raw":return Sc(r);default:return xc(r)}}function vc(e){return{type:"StyleSheet",children:ze(),loc:jf(e)}}function Sc(e){let t=j(e),r=t;while(L(e)!==0)r=B(e);return{type:"Raw",value:e.source.slice(t.start,r.end),loc:I(e,t,r)}}function xc(e){let t=j(e),r=ze(),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=Wn(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:I(e,t,a)}}function xo(e,t){return{type:"Comment",value:e.source.slice(t.start+2,t.end-2),loc:I(e,t,t)}}function Wn(e){let t=j(e);if(t.type!==3)return null;e.pos++;let r=$n(e.source,t.start+1,t.end);ot(e);let i=e.pos,n=j(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=ze();while(L(e)!==0){let g=ar(e);if(g)y.appendData(g)}if(If(y),e.end=p,e.pos=o,y.isEmpty)c=Qi(m,n,d,e);else c={type:"AtrulePrelude",children:y,loc:null}}catch(p){let y=Qi(m,n,d,e);ks(e,`Failed to parse @${r} prelude: ${p.message}`,n,y),c=y,e.pos=o}else c=Qi(m,n,d,e),e.pos=o;else e.pos=o}else e.pos=o;let u=null;if(L(e)===17)B(e);else if(L(e)===23)u=Co(e,Zg.has(r));return{type:"Atrule",name:r,prelude:c,block:u,loc:I(e,t,j(e))}}var Jg=new Set(["is","not","where","has","matches","-moz-any","-webkit-any"]),Zg=new Set(["media","supports","document","layer","container","scope","starting-style","-moz-document","keyframes","-webkit-keyframes","-moz-keyframes","-o-keyframes"]);function Qg(e){let t=j(e),r=ze();while(L(e)!==0){if(j(e).type===13){e.pos++;continue}let i=ar(e);if(i)r.appendData(i)}return{type:"AtrulePrelude",children:r,loc:I(e,t,j(e))}}function $o(e){let t=j(e),r;if(e.parseRulePrelude)r=Eo(e);else{let n=j(e),s=n;while(L(e)!==0&&L(e)!==23)s=B(e);let a=e.source.slice(n.start,s.end).trim();r=Qi(a,n,s,e)}let i=Co(e,!0);return{type:"Rule",prelude:r,block:i,loc:I(e,t,j(e))}}function Co(e,t=!1){let r=j(e);if(L(e)!==23)return{type:"Block",children:ze(),loc:jf(e)};e.pos++;let i=ze(),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=Wn(e);if(l)i.appendData(l);continue}if(t&&Xg(e,e0)){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(L(e)===24)e.pos++;return{type:"Block",children:i,loc:I(e,r,j(e))}}function Xg(e,t){let r=e.pos,i=t(e);return e.pos=r,i}function e0(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 t0(e){let t=j(e),r=ze();while(L(e)!==0&&L(e)!==24){let i=j(e);if(i.type===13){e.pos++;continue}if(i.type===25){r.appendData(xo(e,B(e)));continue}if(i.type===17){e.pos++;continue}if(i.type===3){let s=Wn(e);if(s)r.appendData(s);continue}let n=Ao(e);if(n)r.appendData(n);if(L(e)===17)B(e)}return{type:"DeclarationList",children:r,loc:I(e,t,j(e))}}function Ao(e){ot(e);let t=j(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:A}=e;while(e.pos<A){let $=S[e.pos];if($===0||$===17||$===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),L(e)!==16){ks(e,`Expected ':' after property "${n}"`,j(e),{type:"Raw",value:"",loc:null});let{types:S,end:A}=e;while(e.pos<A){let $=S[e.pos];if($===0||$===17||$===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 A=c+1;while(A<o&&s[A]===13)A++;if(A<o&&s[A]===1){let $=a[A];if(e.ends[A]-$===9&&(e.source.charCodeAt($)|32)===105&&(e.source.charCodeAt($+1)|32)===109&&(e.source.charCodeAt($+2)|32)===112&&(e.source.charCodeAt($+3)|32)===111&&(e.source.charCodeAt($+4)|32)===114&&(e.source.charCodeAt($+5)|32)===116&&(e.source.charCodeAt($+6)|32)===97&&(e.source.charCodeAt($+7)|32)===110&&(e.source.charCodeAt($+8)|32)===116){h=c,f=A,c=A+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:I(e,b,v)};else if(d===l)y={type:"Value",children:ze(),loc:I(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:I(e,t,j(e))}}function r0(e){return Bf(e)}function Bf(e){let t=j(e),r=ze();while(L(e)!==0&&L(e)!==17&&L(e)!==24&&L(e)!==22&&L(e)!==20){let i=ar(e);if(i)r.appendData(i)}return zf(r),{type:"Value",children:r,loc:I(e,t,j(e))}}function If(e){for(let t of e)if("children"in t&&t.children instanceof Je)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 ar(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:Re(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?Re(e,i,n):null};case 10:return e.pos++,{type:"Number",value:s.slice(i,n),loc:e.positions?Re(e,i,n):null};case 11:return e.pos++,{type:"Percentage",value:s.slice(i,n-1),loc:e.positions?Re(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?Re(e,i,n):null}}case 1:return e.pos++,{type:"Identifier",name:Df(s,i,n),loc:e.positions?Re(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?Re(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?Re(e,i,n):null}}case 4:return e.pos++,{type:"Hash",name:s.slice(i+1,n),loc:e.positions?Re(e,i,n):null};case 2:return n0(e);case 21:return a0(e);case 18:return e.pos++,{type:"Operator",value:",",loc:e.positions?Re(e,i,n):null};case 16:return e.pos++,{type:"Operator",value:":",loc:e.positions?Re(e,i,n):null};case 9:{e.pos++;let a=s.charCodeAt(i),o=s[i];if(i0(a))return{type:"Operator",value:o,loc:e.positions?Re(e,i,n):null};return{type:"Identifier",name:o,loc:e.positions?Re(e,i,n):null}}case 19:{e.pos++;let a=ze();while(L(e)!==0&&L(e)!==20){let l=ar(e);if(l)a.appendData(l)}let o=e.pos<e.end?e.ends[e.pos]:n;if(L(e)===20)e.pos++;return{type:"Brackets",children:a,loc:e.positions?Re(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?Re(e,i,n):null}}return e.pos++,null}function $c(e){return e===32||e===9||e===10||e===12||e===13}function i0(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 $n(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 Re(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 n0(e){let t=B(e),r=$n(e.source,t.start,t.end-1),i=ze();while(L(e)!==0&&L(e)!==22){let n=ar(e);if(n)i.appendData(n)}if(L(e)===22)B(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:I(e,t,j(e))}}return{type:"Function",name:r,children:i,loc:I(e,t,j(e))}}function a0(e){let t=B(e),r=ze();while(L(e)!==0&&L(e)!==22){let i=ar(e);if(i)r.appendData(i)}if(L(e)===22)B(e);return{type:"Parentheses",children:r,loc:I(e,t,j(e))}}function Eo(e){let t=j(e),r=ze();while(L(e)!==0){if(ot(e),L(e)===0||L(e)===23)break;let i=_f(e);if(i.children.head!==null)r.appendData(i);if(ot(e),L(e)===18){B(e);continue}break}return{type:"SelectorList",children:r,loc:I(e,t,j(e))}}function _f(e){let t=j(e),r=ze(),i=!0;while(L(e)!==0&&L(e)!==18&&L(e)!==23){let n=j(e);if(n.type===13){if(B(e),!i&&L(e)!==0&&L(e)!==18&&L(e)!==23&&!Cc(e)&&!s0(e)){let a={type:"Combinator",name:" ",loc:I(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=j(e);B(e);let o=B(e),l={type:"Combinator",name:"||",loc:I(e,a,o)};r.appendData(l),i=!0,ot(e);continue}if(Cc(e)){let a=B(e),o={type:"Combinator",name:e.source[a.start],loc:I(e,a,a)};r.appendData(o),i=!0,ot(e);continue}let s=o0(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:I(e,t,j(e))}}function Cc(e){let t=j(e);if(t.type!==9)return!1;let r=e.source[t.start];return r===">"||r==="+"||r==="~"}function s0(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 o0(e){let t=j(e);switch(t.type){case 1:{if(B(e),L(e)===9&&e.source[j(e).start]==="|"&&e.source[j(e).start+1]!=="="&&!(e.types[e.pos+1]===9&&e.source.charCodeAt(e.starts[e.pos+1])===124)){if(B(e),L(e)===1){let r=B(e);return{type:"TypeSelector",name:`${pt(e,t)}|${pt(e,r)}`,loc:I(e,t,r)}}if(L(e)===9&&e.source[j(e).start]==="*"){let r=B(e);return{type:"TypeSelector",name:`${pt(e,t)}|*`,loc:I(e,t,r)}}}return{type:"TypeSelector",name:pt(e,t),loc:I(e,t,t)}}case 11:return B(e),{type:"TypeSelector",name:pt(e,t),loc:I(e,t,t)};case 10:return B(e),{type:"TypeSelector",name:pt(e,t),loc:I(e,t,t)};case 9:{let r=e.source[t.start];if(r==="*")return B(e),{type:"TypeSelector",name:"*",loc:I(e,t,t)};if(r==="."){if(B(e),L(e)===1){let i=B(e);return{type:"ClassSelector",name:pt(e,i),loc:I(e,t,i)}}return null}if(r==="&")return B(e),{type:"NestingSelector",loc:I(e,t,t)};return B(e),null}case 4:return B(e),{type:"IdSelector",name:e.source.slice(t.start+1,t.end),loc:I(e,t,t)};case 16:{B(e);let r=L(e)===16;if(r)B(e);return l0(e,r,t)}case 19:return c0(e)}return null}function l0(e,t,r){let i=j(e);if(i.type===1){B(e);let n=$n(e.source,i.start,i.end);return t?{type:"PseudoElementSelector",name:n,children:null,loc:I(e,r,i)}:{type:"PseudoClassSelector",name:n,children:null,loc:I(e,r,i)}}if(i.type===2){B(e);let n=$n(e.source,i.start,i.end-1),s=ze();if(!t&&Jg.has(n)){let a=j(e),o=a,l=1;while(L(e)!==0&&l>0){if(L(e)===21||L(e)===2)l++;else if(L(e)===22){if(l--,l===0)break}o=B(e)}if(L(e)===22)B(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(L(e)!==0&&L(e)!==22){let a=ar(e);if(a)s.appendData(a)}if(L(e)===22)B(e)}if(t)return{type:"PseudoElementSelector",name:n,children:s,loc:I(e,r,j(e))};return{type:"PseudoClassSelector",name:n,children:s,loc:I(e,r,j(e))}}return null}function c0(e){let t=B(e);ot(e);let r=j(e);if(r.type!==1)return null;B(e);let i={type:"Identifier",name:pt(e,r),loc:I(e,r,r)};ot(e);let n=null,s=null,a=null,o=j(e);if(o.type===9){let c=e.source[o.start],u=e.source[o.start+1];if(c==="=")n="=",B(e);else if((c==="~"||c==="|"||c==="^"||c==="$"||c==="*")&&u==="="){B(e);let d=j(e);if(d.type===9&&e.source[d.start]==="=")B(e),n=`${c}=`}ot(e);let f=j(e);if(f.type===5){B(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:I(e,f,f)}}else if(f.type===1)B(e),s={type:"Identifier",name:pt(e,f),loc:I(e,f,f)};ot(e);let h=j(e);if(h.type===1)B(e),a=pt(e,h)}ot(e);let l=j(e);if(L(e)===20)l=B(e);return{type:"AttributeSelector",name:i,matcher:n,value:s,flags:a,loc:I(e,t,l)}}var Uf=Symbol("walkSkip"),me=Symbol("walkStop");function u0(e){return{root:e,stylesheet:null,atrule:null,atrulePrelude:null,rule:null,selector:null,block:null,declaration:null,function:null}}function f0(e,t){let r=u0(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===me){if(f)r[f]=h;return me}}if(d=h0(l,a,o),d===me){if(f)r[f]=h;return me}if((s===null||s===l.type)&&n){if(n.call(r,l,c,u)===me){if(f)r[f]=h;return me}}if(f)r[f]=h;return}return o(e,null,null)}var qn=Object.assign(f0,{skip:Uf,stop:me});function h0(e,t,r){if("children"in e&&e.children instanceof Je)return d0(e.children,t,r);if(e.type==="Rule"){if(r(e.prelude,null,null)===me)return me;if(r(e.block,null,null)===me)return me;return}if(e.type==="Atrule"){if(e.prelude){if(r(e.prelude,null,null)===me)return me}if(e.block){if(r(e.block,null,null)===me)return me}return}if(e.type==="Declaration")return r(e.value,null,null);if(e.type==="AttributeSelector"){if(r(e.name,null,null)===me)return me;if(e.value)return r(e.value,null,null);return}return}function d0(e,t,r){let i;if(t)e.forEachRight((n,s,a)=>{if(i)return;if(r(n,s,a)===me)i=me});else e.forEach((n,s,a)=>{if(i)return;if(r(n,s,a)===me)i=me});return i}var ei={};Gn(ei,{stringify:()=>qf,parse:()=>Kn,isTraversal:()=>E0,IgnoreCaseMode:()=>k0});var Ac=/(?:\\(?:[\dA-Fa-f]{1,6} ?|[^])|[\w\-\u00B0-\uFFFF])+/y,m0=/\\([\dA-Fa-f]{1,6} ?|[^])/g;function p0(e){return e.replace(m0,(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:p0(e)}var g0=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 y0(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 Xi(e){return e===32||e===9||e===10||e===13||e===12}function Kn(e,t={}){let r=[],i=Gf(r,e,t,0);if(i<e.length)throw Error(`Unmatched selector: ${e.slice(i)}`);return r}function lt(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 Jt(e,t){while(t<e.length&&Xi(e.charCodeAt(t)))t++;return t}function Gf(e,t,r,i){let n=[],s=Jt(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(Xi(u)){let f=s+1;while(f<a&&Xi(t.charCodeAt(f)))f++;if(n.length===0)return f;s=f,mr(n,"descendant");continue}if(u===62||u===60||u===126||u===43||u===124){let f=s+1;while(f<a&&Xi(t.charCodeAt(f)))f++;switch(s=f,u){case 62:mr(n,"child");break;case 60:mr(n,"parent");break;case 126:mr(n,"sibling");break;case 43:mr(n,"adjacent");break;case 124:if(s<a&&t.charCodeAt(s)===124)s++,s=Jt(t,s),mr(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=Jt(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=Jt(t,f+2);continue}if(u===42){s++,n.push({type:"universal",namespace:null});continue}if(u===35){let f=lt(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=lt(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=w0(t,s,n,r,o,l);continue}if(u===58){s=b0(t,s,n,r);continue}if(u===124){s++;let f=lt(t,s);s=f.end,n.push({type:"tag",name:c?f.value.toLowerCase():f.value,namespace:""});continue}{let f=lt(t,s);if(s=f.end,s<a&&t.charCodeAt(s)===124&&t.charCodeAt(s+1)!==61){s++;let h=lt(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 w0(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=lt(e,a);a=d.end,l=d.value}else{let d=lt(e,a);if(a=d.end,l=d.value,e.charCodeAt(a)===124&&e.charCodeAt(a+1)!==61){a++;let m=lt(e,a);a=m.end,l=m.value}}a=Jt(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=y0(h);if(d!==null&&e.charCodeAt(a+1)===61)c=d,a+=2}if(c!=="exists"){a=Jt(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=lt(e,a);u=p.value,a=p.end}a=Jt(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&&g0.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 b0(e,t,r,i){if(e.charCodeAt(t+1)===58){let o=t+2,l=lt(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=lt(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 mr(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 v0={child:" > ",parent:" < ",sibling:" ~ ",adjacent:" + ",descendant:" ","column-combinator":" || "};function qf(e){return e.map(S0).join(", ")}function S0(e){return e.map((t,r)=>x0(t,e[r-1])).join("")}function x0(e,t){switch(e.type){case"tag":return`${Oa(e.namespace)}${Yr(e.name)}`;case"universal":return`${Oa(e.namespace)}*`;case"attribute":{if(e.name==="id"&&e.action==="equals"&&!e.ignoreCase&&!e.namespace)return`#${Yr(e.value)}`;if(e.name==="class"&&e.action==="element"&&!e.ignoreCase&&!e.namespace)return`.${Yr(e.value)}`;let r=`[${Oa(e.namespace)}${Yr(e.name)}`;if(e.action!=="exists"){let i=$0[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 v0[e.type]??" "}return""}var $0={equals:"=",element:"~=",start:"^=",end:"$=",any:"*=",not:"!=",hyphen:"|="};function Oa(e){if(e===null)return"";if(e==="")return"|";return`${Yr(e)}|`}var C0=/[^\w\u00B0-\uFFFF-]/g;function Yr(e){if(e==="")return"";return e.replace(C0,(t)=>`\\${t}`)}var A0=new Set(["adjacent","child","descendant","parent","sibling","column-combinator"]);function E0(e){return A0.has(e.type)}var k0={Unknown:null,QuirksMode:"quirks",IgnoreCase:!0,CaseSensitive:!1},M0={};Gn(M0,{selectOne:()=>Jf,selectAll:()=>Hf,parseAndCompile:()=>Tr,is:()=>Zf,compile:()=>Yn,clearSelectorCache:()=>q0});function T0(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 N0(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)=>{return!0};function kc(e){return e===32||e===9||e===10||e===12||e===13}function Oi(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 P0(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 F0(e,t,r){let i=t.adapter,n=e.action,s=e.name,a=e.value,o=P0(a,e,t);if(o)a=a.toLowerCase();return O0(n,s,a,o,i,r)}function O0(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 Oi(l.toLowerCase(),r)};return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return Oi(l.toLowerCase(),r)&&s(o)}}if(a)return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return Oi(l,r)};return(o)=>{let l=n.getAttributeValue(o,t);if(l==null)return!1;return Oi(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)=>{return!1}}var R0=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"]),D0=new Set(["is","where","matches","-moz-any","-webkit-any"]),L0=new Set(["nth-child","nth-last-child","nth-of-type","nth-last-of-type"]);function j0(e,t,r){let i=t.adapter,n=e.name,s=e.data;if(e.type==="pseudo"&&D0.has(n)){if(!Array.isArray(s))return r;let a=s.map((o)=>Tr(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)=>Tr(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)=>Tr(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"&&L0.has(n)){let a=I0(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"&&R0.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)=>{return!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=Kn(a),l=Mo(o,t);return(c)=>l(c)&&r(c)}}return(a)=>{return!1}}function B0(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 I0(e,t,r){let i=B0(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 z0(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 F0(e,t,r);case"pseudo":case"pseudo-element":return j0(e,t,r);case"descendant":case"child":case"parent":case"sibling":case"adjacent":case"column-combinator":return r}return(s)=>{return!1}}var _0={universal:50,tag:30,attribute:1,pseudo:0,"pseudo-element":0},U0={exists:10,equals:8,not:7,start:6,end:6,hyphen:5,any:4,element:3};function Mc(e){let t=_0[e.type]??0;if(e.type==="attribute")return t+(U0[e.action]??0);return t}function Mo(e,t){if(e.length===1)return Tr(e[0],t);let r=e.map((i)=>Tr(i,t));return(i)=>r.some((n)=>n(i))}function Tr(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=z0(l,t,s);if(a<n.length)s=V0(n[a],s,r)}return s}function V0(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)=>{return!1}}function Yf(e){if(!e||!e.adapter)throw Error("css-select: adapter is required");return e.adapter}var Cn=new WeakMap;function G0(e){return(e.xmlMode?1:0)<<0|(e.lowerCaseAttributeNames===!1?1:0)<<1|(e.lowerCaseTags===!1?1:0)<<2}function W0(e,t){let r=Cn.get(e);if(!r)r=[],Cn.set(e,r);let i=r[t];if(!i)i=new Map,r[t]=i;return i}function Tc(e,t){let r=Kn(e,{xmlMode:t.xmlMode,lowerCaseAttributeNames:t.lowerCaseAttributeNames,lowerCaseTags:t.lowerCaseTags});return Mo(r,t)}function Yn(e,t){if(typeof e!=="string")return Mo(e,t);if(t.cacheResults===!1||!t.adapter)return Tc(e,t);let r=W0(t.adapter,G0(t)),i=r.get(e);if(i!==void 0)return i;return i=Tc(e,t),r.set(e,i),i}function q0(e,t){if(t===void 0){Cn.delete(e);return}let r=Cn.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:Yn(e,r),s=Kf(t,i);return T0(n,s,i,r.xmlMode===!0)}function Jf(e,t,r){let i=Yf(r),n=typeof e==="function"?e:Yn(e,r),s=Kf(t,i);return N0(n,s,i,r.xmlMode===!0)}function Zf(e,t,r){return(typeof t==="function"?t:Yn(t,r))(e)}var si={};Gn(si,{syntax:()=>cy,specificityToString:()=>ly,specificity:()=>No,removeComments:()=>en,minifyBlock:()=>oy,minify:()=>sy,dedupeDeclarations:()=>Qf,compressTree:()=>eh});function en(e,t={}){let r=t.exclamation??!1,i=!1;qn(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){qn(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 K0={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"},Y0={"#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 H0(e){let t=e.toLowerCase();return K0[t]??null}function J0(e){let t=e.toLowerCase();return Y0[t]??null}function Z0(e,t,r){let i=(e<<16|t<<8|r).toString(16).padStart(6,"0");return Xf(`#${i}`)}var Q0=/^rgba?\(\s*([+-]?\d*\.?\d+%?)\s*[,\s]\s*([+-]?\d*\.?\d+%?)\s*[,\s]\s*([+-]?\d*\.?\d+%?)\s*(?:[,/]\s*([+-]?\d*\.?\d+%?)\s*)?\)$/;function X0(e){let t=Q0.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&&!ey(t[4]))return e;return Z0(r,i,n)}function ey(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 ty=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 ry(e,t){let r=To(e);if((r==="0"||r==="-0")&&ty.has(t.toLowerCase()))return{value:"0",unit:""};return{value:r,unit:t}}function iy(e){return To(e)}function ny(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 ay(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)=>ny(n,r);qn(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=iy(o);return}case"Dimension":{let o=i?i(n.value):n.value,l=ry(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=J0(`#${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=H0(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")ay(n);if(n.type==="Function"&&n.__rgbReplaceCandidate&&s&&a){let o=_e(n),l=X0(o);if(l!==o&&l.startsWith("#")){let c={type:"Hash",name:l.slice(1),loc:n.loc};a.replace(s,a.createItem(c))}}}})}function sy(e,t={}){let r=So(e,{context:"stylesheet"});return th(r,t)}function oy(e,t={}){let r=So(e,{context:"declarationList"});return th(r,t)}function th(e,t){if(t.comments===!1)en(e,{exclamation:!1});else if(t.comments==="first-exclamation")en(e,{exclamation:"first-exclamation"});else en(e,{exclamation:!0});return eh(e,{floatPrecision:t.floatPrecision??null}),Qf(e),{css:_e(e),ast:e}}function No(e){let t=[0,0,0];if(typeof e==="string"){let r=Kn(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 ly(e){return e.join(",")}var cy={specificity:No},uy=Object.defineProperty,fy=(e)=>e;function hy(e,t){this[e]=fy.bind(null,t)}var dy=(e,t)=>{for(var r in t)uy(e,r,{get:t[r],enumerable:!0,configurable:!0,set:hy.bind(t,r)})},Lt=(e,t)=>()=>(e&&(t=e(e=0)),t),my=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 py(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function gy(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function yy(e){return e.getStats().size*2}var Rr,yi,nh,wi=Lt(()=>{Rr=new Fo,yi=new Oo,nh={createKey:py,isEquivalent:gy,estimateMemoryUsage:yy}});function wy(e,t={}){let r=bn.cwd();while(r.includes("storage"))r=tc(r,"..");let i=tc(r,e||"");if(t?.relative)return np(bn.cwd(),i);return i}function we(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function by(){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 ah{async format(e){let t=await by(),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:hr.pid,hostname:t(),environment:hr.env.NODE_ENV||"development",platform:hr.platform,version:hr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:hr.env.NODE_ENV||hr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Hn{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={...ti},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??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{...tn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...tn};return{...tn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ti.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!we()&&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 cp(this.config.logDirectory,ac.F_OK|ac.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await up(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(!Mi(this.currentLogFile))await Aa(this.currentLogFile,"",{mode:420});if(i=nc(this.currentLogFile,"a",420),lp(i,o,{flag:"a"}),ic(i),i!==void 0)Ca(i),i=void 0;if((await ur(this.currentLogFile)).size===0){if(await Aa(this.currentLogFile,o,{flag:"w",mode:420}),(await ur(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 fr(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 fr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return fr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(we())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=ap("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=oc(),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(we())return;if(!this.shouldWriteToFile())return;let e=await ur(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 Ti(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 ur(r).catch(()=>null))try{if(await sc(r,o),t.compress)try{let l=`${o}.gz`;await this.compressLogFile(o,l),await Ni(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 ur(r).catch(()=>null))await sc(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Ti(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Ni(fr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=rc(e),i=op(t),n=oc();await dp(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()})),Mi(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(!we()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ti(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ni(fr(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||we())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(we())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(fp(t)||t.startsWith("./")||t.startsWith("../"))t=hp(t);else return null;return Mi(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?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(`
34
+ `);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(!we()){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()&&!we()&&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()&&!we()&&te.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!we()&&te.stdout.isTTY)te.stdout.write(`
37
+ `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!we()&&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+=`
38
+ `,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(!we())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 Hn(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(we())throw Error("createReadStream is not supported in browser environments");if(!Mi(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=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=sp("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 we()}isServerMode(){return!we()}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)=>{return 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(!we())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(we())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}
41
+ `.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(`
42
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||we()||!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(we()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ti(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=fr(this.config.logDirectory,i);if(e.before)try{if((await ur(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 Ni(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,ti,vy,be,H,Sy,Rc,xy,Dc,$y,Cy,La,Ay,Lc,jc,Ey,ja,ky,My,Ty,Ny,Py,tn,sh,Fy,Oy=Lt(()=>{Oc=bn.env.CLARITY_LOG_DIR||ip(wy(),"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},ti={...Da},vy=(async()=>{try{let{loadConfig:e}=await Promise.resolve().then(()=>(Sh(),vh)),t=await e({name:"clarity",alias:"logging",defaultConfig:Da,cwd:bn.cwd()});if(t)Object.assign(ti,t)}catch{}return ti})(),be={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=be,Sy=be.red,Rc=be.green,xy=be.yellow,Dc=be.blue,$y=be.magenta,Cy=be.cyan,La=be.white,Ay=be.gray,Lc=be.bgRed,jc=be.bgYellow,Ey=be.bgGray,ja=be.bold,ky=be.dim,My=be.italic,Ty=be.underline,Ny=be.strikethrough,Py=be.reset,tn={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 ")))},Fy=new Hn("stacks")}),Ry="0.15.9",Dy=()=>{};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 Ge}function Ly(e){return e instanceof An}function jy(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 Ge,An,oi,Ms,Ts,En,Ns,Ps,li,Fs,Os,Ut,Dr=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}`}},An=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})}},oi=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}},Ms=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})}},Ts=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}},En=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})}},Ns=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}},Ps=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}},li=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})}},Fs=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})}},Os=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 An(e,t,r)},configLoad(e,t,r){return new oi(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 En(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 li(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 Jn{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 yi.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=Pi.env[l]||(c?Pi.env[c]:void 0);if(u!==void 0){if(i.verbose){let f=Pi.env[l]?l:c}try{e[n]=this.parseEnvironmentValue(u,typeof s,l,i.customParsers,i.configName)}catch(f){if(f instanceof En)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(Pi.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=Lt(()=>{wi(),Dr()});function By(e,t){let r=my("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(!Ze(t)||!Ze(e))return t;return Uy(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 Iy(e,t);case"smart":return zy(e,t,i);default:return t}return t}function Iy(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Rs(n,i)))r.push(i);return r}function zy(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Ze(t[0])&&Ze(e[0]))return _y(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 _y(e,t,r){let i=[...t];for(let n of e){if(!Ze(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)=>Ze(l)&&(o in l)&&l[o]===n[o])){a=!0;break}}if(!a)i.push(n)}return i}function Uy(e,t,r,i){let n=t;if(Ze(n)&&i.has(n))return i.get(n);let s={...e};if(Ze(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(Ze(o)&&Ze(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(Ze(e)&&Ze(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 Ze(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}var dh,Do=Lt(()=>{dh={replace:"replace",concat:"concat",smart:"smart"}});class Zn{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=Rr.getWithFileCheck("file",e);if(c){if(o)console.log(`Configuration loaded from cache: ${e}`);return c}}let l=async()=>{if(!Fi(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 oi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new oi(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)Rr.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 yi.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()=>{return Fi(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Fi(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(!Fi(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=Lt(()=>{wi(),Dr(),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 yi.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!mp(t))throw new li(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 li(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=Lt(()=>{wi(),Dr(),ph=/^https?:\/\//});function Vy(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 Zn;envProcessor=new Jn;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)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}"${Vy(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,l){let c=o?Hr(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?Hr(e,r,n):r,o=[je(dr(),".config",e),je(dr(),".config"),dr()];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?Hr(e,i,s):i;try{let l=je(r,"package.json");if(!ys(l))return null;let c={};try{c=JSON.parse(yp(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:Ro(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:Hr(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 Rr.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Rr.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(dr(),".config",e),je(dr(),".config"),dr()],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 Gy(e){return Nt.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 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 Wy(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"&&Bc(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"&&Bc(t)))return(await Nt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function qy(e,t,r="replace"){let i=new Zn;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Hr(e,t,r=!1){let i=new Jn,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 Ky(e){let t=je(er.cwd(),e.configDir),r=je(er.cwd(),e.generatedDir),i=je(r,"config-types.ts");if(!ys(lc(i)))pp(lc(i),{recursive:!0,mode:511});let n=ys(t)?gp(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${Ry}
55
+ export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
56
+ `;wp(i,s,{mode:438})}function Yy(e){let t=null,r=null,i=()=>{if(!r)r=yh(e).then((s)=>{return 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,wh,bh,Hy=Lt(()=>{Oy(),Dy(),wi(),Dr(),ch(),mh(),gh(),Do(),Ke=new Hn("bunfig",{showTags:!0}),Nt=new jo,wh=je(er.cwd(),"config"),bh=je(er.cwd(),"src/generated")});function Jy(e){let t=cc(Sp.cwd(),e?.configDir||"./config");function r(){if(!bp(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=vp(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)=>{return{path:s.path,namespace:"bunfig-virtual"}}),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:i(),loader:"ts"}})}}}var Zy=()=>{},vh={};dy(vh,{withErrorRecovery:()=>oh,tryLoadConfig:()=>qy,loadConfigWithResult:()=>Gy,loadConfig:()=>yh,isRetryableError:()=>jy,isConfigNotFoundError:()=>Ly,isBunfigError:()=>lh,globalPerformanceMonitor:()=>yi,globalCache:()=>Rr,getEnvOrDefault:()=>By,generateConfigTypes:()=>Ky,defaultGeneratedDir:()=>bh,defaultConfigDir:()=>wh,deepMergeWithArrayStrategy:()=>Ro,deepMerge:()=>uh,createLibraryConfig:()=>Yy,config:()=>Wy,bunfigPlugin:()=>Jy,applyEnvVarsToConfig:()=>Hr,TypeGenerationError:()=>Ps,SchemaValidationError:()=>li,PluginError:()=>Os,PerformanceMonitor:()=>Oo,FileSystemError:()=>Ns,ErrorFactory:()=>Ut,EnvVarError:()=>En,EnvProcessor:()=>Jn,ConfigValidator:()=>Lo,ConfigValidationError:()=>Ms,ConfigNotFoundError:()=>An,ConfigMergeError:()=>Ts,ConfigLoader:()=>jo,ConfigLoadError:()=>oi,ConfigFileLoader:()=>Zn,ConfigCache:()=>Fo,CacheUtils:()=>nh,BunfigError:()=>Ge,BrowserConfigError:()=>Fs,ArrayMergeStrategies:()=>dh});var Sh=Lt(()=>{Hy(),Dr(),wi(),Dr(),Zy(),ch(),mh(),gh(),Do()});Sh();var Ot=Symbol("visitSkip");function yt(e,t,r){let i=t[e.type];if(i?.enter){if(i.enter(e,r??null)===Ot)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)yt(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++)yt(o[l],t,e)}}if(i?.exit)i.exit(e,r??null)}var Qy="cleanupEnableBackground",Xy="remove or cleanup enable-background attribute when possible",ew=/^new\s0\s0\s([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)\s([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)$/;function Ic(e,t,r,i){let n=ew.exec(e);if(n!=null&&r===n[1]&&i===n[2])return t==="svg"?void 0:"new";return e}var tw=(e)=>{let t=!1;return yt(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=V.parse(r.attributes.style,{context:"declarationList"}),i.type==="DeclarationList"){let a=[];V.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=V.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=V.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=V.generate(i)}}}},Bo={};R(Bo,{name:()=>lw,fn:()=>dw,description:()=>cw});var qt={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([...qt.textContent,"pre","title"]),Io=new Set(["glyph","missing-glyph","path"]),Fe={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"}},rw={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"]),Qn=new Set(["clip-path","color-profile","fill","filter","marker-end","marker-mid","marker-start","mask","stroke","style"]),Xn=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,iw=/^#(.+?)$/,nw=/(\w+)\.[a-z]/i;function aw(e,t){let r="data:image/svg+xml";if(!t||t==="base64")return r+=";base64,",r+xp.from(e).toString("base64");if(t==="enc")return`${r},${encodeURIComponent(e)}`;if(t==="unenc")return`${r},${e}`;return e}function Lr(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?Zt(o):o.toString();if(t.negativeExtraSpace&&n!==""&&(o<0||l.charAt(0)==="."&&s%1!==0))n="";s=o,i+=n+l}return i}function Zt(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 sw=[...Fe.animationEvent??new Set,...Fe.documentEvent??new Set,...Fe.documentElementEvent??new Set,...Fe.globalEvent??new Set,...Fe.graphicalEvent??new Set];function ea(e){if(e.name==="script"&&e.children.length!==0)return!0;if(e.name==="a"){if(Object.entries(e.attributes).some(([t,r])=>{return(t==="href"||t.endsWith(":href"))&&r!=null&&r.trimStart().startsWith("javascript:")}))return!0}return sw.some((t)=>e.attributes[t]!=null)}function ta(e){return new RegExp($h).test(e)}function ow(e){return/var\s*\(\s*--/.test(e)}function Vo(e,t){let r=[];if(Qn.has(e)){let i=t.matchAll($h);for(let n of i)r.push(n[2])}if(e==="href"||e.endsWith(":href")){let i=iw.exec(t);if(i!=null)r.push(i[1])}if(e==="begin"){let i=nw.exec(t);if(i!=null)r.push(i[1])}return r.map((i)=>decodeURI(i))}function Ft(e,t){let r=10**t;return Math.round(e*r)/r}var lw="cleanupIds",cw="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 uw(e,t){for(let r of t)if(e.startsWith(r))return!0;return!1}function fw(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 hw(e){return e.map((t)=>Ch[t]).join("")}var dw=(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||ea(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 Ot}}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)||uw(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=fw(d),g=hw(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={};R(Ah,{name:()=>mw,fn:()=>ww,description:()=>pw});var mw="cleanupListOfValues",pw="rounds list of values to the fixed precision",gw=/^([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)(px|pt|pc|mm|cm|m|in|ft|em|ex|%)?$/,yw=/\s+,?\s*|,\s*/,Wc={cm:37.79527559055118,mm:3.7795275590551185,in:96,pt:1.3333333333333333,pc:16,px:1},ww=(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(yw)){let u=c.match(gw),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=Zt(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={};R(Go,{name:()=>bw,fn:()=>xw,description:()=>vw});var bw="cleanupNumericValues",vw='rounds numeric values to the fixed precision, removes default "px" units',Sw=/^([-+]?\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},xw=(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=Sw.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=Zt(f);else d=f.toString();if(n&&h==="px")h="";a.attributes[l]=d+h}}}}}},Wo={};R(Wo,{name:()=>Ow,fn:()=>Dw,description:()=>Rw});function $w(e){let t=new Map;for(let r of e.children)t.set(r,e),yt(r,{element:{enter:(i,n)=>{t.set(i,n)}}},e);return t}function ra(e){return e.type==="element"}function Rt(e){return e.children??[]}function qo(e){return e.type==="element"||e.type==="root"}function Ls(e,t){return t.some((r)=>{if(ra(r))return e(r)||Ls(e,Rt(r));if(qo(r))return Ls(e,Rt(r));return!1})}function Cw(e,t){return e.attributes[t]}function Aw(e){return e.name}function Ew(e){let t=Rt(e);if(t[0]&&(t[0].type==="text"||t[0].type==="cdata"))return t[0].value;return""}function kw(e,t){return e.attributes[t]!==void 0}function js(e,t){let r=[];for(let i of t)if(ra(i)){if(e(i))r.push(i);r.push(...js(e,Rt(i)))}else if(qo(i))r.push(...js(e,Rt(i)));return r}function Bs(e,t){for(let r of t)if(ra(r)){if(e(r))return r;let i=Bs(e,Rt(r));if(i)return i}else if(qo(r)){let i=Bs(e,Rt(r));if(i)return i}return null}function Mw(e,t){let r=(i)=>{if(!t)t=$w(e);return t.get(i)??null};return{isTag:ra,existsOne:Ls,getAttributeValue:Cw,getChildren:Rt,getName:Aw,getParent:r,getSiblings:(i)=>{let n=r(i);return n?Rt(n):[]},getText:Ew,hasAttrib:kw,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:Mw(e,t)}}function ci(e,t,r){return Hf(t,e,Ko(e,r))}function Eh(e,t,r){return Jf(t,e,Ko(e,r))}function Tw(e,t,r){return Zf(e,t,Ko(e,r))}function U(e,t){t.children=t.children.filter((r)=>r!==e)}var{syntax:Nw}=si,Ri=V.walk.skip;function Kc(e,t){let r=[];e.block.children.forEach((n)=>{if(n.type==="Declaration")r.push({name:n.property,value:V.generate(n.value),important:n.important===!0})});let i=[];return V.walk(e.prelude,(n)=>{if(n.type==="Selector"){let s=V.clone(n),a=!1;V.walk(s,(o,l,c)=>{if(o.type==="PseudoClassSelector"){if(a=!0,c&&l)c.remove(l)}}),i.push({specificity:Nw.specificity(n),dynamic:a||t,selector:V.generate(s),declarations:r})}}),i}function Pw(e,t){let r=[],i=V.parse(e,{parseValue:!1,parseAtrulePrelude:!1});return V.walk(i,(n)=>{if(n.type==="Rule")return r.push(...Kc(n,t||!1)),Ri;if(n.type==="Atrule"){if(["keyframes","-webkit-keyframes","-o-keyframes","-moz-keyframes"].includes(n.name))return Ri;return V.walk(n,(s)=>{if(s.type==="Rule")return r.push(...Kc(s,t||!0)),Ri}),Ri}}),r}function Fw(e){let t=[],r=V.parse(e,{context:"declarationList",parseValue:!1});return V.walk(r,(i)=>{if(i.type==="Declaration")t.push({name:i.property,value:V.generate(i.value),important:i.important===!0})}),t}function Yc(e,t,r){let i={},n=new Map,s=t.attributes,a=Fe.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(Tw(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?[]:Fw(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 ft(e){let t=[],r=new Map;return yt(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(...Pw(a.value,s))}}}}),t.sort((i,n)=>kh(i.specificity,n.specificity)),{rules:t,parents:r}}function ut(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&&Xn.has(a)&&!Uo.has(a))i[a]={...s[a],inherited:!0};n=r.get(n)}return i}function rn(e,t,r=null,i=!1){let n=typeof e==="string"?ei.parse(e,{xmlMode:!0}):ei.parse(V.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(!ei.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 Ow="collapseGroups",Rw="collapses useless groups";function Mh(e,t){if(e.type==="element"){if(qt.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 Dw=(e)=>{let t=ft(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||ut(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(!Xn.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"&&qt.animation.has(s.name))return;let n=i.children.indexOf(r);i.children.splice(n,1,...r.children)}}}}},Yo={};R(Yo,{name:()=>Lw,fn:()=>_w,description:()=>jw});var Lw="convertColors",jw="converts colors: rgb() to #rrggbb and #rrggbb to #rgb",Ba="([+-]?(?:\\d*\\.\\d+|\\d+\\.?)%?)",Hc="(?:\\s*,\\s*|\\s+)",Bw=new RegExp(`^rgb\\(\\s*${Ba}${Hc}${Ba}${Hc}${Ba}\\s*\\)$`),Iw=/^#(([a-f0-9])\2){3}$/i;function zw([e,t,r]){return`#${((256+e<<8|t)<<8|r).toString(16).slice(1).toUpperCase()}`}var _w=(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(Bw);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=zw(m)}}if(s&&!ta(h)&&!ow(h)&&h!=="currentColor"){if(s==="lower")h=h.toLowerCase();else if(s==="upper")h=h.toUpperCase()}if(a){let d=Iw.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={};R(Ho,{name:()=>Uw,fn:()=>Gw,description:()=>Vw});var Uw="convertEllipseToCircle",Vw="converts non-eccentric <ellipse>s to <circle>s",Gw=()=>({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={};R(Th,{name:()=>Ww,fn:()=>Kw,description:()=>qw});var Ww="convertOneStopGradients",qw="converts one-stop (single color) gradients to a plain color",Kw=(e)=>{let t=ft(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=ut(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=ci(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=ci(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--;U(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)U(o,l)}}}}},Jo={};R(Jo,{name:()=>c1,fn:()=>f1,description:()=>u1});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 Yw(e){return e in Nh}function Hw(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(Hw(l))continue;if(s&&l===","){if(a)break;a=!0;continue}if(Yw(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 Di(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=Ft(c,r);let u=Zt(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 kr({pathData:e,precision:t,disableSpaceAfterFlags:r}){if(e.length===1){let{command:s,args:a}=e[0];return s+Di(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+Di(n.command,n.args,t,r)}else if(i+=n.command+Di(n.command,n.args,t,r),s===e.length-1)i+=a+Di(a,o,t,r);else n={command:a,args:o}}return i}var mt=[0,0];function kn(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=kr({pathData:i,precision:r.floatPrecision,disableSpaceAfterFlags:r.noSpaceAfterFlags})}function pr(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=jr(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)),It(f,u[u.length-1])<=0)return!1;if(Jw(u,f))return!0}})});function a(l,c,u){return nn(o(l,u),o(c,jr(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=It(l.list[u],c))>f)f=h,u=++u%l.list.length;return l.list[(u||l.list.length)-1]}}function Jw(e,t){if(e.length===2){let r=e[1],i=e[0],n=jr(e[1]),s=nn(i,r);if(It(n,s)>0)pr(t,Ia(s,r));else pr(t,n),e.shift()}else{let r=e[2],i=e[1],n=e[0],s=nn(i,r),a=nn(n,r),o=jr(r),l=Ia(s,a),c=Ia(a,s);if(It(l,o)>0)if(It(s,o)>0)pr(t,l),e.shift();else pr(t,o),e.splice(0,2);else if(It(c,o)>0)if(It(a,o)>0)pr(t,c),e.splice(1,1);else pr(t,o),e.splice(0,2);else return!0}return!1}function jr(e){return[-e[0],-e[1]]}function nn(e,t){return[e[0]-t[0],e[1]-t[1]]}function It(e,t){return e[0]*t[0]+e[1]*t[1]}function Ia(e,t){let r=[-e[1],e[0]];return It(r,jr(t))<0?jr(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)),mt=[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]+mt[0],o[1]+mt[1]],r(s,c),mt=[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])]),mt=[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*mt[0],o[1]+0.5*mt[1]]),c=[o[0]+mt[0],o[1]+mt[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])]),mt=[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=(E,N,M)=>E*Math.cos(M)-N*Math.sin(M),m=(E,N,M)=>E*Math.sin(M)+N*Math.cos(M),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 E=(e-o)/2,N=(t-l)/2,M=E*E/(r*r)+N*N/(i*i);if(M>1)M=Math.sqrt(M),r=M*r,i=M*i;let F=r*r,G=i*i,Q=(s===a?-1:1)*Math.sqrt(Math.abs((F*G-F*N*N-G*E*E)/(F*N*N+G*E*E)));if(p=Q*r*N/i+(e+o)/2,y=Q*-i*E/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 E=w,N=o,M=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,N,M,[w,E,p,y])}b=w-g;let v=Math.cos(g),S=Math.sin(g),A=Math.cos(w),$=Math.sin(w),P=Math.tan(b/4),O=1.3333333333333333*r*P,x=1.3333333333333333*i*P,C=[-O*S,x*v,o+O*$-e,l-x*A-t,o-e,l-t];if(c)return C.concat(h);h=C.concat(h);let k=[];for(let E=0;E<h.length;E++)k[E]=E%2?m(h[E-1],h[E],f):d(h[E],h[E+1],f);return k}var Zw=new Set(["matrix","rotate","scale","skewX","skewY","translate"]),Qw=/\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(Qw)){if(!i)continue;if(Zw.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:s1(r));return{name:"matrix",data:t.length>0?t.reduce(Lh):[]}}var Ie={rad:(e)=>e*Math.PI/180,deg:(e)=>e*180/Math.PI,cos:(e)=>Math.cos(Ie.rad(e)),acos:(e,t)=>Ft(Ie.deg(Math.acos(e)),t),sin:(e)=>Math.sin(Ie.rad(e)),asin:(e,t)=>Ft(Ie.deg(Math.asin(e)),t),tan:(e)=>Math.tan(Ie.rad(e)),atan:(e,t)=>Ft(Ie.deg(Math.atan(e)),t)};function Xw(e){let t=[],r=e1(e),i=t1(e);if(r)t.push(r);if(i)t.push(i);return t}function e1(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:[Ie.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:[Ie.deg(Math.atan(m/(r*r+i*i)))]});return u}function t1(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:[Ie.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:[Ie.deg(Math.atan(m/(n*n+s*s)))]});return u}function r1(e,t,r){let i=Ie.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 i1(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 n1(e,t){let r=[];for(let i=0;i<e.length;i++){let n=e[i];if(i1(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(r1(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 a1(e,t){let r=Xw(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 ia(u,t)}),o=n1(a,s),l=Mn(o,t).length;if(l<n)i=o,n=l}return i??[e]}function s1(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=Ie.cos(e.data[0]),r=Ie.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,Ie.tan(e.data[0]),1,0,0];case"skewY":return[1,Ie.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 ia(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(Ft(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 Mn(e,t){return e.map((r)=>{return ia(r,t),`${r.name}(${Lr(r.data,t)})`}).join("")}var _a=/[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g;function tt(e,t,r){return[e[0]*t+e[2]*r+e[4],e[1]*t+e[3]*r+e[5]]}function rt(e,t,r){return[e[0]*t+e[2]*r,e[1]*t+e[3]*r]}function o1(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]=tt(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]=rt(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]=tt(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]=rt(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]=tt(t,a[0],a[1]),[c,u]=tt(t,a[2],a[3]),[f,h]=tt(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]=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==="S"){i[0]=a[2],i[1]=a[3];let[o,l]=tt(t,a[0],a[1]),[c,u]=tt(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]=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]=tt(t,a[0],a[1]),[c,u]=tt(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==="T"){i[0]=a[0],i[1]=a[1];let[o,l]=tt(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]=rt(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]=tt(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]=rt(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 l1=(e,t)=>{let r=ft(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])=>Qn.has(h)&&ta(d)))return;let n=ut(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)=>Zt(Number(h)*u)),i.attributes["stroke-dashoffset"]!=null)i.attributes["stroke-dashoffset"]=i.attributes["stroke-dashoffset"].trim().replace(_a,(h)=>Zt(Number(h)*u));if(i.attributes["stroke-dasharray"]!=null)i.attributes["stroke-dasharray"]=i.attributes["stroke-dasharray"].trim().replace(_a,(h)=>Zt(Number(h)*u))}}}let f=kn(i);o1(f,a.data),delete i.attributes.transform}}}},c1="convertPathData",u1="optimizes path data: writes in shorter form, applies transformations",Mt,at,ue,el,tl,f1=(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)yt(e,l1(e,{transformPrecision:f,applyTransformsStroked:i},{multipassCount:0}));let S=ft(e);return{element:{enter:(A)=>{if(Io.has(A.name)&&A.attributes.d!=null){let $=ut(S,A);if(at=u,ue=at!==!1?+(0.1**at).toFixed(at):0.01,Mt=at!==!1&&at>0&&at<20?p1:g1,n)el=n.threshold,tl=n.tolerance;let P=$["marker-mid"]!=null,O=$.stroke&&($.stroke.type==="dynamic"||$.stroke.value!=="none"),x=$["stroke-linecap"]&&($["stroke-linecap"].type==="dynamic"||$["stroke-linecap"].value!=="butt"),C=O?$["stroke-linecap"]?.type==="static"&&$["stroke-linecap"].value==="round"&&$["stroke-linejoin"]?.type==="static"&&$["stroke-linejoin"].value==="round":!0,k=(N,M)=>{if(!O)return!0;if(N)return!x;return M},E=kn(A);if(E.length){let N=E.some((M)=>M.command!=="m"&&M.command!=="M");if(h1(E),E=d1(E,v,{isSafeToUseZ:C,isSafeToRemove:k,hasMarkerMid:P}),p)E=m1(E,v);if((A.attributes["marker-start"]!=null||A.attributes["marker-end"]!=null)&&N&&E.every((M)=>M.command==="m"||M.command==="M"))E.push({command:"z",args:[]});Ph(A,E,{floatPrecision:typeof v.floatPrecision==="number"?v.floatPrecision:void 0,noSpaceAfterFlags:v.noSpaceAfterFlags})}}}}}};function h1(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 d1(e,t,{isSafeToUseZ:r,isSafeToRemove:i,hasMarkerMid:n}){let s=w1.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=y1(g))){let v=Mt([w.radius])[0],S=Ga(g,w),A=g[5]*g[0]-g[4]*g[1]>0?1:0,$={command:"a",args:[v,v,0,0,A,g[4],g[5]],coords:u.coords.slice(),base:u.base},P=[$],O=[w.center[0]-g[4],w.center[1]-g[5]],x={center:O,radius:w.radius},C=[u],k=0,E="",N;if(l.command==="c"&&Ua(l.args)&&lu(l.args,w)||l.command==="a"&&l.sdata&&lu(l.sdata,w)){C.unshift(l),$.base=l.base,$.args[5]=$.coords[0]-$.base[0],$.args[6]=$.coords[1]-$.base[1];let M=l.command==="a"?l.sdata:l.args,F=Ga(M,{center:[M[4]+w.center[0],M[5]+w.center[1]],radius:w.radius});if(S+=F,S>Math.PI)$.args[3]=1;k=1}for(let M=f;(y=h[++M])&&(y.command==="c"||y.command==="s");){let F=y.args;if(y.command==="s")N=Li({command:"s",args:y.args.slice()},h[M-1].args),F=N.args,N.args=F.slice(0,2),E=s([N]);if(Ua(F)&&Bh(F,x)){if(S+=Ga(F,x),S-2*Math.PI>0.001)break;if(S>Math.PI)$.args[3]=1;if(C.push(y),2*Math.PI-S>0.001)$.coords=y.coords,$.args[5]=$.coords[0]-$.base[0],$.args[6]=$.coords[1]-$.base[1];else{$.args[5]=2*(x.center[0]-F[4]),$.args[6]=2*(x.center[1]-F[5]),$.coords=[$.base[0]+$.args[5],$.base[1]+$.args[6]],$={command:"a",args:[v,v,0,0,A,y.coords[0]-$.coords[0],y.coords[1]-$.coords[1]],coords:y.coords,base:$.coords},P.push($),M++;break}O[0]-=F[4],O[1]-=F[5]}else break}if((s(P)+E).length<s(C).length){if(h[y?y.command==="s"?e.indexOf(y):-1:-1]);if(k){let M=P.shift();Mt(M.args),a[0]+=M.args[5]-l.args[l.args.length-2],a[1]+=M.args[6]-l.args[l.args.length-1],l.command="a",l.args=M.args,u.base=l.coords=M.coords}if($=P.shift(),C.length===1)u.sdata=g.slice();else if(C.length-1-k>0)e.splice(f+1,C.length-1-k,...P);if(!$)return!1;m="a",p=$.args,u.coords=$.coords}}if(at!==!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(Mt(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(Mt(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&&at)for(let v=at;v>=0;v--){let S=Ft(p[0],v),A=su([S,S,...p.slice(2)]);if(Math.abs(b-A)<ue)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")Li(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")Li(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<ue))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)<ue*2){let A=0.75*(u.base[1]+p[1])-0.25*u.base[1],$=0.75*(u.base[1]+p[3])-0.25*(u.base[1]+p[5]);if(Math.abs(A-$)<ue*2){let P=p.slice();P.splice(0,4,v+S-u.base[0],A+$-u.base[1]),Mt(P);let O=Lr(p,t).length;if(Lr(P,t).length<O){if(m="q",p=P,y&&y.command==="s")Li(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]))<ue&&Math.abs(p[1]- -(l.args[3]-l.args[5]))<ue)m="s",p=p.slice(2);else if(l.command==="s"&&Math.abs(p[0]- -(l.args[0]-l.args[2]))<ue&&Math.abs(p[1]- -(l.args[1]-l.args[3]))<ue)m="s",p=p.slice(2);else if(l.command!=="c"&&l.command!=="s"&&Math.abs(p[0])<ue&&Math.abs(p[1])<ue)m="s",p=p.slice(2)}else if(m==="q"){if(l.command==="q"&&Math.abs(p[0]-(l.args[2]-l.args[0]))<ue&&Math.abs(p[1]-(l.args[3]-l.args[1]))<ue)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])<ue&&Math.abs(v[1]-S[1])<ue)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])<ue&&Math.abs(o[1]-u.coords[1])<ue)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])<ue/10&&Math.abs(u.base[1]-u.coords[1])<ue/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 m1(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];Mt(o),Mt(l);let c=Lr(o,t),u=Lr(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 p1(e){let t=at||0;for(let r=e.length;r-- >0;){let i=Ft(e[r],t);if(i!==e[r]){let n=Ft(e[r],t-1);e[r]=Ft(Math.abs(n-e[r]),t+1)>=ue?i:n}}return e}function g1(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)>ue)return!1;return!0}function su(e){if(e[3]===1)return;let t=e[0],r=e[1];if(Math.abs(t-r)>ue)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 Li(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 y1(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*ue,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*ue,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 w1(e,t){return t.reduce((r,i)=>{let n="";if(i.args)n=Lr(Mt(i.args.slice()),e);return r+i.command+n},"")}var rl={};R(rl,{name:()=>b1,fn:()=>x1,description:()=>v1});var b1="convertShapeToPath",v1="converts basic shapes to more compact path form",S1=/[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g,x1=(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=kr({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=kr({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(S1)||[]).map(Number);if(a.length<4){U(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=kr({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=kr({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=kr({pathData:u,precision:i}),delete n.attributes.cx,delete n.attributes.cy,delete n.attributes.rx,delete n.attributes.ry}}}}},Ih={};R(Ih,{name:()=>$1,fn:()=>O1,description:()=>C1});var $1="convertStyleToAttrs",C1="converts style to attributes",bi=(...e)=>`(?:${e.join("|")})`,A1=Fe.presentation,Vr="\\\\(?:[0-9a-f]{1,6}\\s?|\\r\\n|.)",E1=`\\s*(${bi("[^:;\\\\]",Vr)}*?)\\s*`,na=`'(?:[^'\\n\\r\\\\]|${Vr})*?(?:'|$)`,aa=`"(?:[^"\\n\\r\\\\]|${Vr})*?(?:"|$)`,k1=new RegExp(`^${bi(na,aa)}$`),M1=`\\(${bi(`[^'"()\\\\]+`,Vr,na,aa)}*?\\)`,T1=`\\s*(${bi(`[^!'"();\\\\]+?`,Vr,na,aa,M1,"[^;]*?")}*?)`,N1="\\s*(?:;\\s*|$)",P1="(\\s*!important(?![-(\\w]))?",cu=new RegExp(`${E1}:${T1}${P1}${N1}`,"ig"),F1=new RegExp(bi(Vr,na,aa,"/\\*[^]*?\\*/"),"ig"),O1=(e,t)=>{let{keepImportant:r=!1}=t||{};return{element:{enter:(i)=>{if(i.attributes.style!=null){let n=[],s={},a=i.attributes.style.replace(F1,(l)=>{return 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(k1.test(u))u=u.slice(1,-1);if(A1.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={};R(il,{name:()=>R1,fn:()=>L1,description:()=>D1});var R1="convertTransform",D1="collapses multiple transformations and optimizes it",L1=(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=j1(i,r),r.collapseIntoOne&&i.length>1)i=[Dh(i)];if(r.convertToShorts)i=I1(i,r);else i.forEach((n)=>ia(n,r));if(r.removeUseless)i=z1(i);if(i.length)e.attributes[t]=Mn(i,r);else delete e.attributes[t]}function j1(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(B1))||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 B1(e){let t=e.toString();return t.slice(t.indexOf(".")).length-1}function I1(e,t){for(let r=0;r<e.length;r++){let i=e[r];if(t.matrixToTransform&&i.name==="matrix"){let n=a1(i,t);if(Mn(n,t).length<=Mn([i],t).length)e.splice(r,1,...n);i=e[r]}if(ia(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 z1(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={};R(nl,{name:()=>_1,fn:()=>G1,description:()=>U1});var{syntax:uu}=si,_1="inlineStyles",U1="inline styles (additional options)",V1=[...Vc.functional??new Set,...Vc.treeStructural??new Set],G1=(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 Ot;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=V.parse(u,{parseValue:!1,parseCustomProperty:!1})}catch{return}if(f.type==="StyleSheet")a.push({node:l,parentNode:c,cssAst:f});V.walk(f,{visit:"Rule",enter(h){let d=this.atrule,m="";if(d!=null){if(m=d.name,d.prelude!=null)m+=` ${V.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")&&!V1.includes(b.name))g.push({item:v,list:S})});let w=V.generate({type:"Selector",children:new V.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=V.generate(c.item.data),f=[];try{for(let h of ci(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=V.parse(h.attributes.style??"",{context:"declarationList",parseValue:!1});if(d.type!=="DeclarationList")continue;let m=new Map,p=null;V.walk(d,{visit:"Declaration",enter(g,w){if(w==null)return;if(p==null)p=w;m.set(g.property.toLowerCase(),w)}}),V.walk(c.rule,{visit:"Declaration",enter(g){let w=g.property;if(Fe.presentation.has(w)&&!o.some((S)=>rn(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=V.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)=>rn(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)=>rn(d.item,"id",h.name,!0)))delete u.attributes.id}}for(let c of a)if(V.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)U(c.node,c.parentNode);else{let u=c.node.children[0];if(u&&(u.type==="text"||u.type==="cdata"))u.value=V.generate(c.cssAst)}}}}},al={};R(al,{name:()=>W1,fn:()=>Y1,description:()=>q1});var W1="mergePaths",q1="merges multiple paths in one if possible";function K1(e,t){let r=e[t];if(r?.type==="static")return ta(r.value);return!1}var Y1=(e,t)=>{let{force:r=!1,floatPrecision:i=3,noSpaceAfterFlags:n=!1}=t||{},s=ft(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=ut(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)=>K1(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=kn(h);if(c=c??kn(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={};R(sl,{name:()=>H1,fn:()=>Z1,description:()=>J1});var H1="mergeStyles",J1="merge multiple style elements into one",Z1=()=>{let e=null,t="",r="text";return{element:{enter:(i,n)=>{if(i.name==="foreignObject")return Ot;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){U(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{U(i,n);let a={type:r,value:t};e.children=[a]}}}}},ol={};R(ol,{name:()=>Q1,fn:()=>eb,description:()=>X1});var Q1="minifyStyles",X1="minifies styles and removes unused styles",eb=(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(ea(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=si.minify(w,{...i,usage:m}).css;if(b.length===0){U(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=si.minifyBlock(y,{...i}).css}}}}},ll={};R(ll,{name:()=>tb,fn:()=>ib,description:()=>rb});var tb="moveElemsAttrsToGroup",rb="Move common attributes of group children to the group",ib=(e)=>{let t=!1;return yt(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(Xn.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={};R(cl,{name:()=>nb,fn:()=>ob,description:()=>ab});var nb="moveGroupAttrsToElems",ab="moves some group attributes to the content elements",sb=[...Io,"g","text"],ob=()=>({element:{enter:(e)=>{if(e.name==="g"&&e.children.length!==0&&e.attributes.transform!=null&&!Object.entries(e.attributes).some(([t,r])=>Qn.has(t)&&ta(r))&&e.children.every((t)=>t.type==="element"&&sb.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={};R(zh,{name:()=>lb,fn:()=>mb,description:()=>cb});var lb="prefixIds",cb="prefix IDs";function ub(e){let t=/[/\\]?([^/\\]+)$/.exec(e);if(t)return t[1];return""}function fb(e){return e.replace(/[. ]/g,"_")}function hb(e){if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);return e}function Jr(e,t){let r=e(t);if(t.startsWith(r))return t;return r+t}function qa(e,t){if(t.startsWith("#"))return`#${Jr(e,t.slice(1))}`;return null}function db(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 fb(ub(r.path))+n;return`prefix${n}`}var mb=(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)=>db(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=V.parse(f,{parseValue:!0,parseCustomProperty:!1})}catch{return}V.walk(h,(d)=>{if(s&&d.type==="IdSelector"||a&&d.type==="ClassSelector"){d.name=Jr(c,d.name);return}if(d.type==="Url"&&d.value.length>0){let m=qa(c,hb(d.value));if(m!=null)d.value=m}}),u.value=V.generate(h)}}if(s&&l.attributes.id!=null&&l.attributes.id.length!==0)l.attributes.id=Jr(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)=>Jr(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 Qn)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`${Jr(c,d)}.${m}`}return h});l.attributes[u]=f.join("; ")}}}}},ul={};R(ul,{name:()=>pb,fn:()=>wb,description:()=>gb});var pb="removeComments",gb="removes comments",yb=[/^!/],wb=(e,t)=>{let{preservePatterns:r=yb}=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}U(i,n)}}}},fl={};R(fl,{name:()=>bb,fn:()=>xb,description:()=>vb});var bb="removeDeprecatedAttrs",vb="removes deprecated attributes";function Sb(e){let t=new Set;return e.rules.forEach((r)=>{ei.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 xb=(e,t)=>{let r=ft(e),i=Sb(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,rw[a],t||{},i)}),fu(n,s.deprecated,t||{},i)}}}},hl={};R(hl,{name:()=>$b,fn:()=>Eb,description:()=>Cb});var $b="removeDesc",Cb="removes <desc>",Ab=/^(?:Created with|Created using)/,Eb=(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"&&Ab.test(i.children[0].value))U(i,n)}}}}},dl={};R(dl,{name:()=>kb,fn:()=>Tb,description:()=>Mb});var kb="removeDoctype",Mb="removes doctype declaration",Tb=()=>({doctype:{enter:(e,t)=>{U(e,t)}}}),ml={};R(ml,{name:()=>Nb,fn:()=>Fb,description:()=>Pb});var Nb="removeEditorsNSData",Pb="removes editors namespaces, elements and attributes",Fb=(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))U(n,s)}}}}},pl={};R(pl,{name:()=>Ob,fn:()=>Db,description:()=>Rb});var Ob="removeEmptyAttrs",Rb="removes empty attributes",Db=()=>({element:{enter:(e)=>{let t=e.attributes;for(let r in t)if(t[r]===""&&!Fe.conditionalProcessing.has(r))delete t[r]}}}),gl={};R(gl,{name:()=>Lb,fn:()=>Bb,description:()=>jb});var Lb="removeEmptyContainers",jb="removes empty container elements",Bb=(e)=>{let t=ft(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"||!qt.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||ut(t,n).filter))return;if(U(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)U(a.node,a.parent)}}}}},yl={};R(yl,{name:()=>Ib,fn:()=>_b,description:()=>zb});var Ib="removeEmptyText",zb="removes empty <text> elements",_b=(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)U(s,a);if(i&&s.name==="tspan"&&s.children.length===0)U(s,a);if(n&&s.name==="tref"&&s.attributes["xlink:href"]==null)U(s,a)}}}},wl={};R(wl,{name:()=>Vb,fn:()=>Wb,description:()=>Gb});var Ub=qt.nonRendering,Vb="removeHiddenElems",Gb="removes hidden elements (zero sized, with absent attributes)",Wb=(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=ft(e),w=new Map,b=new Set,v=new Map,S=new Set,A=new Map,$=!1;function P(x){if(S.has(x.attributes.id))return!1;for(let C of x.children)if(C.type==="element"&&!P(C))return!1;return!0}function O(x,C){if(x.type==="element"&&x.attributes.id!=null&&C.type==="element"&&C.name==="defs")b.add(x.attributes.id);U(x,C)}return yt(e,{element:{enter:(x,C)=>{if(Ub.has(x.name))return w.set(x,C),Ot;let k=ut(g,x);if(n&&k.opacity&&k.opacity.type==="static"&&k.opacity.value==="0"){if(x.name==="path")return w.set(x,C),Ot;O(x,C)}}}}),{element:{enter:(x,C)=>{if(x.name==="style"&&x.children.length!==0||ea(x)){$=!0;return}if(x.name==="defs")v.set(x,C);if(x.name==="use")for(let N of Object.keys(x.attributes)){if(N!=="href"&&!N.endsWith(":href"))continue;let M=x.attributes[N].slice(1),F=A.get(M);if(!F)F=[],A.set(M,F);F.push({node:x,parentNode:C})}if(s&&x.name==="circle"&&x.children.length===0&&x.attributes.r==="0"){O(x,C);return}if(a&&x.name==="ellipse"&&x.children.length===0&&x.attributes.rx==="0"){O(x,C);return}if(o&&x.name==="ellipse"&&x.children.length===0&&x.attributes.ry==="0"){O(x,C);return}if(l&&x.name==="rect"&&x.children.length===0&&x.attributes.width==="0"){O(x,C);return}if(c&&l&&x.name==="rect"&&x.children.length===0&&x.attributes.height==="0"){O(x,C);return}if(u&&x.name==="pattern"&&x.attributes.width==="0"){O(x,C);return}if(f&&x.name==="pattern"&&x.attributes.height==="0"){O(x,C);return}if(h&&x.name==="image"&&x.attributes.width==="0"){O(x,C);return}if(d&&x.name==="image"&&x.attributes.height==="0"){O(x,C);return}if(p&&x.name==="polyline"&&x.attributes.points==null){O(x,C);return}if(y&&x.name==="polygon"&&x.attributes.points==null){O(x,C);return}let k=ut(g,x);if(r&&k.visibility&&k.visibility.type==="static"&&k.visibility.value==="hidden"&&Eh(x,"[visibility=visible]")==null){O(x,C);return}if(i&&k.display&&k.display.type==="static"&&k.display.value==="none"&&x.name!=="marker"){O(x,C);return}if(m&&x.name==="path"){if(x.attributes.d==null){O(x,C);return}let N=Zo(x.attributes.d);if(N.length===0){O(x,C);return}if(N.length===1&&k["marker-start"]==null&&k["marker-end"]==null){O(x,C);return}}let E=x.attributes;for(let N in E){let M=Vo(N,E[N]);for(let F of M)S.add(F)}}},root:{exit:()=>{for(let x of b){let C=A.get(x);if(C)for(let{node:k,parentNode:E}of C)U(k,E)}if(!$){for(let[x,C]of w.entries())if(P(x))U(x,C)}for(let[x,C]of v.entries())if(x.children.length===0)U(x,C)}}}},bl={};R(bl,{name:()=>qb,fn:()=>Yb,description:()=>Kb});var qb="removeMetadata",Kb="removes <metadata>",Yb=()=>({element:{enter:(e,t)=>{if(e.name==="metadata")U(e,t)}}}),vl={};R(vl,{name:()=>Hb,fn:()=>Zb,description:()=>Jb});var Hb="removeNonInheritableGroupAttrs",Jb="removes non-inheritable group's presentational attributes",Zb=()=>({element:{enter:(e)=>{if(e.name==="g"){for(let t of Object.keys(e.attributes))if(Fe.presentation.has(t)&&!Xn.has(t)&&!Uo.has(t))delete e.attributes[t]}}}}),Sl={};R(Sl,{name:()=>Qb,fn:()=>ev,description:()=>Xb});var Qb="removeUnknownsAndDefaults",Xb="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=qt[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=Fe[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 ev=(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=ft(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 Ot;if(r&&h.type==="element"){let g=_s.get(h.name);if(g==null||g.size===0){if(_s.get(f.name)==null){U(f,h);return}}else if(!g.has(f.name)){U(f,h);return}}let d=_h.get(f.name),m=Uh.get(f.name),p=h.type==="element"?ut(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)=>rn(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={};R(xl,{name:()=>tv,fn:()=>iv,description:()=>rv});var tv="removeUnusedNS",rv="removes unused namespaces declaration",iv=()=>{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={};R($l,{name:()=>nv,fn:()=>sv,description:()=>av});var nv="removeUselessDefs",av="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 sv=()=>({element:{enter:(e,t)=>{if(e.name==="defs"||qt.nonRendering.has(e.name)&&e.attributes.id==null){let r=[];if(Vh(e,r),r.length===0)U(e,t);e.children=r}}}}),Cl={};R(Cl,{name:()=>ov,fn:()=>cv,description:()=>lv});var ov="removeUselessStrokeAndFill",lv="removes useless stroke and fill attributes",cv=(e,t)=>{let{stroke:r=!0,fill:i=!0,removeNone:n=!1}=t||{},s=!1;if(yt(e,{element:{enter:(o)=>{if(o.name==="style"||ea(o))s=!0}}}),s)return null;let a=ft(e);return{element:{enter:(o,l)=>{if(o.attributes.id!=null)return Ot;if(!qt.shape.has(o.name))return;let c=ut(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"?ut(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"))U(o,l)}}}}},Al={};R(Al,{name:()=>uv,fn:()=>hv,description:()=>fv});var uv="removeXMLProcInst",fv="removes XML processing instructions",hv=()=>({instruction:{enter:(e,t)=>{if(e.name==="xml")U(e,t)}}}),El={};R(El,{name:()=>dv,fn:()=>pv,description:()=>mv});var dv="sortAttrs",mv="Sort element attributes for better compression",pv=(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={};R(kl,{name:()=>gv,fn:()=>wv,description:()=>yv});var gv="sortDefsChildren",yv="Sorts children of <defs> to improve compression",wv=()=>({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)yt(e,h)}}function bv({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 vv=bv({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]}),Sv=vv,Wh={};R(Wh,{name:()=>xv,fn:()=>Av,description:()=>$v});var xv="removeAttributesBySelector",$v="removes attributes of elements that match a css selector",Cv=`Warning: The plugin "removeAttributesBySelector" is missing parameters.
74
+ It should have a list of "selectors", or one "selector" and one "attributes".`,Av=(e,t)=>{if(!Array.isArray(t?.selectors)&&(!t?.selector||!t?.attributes))return console.warn(Cv),null;let r=Array.isArray(t.selectors)?t.selectors:[t];for(let{selector:i,attributes:n}of r){let s=ci(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={};R(qh,{name:()=>Ev,fn:()=>Mv,description:()=>kv});var Ev="removeAttrs",kv="removes specified attributes",Mv=(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={};R(Kh,{name:()=>Tv,fn:()=>Pv,description:()=>Nv});var Tv="removeDimensions",Nv="removes width and height in presence of viewBox (opposite to removeViewBox)",Pv=()=>({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={};R(Yh,{name:()=>Fv,fn:()=>Rv,description:()=>Ov});var Fv="removeElementsByAttr",Ov="removes arbitrary elements by ID or className",Rv=(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))U(n,s)}if(n.attributes.class&&i.length!==0){let a=n.attributes.class.split(" ");for(let o of i)if(a.includes(o)){U(n,s);break}}}}}},Hh={};R(Hh,{name:()=>Dv,fn:()=>jv,description:()=>Lv});var Dv="removeOffCanvasPaths",Lv="removes elements that are drawn outside of the viewBox",jv=()=>{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 Ot;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))U(t,r)}}}}},Jh={};R(Jh,{name:()=>Bv,fn:()=>zv,description:()=>Iv});var Bv="removeRasterImages",Iv="removes raster images",zv=()=>({element:{enter:(e,t)=>{if(e.name==="image"&&e.attributes["xlink:href"]!=null&&/(?:\.|image\/)(?:jpe?g|png|gif)/.test(e.attributes["xlink:href"]))U(e,t)}}}),Zh={};R(Zh,{name:()=>_v,fn:()=>Gv,description:()=>Uv});var _v="removeScripts",Uv="removes scripts",Vv=[...Fe.animationEvent??new Set,...Fe.documentEvent??new Set,...Fe.documentElementEvent??new Set,...Fe.globalEvent??new Set,...Fe.graphicalEvent??new Set],Gv=()=>({element:{enter:(e,t)=>{if(e.name==="script"){U(e,t);return}for(let r of Vv)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={};R(Qh,{name:()=>Wv,fn:()=>Kv,description:()=>qv});var Wv="removeStyleElement",qv="removes <style> element",Kv=()=>({element:{enter:(e,t)=>{if(e.name==="style")U(e,t)}}}),Xh={};R(Xh,{name:()=>Yv,fn:()=>Jv,description:()=>Hv});var Yv="removeTitle",Hv="removes <title>",Jv=()=>({element:{enter:(e,t)=>{if(e.name==="title")U(e,t)}}}),ed={};R(ed,{name:()=>Zv,fn:()=>e2,description:()=>Qv});var Zv="removeViewBox",Qv="removes viewBox attribute when possible",Xv=new Set(["pattern","svg","symbol"]),e2=()=>({element:{enter:(e,t)=>{if(Xv.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={};R(td,{name:()=>t2,fn:()=>a2,description:()=>r2});var t2="removeXlink",r2="remove xlink namespace and replaces attributes with the SVG 2 equivalent where applicable",hu="http://www.w3.org/1999/xlink",i2={new:"_blank",replace:"_self"},n2=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 a2=(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=i2[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&&n2.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={};R(rd,{name:()=>s2,fn:()=>l2,description:()=>o2});var s2="removeXMLNS",o2="removes xmlns attribute (for inline svg)",l2=()=>({element:{enter:(e)=>{if(e.name==="svg")delete e.attributes.xmlns}}}),id={};R(id,{name:()=>c2,fn:()=>f2,description:()=>u2});var c2="reusePaths",u2="Finds <path> elements with the same d, fill, and stroke, and converts them to <use> elements referencing a single <path> def.",f2=(e)=>{let t=ft(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){U(h,o);continue}if(Object.keys(h.attributes).length===1&&h.attributes.id!=null){U(h,o);let d=`[xlink\\:href="#${h.attributes.id}"], [href="#${h.attributes.id}"]`;for(let m of ci(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)}}}}}},h2=Object.freeze([Sv,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 d2(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 m2(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}=d2(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 A=e.slice(b,l),$=mu(A,a?s:null);if(S)u({type:"text",value:$});else{let P=$.trim();if(P.length>0)u({type:"text",value:P})}}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 A=e.charCodeAt(b);if(A===91)v=!0;else if(A===93)v=!1;else if(A===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 A;while((A=pu.exec(S))!=null)s[A[1]]=A[2]??A[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/),A=S<0?v:v.slice(0,S),$=S<0?"":v.slice(S+1);u({type:"instruction",name:A,value:$}),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 P=e.charCodeAt(m);if(P===61||P===32||P===9||P===10||P===13||P===47||P===62)break;m++}let S=e.slice(v,m);while(m<o){let P=e.charCodeAt(m);if(P!==32&&P!==9&&P!==10&&P!==13)break;m++}if(e.charCodeAt(m)!==61){y[S]="";continue}m++;while(m<o){let P=e.charCodeAt(m);if(P!==32&&P!==9&&P!==10&&P!==13)break;m++}let A=e.charCodeAt(m),$;if(A===34||A===39){let P=e.indexOf(A===34?'"':"'",m+1);if(P<0)c("Unterminated attribute value",m);$=e.slice(m+1,P),m=P+1}else{let P=m;while(m<o){let O=e.charCodeAt(m);if(O===32||O===9||O===10||O===13||O===47||O===62)break;m++}$=e.slice(P,m)}y[S]=mu($,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 p2={"&":"&amp;","'":"&apos;",'"':"&quot;",">":"&gt;","<":"&lt;"};function vi(e){return p2[e]}var st={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:vi,pretty:!1,useShortTags:!0,eol:"lf",finalNewline:!1};function g2(e,t={}){let r={...st,...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+=S2(n,t,r);break;case"text":i+=C2(n,t,r);break;case"doctype":i+=y2(n,t);break;case"instruction":i+=w2(n,t);break;case"comment":i+=b2(n,t);break;case"cdata":i+=v2(n,t,r);break}return r.indentLevel--,i}function Mr(e,t){if(e.pretty&&t.textContext==null)return t.indent.repeat(t.indentLevel-1);return""}function y2(e,t){return t.doctypeStart+e.data.doctype+t.doctypeEnd}function w2(e,t){return`${t.procInstStart+e.name} ${e.value}${t.procInstEnd}`}function b2(e,t){return t.commentStart+e.value+t.commentEnd}function v2(e,t,r){return Mr(t,r)+t.cdataStart+e.value+t.cdataEnd}function S2(e,t,r){if(e.children.length===0){if(t.useShortTags)return Mr(t,r)+t.tagShortStart+e.name+Ya(e,t)+t.tagShortEnd;return Mr(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=Mr(t,r),l=Mr(t,r);if(r.textContext)i=st.tagOpenStart,n=st.tagOpenEnd,s=st.tagCloseStart,a=st.tagCloseEnd,o="";else if(xh.has(e.name))n=st.tagOpenEnd,s=st.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 x2(e){if(e.indexOf("&")<0&&e.indexOf('"')<0&&e.indexOf("<")<0&&e.indexOf(">")<0)return e;return e.replace(st.regValEntities,vi)}function $2(e){if(e.indexOf("&")<0&&e.indexOf("'")<0&&e.indexOf('"')<0&&e.indexOf("<")<0&&e.indexOf(">")<0)return e;return e.replace(st.regEntities,vi)}function Ya(e,t){let r="",i=t.encodeEntity===vi&&t.regValEntities===st.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?x2(o):o.replace(t.regValEntities,t.encodeEntity);r+=t.attrStart+l+t.attrEnd}}return r}function C2(e,t,r){let i=t.encodeEntity===vi&&t.regEntities===st.regEntities?$2(e.value):e.value.replace(t.regEntities,t.encodeEntity);return Mr(t,r)+t.textStart+i+(r.textContext?"":t.textEnd)}var Us=new Map;for(let e of h2)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 A2(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=m2(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(A2).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=g2(o,t.js2svg),n.length<i)e=n,i=n.length;else break}if(t.datauri)n=aw(n,t.datauri);return{data:n}}var dS=Object.defineProperty,mS=(e)=>e;function pS(e,t){this[e]=mS.bind(null,t)}var gS=(e,t)=>{for(var r in t)dS(e,r,{get:t[r],enumerable:!0,configurable:!0,set:pS.bind(t,r)})},yS=(e,t)=>()=>(e&&(t=e(e=0)),t),cd={};gS(cd,{withErrorRecovery:()=>hd,tryLoadConfig:()=>zS,loadConfigWithResult:()=>BS,loadConfig:()=>yd,isRetryableError:()=>FS,isConfigNotFoundError:()=>PS,isBunfigError:()=>dd,globalPerformanceMonitor:()=>Si,globalCache:()=>Br,getEnvOrDefault:()=>OS,generateConfigTypes:()=>_S,defaultGeneratedDir:()=>Ad,defaultConfigDir:()=>Cd,deepMergeWithArrayStrategy:()=>Fl,deepMerge:()=>md,createLibraryConfig:()=>US,config:()=>IS,bunfigPlugin:()=>VS,applyEnvVarsToConfig:()=>Zr,TypeGenerationError:()=>Zs,SchemaValidationError:()=>hi,PluginError:()=>Xs,PerformanceMonitor:()=>Tl,FileSystemError:()=>Js,ErrorFactory:()=>Vt,EnvVarError:()=>Bn,EnvProcessor:()=>sa,ConfigValidator:()=>Ol,ConfigValidationError:()=>Ys,ConfigNotFoundError:()=>jn,ConfigMergeError:()=>Hs,ConfigLoader:()=>Rl,ConfigLoadError:()=>fi,ConfigFileLoader:()=>oa,ConfigCache:()=>Ml,CacheUtils:()=>bd,BunfigError:()=>We,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 wS(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function bS(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function vS(e){return e.getStats().size*2}function Nl(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ce(t[0])&&"id"in t[0]&&t[0].id===3&&ce(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ce(t)&&ce(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(ce(e)&&"arr"in e&&Array.isArray(e.arr)&&ce(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ce(t[0])&&ce(e[0])){let i=[...t];for(let n of e)if(ce(n)&&"name"in n){if(!i.find((s)=>ce(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(ce(n)&&"path"in n){if(!i.find((s)=>ce(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>On(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(!ce(t)||!ce(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(ce(n)&&ce(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&&ce(n[0])&&ce(r[i][0])){let s=[...n];for(let a of r[i])if(ce(a)&&"name"in a){if(!s.find((o)=>ce(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(ce(a)&&"path"in a){if(!s.find((o)=>ce(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>On(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 On(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(!On(e[r],t[r]))return!1;return!0}if(ce(e)&&ce(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(!On(e[n],t[n]))return!1}return!0}return!1}function ce(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function SS(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 xS({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=Pn(i,`${a}${o}`),c=await SS(l,r);if(c!==null)return c}try{let a=Pn(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 $S(e,t={}){let r=Nn.cwd();while(r.includes("storage"))r=Su(r,"..");let i=Su(r,e||"");if(t?.relative)return D2(Nn.cwd(),i);return i}async function CS(){try{let e=await xS({name:"clarity",defaultConfig:sn,cwd:Nn.cwd(),endpoint:"",headers:{}});return{...sn,...e}}catch{return sn}}function de(){if(At.env.NODE_ENV==="test"||At.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function AS(){if(At.env.NODE_ENV==="test"||At.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof At<"u"){let e=At.type;if(e==="renderer"||e==="worker")return!1;return!!(At.versions&&(At.versions.node||At.versions.bun))}return!1}class ud{async format(e){let t=await AS(),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:br.pid,hostname:t(),environment:br.env.NODE_ENV||"development",platform:br.platform,version:br.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:br.env.NODE_ENV||br.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Rn{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??Me.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{...on,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...on};return{...on,...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 z2(this.config.logDirectory,Au.F_OK|Au.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await _2(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(!Qa(this.currentLogFile))await Xa(this.currentLogFile,"",{mode:420});if(i=Cu(this.currentLogFile,"a",420),I2(i,o,{flag:"a"}),$u(i),i!==void 0)Za(i),i=void 0;if((await yr(this.currentLogFile)).size===0){if(await Xa(this.currentLogFile,o,{flag:"w",mode:420}),(await yr(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 wr(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 wr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return wr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(de())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=L2("aes-256-gcm",t,r),n=Bt.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:Bt.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(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(de())return;let e=await yr(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 ji(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 yr(r).catch(()=>null))try{if(await Eu(r,o),t.compress)try{let l=`${o}.gz`;await this.compressLogFile(o,l),await Bi(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 yr(r).catch(()=>null))await Eu(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await ji(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await Bi(wr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=xu(e),i=B2(t),n=ku();await U2(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(!de()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ji(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Bi(wr(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?le.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=Me.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} ${le.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&&!de()){let c=vd[e],u=this.options.showTags!==!1&&this.name?le.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:n,icon:c,tag:u,message:le.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:le.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:le.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!de()){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&&!de()){let r=this.options.showTags!==!1&&this.name?le.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:le.blue("\u25D0"),tag:r,message:`${le.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&&!de()){let c=this.options.showTags!==!1&&this.name?le.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:o,icon:le.green("\u2713"),tag:c,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!de())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 Rn(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(de())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=Bt.isBuffer(e)?e:Bt.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),a=i.slice(16,-16),o=j2("aes-256-gcm",r,n);return o.setAuthTag(s),Bt.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 de()}isServerMode(){return!de()}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&&!de()){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:le.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:le.cyan(o)})),c.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:le.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:le.cyan(l),showTimestamp:!1}))}else if(!de())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(de())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${le.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();Me.stdin.removeListener("data",r);try{if(typeof Me.stdin.setRawMode==="function")Me.stdin.setRawMode(!1)}catch{}Me.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof Me.stdin.setRawMode==="function")Me.stdin.setRawMode(!0)}catch{}Me.stdin.resume(),Me.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&&!de()){let n=this.options.showTags!==!1&&this.name?le.gray(this.formatTag(this.name)):"",s=le.blue("\u25D0");console.error(`${s} ${n} ${le.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||de()||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||de())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||de())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||de())return;Me.stdout.write(`${"\r".padEnd(Me.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||de()||!Me.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=le.green("\u2501".repeat(i)),a=le.gray("\u2501".repeat(n)),o=`[${s}${a}]`,l=`${r}%`.padStart(4),c=e.message?` ${e.message}`:"",u=t||r===100?le.green("\u2713"):le.blue("\u25B6"),f=this.options.showTags!==!1&&this.name?` ${le.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${o} ${l}${c}`,d=Me.stdout.columns||80,m=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${m}`,Me.stdout.write(e.lastRenderedLine),t)Me.stdout.write(`
91
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||de()||!Me.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(de()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ji(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=wr(this.config.logDirectory,i);if(e.before)try{if((await yr(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 Bi(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 an(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ne(t[0])&&"id"in t[0]&&t[0].id===3&&ne(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ne(t)&&ne(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(ne(e)&&"arr"in e&&Array.isArray(e.arr)&&ne(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ne(t[0])&&ne(e[0])){let i=[...t];for(let n of e)if(ne(n)&&"name"in n){if(!i.find((s)=>ne(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(ne(n)&&"path"in n){if(!i.find((s)=>ne(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>Dn(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(!ne(t)||!ne(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(ne(n)&&ne(r[i]))r[i]=an(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&ne(n[0])&&ne(r[i][0])){let s=[...n];for(let a of r[i])if(ne(a)&&"name"in a){if(!s.find((o)=>ne(o)&&("name"in o)&&o.name===a.name))s.push(a)}else if(ne(a)&&"path"in a){if(!s.find((o)=>ne(o)&&("path"in o)&&o.path===a.path))s.push(a)}else if(!s.some((o)=>Dn(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:an(e,t);if(Array.isArray(e))return r==="replace"?t:an(e,t);if(!ne(t)||!ne(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]=an(a,s);else if(ne(s)&&ne(a))i[n]=Pl(a,s,r);else i[n]=s}return i}function Dn(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(!Dn(e[r],t[r]))return!1;return!0}if(ne(e)&&ne(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(!Dn(e[n],t[n]))return!1}return!0}return!1}function ne(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Ki(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 ES(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)Ne.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=ui.env[d]||ui.env[m];if(p!==void 0){if(r)Ne.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 kS({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)?ES(e,n,s):n,c=r||ui.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Ne.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,De(c,"config"),De(c,".config"),i?De(c,i):void 0].filter(Boolean)));for(let y of p){if(s)Ne.info(`Searching for configuration in: ${y}`);let g=[De(c,"config"),De(c,".config")].concat(i?[De(c,i)]:[]).includes(y)?[...f,...h,...d,...m]:[...h,...f,...m,...d];for(let w of g)for(let b of u){let v=De(y,`${w}${b}`),S=await Ki(v,l,o);if(S!==null){if(s)Ne.success(`Configuration loaded from: ${v}`);return S}}}if(e){let y=De(Ha(),".config",e),g=["config",`${e}.config`];if(t)g.push(`${t}.config`);if(s)Ne.info(`Checking user config directory: ${y}`);for(let w of g)for(let b of u){let v=De(y,`${w}${b}`),S=await Ki(v,l,o);if(S!==null){if(s)Ne.success(`Configuration loaded from user config directory: ${v}`);return S}}}if(e){let y=De(Ha(),".config"),g=[`.${e}.config`];if(t)g.push(`.${t}.config`);if(s)Ne.info(`Checking user config directory for dotfile configs: ${y}`);for(let w of g)for(let b of u){let v=De(y,`${w}${b}`),S=await Ki(v,l,o);if(S!==null){if(s)Ne.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)Ne.info(`Checking user home directory for dotfile configs: ${y}`);for(let w of g)for(let b of u){let v=De(y,`${w}${b}`),S=await Ki(v,l,o);if(S!==null){if(s)Ne.success(`Configuration loaded from user home directory: ${v}`);return S}}}try{let y=De(c,"package.json");if(od(y)){let g=await import(y),w=g[e];if(!w&&t){if(w=g[t],w&&s)Ne.success(`Using alias "${t}" configuration from package.json`)}if(w&&typeof w==="object"&&!Array.isArray(w))try{if(s)Ne.success(`Configuration loaded from package.json: ${w===g[e]?e:t}`);return Pl(l,w,o)}catch(b){if(s)Ne.warn("Failed to merge package.json config:",b)}}}catch(y){if(s)Ne.warn("Failed to load package.json:",y)}if(s)Ne.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return l}function MS(e,t={}){let r=Tn.cwd();while(r.includes("storage"))r=vu(r,"..");let i=vu(r,e||"");if(t?.relative)return O2(Tn.cwd(),i);return i}async function TS(){try{let e=await kS({name:"clarity",alias:"logging",defaultConfig:ln,cwd:Tn.cwd()});return{...ln,...e||{}}}catch{return ln}}function ve(){if(Et.env.NODE_ENV==="test"||Et.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function NS(){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 fd{async format(e){let t=await NS(),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:xr.pid,hostname:t(),environment:xr.env.NODE_ENV||"development",platform:xr.platform,version:xr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xr.env.NODE_ENV||xr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ln{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??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},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{...cn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...cn};return{...cn,...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!ve()&&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 K2(this.config.logDirectory,Pu.F_OK|Pu.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Y2(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(!Ii(this.currentLogFile))await rs(this.currentLogFile,"",{mode:420});if(i=Nu(this.currentLogFile,"a",420),q2(i,o,{flag:"a"}),Tu(i),i!==void 0)ts(i),i=void 0;if((await vr(this.currentLogFile)).size===0){if(await rs(this.currentLogFile,o,{flag:"w",mode:420}),(await vr(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 Sr(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 Sr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Sr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ve())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=V2("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=Ou(),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(ve())return;if(!this.shouldWriteToFile())return;let e=await vr(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 zi(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 vr(r).catch(()=>null))try{if(await Fu(r,o),t.compress)try{let l=`${o}.gz`;await this.compressLogFile(o,l),await _i(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 vr(r).catch(()=>null))await Fu(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await zi(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await _i(Sr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Mu(e),i=W2(t),n=Ou();await Z2(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()})),Ii(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(!ve()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await zi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await _i(Sr(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||ve())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(ve())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(H2(t)||t.startsWith("./")||t.startsWith("../"))t=J2(t);else return null;return Ii(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?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(`
92
+ `);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(!ve()){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()&&!ve()&&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()&&!ve()&&re.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!ve()&&re.stdout.isTTY)re.stdout.write(`
95
+ `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!ve()&&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+=`
96
+ `,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(!ve())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 Ln(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(ve())throw Error("createReadStream is not supported in browser environments");if(!Ii(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=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=G2("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 ve()}isServerMode(){return!ve()}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)=>{return 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(!ve())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(ve())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}
99
+ `.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(`
100
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ve()||!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(ve()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await zi(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=Sr(this.config.logDirectory,i);if(e.before)try{if((await vr(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 _i(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 We}function PS(e){return e instanceof jn}function FS(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 sa{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 Si.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=Ui.env[l]||(c?Ui.env[c]:void 0);if(u!==void 0){if(i.verbose){let f=Ui.env[l]?l:c}try{e[n]=this.parseEnvironmentValue(u,typeof s,l,i.customParsers,i.configName)}catch(f){if(f instanceof Bn)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(Ui.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 OS(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(!Qe(t)||!Qe(e))return t;return jS(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 RS(e,t);case"smart":return DS(e,t,i);default:return t}return t}function RS(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Ws(n,i)))r.push(i);return r}function DS(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Qe(t[0])&&Qe(e[0]))return LS(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 LS(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 jS(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]=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(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(!Ws(e[n],t[n]))return!1}return!0}return!1}function Qe(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class oa{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=Br.getWithFileCheck("file",e);if(c){if(o)console.log(`Configuration loaded from cache: ${e}`);return c}}let l=async()=>{if(!Vi(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 fi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new fi(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)Br.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 Si.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()=>{return Vi(e)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Vi(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(!Vi(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 Si.track("validateConfiguration",c);return c()}async validateWithSchemaFile(e,t,r){try{if(!Q2(t))throw new hi(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 hi(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 oa;envProcessor=new sa;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)it.warn(`Slow configuration loading detected: ${l.duration}ms for ${a.name}`);o.metrics=l}return o}catch(o){let l=Date.now()-t;throw it.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}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,a,o,l){let c=o?Zr(e,n,a):n,u=this.getLocalDirectories(r,i);for(let f of u){if(a)it.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)it.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?Zr(e,r,n):r,o=[Be(gr(),".config",e),Be(gr(),".config"),gr()];for(let l of o){if(n)it.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)it.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?Zr(e,i,s):i;try{let l=Be(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)it.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)it.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:Zr(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 Br.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Br.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,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(gr(),".config",e),Be(gr(),".config"),gr()],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 BS(e){return Pt.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 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)it.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 IS(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"&&Uu(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"&&Uu(t)))return(await Pt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function zS(e,t,r="replace"){let i=new oa;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Zr(e,t,r=!1){let i=new sa,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 _S(e){let t=Be(tr.cwd(),e.configDir),r=Be(tr.cwd(),e.generatedDir),i=Be(r,"config-types.ts");if(!Vs(bu(i)))T2(bu(i),{recursive:!0,mode:511});let n=Vs(t)?N2(t).map((a)=>a.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${gx}
113
+ export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
114
+ `;P2(i,s,{mode:438})}function US(e){let t=null,r=null,i=()=>{if(!r)r=yd(e).then((s)=>{return t=s,s},(s)=>{let a="defaultConfig"in e?e.defaultConfig:{};if(t=a,"verbose"in e&&e.verbose)it.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 VS(e){let t=Ru(tS.cwd(),e?.configDir||"./config");function r(){if(!X2(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],a=eS(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)=>{return{path:s.path,namespace:"bunfig-virtual"}}),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:i(),loader:"ts"}})}}}var wd,Br,Si,bd,GS,WS,Vu,sn,qs,Te,le,qS,Gu,KS,Wu,YS,HS,ls,JS,qu,Ku,cs,ZS,QS,XS,ex,on,vd,tx,Ne,rx,ix,Yu,ln,Ks,Se,J,nx,Hu,ax,Ju,sx,ox,us,lx,Zu,Qu,cx,fs,ux,fx,hx,dx,mx,cn,Sd,px,gx="0.15.6",We,jn,fi,Ys,Hs,Bn,Js,Zs,hi,Qs,Xs,Vt,xd,$d,it,Pt,Cd,Ad,yx=yS(async()=>{wd=import.meta.require,Br=new Ml,Si=new Tl,bd={createKey:wS,isEquivalent:bS,estimateMemoryUsage:vS},GS=Pn(Gs.cwd(),"config"),WS=Pn(Gs.cwd(),"src/generated"),Vu=Nn.env.CLARITY_LOG_DIR||R2($S(),"logs"),sn={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 CS(),Te={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"},le=Te,qS=Te.red,Gu=Te.green,KS=Te.yellow,Wu=Te.blue,YS=Te.magenta,HS=Te.cyan,ls=Te.white,JS=Te.gray,qu=Te.bgRed,Ku=Te.bgYellow,cs=Te.bold,ZS=Te.dim,QS=Te.italic,XS=Te.underline,ex=Te.reset,on={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 ")))},tx=new Rn("stacks"),Ne=new Rn("bunfig",{showTags:!0}),rx=De(ui.cwd(),"config"),ix=De(ui.cwd(),"src/generated"),Yu=Tn.env.CLARITY_LOG_DIR||F2(MS(),"logs"),ln={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 TS(),Se={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=Se,nx=Se.red,Hu=Se.green,ax=Se.yellow,Ju=Se.blue,sx=Se.magenta,ox=Se.cyan,us=Se.white,lx=Se.gray,Zu=Se.bgRed,Qu=Se.bgYellow,cx=Se.bgGray,fs=Se.bold,ux=Se.dim,fx=Se.italic,hx=Se.underline,dx=Se.strikethrough,mx=Se.reset,cn={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 ")))},px=new Ln("stacks"),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}`}},jn=class extends We{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})}},fi=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}},Ys=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})}},Hs=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}},Bn=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})}},Js=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}},Zs=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}},hi=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})}},Qs=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})}},Xs=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 jn(e,t,r)},configLoad(e,t,r){return new fi(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 Bn(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 hi(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?:\/\//,it=new Ln("bunfig",{showTags:!0}),Pt=new Rl,Cd=Be(tr.cwd(),"config"),Ad=Be(tr.cwd(),"src/generated")});function wx(e,t={}){let r=Fn.cwd();while(r.includes("storage"))r=Du(r,"..");let i=Du(r,e||"");if(t?.relative)return iS(Fn.cwd(),i);return i}var bx=Fn.env.CLARITY_LOG_DIR||rS(wx(),"logs"),Ed={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:bx,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},In={...Ed},SE=(async()=>{try{let{loadConfig:e}=await yx().then(()=>cd),t=await e({name:"clarity",alias:"logging",defaultConfig:Ed,cwd:Fn.cwd()});if(t)Object.assign(In,t)}catch{}return In})();function xe(){if(kt.env.NODE_ENV==="test"||kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vx(){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 kd{async format(e){let t=await vx(),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:Ar.pid,hostname:t(),environment:Ar.env.NODE_ENV||"development",platform:Ar.platform,version:Ar.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ar.env.NODE_ENV||Ar.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var Ee={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=Ee,xE=Ee.red,Sx=Ee.green,$E=Ee.yellow,xx=Ee.blue,CE=Ee.magenta,AE=Ee.cyan,Xu=Ee.white,EE=Ee.gray,$x=Ee.bgRed,Cx=Ee.bgYellow,kE=Ee.bgGray,ef=Ee.bold,ME=Ee.dim,TE=Ee.italic,NE=Ee.underline,PE=Ee.strikethrough,FE=Ee.reset,hs={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ax={debug:"\uD83D\uDD0D",info:xx("\u2139"),success:Sx("\u2713"),warning:Cx(Xu(ef(" WARN "))),error:$x(Xu(ef(" ERROR ")))};class la{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={...In},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??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,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:In.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!xe()&&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 lS(this.config.logDirectory,Iu.F_OK|Iu.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await cS(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(!Gi(this.currentLogFile))await os(this.currentLogFile,"",{mode:420});if(i=Bu(this.currentLogFile,"a",420),oS(i,o,{flag:"a"}),ju(i),i!==void 0)ss(i),i=void 0;if((await $r(this.currentLogFile)).size===0){if(await os(this.currentLogFile,o,{flag:"w",mode:420}),(await $r(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 Cr(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 Cr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Cr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(xe())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=nS("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=_u(),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(xe())return;if(!this.shouldWriteToFile())return;let e=await $r(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 Wi(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 $r(r).catch(()=>null))try{if(await zu(r,o),t.compress)try{let l=`${o}.gz`;await this.compressLogFile(o,l),await qi(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 $r(r).catch(()=>null))await zu(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Wi(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,a)=>a.localeCompare(s));for(let s of n.slice(t.maxFiles))await qi(Cr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Lu(e),i=sS(t),n=_u();await hS(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()})),Gi(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(!xe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Wi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await qi(Cr(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||xe())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(xe())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(uS(t)||t.startsWith("./")||t.startsWith("../"))t=fS(t);else return null;return Gi(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?"":Ax[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(`
122
+ `);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(!xe()){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()&&!xe()&&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()&&!xe()&&ie.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!xe()&&ie.stdout.isTTY)ie.stdout.write(`
125
+ `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!xe()&&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+=`
126
+ `,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(!xe())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 la(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(xe())throw Error("createReadStream is not supported in browser environments");if(!Gi(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=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=aS("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 xe()}isServerMode(){return!xe()}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)=>{return 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(!xe())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(xe())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}
129
+ `.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(`
130
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||xe()||!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(xe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Wi(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=Cr(this.config.logDirectory,i);if(e.before)try{if((await $r(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 qi(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 OE=new la("stacks"),Nr=new la("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 E2(e)).isDirectory())return[M2(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)=>{return k2(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 Ex(e,t,r,i={}){let n=await Md(e,{...i,patterns:t}),s=new AbortController;for(let a of n)W("watch",`Would watch file: ${a}`,!0);return()=>s.abort()}function kx(e,t){return t.some((r)=>{return new Bun.Glob(r).match(e)})}function Mx(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 W(e,t,r){if(r===!1)return;if(r===!0||T.verbose===!0)Nr.debug(`[imgx:${e}] ${t}`);if(Array.isArray(r)){if(r.some((i)=>e.startsWith(i)))Nr.info(`[imgx:${e}] ${t}`)}if(Array.isArray(T.verbose)){if(T.verbose.some((i)=>e.startsWith(i)))Nr.debug(`[imgx:${e}] ${t}`)}}function Tx(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 un(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 Nx(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;Nr.box(`
131
+ Successfully processed ${t.length} files:
132
+ - Total input size: ${un(i)}
133
+ - Total output size: ${un(n)}
134
+ - Total saved: ${un(s)} (${a.toFixed(2)}%)
135
+ `)}if(r.length>0)Nr.error(`
136
+ Failed to process ${r.length} files:`),r.forEach((i)=>{Nr.error(`- ${i?.inputPath}: ${i?.error?.message}`)})}function Px(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 Gt(e){let t=ff(e);await uf(t,{recursive:!0})}async function Wt(e){let t,r;if(typeof e==="string")t=new Uint8Array(await mi(e)),r=(await ct(e)).size;else t=new Uint8Array(e),r=e.length;return{imageData:await Oe(t),originalSize:r}}async function rr(e,t,r,i={}){let n=await et(e,t,i);if(r)await Gt(r),await Qt(r,n);return n}async function eo(e){let{input:t,output:r,quality:i=80,resize:n,format:s,progressive:a=!0}=e;W("process",`Processing image with options: ${JSON.stringify(e)}`);try{let{imageData:o,originalSize:l}=await Wt(t),c=o;if(n){let m=Px(n);if(m)c=Ae(c,{width:m.width,height:m.height})}let u=s||Ur(typeof t==="string"?new Uint8Array(await mi(t)):new Uint8Array(t))||"png",f=(await rr(c,u,r,{quality:i,progressive:a})).length,h=l-f,d=h/l*100;return W("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 W("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;W("process",`Processing SVG with options: ${JSON.stringify(e)}`);try{let n,s;if(typeof t==="string")n=await mi(t,"utf-8"),s=(await ct(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 Gt(r),await Qt(r,a);let o=yn.from(a).length,l=s-o,c=l/s*100;return W("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 W("error",`Failed to process SVG: ${s.message}`),s}}async function Td(e,t={}){let{output:r,prettify:i=T.svg?.prettify||!1,precision:n=T.svg?.precision||3,multipass:s=T.svg?.multipass||!1,removeComments:a=T.svg?.removeComments||!0,removeMetadata:o=T.svg?.removeMetadata||!0,removeViewBox:l=T.svg?.removeViewBox||!1,removeDimensions:c=T.svg?.removeDimensions||!0,removeHiddenElements:u=T.svg?.removeHiddenElements||!0,removeEmptyAttrs:f=T.svg?.removeEmptyAttrs||!0,removeEmptyContainers:h=T.svg?.removeEmptyContainers||!0,removeUnusedNS:d=T.svg?.removeUnusedNS||!0,cleanupIDs:m=T.svg?.cleanupIDs||!0,cleanupNumericValues:p=T.svg?.cleanupNumericValues||!0,cleanupListOfValues:y=T.svg?.cleanupListOfValues||!0,collapseGroups:g=T.svg?.collapseGroups||!0,convertColors:w=T.svg?.convertColors||!0,convertPathData:b=T.svg?.convertPathData||!0,convertShapeToPath:v=T.svg?.convertShapeToPath||!0,convertStyleToAttrs:S=T.svg?.convertStyleToAttrs||!0,convertTransform:A=T.svg?.convertTransform||!0,inlineStyles:$=T.svg?.inlineStyles||!0,minifyStyles:P=T.svg?.minifyStyles||!0,mergePaths:O=T.svg?.mergePaths||!0,prefixIds:x=T.svg?.prefixIds||!1,prefixClassNames:C=T.svg?.prefixClassNames||!1,removeXMLNS:k=T.svg?.removeXMLNS||!1,removeOffCanvasPaths:E=T.svg?.removeOffCanvasPaths||!1,reusePaths:N=T.svg?.reusePaths||!1,sortAttrs:M=T.svg?.sortAttrs||!0,sortDefsChildren:F=T.svg?.sortDefsChildren||!0,removeDoctype:G=T.svg?.removeDoctype||!0,removeXMLProcInst:Q=T.svg?.removeXMLProcInst||!0,removeTitle:X=T.svg?.removeTitle||!1,removeDesc:fe=T.svg?.removeDesc||!1,removeScriptElement:K=T.svg?.removeScriptElement||!1,removeStyleElement:oe=T.svg?.removeStyleElement||!1,stats:q=!1}=t;W("processor",`Optimizing SVG with ${s?"multipass":"single pass"} mode`);try{let z,ae=typeof e==="string"&&!e.trim().startsWith("<")?e:"buffer",$e;if(typeof e==="string")if(e.trim().startsWith("<"))z=e,$e=yn.from(e).length;else z=await mi(e,"utf-8"),$e=(await ct(e)).size;else z=e.toString("utf-8"),$e=e.length;let D={multipass:s,plugins:[{name:"preset-default",params:{overrides:{removeViewBox:l,removeComments:a,removeMetadata:o,removeDoctype:G,removeXMLProcInst:Q,removeTitle:X,removeDesc:fe,convertPathData:b,convertTransform:A,inlineStyles:$,mergePaths:O,minifyStyles:P,cleanupNumericValues:p,collapseGroups:g,convertColors:w,removeEmptyAttrs:f,removeEmptyContainers:h,removeUnusedNS:d,sortAttrs:M,sortDefsChildren:F}}}],js2svg:{pretty:i,indent:2,precision:n}};if(m)D.plugins.push({name:"cleanupIds"});if(y)D.plugins.push({name:"cleanupListOfValues"});if(v)D.plugins.push({name:"convertShapeToPath"});if(S)D.plugins.push({name:"convertStyleToAttrs"});if(u)D.plugins.push({name:"removeHiddenElems"});if(c)D.plugins.push({name:"removeDimensions"});if(x)D.plugins.push({name:"prefixIds",params:{prefix:typeof x==="string"?x:"id-",delim:"-"}});if(C)D.plugins.push({name:"prefixClassNames",params:{prefix:typeof C==="string"?C:"class-",delim:"-"}});if(k)D.plugins.push({name:"removeXMLNS"});if(N)D.plugins.push({name:"reusePaths"});if(E)D.plugins.push({name:"removeOffCanvasPaths"});if(K)D.plugins.push({name:"removeScriptElems"});if(oe)D.plugins.push({name:"removeStyleElems"});let se=sd(z,D).data,ke=yn.from(se).length,pe=$e-ke,ht=pe/$e*100,Kt=q?{}:null,Ce=r;if(Ce)await Gt(Ce),await Qt(Ce,se);else if(typeof e==="string"&&!e.trim().startsWith("<")){let Yt=ri(e);Ce=e.replace(new RegExp(`${Yt}$`),`.optimized${Yt}`),await Gt(Ce),await Qt(Ce,se)}else Ce="buffer";return W("processor",`Optimized SVG: saved ${ht.toFixed(2)}% (${pe} bytes)`),{inputPath:ae,outputPath:Ce,inputSize:$e,outputSize:ke,saved:pe,savedPercentage:ht,content:se,prettified:i,multipass:s,stats:Kt}}catch(z){let ae=z instanceof Error?z:Error(typeof z==="string"?z:"Unknown error optimizing SVG");throw W("error",`Failed to optimize SVG: ${ae.message}`),ae}}async function Fx(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;W("processor",`Converting image to SVG using ${i} mode`);try{let{imageData:u}=await Wt(e),f=typeof e==="string"?e:"buffer",h=u.width,d=u.height,m=$g({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 Gt(p),await Qt(p,m);else if(typeof e==="string"){let y=ri(e);p=e.replace(new RegExp(`${y}$`),".svg"),await Gt(p),await Qt(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 W("error",`Failed to convert image to SVG: ${f.message}`),f}}async function Ox(e,t={}){let{width:r=T.placeholders?.width||20,height:i=T.placeholders?.height,quality:n=T.placeholders?.quality||50,format:s=T.placeholders?.format||"webp",blurLevel:a=T.placeholders?.blurLevel||40,base64Encode:o=T.placeholders?.base64Encode!==void 0?T.placeholders.base64Encode:!0,thumbhash:l=T.placeholders?.useThumbhash||!1,outputPath:c,strategy:u=l?"thumbhash":"blur",saturation:f=1.2,cssFilter:h=!1}=t;W("processor",`Generating placeholder for ${e} using strategy: ${u}`);let{imageData:d}=await Wt(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=Ae(d,{width:r,height:i,fit:"inside"});if(u==="blur"){let v=a/10;g=ca(g,v)}else if(u==="pixelate"){let v=Math.max(8,Math.floor(r/8)),S=Ae(d,{width:v,fit:"inside"});g=Ae(S,{width:r,height:i,kernel:"nearest"})}if(f!==1)g=Dd(g,{saturation:f});let w,b;if(o){w=await et(g,s,{quality:n});let v=yn.from(w).toString("base64"),S=`data:${`image/${s==="jpeg"?"jpeg":s}`};base64,${v}`,A={dataURL:S,width:m,height:p,aspectRatio:y,originalWidth:m,originalHeight:p,strategy:u};if(h){let $=`
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{...A,css:$}}return A}else return b=c||e.replace(/\.[^/.]+$/,`.placeholder.${s}`),await rr(g,s,b,{quality:n}),{dataURL:b,width:m,height:p,aspectRatio:y,originalWidth:m,originalHeight:p,strategy:u}}async function Rx(e,t,r={}){let{outputDir:i,quality:n=T.conversion?.quality||80,lossless:s=T.conversion?.lossless||!1,progressive:a=T.conversion?.progressive!==void 0?T.conversion.progressive:!0,filenamePrefix:o="",filenameSuffix:l="",resize:c,preserveMetadata:u=!1,effort:f=6}=r;W("processor",`Converting ${e} to ${t}`);let h=(await ct(e)).size,d=ri(e),m=e.slice(0,-d.length),p=m.split("/").pop()||"image",y=`${o}${p}${l}.${t}`,g=i?Ji(i,y):`${m}.${t}`;if(i)await Gt(g);let{imageData:w}=await Wt(e),b=w;if(c)b=Ae(b,{width:c.width,height:c.height,fit:c.fit||"contain"});await rr(b,t,g,{quality:n,lossless:s,progressive:a,effort:f});let v=(await ct(g)).size,S=h-v,A=S/h*100;return{inputPath:e,outputPath:g,format:t,width:b.width,height:b.height,originalSize:h,convertedSize:v,saved:S,savedPercentage:A}}async function Dx(e,t={}){let{outputDir:r=e,formats:i=T.batch?.formats||["webp"],quality:n=T.batch?.quality||80,resize:s=T.batch?.resize,recursive:a=T.batch?.recursive||!1,filter:o=T.batch?.filter?new RegExp(T.batch.filter,"i"):/\.(jpe?g|png|gif|bmp|tiff?)$/i,skipExisting:l=T.batch?.skipExisting!==void 0?T.batch.skipExisting:!0,concurrency:c=T.concurrent||4,preserveStructure:u=!0,filenameTemplate:f="[name].[format]",preserveMetadata:h=!1,optimizationPreset:d="web",transformations:m=[],progressCallback:p}=t;W("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=(C)=>{if(typeof n==="number")return n;if(n[C])return n[C];switch(C){case"webp":return 80;case"avif":return 70;case"jpeg":return 85;case"png":return 90;default:return 80}},A=(C,k)=>{let E=S(C);switch(d){case"web":return{quality:E,effort:6,lossless:!1,progressive:C==="jpeg"||C==="png"};case"quality":return{quality:Math.min(E+10,100),effort:9,lossless:C==="png"||k<102400,progressive:C==="jpeg"||C==="png"};case"performance":return{quality:Math.max(E-10,60),effort:3,lossless:!1,progressive:!1};default:return{quality:E}}},$=(C)=>{let k=C;for(let E of m)switch(E.type){case"resize":k=Ae(k,E.options??{});break;case"rotate":k=so(k,E.options?.angle||0,E.options);break;case"flip":k=Qr(k);break;case"flop":k=lo(k);break;case"blur":k=ca(k,E.options?.sigma||1);break;case"sharpen":k=Od(k,E.options);break;case"grayscale":k=Rd(k);break}return k};async function P(C){let k=await Dm(C,{withFileTypes:!0});for(let E of k){let N=Ji(C,E.name);if(E.isDirectory()&&a){await P(N);continue}if(!E.isFile()||!o.test(E.name))continue;b.push(N),g.totalFiles++}}async function O(C){if(v.get(C))return;v.set(C,!0);try{let k=[],E=C.replace(e,"").replace(/^\//,""),N=r;if(u){let X=ff(E);if(X!==".")N=Ji(r,X),await uf(N,{recursive:!0})}let M=(C.split("/").pop()||"image").replace(/\.[^/.]+$/,""),F=await ct(C);g.originalSize+=F.size;let{imageData:G}=await Wt(C);for(let X of i){let fe=f.replace(/\[name\]/g,M).replace(/\[format\]/g,X).replace(/\[width\]/g,G.width.toString()).replace(/\[height\]/g,G.height.toString()).replace(/\[quality\]/g,S(X).toString()),K=Ji(N,fe);if(l)try{await ct(K);let $e=await ct(K);k.push({path:K,format:X,size:$e.size,saved:F.size-$e.size});continue}catch{}let oe=A(X,F.size),q=$(G);if(s)q=Ae(q,{width:s.width,height:s.height});await rr(q,X,K,oe);let z=await ct(K),ae=F.size-z.size;k.push({path:K,format:X,size:z.size,saved:ae}),g.optimizedSize+=z.size,g.saved+=ae}let Q={input:C,outputs:k,success:!0};if(y.push(Q),g.successCount++,p)p({completed:g.successCount+g.errorCount,total:g.totalFiles,percentage:(g.successCount+g.errorCount)/g.totalFiles*100,currentFile:C,success:!0})}catch(k){let E=k instanceof Error?k.message:String(k);if(y.push({input:C,outputs:[],success:!1,error:E}),g.errorCount++,p)p({completed:g.successCount+g.errorCount,total:g.totalFiles,percentage:(g.successCount+g.errorCount)/g.totalFiles*100,currentFile:C,success:!1})}v.delete(C)}await P(e);while(b.length>0){let C=b.splice(0,Math.min(c,b.length));await Promise.all(C.map((k)=>O(k)))}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 Lx(e,t,r={}){let{quality:i=T.optimization?.quality||80,lossless:n=T.optimization?.lossless||!1,progressive:s=T.optimization?.progressive!==void 0?T.optimization.progressive:!0,effort:a=T.optimization?.effort||7,metadata:o=T.optimization?.preserveMetadata||!1}=r;W("processor",`Optimizing image: ${e}`);try{let l=(await ct(e)).size,c=await mi(e),u=Ur(new Uint8Array(c))||"png",{imageData:f}=await Wt(e),h=i;switch(u){case"jpeg":h=r.quality||T.optimization?.jpeg?.quality||i;break;case"png":h=r.quality||T.optimization?.png?.quality||i;break;case"webp":h=r.quality||T.optimization?.webp?.quality||i;break;case"avif":h=r.quality||T.optimization?.avif?.quality||i;break}await rr(f,u,t,{quality:h,lossless:n,progressive:s,effort:a});let d=(await ct(t)).size;if(d>=l)return await Qt(t,new Uint8Array(c)),d=l,W("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 W("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 W("error",`Failed to optimize image: ${c}`),{originalSize:0,optimizedSize:0,saved:0,savedPercentage:0,success:!1,outputPath:t}}}async function jx(e,t={}){let{output:r,text:i,image:n,position:s=T.watermark?.position||"bottom-right",margin:a=T.watermark?.margin||20,opacity:o=T.watermark?.opacity||0.5,scale:l=T.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";W("processor",`Applying ${h} watermark to ${typeof e==="string"?e:"buffer"}`);let{imageData:d}=await Wt(e),m=typeof e==="string"?e:"buffer",p=d.width,y=d.height,g=(v,S)=>{let A={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 A[s]||A["bottom-right"]},w=d;if(i){let v=T.watermark?.textOptions||{},{fontSize:S=v.fontSize||24,color:A=v.color||"rgba(255, 255, 255, 0.5)"}=f,$=A.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/),P=$?parseInt($[1]):255,O=$?parseInt($[2]):255,x=$?parseInt($[3]):255,C=$&&$[4]?Math.floor(parseFloat($[4])*255):128,k=Math.min(Math.floor(p*0.3),i.length*S*0.6),E=S+20,N=_(k,E,{fill:{r:P,g:O,b:x,a:Math.floor(C*o)}}),{left:M,top:F}=g(k,E);w=Pr(d,N,{left:M,top:F,blend:"normal"})}else if(n){let{imageData:v}=await Wt(n),S=Math.floor(p*l),A=Math.floor(S*(v.height/v.width)),$=Ae(v,{width:S,height:A});if(c!==0)$=so($,c);if(o<1){let x=Math.floor(o*255);for(let C=3;C<$.data.length;C+=4)$.data[C]=Math.floor($.data[C]*o)}let{left:P,top:O}=g($.width,$.height);if(u){let x=d;for(let C=0;C<y;C+=$.height+a*2)for(let k=0;k<p;k+=$.width+a*2)x=Pr(x,$,{left:k,top:C,blend:"normal"});w=x}else w=Pr(d,$,{left:P,top:O,blend:"normal"})}let b=r;if(b){await Gt(b);let v=ri(b).slice(1)||"png";await rr(w,v,b)}else if(typeof e==="string"){let v=ri(e);b=e.replace(new RegExp(`${v}$`),`.watermarked${v}`);let S=v.slice(1)||"png";await rr(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=_(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=Er(u+v,0,e.width-1),A=Er(f+b,0,e.height-1);m[b+1][v+1]=Ye(e,S,A)}}let p=Yi(m,h,d,"r"),y=Yi(m,h,d,"g"),g=Yi(m,h,d,"b"),w=Yi(m,h,d,"a");zr(i,o,a,{r:Er(Math.round(p),0,255),g:Er(Math.round(y),0,255),b:Er(Math.round(g),0,255),a:Er(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 Yi(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 Er(e,t,r){return Math.min(r,Math.max(t,e))}function Pd(e,t,r){let i=_(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=Ye(e,u,f),g=Ye(e,h,f),w=Ye(e,u,d),b=Ye(e,h,d),v=Hi(y.r,g.r,w.r,b.r,m,p),S=Hi(y.g,g.g,w.g,b.g,m,p),A=Hi(y.b,g.b,w.b,b.b,m,p),$=Hi(y.a,g.a,w.a,b.a,m,p);zr(i,o,a,{r:v,g:S,b:A,a:$})}return i}function Hi(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=Bx(e,t,i);return Ix(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 Bx(e,t,r){let i=_(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=gt(y,0,e.width-1),b=Ye(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;zr(i,o,a,{r:gt(Math.round(f),0,255),g:gt(Math.round(h),0,255),b:gt(Math.round(d),0,255),a:gt(Math.round(m),0,255)})}return i}function Ix(e,t,r){let i=_(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=gt(y,0,e.height-1),b=Ye(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;zr(i,a,o,{r:gt(Math.round(f),0,255),g:gt(Math.round(h),0,255),b:gt(Math.round(d),0,255),a:gt(Math.round(m),0,255)})}return i}function gt(e,t,r){return Math.min(r,Math.max(t,e))}function Ae(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=_x(e,o,l,n);if(c&&u&&f)h=zx(h,u,f,a);return h}function zx(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 _x(e,t,r,i){switch(i){case"nearest":return Ux(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 Ux(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 ca(e,t){if(t<=0)return{...e,data:new Uint8ClampedArray(e.data)};let r=Vx(t),i=Math.floor(r.length/2),n=Gx(e,r,i);return Wx(n,r,i)}function Vx(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 Gx(e,t,r){let i=_(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 Wx(e,t,r){let i=_(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 qx(e,t){if(t<=0)return{...e,data:new Uint8ClampedArray(e.data)};let r=Math.floor(t),i=r*2+1,n=_(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=_(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=ca(e,r),a=_(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]=fn(e.data[o]+l*i),a.data[o+1]=fn(e.data[o+1]+c*i),a.data[o+2]=fn(e.data[o+2]+u*i),a.data[o+3]=e.data[o+3]}return a}function Kx(e,t=1){let r=1+4*t,i=-t,n=_(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]=fn(g)}n.data[o+3]=e.data[o+3]}return n}function fn(e){return Math.min(255,Math.max(0,Math.round(e)))}function zn(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=_(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]=hn(c/r+i),a.data[h+1]=hn(u/r+i),a.data[h+2]=hn(f/r+i),a.data[h+3]=e.data[(o*e.width+l)*4+3]}return a}function Yx(e){let t=[[-1,0,1],[-2,0,2],[-1,0,1]],r=[[-1,-2,-1],[0,0,0],[1,2,1]],i=zn(e,t,1,0),n=zn(e,r,1,0),s=_(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]=hn(Math.sqrt(l*l+c*c))}s.data[a+3]=e.data[a+3]}return s}function Hx(e,t=1){let r=[[-2*t,-t,0],[-t,1,t],[0,t,2*t]];return zn(e,r,1,128)}var Jx={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 hn(e){return Math.min(255,Math.max(0,Math.round(e)))}function Rd(e){let t=_(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 Zx(e,t=128,r={}){let{grayscale:i=!0}=r,n=_(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=_(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 Qx(e){let t=_(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 Xx(e,t=1){let r=_(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 e$(e,t=1){let r=_(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 t$(e,t=1){let r=_(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 r$(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=_(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 i$(e,t,r=0.5){let i=_(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 dn(e){if(e=e/255,e<=0.04045)return e/12.92;return((e+0.055)/1.055)**2.4}function mn(e){if(e<=0.0031308)return Math.round(e*12.92*255);return Math.round((1.055*e**0.4166666666666667-0.055)*255)}function n$(e,t){if(e.colorSpace===t)return{...e,data:new Uint8ClampedArray(e.data)};let r=_(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(dn(e.data[i])*255),r.data[i+1]=Math.round(dn(e.data[i+1])*255),r.data[i+2]=Math.round(dn(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]=mn(e.data[i]/255),r.data[i+1]=mn(e.data[i+1]/255),r.data[i+2]=mn(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 Pr(e,t,r={}){let{blend:i="normal",opacity:n=1,left:s=0,top:a=0,tile:o=!1}=r,l=_(e.width,e.height,{colorSpace:e.colorSpace,hasAlpha:e.hasAlpha,bitDepth:e.bitDepth});l.data.set(e.data);let c=s$(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,A=t.data[p+2]/255,$=t.data[p+3]/255*n,P=c(y,v),O=c(g,S),x=c(w,A),C=$+b*(1-$);if(C>0){let k=(v*$+y*b*(1-$))/C,E=(S*$+g*b*(1-$))/C,N=(A*$+w*b*(1-$))/C,M=y+(P-y)*$,F=g+(O-g)*$,G=w+(x-w)*$;if(i==="normal"||i==="source-over")l.data[m]=Math.round(k*255),l.data[m+1]=Math.round(E*255),l.data[m+2]=Math.round(N*255);else l.data[m]=Math.round(M*255),l.data[m+1]=Math.round(F*255),l.data[m+2]=Math.round(G*255);l.data[m+3]=Math.round(C*255)}}return l}function a$(e,t){let r=e;for(let i of t)r=Pr(r,i.input,i.options);return r}function s$(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 o$(e,t,r){return _(e,t,{colorSpace:"srgb",hasAlpha:!0,bitDepth:8,fill:r})}function l$(e,t,r,i,n="horizontal"){let s=_(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 c$=new Set([".svg"]),u$=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=c$.has(r),n=u$.has(r);if(!i&&!n)throw Error(`Unsupported file extension: ${r}`);return W("process",`Processing ${i?"SVG":"image"}: ${t}`),i?to(e):eo(e)}return e.isSvg??!1?to(e):eo(e)}async function f$(e,t){W("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 W("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 W("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 q=0,z=0;q<e*t;q++,z+=4){let ae=r[z+3]/255;l+=ae/255*r[z],c+=ae/255*r[z+1],u+=ae/255*r[z+2],f+=ae}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 q=0,z=0;q<e*t;q++,z+=4){let ae=r[z+3]/255,$e=l*(1-ae)+ae/255*r[z],D=c*(1-ae)+ae/255*r[z+1],se=u*(1-ae)+ae/255*r[z+2];y[q]=($e+D+se)/3,g[q]=($e+D)/2-se,w[q]=$e-D,b[q]=ae}let v=(q,z,ae)=>{let $e=0,D=[],se=0,ke=[];for(let pe=0;pe<ae;pe++)for(let ht=0;ht*ae<z*(ae-pe);ht++){let Kt=0;for(let Ce=0;Ce<e;Ce++)ke[Ce]=a(i/e*ht*(Ce+0.5));for(let Ce=0;Ce<t;Ce++)for(let Yt=0,um=a(i/t*pe*(Ce+0.5));Yt<e;Yt++)Kt+=q[Yt+Ce*e]*ke[Yt]*um;if(Kt/=e*t,ht||pe)D.push(Kt),se=s(se,o(Kt));else $e=Kt}if(se)for(let pe=0;pe<D.length;pe++)D[pe]=0.5+0.5/se*D[pe];return[$e,D,se]},[S,A,$]=v(y,s(3,m),s(3,p)),[P,O,x]=v(g,3,3),[C,k,E]=v(w,3,3),[N,M,F]=h?v(b,5,5):[0,[],0],G=e>t,Q=n(63*S)|n(31.5+31.5*P)<<6|n(31.5+31.5*C)<<12|n(31*$)<<18|Number(h)<<23,X=(G?p:m)|n(63*x)<<3|n(63*E)<<9|Number(G)<<15,fe=[Q&255,Q>>8&255,Q>>16,X&255,X>>8],K=h?6:5,oe=0;if(h)fe.push(n(15*N)|n(15*F)<<4);for(let q of h?[A,O,k,M]:[A,O,k])for(let z of q)fe[K+(oe>>1)]|=n(15*z)<<((oe++&1)<<2);return new Uint8Array(fe)}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,A=(G,Q,X)=>{let fe=[];for(let K=0;K<Q;K++)for(let oe=K?0:1;oe*Q<G*(Q-K);oe++)fe.push(((e[v+(S>>1)]>>((S++&1)<<2)&15)/7.5-1)*X);return fe},$=A(y,g,f),P=A(3,3,d*1.25),O=A(3,3,m*1.25),x=h?A(5,5,b):!1,C=Ud(e),k=s(C>1?32:32*C),E=s(C>1?32/C:32),N=new Uint8Array(k*E*4),M=[],F=[];for(let G=0,Q=0;G<E;G++)for(let X=0;X<k;X++,Q+=4){let fe=l,K=c,oe=u,q=w;for(let D=0,se=i(y,h?5:3);D<se;D++)M[D]=n(t/k*(X+0.5)*D);for(let D=0,se=i(g,h?5:3);D<se;D++)F[D]=n(t/E*(G+0.5)*D);for(let D=0,se=0;D<g;D++)for(let ke=D?0:1,pe=F[D]*2;ke*g<y*(g-D);ke++,se++)fe+=$[se]*M[ke]*pe;for(let D=0,se=0;D<3;D++)for(let ke=D?0:1,pe=F[D]*2;ke<3-D;ke++,se++){let ht=M[ke]*pe;K+=P[se]*ht,oe+=O[se]*ht}if(h&&x)for(let D=0,se=0;D<5;D++)for(let ke=D?0:1,pe=F[D]*2;ke<5-D;ke++,se++)q+=x[se]*M[ke]*pe;let z=fe-0.6666666666666666*K,ae=(3*fe-z+oe)/2,$e=ae-oe;N[Q]=i(0,255*r(1,ae)),N[Q+1]=i(0,255*r(1,$e)),N[Q+2]=i(0,255*r(1,z)),N[Q+3]=i(0,255*r(1,q))}return{w:k,h:E,rgba:N}}function h$(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 Oe(t),i=Ae(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(Ir(e,"AppIcon.appiconset"),{recursive:!0})}async function Hd(e,t=T.appIcon?.outputDir||"assets/app-icons"){let r=Kd(t,"AppIcon.appiconset");await Yd(t),W("app-icon",`Generating macOS app icons from ${e} to ${r}`);let i=[],n=new Uint8Array(await qd(e)),s=await Oe(n);for(let{size:l,scale:c,filename:u}of no){let f=l*c,h=Ir(r,u),d=Ae(s,{width:f,height:f}),m=await et(d,"png");await di(h,m),i.push({size:f,path:h,filename:u})}let a=Zd("macos",no),o=Ir(r,"Contents.json");return await di(o,a),await Qd(t,"macos"),{platform:"macos",sizes:i,contentsJson:a}}async function Jd(e,t=T.appIcon?.outputDir||"assets/app-icons"){let r=Kd(t,"AppIcon.appiconset");await Yd(t),W("app-icon",`Generating iOS app icons from ${e} to ${r}`);let i=[],n=new Uint8Array(await qd(e)),s=await Oe(n);for(let{size:l,scale:c,filename:u}of ao){let f=Math.round(l*c),h=Ir(r,u),d=Ae(s,{width:f,height:f}),m=await et(d,"png");await di(h,m),i.push({size:f,path:h,filename:u})}let a=Zd("ios",ao),o=Ir(r,"Contents.json");return await di(o,a),await Qd(t,"ios"),{platform:"ios",sizes:i,contentsJson:a}}async function d$(e,t={}){let r=t.platform||T.appIcon?.platform||"all",i=t.outputDir||T.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=Ir(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 di(i,n)}async function p$(e,t,r={}){let{padding:i=2,maxWidth:n=2048,prefix:s="sprite",format:a="png",quality:o=90,scale:l=1}=r;W("sprite",`Generating sprite sheet from ${e.length} images`);let c=await Promise.all(e.map(async({path:P,name:O})=>{let x=new Uint8Array(await m$(P)),C=await Oe(x),k=C;if(l!==1){let E=Math.ceil(C.width*l),N=Math.ceil(C.height*l);k=Ae(C,{width:E,height:N})}return{name:O,imageData:k,width:k.width,height:k.height}})),u=0,f=0,h=0,d=0,m=0,p=c.map((P)=>{if(u+P.width+i>n)u=0,f+=h+i,h=0;let O={x:u,y:f,width:P.width,height:P.height};return u+=P.width+i,h=Math.max(h,P.height),d=Math.max(d,u),m=Math.max(m,f+P.height),O}),y=_(d,m,{fill:{r:0,g:0,b:0,a:0}});for(let P=0;P<c.length;P++){let O=c[P],x=p[P];y=Pr(y,O.imageData,{left:x.x,top:x.y,blend:"normal"})}let g=ps(t,`${s}-sprite.${a}`),w=await et(y,a,{quality:o});await ms(g,w);let b=p.map((P,O)=>({name:c[O].name,...P})),v=g$(s,b,a),S=ps(t,`${s}-sprite.css`);await ms(S,v);let A=y$(s,b,a),$=ps(t,`${s}-sprite.scss`);return await ms($,A),{imagePath:g,cssPath:S,width:d,height:m,sprites:b}}function g$(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 y$(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 w$,readFile as b$,writeFile as ua}from"fs/promises";import{join as fa}from"path";import{readFile as S$,writeFile as x$}from"fs/promises";import{join as $$}from"path";import{readFile as tm,writeFile as rm}from"fs/promises";import{join as im}from"path";import{mkdir as C$,writeFile as A$}from"fs/promises";import{readFile as E$}from"fs/promises";import{join as k$}from"path";var v$=[16,32,48,96,144,180,192,384,512],Dl=[16,32,48];async function Sk(e,t,r={}){W("favicon",`Generating favicons from ${e} \u2192 ${t}`),await w$(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([...v$,...Dl])).sort((f,h)=>f-h),n=new Uint8Array(await b$(e)),s=await Oe(n),a=[],o=new Map;for(let f of i){let h=Ae(s,{width:f,height:f}),d=await et(h,"png");o.set(f,d);let m=fa(t,`favicon-${f}x${f}.png`);await ua(m,d),a.push({size:f,path:m,type:"png"})}let l=o.get(180);if(l){let f=fa(t,"apple-touch-icon.png");await ua(f,l),a.push({size:180,path:f,type:"png"})}let c=em(Dl.map((f)=>({size:f,png:o.get(f)}))),u=fa(t,"favicon.ico");if(await ua(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=fa(t,"site.webmanifest");await ua(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 xk={encodeIco:em};async function Ak(e,t,r={}){W("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 S$(e)),a=await Oe(s);for(let[o,l]of Object.entries(i)){let c=$$(t,`${o}.png`),u=Ae(a,{width:l.width,height:l.height,fit:"cover"}),f=await et(u,"png",{quality:r.quality||80});await x$(c,f),n[o]=c}return n}async function Mk(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");W("responsive",`Generating responsive images for ${t}`);let l=new Uint8Array(await tm(t)),c=await Oe(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=Ae(c,{width:y}),S=await et(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 Tk(e){let{input:t,name:r,sizes:i,outputDir:n,format:s="png",quality:a=80}=e;W("imageset",`Generating image set for ${t}`);let o=new Uint8Array(await tm(t)),l=await Oe(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=Ae(l,{width:u.width,height:u.height,fit:u.height?"fill":"cover"}),m=await et(d,s,{quality:a});await rm(h,m),c.push({size:u,path:h})}return c}var Ok=32,Wr=[0.025,0.1,0.2,0.35],Gr=[new Float64Array(1923),new Float64Array(1923),new Float64Array(1923),new Float64Array(1923)],Il=Array.from({length:4}),xi=[0,0,0,0],zl=[0,0,0,0],nm=new Float64Array(1024),ma=new Float64Array(256),_l=new Float64Array(1025);function M$(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=Wr[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;Gr[e][a]=o}let i=0;for(let a=0;a<32;a++){if(Gr[e][a*a]<0.0000001)break;i=a}xi[e]=i;let n=new Float64Array(i+1);for(let a=0;a<=i;a++)n[a]=Gr[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;ma[e]=t<=0.04045?t/12.92:((t+0.055)/1.055)**2.4}for(let e=0;e<1024;e++)nm[e]=M$(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 pa(e){let t=0,r=Math.abs(Wr[0]-e);for(let i=1;i<4;i++){let n=Math.abs(Wr[i]-e);if(n<r)r=n,t=i}return t}function T$(e,t,r){let i=U$(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=z$(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=j$(u,f,h,32,32,d,6);if(m.length>0)m=R$(m,i,n,s,a,32,32);return B$(l,m)}function N$(e){return T$(e.data,e.width,e.height)}function P$(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}=I$(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)_$(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}=G$(o[f],o[f+1],o[f+2]),p=(c*s+u)*4;l[p]=he(Math.round(h*255+0.5),0,255),l[p+1]=he(Math.round(d*255+0.5),0,255),l[p+2]=he(Math.round(m*255+0.5),0,255),l[p+3]=255}return{width:s,height:a,rgba:l}}var jt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function F$(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+=jt[i>>2],t+=jt[(i&3)<<4|n>>4],t+=r+1<e.length?jt[(n&15)<<2|s>>6]:"=",t+=r+2<e.length?jt[s&63]:"="}return t}function Rk(e){let t=e.replace(/=+$/,""),r=[],i=0,n=0;for(let s of t){let a=jt.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 O$(e){let{width:t,height:r,rgba:i}=P$(e);return`data:image/bmp;base64,${W$(t,r,i)}`}function R$(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)=>L$(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 D$(s,a,r)}function D$(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 L$(e,t,r){let i=new Float64Array(t*r),n=pa(e.sigma),s=xi[n],a=Math.floor(e.x*t),o=Math.floor(e.y*r),l=he(o-s,0,r-1),c=he(o+s,0,r-1),u=he(a-s,0,t-1),f=he(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]=Gr[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 j$(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 C=Il[x],k=xi[x],E=1/zl[x];for(let N=0;N<n;N++){let M=N*i;for(let F=0;F<i;F++){let G=C[0]*e[M+F],Q=C[0]*t[M+F],X=C[0]*r[M+F];for(let fe=1;fe<=k;fe++){let K=C[fe],oe=F-fe;if(oe>=0){if(G+=K*e[M+oe],l)Q+=K*t[M+oe],X+=K*r[M+oe]}let q=F+fe;if(q<i){if(G+=K*e[M+q],l)Q+=K*t[M+q],X+=K*r[M+q]}}if(s.tmpL[M+F]=G,l)s.tmpA[M+F]=Q,s.tmpB[M+F]=X}}for(let N=0;N<i;N++)for(let M=0;M<n;M++){let F=C[0]*s.tmpL[M*i+N],G=C[0]*s.tmpA[M*i+N],Q=C[0]*s.tmpB[M*i+N];for(let K=1;K<=k;K++){let oe=C[K],q=M-K;if(q>=0){if(F+=oe*s.tmpL[q*i+N],l)G+=oe*s.tmpA[q*i+N],Q+=oe*s.tmpB[q*i+N]}let z=M+K;if(z<n){if(F+=oe*s.tmpL[z*i+N],l)G+=oe*s.tmpA[z*i+N],Q+=oe*s.tmpB[z*i+N]}}let X=M*i+N,fe=l?(F*F+G*G+Q*Q)*E:F*F*E;if(fe>s.scoreMap[X])s.scoreMap[X]=fe,s.sigmaMap[X]=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=xi[d],y=zl[d],g=0,w=0,b=0;for(let x=-p;x<=p;x++){let C=h+x;if(C<0||C>=n)continue;let k=m[Math.abs(x)];for(let E=-p;E<=p;E++){let N=f+E;if(N<0||N>=i)continue;let M=k*m[Math.abs(E)],F=C*i+N;g+=M*e[F],w+=M*t[F],b+=M*r[F]}}let v=1/y,S={x:f/i,y:h/n,sigma:Wr[d],l:g*v,a:w*v,b:b*v,isLepton:!l};o.push(S);let A=he(h-p,0,n-1),$=he(h+p,0,n-1),P=he(f-p,0,i-1),O=he(f+p,0,i-1);for(let x=A;x<=$;x++){let C=x-h,k=x*i;for(let E=P;E<=O;E++){let N=E-f,M=N*N+C*C;if(M>=1923)continue;let F=Gr[d][M];if(F===0)continue;let G=k+E;e[G]-=S.l*F,t[G]-=S.a*F,r[G]-=S.b*F}}}return o}function B$(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(he(Math.floor(n.x*15+0.5),0,15),4),r.write(he(Math.floor(n.y*15+0.5),0,15),4),r.write(pa(n.sigma),2),r.write(ha(n.l,-0.8,0.8,4),4),r.write(ha(n.a,-0.4,0.4,4),4),r.write(ha(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(he(Math.floor(n.x*15+0.5),0,15),4),r.write(he(Math.floor(n.y*15+0.5),0,15),4),r.write(pa(n.sigma),2),r.write(ha(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 I$(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:Wr[c],l:da(u,-0.8,0.8,4),a:da(f,-0.4,0.4,4),b:da(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:Wr[c],l:da(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 z$(e,t,r){let i=he(Math.floor(e*63.5),0,63),n=he(Math.floor((t+0.2)/0.4*31.5),0,31),s=he(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 ha(e,t,r,i){let n=(1<<i)-1;return he(Math.floor((e-t)/(r-t)*n+0.5),0,n)}function da(e,t,r,i){let n=(1<<i)-1;return e/n*(r-t)+t}function _$(e,t,r,i){let n=pa(t.sigma),s=xi[n],a=Math.floor(t.x*r),o=Math.floor(t.y*i),l=he(o-s,0,i-1),c=he(o+s,0,i-1),u=he(a-s,0,r-1),f=he(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=Gr[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 U$(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=ma[e[u]],h=ma[e[u+1]],d=ma[e[u+2]],{l:m,a:p,b:y}=V$(f,h,d),g=(a*i+l)*3;s[g]=m,s[g+1]=p,s[g+2]=y}}return s}function V$(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 G$(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 W$(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+=jt[u>>2],l+=jt[(u&3)<<4|f>>4],l+=c+1<a.length?jt[(f&15)<<2|h>>6]:"=",l+=c+2<a.length?jt[h&63]:"="}return l}function he(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 q$={avif:"avif",webp:"webp",jpeg:"jpg",png:"png"};async function K$(e,t,r){try{let i=await et(e,t,{quality:r});if(!i||i.length===0)return null;let n=await Oe(i);if(n.width!==e.width||n.height!==e.height)return null;return{bytes:i,psnr:cm(e.data,n.data)}}catch(i){return W("picture-set",`${t} skipped: ${i.message}`),null}}async function Dk(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 C$(r,{recursive:!0});let u=typeof t==="string"?await Oe(new Uint8Array(await E$(t))):await Oe(t),f=N$(u),h=F$(f),d=O$(f),m=[];for(let{label:p,width:y}of n){let g=Math.min(y,u.width),w=g===u.width?u:Ae(u,{width:g}),b=null;for(let S of s){let A=await K$(w,S,a);if(!A||A.psnr<o)continue;if(!b||A.bytes.length<b.bytes.length)b={format:S,...A}}if(!b){let S=await et(w,l,{quality:c}),A=await Oe(S).catch(()=>null);b={format:l,bytes:S,psnr:A?cm(w.data,A.data):0}}let v=k$(r,`${i}-${p}.${q$[b.format]??b.format}`);await A$(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{_ as us,fm as vs,Ye as ws,zr as xs,nf as ys,ir as zs,_r as As,so as Bs,pn as Cs,oo as Ds,gn as Es,Qr as Fs,lo as Gs,co as Hs,hm as Is,dm as Js,mm as Ks,af as Ls,sf as Ms,Oe as Ns,et as Os,lf as Ps,cf as Qs,Pm as Rs,T as Ss,Md as Ts,Ex as Us,kx as Vs,Mx as Ws,W as Xs,Tx as Ys,un as Zs,Nx as _s,eo as $s,to as at,Td as bt,Fx as ct,Ox as dt,Rx as et,Dx as ft,Lx as gt,jx as ht,Nd as it,Pd as jt,ro as kt,Ae as lt,ca as mt,qx as nt,Od as ot,Kx as pt,zn as qt,Yx as rt,Hx as st,Jx as tt,Rd as ut,Zx as vt,Dd as wt,Qx as xt,Xx as yt,e$ as zt,t$ as At,r$ as Bt,i$ as Ct,Ld as Dt,jd as Et,Bd as Ft,dn as Gt,mn as Ht,n$ as It,Pr as Jt,a$ as Kt,o$ as Lt,l$ as Mt,Id as Nt,f$ as Ot,zd as Pt,_d as Qt,h$ as Rt,Ud as St,Vd as Tt,Gd as Ut,Wd as Vt,Hd as Wt,Jd as Xt,d$ as Yt,p$ as Zt,Sk as _t,xk as $t,Ak as au,Mk as bu,Tk as cu,Ok as du,T$ as eu,N$ as fu,P$ as gu,F$ as hu,Rk as iu,O$ as ju,Dk as ku};