@solarpunkltd/swarm-chat-js 6.2.4 → 6.2.6

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.
package/dist/index.js CHANGED
@@ -7,5 +7,5 @@
7
7
  `],t.start||0):e.indexOf(t.opening,t.start||0);for(;;){if(s===-1)return n;const o=rs(e,{...t,start:s});if(!o)return n;n.push(o),s=t.wordBoundary?$e(e,[`${t.opening} `,`${t.opening}
8
8
  `],s+o.length):e.indexOf(t.opening,s+o.length)}}function wo(e,t,n){let s=0;for(;;){const o=a.Strings.extractBlock(e,{...n,start:s});if(!o)return e;const d=t(o);s=e.indexOf(o,s)+d.length,e=e.replace(o,d)}}function bo(e,t){const n=[];let s=0;for(;s<e.length;){const o=e.indexOf(t,s);if(o===-1){n.push({string:e.slice(s),symbol:null});break}const d=e.indexOf(t,o+t.length);if(o>s&&d!==-1&&n.push({string:e.slice(s,o),symbol:null}),d===-1){n.push({string:e.slice(s),symbol:null});break}n.push({string:e.slice(o+t.length,d),symbol:t}),s=d+t.length}return n}function _o(e){const t=[];let n=0;for(;n<e.length;){const s=yo(e,n);if(s===-1){t.push({string:e.slice(n),symbol:null});break}const o=go(e,s+1);if(o===-1){t.push({string:e.slice(n,s),symbol:null}),t.push({string:e.slice(s+1),symbol:"#"});break}s>n&&t.push({string:e.slice(n,s),symbol:null}),t.push({string:e.slice(s+1,o),symbol:"#"}),n=o}return t}function xo(e){const t=[];let n=0;for(;n<e.length;){const s=$e(e,["http://","https://"],n);if(s===-1){t.push({string:e.slice(n),symbol:null});break}const o=$e(e,[" ",`
9
9
  `],s);if(o===-1){s>n&&t.push({string:e.slice(n,s),symbol:null}),t.push({string:e.slice(s),symbol:"http"});break}s>n&&t.push({string:e.slice(n,s),symbol:null}),t.push({string:e.slice(s,o),symbol:"http"}),n=o}return t}const ns="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ss="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function ko(e){return is(e,ns)}function Eo(e){return as(e,ns)}function So(e){return is(e,ss)}function To(e){return as(e,ss)}function is(e,t){const n="=",s=t.length;let o=0,d=0;const p=[];for(let v=0;v<e.length;v++){const m=e[v];if(m===n)break;const k=t.indexOf(m);if(k===-1)throw new Error(`Invalid character: ${m}`);d=d<<Math.log2(s)|k,o+=Math.log2(s),o>=8&&(o-=8,p.push(d>>o&255))}return new Uint8Array(p)}function as(e,t){const n=t.length;let s=0,o=0,d="";for(let p=0;p<e.length;p++)for(o=o<<8|e[p],s+=8;s>=Math.log2(n);)s-=Math.log2(n),d+=t[o>>s&n-1];return s>0&&(d+=t[o<<Math.log2(n)-s&n-1]),d.length%4!==0&&(d+="=".repeat(4-d.length%4)),d}function Ao(e){e.startsWith("0x")&&(e=e.slice(2));const t=e.length/2,n=new Uint8Array(t);for(let s=0;s<t;s++){const o=parseInt(e.slice(s*2,s*2+2),16);n[s]=o}return n}function Oo(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function Io(e,t){const n=e.split("/").filter(d=>d),s=t.split("/").filter(d=>d);if(n.length!==s.length)return null;const o={};for(let d=0;d<n.length;d++){const p=n[d];if(p.startsWith(":"))o[p.slice(1)]=s[d];else if(p!==s[d])return null}return o}function ar(e,t,n){const s=[];for(const o of n)o!==t&&s.push(e.replace(t,o));return s}function Mo(e,t,n,s=Math.random){const o=a.Arrays.shuffle(t.map(p=>({variants:a.Arrays.shuffle(p.variants.map(v=>v),s),avoid:p.avoid})),s),d=[];for(const p of o){const v=p.variants.filter(k=>k!==p.avoid),m=v.find(k=>e.includes(k));if(m&&(At(d,ar(e,m,v)),d.length>=n))break}if(d.length<n)for(const p of o){const v=p.variants.find(m=>e.includes(m));if(v&&(At(d,ar(e,v,p.variants)),d.length>=n))break}return d.slice(0,n)}function $o(e,t,n,s=!1){const o=new RegExp(s?`(?<=\\s|^)${t}(?=\\s|$)`:`\\b${t}\\b`,"g");return e.replace(o,n)}function Ro(e,t){const n=/\b[A-Z][a-zA-Z0-9]*\b/g;return e.replace(n,s=>s.toUpperCase()===s?s:t(s))}function Co(e){return e.replace(/<[^>]*>/g,"")}function os(e){const t=e.lastIndexOf(" ");if(t===-1)return{line:e,rest:""};const n=e.slice(0,t),s=e.slice(t+1);return{line:n,rest:s}}function No(e,t={}){return[...e].reduce((n,s)=>n+(t[s]||1),0)}function jo(e,t,n={}){const s=[];let o="",d=0;for(let p=0;p<e.length;p++){const v=e[p],m=n[v]||1;if(o+=v,d+=m,d>t){const{line:k,rest:$}=os(o);s.push(k),o=$,d=$.split("").map(U=>n[U]||1).reduce((U,je)=>U+je,0)}}return o&&s.push(o),s}function Do(e,t){const n=[];for(let s=0;s<=e.length;s++)n[s]=[s];for(let s=0;s<=t.length;s++)n[0][s]=s;for(let s=1;s<=e.length;s++)for(let o=1;o<=t.length;o++){const d=e[s-1]===t[o-1]?0:1;n[s][o]=Math.min(n[s-1][o]+1,n[s][o-1]+1,n[s-1][o-1]+d)}return n[e.length][t.length]}function or(e,t){return new RegExp(`\\b${t}\\b`).test(e)}function Po(e,t,n){return n==="any"?t.some(s=>or(e,s)):t.every(s=>or(e,s))}function Uo(e){const t={},n=e.match(/([a-z\-]+)="([^"]+)"/g);if(n)for(const s of n){const[o,d]=nr(s,"=");t[o]=d.slice(1,d.length-1)}return t}function Mt(e,t,n=[]){let s="";for(;t<e.length&&(Ge(e[t])||n.includes(e[t]));)s+=e[t++];return s}function Zo(e,t,n="$",s=":"){for(const o in t)e=cs(e,o,t[o],n,s);return e=us(e),e}function cs(e,t,n,s="$",o=":"){if(n==="")return e;let d=e.indexOf(`${s}${t}`);for(;d!==-1;){if(e[d+t.length+1]===o)if(e[d+t.length+2]===o)e=e.replace(`${s}${t}${o}${o}`,n);else{const p=Mt(e,d+t.length+2,["_"]);e=e.replace(`${s}${t}${o}${p}`,n)}else e=e.replace(`${s}${t}`,n);d=e.indexOf(`${s}${t}`,d+n.length)}return e}function us(e,t="$",n=":"){let s=e.indexOf(t);for(;s!==-1;){const o=Mt(e,s+1);if(e[s+o.length+1]===n)if(e[s+o.length+2]===n)e=e.replace(`${t}${o}${n}${n}`,"");else{const d=Mt(e,s+o.length+2);e=e.replace(`${t}${o}${n}${d}`,d)}s=e.indexOf(t,s+1)}return e}function Bo(e,t){let n=e.indexOf("](");for(;n!==-1;){const s=es(e,"[",n),o=e.indexOf(")",n);if(s!==-1&&o!==-1){const[d,p]=e.slice(s+1,o).split("]("),v=t(d,p);e=e.slice(0,s)+v+e.slice(o+1)}n=e.indexOf("](",n+1)}return e}function ls(e,t=!0){const n=Object.entries(e).filter(([s,o])=>o!=null).map(([s,o])=>`${s}=${encodeURIComponent(o)}`).join("&");return n?(t?"?":"")+n:""}function Lo(e){const t={},n=e.split("&");for(const s of n){const[o,d]=s.split("=");o&&d&&(t[o]=decodeURIComponent(d))}return t}function zo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Vo(e,t){let n=null,s=-1/0;for(const[o,d]of Object.entries(e)){const p=t(d);p>s&&(s=p,n=o)}return n?[n,e[n]]:null}function Fo(e,t,n,s){const o=e.find(p=>p[t]===n),d=e.find(p=>p[t]===n+s);o&&d?(o[t]=n+s,d[t]=n):o&&(o[t]=n+s),e.sort((p,v)=>St(p[t])-St(v[t])),e.forEach((p,v)=>p[t]=v+1)}function Wo(e){const t=Object.keys(e);if(t.length===1)return e[t[0]];throw new Error("Expected object to have a single key")}function Ho(e,t=":"){return Object.fromEntries(e.map(n=>nr(n,t)).map(n=>n[0]&&n[1]?[qe(n[0]),qe(n[1])]:null).filter(n=>n))}function qo(e,t,n){return ps(e,t)+ls(n||{})}function Go(e,t=",",n='"'){const s=[];let o="",d=!1;const p=e.split("");for(const v of p)v===t&&!d?(s.push(o),o=""):v===n&&(!o&&!d||d)?d=!d:o+=v;return s.push(o),s}function Ko(e){return`[${Math.floor(e.progress*100)}%] ${$t(e.deltaMs)} out of ${$t(e.totalTimeMs)} (${$t(e.remainingTimeMs)} left) [${Math.round(e.baseTimeMs)} ms each]`}async function Jo(e,t,n){for(let s=0;s<n;s++){try{if(await e())return!0}catch{}s<n-1&&await l(t)}return!1}function Yo(e,t){const n=[];for(let s=e.length-1;s>=0;s--)t(e[s])&&n.push(e.splice(s,1)[0]);return n}function Qo(e){return JSON.parse(JSON.stringify(e))}function Xo(e){return Math.ceil((e||Date.now())/1e3)}function ec(e){return(e||new Date).toISOString().slice(0,10)}function tc(e){return(e||new Date).toISOString().slice(0,19).replace(/T|:/g,"-")}function rc(e){const t=new Date(e);return new Date(t.getTime()-t.getTimezoneOffset()*6e4)}function nc(e){return new Date(e)}function Y(e){return String(Math.floor(e)).padStart(2,"0")}function sc(e){let[t,n]=e.split(":");le(parseInt(t,10))||(t="0"),le(parseInt(n,10))||(n="0");let s=fr(Xt(t),0,23),o=fr(Xt(n),0,59);return`${Y(s)}:${Y(o)}`}function $t(e){const t=Math.floor(e/36e5);e=e%36e5;const n=Math.floor(e/6e4);e=e%6e4;const s=Math.floor(e/1e3);return t?`${Y(t)}:${Y(n)}:${Y(s)}`:`${Y(n)}:${Y(s)}`}function _e(e){return Math.floor((Me(e)?e.getTime():e)/864e5)}const ic={today:(e,t)=>Y(e)+":"+Y(t),yesterday:()=>"Yesterday",monday:()=>"Mon",tuesday:()=>"Tue",wednesday:()=>"Wed",thursday:()=>"Thu",friday:()=>"Fri",saturday:()=>"Sat",sunday:()=>"Sun",weeks:e=>`${e}w`};function ac(e,t){const n=new Date((t==null?void 0:t.now)||Date.now()),s=(t==null?void 0:t.labels)||ic,o=Me(e)?e:new Date(e);if(_e(n)===_e(o))return s.today(o.getUTCHours(),o.getUTCMinutes(),o.getUTCHours()>12);if(_e(n)-_e(o)===1)return s.yesterday();const d=ur(o);return _e(n)-_e(o)<7?s[d.day]():s.weeks(Math.round((n.getTime()-o.getTime())/6048e5))}const ds={now:()=>"A few seconds",seconds:e=>`${e} seconds`,minutes:e=>`${e} minutes`,hours:e=>`${e} hours`,days:e=>`${e} days`,weeks:e=>`${e} weeks`};function fs(e,t){const n=(t==null?void 0:t.now)??Date.now(),s=(t==null?void 0:t.labels)||ds,o=a.Types.isDate(e)?e.getTime():e;let d=(n-o)/1e3;return d<10?s.now():d<120?s.seconds(Math.floor(d)):(d/=60,d<120?s.minutes(Math.floor(d)):(d/=60,d<48?s.hours(Math.floor(d)):(d/=24,d<14?s.days(Math.floor(d)):(d/=7,s.weeks(Math.floor(d))))))}function oc(e,t=ds){return fs(0,{now:e*1e3,labels:t})}function cc(e,t,n){const s=((n==null?void 0:n.now)??Date.now())-e,o=Math.floor(s/t),d=t/((n==null?void 0:n.precision)??1)-Math.ceil(s%t/((n==null?void 0:n.precision)??1));return{cycles:o,remaining:d}}const cr={};function uc(e,t){return!cr[e]||Date.now()>cr[e]?(cr[e]=Date.now()+t,!0):!1}const lc={s:1e3,m:6e4,h:36e5,d:864e5};function dc(e,t,n){return t=Me(t)?t.getTime():t,n=n?Me(n)?n.getTime():n:Date.now(),(n-t)/lc[e]}function fc(e,t,n,s){s||(s=Date.now());const o=t/n,d=s-e,p=d/t,v=p*n,m=v-d;return{deltaMs:d,progress:o,baseTimeMs:p,totalTimeMs:v,remainingTimeMs:m}}const hc={0:"sunday",1:"monday",2:"tuesday",3:"wednesday",4:"thursday",5:"friday",6:"saturday"};function hs(e){return{zeroBasedIndex:e,day:hc[e]}}function ur(e){return hs(e.getDay())}function pc(e){return ur(new Date(e))}function mc(e){return e*1e3}function gc(e){return e*6e4}function yc(e){return e*36e5}function vc(e){return e*864e5}const wc={ms:1,milli:1,millis:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:6e4,min:6e4,minute:6e4,minutes:6e4,h:36e5,hour:36e5,hours:36e5,d:864e5,day:864e5,days:864e5,w:6048e5,week:6048e5,weeks:6048e5,month:2592e6,months:2592e6,y:31536e6,year:31536e6,years:31536e6};function bc(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=wc[n];if(!s)throw Error(`Unknown unit: "${n}"`);return t*s}const _c={b:1,byte:1,bytes:1,kb:1024,kilobyte:1024,kilobytes:1024,mb:1024**2,megabyte:1024**2,megabytes:1024**2,gb:1024**3,gigabyte:1024**3,gigabytes:1024**3,tb:1024**4,terabyte:1024**4,terabytes:1024**4};function xc(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=_c[n];if(!s)throw Error(`Unknown unit: "${n}"`);return t*s}function kc(e){return e.replace(/ +/g," ").replace(/^ /gm,"")}const lr={};async function Ec(e,t,n){const s=Date.now(),o=lr[e];if(o&&o.validUntil>s)return o.value;const d=await n(),p=s+t;return lr[e]={value:d,validUntil:p},d}function Sc(e){delete lr[e]}function ps(...e){return e.filter(t=>t).join("/").replace(new RegExp("(?<!:)\\/+","g"),"/")}function Tc(e,t,n,s,o=!0){const d=e.indexOf(t),p=e.indexOf(n,d+t.length);if(d===-1||p===-1)throw Error("Start or end not found");return o?e.substring(0,d+t.length)+s+e.substring(p):e.substring(0,d)+s+e.substring(p+n.length)}function Ac(e){let t="p";e.startsWith("#")?(t="h1",e=e.slice(1).trim()):e.startsWith("-")&&(t="li",e=e.slice(1).trim());const n=e[0]===e[0].toUpperCase(),s=/[.?!]$/.test(e),o=/:$/.test(e);return{type:t,isCapitalized:n,hasPunctuation:s,endsWithColon:o}}function Oc(e,t="(",n=")"){let s=0,o=0;for(;o<e.length;)if(e.startsWith(t,o)?(s++,o+=t.length):e.startsWith(n,o)?(s--,o+=n.length):o++,s<0)return!1;return t===n?s%2===0:s===0}function Ic(e){e=e.normalize("NFD").replace(/[\u0300-\u036f]/g,"");let t=e.length;for(;e=e.replace(/(\w+)[\s,']+\w+/g,"$1"),e.length!==t;)t=e.length;return e=e.replaceAll(/[A-Z][a-zA-Z0-9]*/g,"A"),e=e.replaceAll(/[a-z][a-zA-Z0-9]*/g,"a"),e=e.replaceAll(/[\u4E00-\u9FA5]+/g,"Z"),e}function ms(e){const t=Object.keys(e).sort((s,o)=>s.localeCompare(o)),n={};for(const s of t)n[s]=xe(e[s]);return n}function gs(e){const t=[];return e.sort((n,s)=>JSON.stringify(xe(n)).localeCompare(JSON.stringify(xe(s)))).forEach(n=>t.push(xe(n))),t}function xe(e){return Array.isArray(e)?gs(e):ue(e)?ms(e):e}function ys(e,t){return JSON.stringify(xe(e))===JSON.stringify(xe(t))}function Mc(...e){for(let t=1;t<e.length;t++)if(!ys(e[t-1],e[t]))return!1;return!0}function $c(e){try{return JSON.parse(e)}catch{return null}}function Rc(){let e=0;return{next:()=>e++}}function Cc(e){let t=0;return{next:()=>e[t++%e.length]}}function Nc(e){let t;return n=>{const s=n===e&&t!==e;return t=n,s}}function jc(e,t,n,s,o){const d={};for(const p of Object.keys(t))d[p]=[];d[s]=[],o&&(e=e.sort(o));for(const p of e){const v=p[n],m=t[v]?v:s;d[m].length>=t[m]?d[s].push(p):d[m].push(p)}return d}function Dc(e,t){const n=Object.keys(e),s=Object.keys(t);return{uniqueToA:n.filter(o=>!s.includes(o)),uniqueToB:s.filter(o=>!n.includes(o))}}function vs(e){const t=Object.keys(e);return t[Math.floor(Math.random()*t.length)]}function Pc(e,t){const n=vs(e);return e[n]=t(e[n]),n}function Uc(e){return e=e.replace(/\r\n/g,`
10
- `),e=e.replace(/(\w+)\((.+)\)/g,(t,n,s)=>`${n}(${s.replaceAll(",","&comma;")})`),e=e.replace(/(,)(\s+})/g,"$2"),e=e.replace(/\.\.\..+?,/g,""),e=e.replace(/({\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/(,\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/:(.+)\?(.+):/g,(t,n,s)=>`: (${n.trim()} && ${s.trim()}) ||`),e=e.replace(/([a-zA-Z0-9]+)( ?: ?{)/g,'"$1"$2'),e=e.replace(/([a-zA-Z0-9]+) ?: ?(.+?)(,|\n|})/g,(t,n,s,o)=>`"${n}":"${s.trim()}"${o}`),e=e.replace(/("'|'")/g,'"'),e=e.replaceAll("&comma;",","),JSON.parse(e)}const de=[1e3,1e6,1e9,1e12,1e15,1e18,1e21,1e24,1e27,1e30,1e9,1e16,1e18,1e18,1e18,1e33],Zc=["thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion","gwei","bzz","btc","eth","dai","decillion"],ws=["K","M","B","T","Qa","Qi","Sx","Sp","O","N","gwei","bzz","eth","btc","dai","D"];function Bc(e,t,n){let s=e.length-t;if(s<=0)return"0."+"0".repeat(-s)+e+(n?" "+n:"");let o=e.substring(0,s),d=e.substring(s);return o===""&&(o="0"),o+"."+d+(n?" "+n:"")}function Lc(e,t){const n=(t==null?void 0:t.longForm)??!1,s=t!=null&&t.unit?` ${t.unit}`:"",o=n?Zc:ws,d=(t==null?void 0:t.precision)??1;if(e<de[0])return`${e}${s}`;for(let p=0;p<de.length-1;p++)if(e<de[p+1])return`${(e/de[p]).toFixed(d)}${n?" ":""}${o[p]}${s}`;return`${(e/de[de.length-1]).toFixed(d)}${n?" ":""}${o[de.length-1]}${s}`}function dr(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeNumber got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim(),s=ws.findIndex(o=>o.toLowerCase()===n.toLowerCase());return s===-1?t:t*de[s]}function fr(e,t,n){return e<t?t:e>n?n:e}function zc(e,t,n){const s=e+t;return s>n?n:s}function Vc(e,t,n){const s=e-t;return s<n?n:s}function Fc(e,t){return t(e),e}function Wc(e,t){e&&t(e)}function Hc(e,t){const n=Object.keys(t);for(const s of n)Array.isArray(t[s])&&Array.isArray(e[s])&&At(e[s],t[s])}function qc(e){return e.splice(0,e.length),e}function Gc(e){for(const t of Object.keys(e))(Rn(e[t])||Array.isArray(e[t])&&e[t].every(n=>n==null))&&delete e[t];return e}function Kc(e){for(const t of Object.entries(e))(t[1]===null||t[1]===void 0||W(t[1])&&Et(t[1]))&&delete e[t[0]];return e}function Jc(e,t){const n={};for(const[s,o]of Object.entries(e))t(s)&&(n[s]=o);return n}function Yc(e,t){const n={};for(const[s,o]of Object.entries(e))t(o)&&(n[s]=o);return n}function Qc(e,t){const n={};for(const s of Object.entries(e))n[s[0]]=t(s[1]);return n}function Xc(e,t){const n=[];let s=0;for(const o of e)n.push(t(o,s++));return n}async function eu(e,t){try{return await e()}catch{throw t}}function tu(e,t,n){n!=null&&(e[t]=n)}function ru(e,t,n,s){const o=ve(n,s);o!=null&&we(e,t,o)}function nu(e){const t={};for(const[n,s]of Object.entries(e))t[s]=n;return t}function su(e){const t=Object.keys(e),n=t.map(v=>e[v].length),s=n.reduce((v,m)=>v*=m);let o=1;const d=[1];for(let v=0;v<n.length-1;v++)o*=n[v],d.push(o);const p=[];for(let v=0;v<s;v++){const m={};for(let k=0;k<t.length;k++){const $=e[t[k]],U=Math.floor(v/d[k])%$.length;m[t[k]]=$[U]}p.push(m)}return p}function iu(e){return Object.values(e).filter(t=>t).length}function au(e,t,n){return e+(n?"["+t+"]":(e.length?".":"")+t)}function Rt(e,t,n,s,o){if(!ue(t))return t;for(const[d,p]of Object.entries(t)){const v=au(n,d,s);Array.isArray(p)?o?Rt(e,p,v,!0,o):e[v]=p.map(m=>Rt(Array.isArray(m)?[]:{},m,"",!1,o)):ue(p)?Rt(e,p,v,!1,o):e[v]=p}return e}function ou(e,t=!1,n){return Rt({},e,n||"",!1,t)}function bs(e){if(!ue(e))return e;const t=Array.isArray(e)?[]:{};for(const[n,s]of Object.entries(e))Array.isArray(s)?we(t,n,s.map(o=>bs(o))):we(t,n,s);return t}function cu(e,t,n){return t[e]?t[e]:n}function _s(e,t){const n={};for(const s of e){const o=t(s);n[o]=s}return n}function uu(e,t){const n={};for(const s of e){const o=t(s);n[o]||(n[o]=[]),n[o].push(s)}return n}function lu(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function xs(e,t){const n=Math.ceil(e.length/t),s=[];for(let o=0;o<e.length;o+=n)s.push(e.slice(o,o+n));return s}function ks(e,t){const n=[],s=Math.ceil(e.length/t);for(let o=0;o<s;o++)n.push(e.slice(o*t,o*t+t));return n}function du(e,t){const n=Math.ceil(e.length/t);return ks(e,n)}function fu(e,t){return Object.values(_s(e,t))}function hu(e,t,n,s,o){const d=t?e.map(t):e,p={};for(const m of d)p[m]=(p[m]||0)+1;const v=s?Es(p,o?(m,k)=>m[1]-k[1]:(m,k)=>k[1]-m[1]):p;return n?Object.keys(v):v}function Es(e,t){return Object.fromEntries(Object.entries(e).sort(t))}function pu(e){const t=[],n=Object.keys(e),s=e[n[0]].length;for(let o=0;o<s;o++){const d={};for(const p of n)d[p]=e[p][o];t.push(d)}return t}function mu(e,t,n=1){for(const s of e)s[t]+=n}function gu(e,t,n){for(const s of e)s[t]=n}function hr(e,t){const n=[];let s=[];return e.forEach((o,d)=>{(d===0||!t(o,e[d-1]))&&(s=[],n.push(s)),s.push(o)}),n}function yu(){return{map:new Map,keys:[]}}function vu(){return{map:new Map,keys:[]}}function Ss(e,t,n,s=100){if(e.map.has(t)){const o=e.keys.indexOf(t);e.keys.splice(o,1)}if(e.map.set(t,n),e.keys.push(t),e.keys.length>s){const o=e.keys.shift();o&&e.map.delete(o)}}function wu(e,t,n,s=100){if(e.map.has(t)){const o=e.keys.indexOf(t);e.keys.splice(o,1)}if(e.map.set(t,n),e.keys.unshift(t),e.keys.length>s){const o=e.keys.shift();o&&e.map.delete(o)}}function bu(e,t,n,s,o=100){Ss(e,t,{validUntil:Date.now()+s,data:n},o)}function _u(e,t){const n=e.map.get(t);return n&&n.validUntil>Date.now()?n.data:null}class fe{constructor(t){this.value=t}static of(t){return new fe(t)}static empty(){return new fe(null)}map(t){return new fe(this.value!==null&&this.value!==void 0?t(this.value):null)}mapAsync(t){return this.value!==null&&this.value!==void 0?t(this.value).then(n=>fe.of(n)):Promise.resolve(fe.empty())}ifPresent(t){return this.value!==null&&this.value!==void 0&&t(this.value),this}ifPresentAsync(t){return this.value!==null&&this.value!==void 0?t(this.value).then(()=>this):Promise.resolve(this)}ifAbsent(t){return(this.value===null||this.value===void 0)&&t(),this}ifAbsentAsync(t){return this.value===null||this.value===void 0?t().then(()=>this):Promise.resolve(this)}getOrFallback(t){return this.value??t()}getOrFallbackAsync(t){return this.value!==null&&this.value!==void 0?Promise.resolve(this.value):t()}getOrThrow(){if(this.value===null||this.value===void 0)throw Error("Optional.value is empty");return this.value}}a.Optional=fe;class xu{constructor(t){this.supplier=t,this.value=null}get(){return this.value||(this.value=this.supplier()),this.value}}a.Lazy=xu;class ku{constructor(t){this.supplier=t,this.value=null}async get(){return this.value||(this.value=await this.supplier()),this.value}}a.AsyncLazy=ku;function Eu(e){return()=>e.forEach(t=>t())}function Su(e,t){return e.reduce((n,s)=>t(n)>t(s)?n:s)}function Tu(e,t){const n=e.find(s=>s instanceof t);return fe.of(n)}function Au(e,t){return e.filter(n=>n instanceof t)}function Ou(e,t){const n=[],s=Math.max(e.length,t.length);for(let o=0;o<s;o++)e[o]&&n.push(e[o]),t[o]&&n.push(t[o]);return n}function Iu(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}class Mu{constructor(t){this.value=t,this.children=[]}}function $u(e,t,n,s,o=!1){const d=new Map,p=[];e.forEach(m=>{const k=new Mu(m);d.set(m[t],k)}),e.forEach(m=>{const k=d.get(m[t]);if(!k)return;const $=m[n];if($){const U=d.get($);U&&U.children.push(k)}else p.push(k)});const v=m=>{m.children.sort((k,$)=>{const U=k.value[s],je=$.value[s];return o?je-U:U-je}),m.children.forEach(v)};return p.forEach(v),p}function Ts(e,t){if(Math.log2(e.length)%1!==0)throw new Error("Array length must be a power of 2");let n=[...e];for(;n.length>1;){const s=[];for(let o=0;o<n.length;o+=2){const d=n[o+1];s.push(t(n[o],d))}n=s}return n[0]}function Re(...e){const t=e.reduce((o,d)=>o+d.length,0),n=new Uint8Array(t);let s=0;return e.forEach(o=>{n.set(o,s),s+=o.length}),n}function As(e){return e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}function Os(e){return e[0]===255&&e[1]===216}function Is(e){return e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function Ru(e){return As(e)||Os(e)||Is(e)}function Cu(e){return new Uint8Array([e])}function Nu(e){return e[0]}function ju(e,t){const n=new ArrayBuffer(2);return new DataView(n).setUint16(0,e,t==="LE"),new Uint8Array(n)}function Du(e,t){return new DataView(e.buffer).getUint16(e.byteOffset,t==="LE")}function Pu(e,t){const n=new ArrayBuffer(4);return new DataView(n).setUint32(0,e,t==="LE"),new Uint8Array(n)}function Uu(e,t){return new DataView(e.buffer).getUint32(e.byteOffset,t==="LE")}function pr(e,t){const n=new ArrayBuffer(8);return new DataView(n).setBigUint64(0,BigInt(e),t==="LE"),new Uint8Array(n)}function Zu(e,t){return new DataView(e.buffer).getBigUint64(e.byteOffset,t==="LE")}function Ce(e,t){const n=new Uint8Array(32);let s=e;if(t==="LE"){for(let o=0;o<32;o++)n[o]=Number(s&0xffn),s>>=8n;return n}for(let o=31;o>=0;o--)n[o]=Number(s&0xffn),s>>=8n;return n}function Ne(e,t){let n=0n;if(t==="LE"){for(let s=31;s>=0;s--)n=n<<8n|BigInt(e[s]);return n}for(let s=0;s<32;s++)n=n<<8n|BigInt(e[s]);return n}function Bu(e,t){const n=[];let s=0;for(const o of t)n.push(e.subarray(s,s+o)),s+=o;return n}function mr(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.subarray(s,s+t));return n}const Ms=[0,1,0,32898,2147483648,32906,2147483648,2147516416,0,32907,0,2147483649,2147483648,2147516545,2147483648,32777,0,138,0,136,0,2147516425,0,2147483658,0,2147516555,2147483648,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,0,32778,2147483648,2147483658,2147483648,2147516545,2147483648,32896,0,2147483649,2147483648,2147516424];function Lu(e){for(let t=0;t<24;t++){const n=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],d=e[3]^e[13]^e[23]^e[33]^e[43],p=e[4]^e[14]^e[24]^e[34]^e[44],v=e[5]^e[15]^e[25]^e[35]^e[45],m=e[6]^e[16]^e[26]^e[36]^e[46],k=e[7]^e[17]^e[27]^e[37]^e[47],$=e[8]^e[18]^e[28]^e[38]^e[48],U=e[9]^e[19]^e[29]^e[39]^e[49],je=o<<1|d>>>31,kl=d<<1|o>>>31,Ye=$^je,Qe=U^kl,El=p<<1|v>>>31,Sl=v<<1|p>>>31,Xe=n^El,et=s^Sl,Tl=m<<1|k>>>31,Al=k<<1|m>>>31,tt=o^Tl,rt=d^Al,Ol=$<<1|U>>>31,Il=U<<1|$>>>31,nt=p^Ol,st=v^Il,Ml=n<<1|s>>>31,$l=s<<1|n>>>31,it=m^Ml,at=k^$l;e[0]^=Ye,e[1]^=Qe,e[2]^=Xe,e[3]^=et,e[4]^=tt,e[5]^=rt,e[6]^=nt,e[7]^=st,e[8]^=it,e[9]^=at,e[10]^=Ye,e[11]^=Qe,e[12]^=Xe,e[13]^=et,e[14]^=tt,e[15]^=rt,e[16]^=nt,e[17]^=st,e[18]^=it,e[19]^=at,e[20]^=Ye,e[21]^=Qe,e[22]^=Xe,e[23]^=et,e[24]^=tt,e[25]^=rt,e[26]^=nt,e[27]^=st,e[28]^=it,e[29]^=at,e[30]^=Ye,e[31]^=Qe,e[32]^=Xe,e[33]^=et,e[34]^=tt,e[35]^=rt,e[36]^=nt,e[37]^=st,e[38]^=it,e[39]^=at,e[40]^=Ye,e[41]^=Qe,e[42]^=Xe,e[43]^=et,e[44]^=tt,e[45]^=rt,e[46]^=nt,e[47]^=st,e[48]^=it,e[49]^=at;const _r=e[0],xr=e[1],kr=e[2]<<1|e[3]>>>31,Er=e[3]<<1|e[2]>>>31,Sr=e[5]<<30|e[4]>>>2,Tr=e[4]<<30|e[5]>>>2,Ar=e[6]<<28|e[7]>>>4,Or=e[7]<<28|e[6]>>>4,Ir=e[8]<<27|e[9]>>>5,Mr=e[9]<<27|e[8]>>>5,$r=e[11]<<4|e[10]>>>28,Rr=e[10]<<4|e[11]>>>28,Cr=e[13]<<12|e[12]>>>20,Nr=e[12]<<12|e[13]>>>20,jr=e[14]<<6|e[15]>>>26,Dr=e[15]<<6|e[14]>>>26,Pr=e[17]<<23|e[16]>>>9,Ur=e[16]<<23|e[17]>>>9,Zr=e[18]<<20|e[19]>>>12,Br=e[19]<<20|e[18]>>>12,Lr=e[20]<<3|e[21]>>>29,zr=e[21]<<3|e[20]>>>29,Vr=e[22]<<10|e[23]>>>22,Fr=e[23]<<10|e[22]>>>22,Wr=e[25]<<11|e[24]>>>21,Hr=e[24]<<11|e[25]>>>21,qr=e[26]<<25|e[27]>>>7,Gr=e[27]<<25|e[26]>>>7,Kr=e[29]<<7|e[28]>>>25,Jr=e[28]<<7|e[29]>>>25,Yr=e[31]<<9|e[30]>>>23,Qr=e[30]<<9|e[31]>>>23,Xr=e[33]<<13|e[32]>>>19,en=e[32]<<13|e[33]>>>19,tn=e[34]<<15|e[35]>>>17,rn=e[35]<<15|e[34]>>>17,nn=e[36]<<21|e[37]>>>11,sn=e[37]<<21|e[36]>>>11,an=e[38]<<8|e[39]>>>24,on=e[39]<<8|e[38]>>>24,cn=e[40]<<18|e[41]>>>14,un=e[41]<<18|e[40]>>>14,ln=e[42]<<2|e[43]>>>30,dn=e[43]<<2|e[42]>>>30,fn=e[45]<<29|e[44]>>>3,hn=e[44]<<29|e[45]>>>3,pn=e[47]<<24|e[46]>>>8,mn=e[46]<<24|e[47]>>>8,gn=e[48]<<14|e[49]>>>18,yn=e[49]<<14|e[48]>>>18;e[0]=_r^~Cr&Wr,e[1]=xr^~Nr&Hr,e[2]=Cr^~Wr&nn,e[3]=Nr^~Hr&sn,e[4]=Wr^~nn&gn,e[5]=Hr^~sn&yn,e[6]=nn^~gn&_r,e[7]=sn^~yn&xr,e[8]=gn^~_r&Cr,e[9]=yn^~xr&Nr,e[10]=Ar^~Zr&Lr,e[11]=Or^~Br&zr,e[12]=Zr^~Lr&Xr,e[13]=Br^~zr&en,e[14]=Lr^~Xr&fn,e[15]=zr^~en&hn,e[16]=Xr^~fn&Ar,e[17]=en^~hn&Or,e[18]=fn^~Ar&Zr,e[19]=hn^~Or&Br,e[20]=kr^~jr&qr,e[21]=Er^~Dr&Gr,e[22]=jr^~qr&an,e[23]=Dr^~Gr&on,e[24]=qr^~an&cn,e[25]=Gr^~on&un,e[26]=an^~cn&kr,e[27]=on^~un&Er,e[28]=cn^~kr&jr,e[29]=un^~Er&Dr,e[30]=Ir^~$r&Vr,e[31]=Mr^~Rr&Fr,e[32]=$r^~Vr&tn,e[33]=Rr^~Fr&rn,e[34]=Vr^~tn&pn,e[35]=Fr^~rn&mn,e[36]=tn^~pn&Ir,e[37]=rn^~mn&Mr,e[38]=pn^~Ir&$r,e[39]=mn^~Mr&Rr,e[40]=Sr^~Pr&Kr,e[41]=Tr^~Ur&Jr,e[42]=Pr^~Kr&Yr,e[43]=Ur^~Jr&Qr,e[44]=Kr^~Yr&ln,e[45]=Jr^~Qr&dn,e[46]=Yr^~ln&Sr,e[47]=Qr^~dn&Tr,e[48]=ln^~Sr&Pr,e[49]=dn^~Tr&Ur,e[0]^=Ms[t*2],e[1]^=Ms[t*2+1]}}function $s(e){const t=[];for(let n=0;n<e.length;n+=4)t.push(e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24);return t}function Rs(e,t){if(!e.length){const o=new Uint8Array(136);return o[0]=t,o[135]=128,[$s(o)]}const n=mr(e,136),s=n[n.length-1];if(s.length<136){const o=new Uint8Array(136);o.set(s),o[s.length]=t,o[135]|=128,n[n.length-1]=o}if(s.length===136){const o=new Uint8Array(136);o[0]=t,o[135]=128,n.push(o)}return n.map($s)}function Cs(e,t){for(const n of t){for(let s=0;s<34;s+=2)e[s]^=n[s+1],e[s+1]^=n[s];Lu(e)}return e}function Ns(e){return new Uint8Array([e[1],e[1]>>-24,e[1]>>-16,e[1]>>-8,e[0],e[0]>>8,e[0]>>16,e[0]>>24,e[3],e[3]>>-24,e[3]>>-16,e[3]>>-8,e[2],e[2]>>8,e[2]>>16,e[2]>>24,e[5],e[5]>>-24,e[5]>>-16,e[5]>>-8,e[4],e[4]>>8,e[4]>>16,e[4]>>24,e[7],e[7]>>-24,e[7]>>-16,e[7]>>-8,e[6],e[6]>>8,e[6]>>16,e[6]>>24])}function ie(e){return Ns(Cs(new Array(50).fill(0),Rs(e,1)))}function zu(e){return Ns(Cs(new Array(50).fill(0),Rs(e,6)))}function Vu(e,t,n){const s=Math.min(e.length,t.length,n/8+1);for(let o=0;o<s;o++){const d=e[o]^t[o];for(let p=0;p<8;p++)if(d>>7-p&1)return o*8+p}return n}function Fu(e,t){const n=Math.min(e.length,t.length);for(let s=0;s<n;s++)if(e[s]!==t[s])return e.subarray(0,s);return e.subarray(0,n)}function Wu(e,t,n,s){const o=Math.floor(t/8),d=t%8;n===1?e[o]|=1<<(s==="BE"?7-d:d):e[o]&=~(1<<(s==="BE"?7-d:d))}function Hu(e,t,n){const s=Math.floor(t/8),o=t%8;return e[s]>>(n==="BE"?7-o:o)&1}function qu(e,t,n=0){for(let s=n;s<e.length;s++)for(let o=0;o<t.length&&e[s+o]===t[o];o++)if(o===t.length-1)return s;return-1}function js(e,t,n=0){if(e.length>=t)return e;const s=new Uint8Array(t);return s.fill(n),s.set(e,t-e.length),s}function Gu(e,t,n=0){const s=e.length%t;return s===0?e:js(e,e.length+t-s,n)}function Ds(e,t,n=0){if(e.length>=t)return e;const s=new Uint8Array(t);return s.fill(n),s.set(e,0),s}function Ku(e,t,n=0){const s=e.length%t;return s===0?e:Ds(e,e.length+t-s,n)}function Ju(e,t){const n=new Uint8Array(e.length);for(let s=0;s<e.length;s++)n[s]=e[s]^t[s%t.length];return n}function Yu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function R(e,t){return(e%t+t)%t}function Ke(e,t){e=R(e,t);let[n,s]=[0n,1n],[o,d]=[t,e];for(;d!==0n;){const p=o/d;[n,s]=[s,n-p*s],[o,d]=[d,o-p*d]}if(o>1n)throw new Error("a is not invertible");return n<0n&&(n+=t),n}function Qu(e,t,n){let s=1n;for(e=R(e,n);t>0;)t%2n===1n&&(s=R(s*e,n)),e=R(e*e,n),t=t/2n;return s}function Ps(e,t){return R(e,t)===0n?0n:t%4n===3n?Qu(e,(t+1n)/4n,t):null}const B=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,P=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Ct=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Nt=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;function gr(e,t,n){if(t===0n)return[0n,0n];const s=R(3n*e*e*Ke(2n*t,n),n),o=R(s*s-2n*e,n),d=R(s*(e-o)-t,n);return[o,d]}function jt(e,t,n,s,o){if(e===0n&&t===0n)return[n,s];if(n===0n&&s===0n)return[e,t];if(e===n&&t===R(-s,o))return[0n,0n];if(e===n&&t===s)return gr(e,t,o);const d=R((s-t)*Ke(n-e,o),o),p=R(d*d-e-n,o),v=R(d*(e-p)-t,o);return[p,v]}function Xu(e){if(e<=0n||e>=P)throw new Error("Invalid private key");return ke(Ct,Nt,e,B)}function el(e){const t=e[1]%2n===0n?2:3;return new Uint8Array([t,...Ce(e[0],"BE")])}function tl(e){if(e.length!==33||e[0]!==2&&e[0]!==3)throw new Error("Invalid compressed public key");const t=Ne(e.slice(1),"BE"),n=Ps(R(t**3n+7n,B),B);if(!n)throw Error("Invalid x: does not correspond to a valid curve point");const s=R(-n,B),o=n%2n===0n;return[t,e[0]===2?o?n:s:o?s:n]}function rl(e){const t=new Uint8Array(20),n=ie(Re(Ce(e[0],"BE"),Ce(e[1],"BE")));return t.set(n.subarray(12)),t}function nl(e){const t=a.Binary.uint8ArrayToHex(e),n=a.Binary.uint8ArrayToHex(a.Binary.keccak256(new Uint8Array([...t].map(o=>o.charCodeAt(0)))));let s="0x";for(let o=0;o<t.length;o++)parseInt(n[o],16)>7?s+=t[o].toUpperCase():s+=t[o];return s}function ke(e,t,n,s){let o=[0n,0n],d=[e,t];const p=n.toString(2);for(const v of p)v==="0"?(d=jt(o[0],o[1],d[0],d[1],s),o=gr(o[0],o[1],s)):(o=jt(o[0],o[1],d[0],d[1],s),d=gr(d[0],d[1],s));return o}function sl(e,t,n){return Us(Ne(ie(e),"BE"),t,n)}function Us(e,t,n){if(t<=0n||t>=P)throw new Error("Invalid private key");if(n||(n=R(Ne(ie(Re(ie(Ce(t,"BE")),Ce(e,"BE"))),"BE"),P)),n<=0n||n>=P)throw new Error("Invalid nonce");const s=R(e,P),o=ke(Ct,Nt,n,B),d=R(o[0],P);let p=R((s+R(d,P)*t)*Ke(n,P),P);if(d===0n||p===0n)throw new Error("Invalid r or s value");let v=o[1]%2n===0n?27n:28n;return p>P/2n&&(p=P-p,v=v===27n?28n:27n),[d,p,v]}function il(e,t,n,s){const o=Ps(R(t**3n+7n,B),B);if(!o)throw new Error("Invalid r: does not correspond to a valid curve point");const d=s===27n?0n:1n,p=o%2n===d?o:B-o,v=R(Ne(ie(e),"BE"),P),m=ke(t,p,n,B),k=ke(Ct,Nt,v,B),$=jt(m[0],m[1],k[0],R(-k[1],B),B);return ke($[0],$[1],Ke(t,P),B)}function al(e,t,n,s){const o=R(Ne(ie(e),"BE"),P),d=Ke(s,P),p=R(o*d,P),v=R(n*d,P),m=ke(Ct,Nt,p,B),k=ke(t[0],t[1],v,B),$=jt(m[0],m[1],k[0],k[1],B);return n===R($[0],P)}class Zs{constructor(t){this.cursor=0,this.buffer=t}read(t){const n=this.buffer.subarray(this.cursor,this.cursor+t);return this.cursor+=t,n}max(){return this.buffer.length-this.cursor}}a.Uint8ArrayReader=Zs;class Bs{constructor(t){this.buffer=t,this.cursor=0}write(t){const n=Math.min(this.max(),t.max());return this.buffer.set(t.read(n),this.cursor),this.cursor+=n,n}max(){return this.buffer.length-this.cursor}}a.Uint8ArrayWriter=Bs;class Dt{constructor(t,n=0n){this.span=n,this.writer=new Bs(new Uint8Array(t))}build(){return Re(pr(this.span,"LE"),this.writer.buffer)}hash(){const t=Ts(mr(this.writer.buffer,32),(n,s)=>ie(Re(n,s)));return ie(Re(pr(this.span,"LE"),t))}}a.Chunk=Dt;class yr{constructor(t,n=4096){this.counters=[1],this.capacity=n,this.chunks=[new Dt(n)],this.onChunk=t}static async root(t,n=4096){const s=new r(r.NOOP,n);return await s.append(t),s.finalize()}async append(t,n=0,s=0n){const o=new Zs(t);for(;o.max()>0;){this.chunks[n].writer.max()===0&&await this.elevate(n);const d=this.chunks[n].writer.write(o);s?this.chunks[n].span+=s:this.chunks[0].span+=BigInt(d)}}async elevate(t){this.counters[t]=++this.counters[t]%(this.capacity/32),this.chunks[t+1]||(this.chunks.push(new Dt(this.capacity)),this.counters.push(1)),await this.append(this.chunks[t].hash(),t+1,this.chunks[t].span),await this.onChunk(this.chunks[t]),this.chunks[t]=new Dt(this.capacity)}async finalize(t=0){return this.chunks[t+1]?this.counters[t]===1?(await this.elevate(t+1),this.chunks[t+1]=this.chunks[t],this.finalize(t+1)):(await this.elevate(t),this.finalize(t+1)):(await this.onChunk(this.chunks[t]),this.chunks[t])}}a.MerkleTree=yr,r=yr,yr.NOOP=async e=>{};class Q{constructor(t,n){if(n<0)throw Error("Scale must be non-negative");this.value=BigInt(t),this.scale=n}static fromDecimalString(t,n){let[s,o]=t.split(".");return o=(o||"").padEnd(n,"0").slice(0,n),new Q(BigInt(s+o),n)}add(t){return this.assertSameScale(t),new Q(this.value+t.value,this.scale)}subtract(t){return this.assertSameScale(t),new Q(this.value-t.value,this.scale)}multiply(t){return new Q(this.value*t,this.scale)}divmod(t){if(t===0n)throw new Error("Division by zero is not allowed");const n=this.value/t,s=this.value%t;return[new Q(n,this.scale),new Q(s,this.scale)]}exchange(t,n,s){if(t==="*"){const d=this.value*n.value/10n**BigInt(this.scale);return new Q(d,s)}this.assertSameScale(n);const o=this.value*10n**BigInt(s)/n.value;return new Q(o,s)}compare(t){return this.assertSameScale(t),this.value>t.value?1:this.value<t.value?-1:0}toDecimalString(){if(this.scale===0)return this.value.toString();const t=this.value.toString(),n=t.slice(0,-this.scale)||"0",s=t.slice(-this.scale).padStart(this.scale,"0");return`${n}.${s}`}toString(){return this.value.toString()}toJSON(){return this.toString()}assertSameScale(t){if(this.scale!==t.scale)throw new Error(`Scale mismatch: expected ${this.scale}, but got ${t.scale}`)}}a.FixedPointNumber=Q;function ol(e){if(e.length===0)return null;const t=e[0];return t.ttlMax?--t.ttl<=0&&e.shift():t.ttlMax=t.ttl,{progress:(t.ttlMax-t.ttl)/t.ttlMax,data:t.data}}function Pt(e,t,n,s){const o=e.findIndex(v=>v===`--${t}`||v.startsWith(`--${t}=`)),d=e[o];if(!d)return(n||{})[s||t||""]||null;if(d.includes("="))return d.split("=")[1];const p=e[o+1];return p&&!p.startsWith("-")?p:(n||{})[s||t||""]||null}function cl(e,t,n,s){const o=Pt(e,t,n,s);if(!o)return null;try{return dr(o)}catch{throw new Error(`Invalid number argument ${t}: ${o}`)}}function ul(e,t,n,s){const o=e.some(m=>m.endsWith("-"+t)),d=Pt(e,t,n,s);if(!d&&o)return!0;if(!d&&!o)return null;const p=["true","1","yes","y","on"],v=["false","0","no","n","off"];if(p.includes(d.toLowerCase()))return!0;if(v.includes(d.toLowerCase()))return!1;throw Error(`Invalid boolean argument ${t}: ${d}`)}function Ls(e,t,n,s){const o=Pt(e,t,n,s);if(!o)throw new Error(`Missing argument ${t}`);return o}function ll(e,t,n,s){const o=Ls(e,t,n,s);try{return dr(o)}catch{throw new Error(`Invalid argument ${t}: ${o}`)}}function zs(e,t){const n=e[t];e.splice(t,1),e.unshift(n)}function dl(e,t){const n=[...e];return zs(n,t),n}function Vs(e,t){return{x:e.x+t.x,y:e.y+t.y}}function fl(e,t){return{x:e.x-t.x,y:e.y-t.y}}function vr(e,t){return{x:e.x*t,y:e.y*t}}function hl(e){const t=Math.sqrt(e.x*e.x+e.y*e.y);return{x:e.x/t,y:e.y/t}}function Fs(e,t,n){return{x:e.x+Math.cos(t)*n,y:e.y+Math.sin(t)*n}}function Ws(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Je(e,t,n="row-first"){const s=[];if(n==="column-first")for(let o=0;o<e.length;o++)for(let d=0;d<e[0].length;d++)t(o,d)&&s.push({x:o,y:d});else for(let o=0;o<e[0].length;o++)for(let d=0;d<e.length;d++)t(d,o)&&s.push({x:d,y:o});return s}function pl(e,t,n){var s,o;return((s=e[t+1])==null?void 0:s[n])&&((o=e[t-1])==null?void 0:o[n])&&!e[t][n-1]&&!e[t][n+1]}function ml(e,t,n){var s,o;return e[t][n+1]&&e[t][n-1]&&!((s=e[t-1])!=null&&s[n])&&!((o=e[t+1])!=null&&o[n])}function Hs(e,t,n){var s;return!((s=e[t-1])!=null&&s[n])}function qs(e,t,n){var s;return!((s=e[t+1])!=null&&s[n])}function Gs(e,t,n){return!e[t][n-1]}function Ks(e,t,n){return!e[t][n+1]}function gl(e,t,n){var o,d,p,v,m,k,$,U;const s=[];return e[t][n]?pl(e,t,n)||ml(e,t,n)?[]:(!((o=e[t-1])!=null&&o[n-1])&&Hs(e,t,n)&&Gs(e,t,n)&&s.push({x:t,y:n}),!((d=e[t+1])!=null&&d[n-1])&&qs(e,t,n)&&Gs(e,t,n)&&s.push({x:t+1,y:n}),!((p=e[t-1])!=null&&p[n+1])&&Hs(e,t,n)&&Ks(e,t,n)&&s.push({x:t,y:n+1}),!((v=e[t+1])!=null&&v[n+1])&&qs(e,t,n)&&Ks(e,t,n)&&s.push({x:t+1,y:n+1}),s):((m=e[t-1])!=null&&m[n]&&e[t][n-1]&&s.push({x:t,y:n}),(k=e[t+1])!=null&&k[n]&&e[t][n-1]&&s.push({x:t+1,y:n}),($=e[t-1])!=null&&$[n]&&e[t][n+1]&&s.push({x:t,y:n+1}),(U=e[t+1])!=null&&U[n]&&e[t][n+1]&&s.push({x:t+1,y:n+1}),s)}function yl(e,t,n,s){const o=[{x:0,y:0},{x:n,y:0},{x:0,y:s},{x:n,y:s}];for(let d=0;d<e.length;d++)for(let p=0;p<e[0].length;p++){const v=gl(e,d,p);for(const m of v)o.some(k=>k.x===m.x&&k.y===m.y)||o.push(m)}return o.map(d=>({x:d.x*t,y:d.y*t}))}function vl(e,t){const n=Je(e,(m,k)=>e[m][k]===0&&e[m][k+1]!==0,"row-first").map(m=>({...m,dx:1,dy:0})),s=Je(e,(m,k)=>e[m][k]===0&&e[m][k-1]!==0,"row-first").map(m=>({...m,dx:1,dy:0})),o=Je(e,(m,k)=>{var $;return e[m][k]===0&&(($=e[m-1])==null?void 0:$[k])!==0},"column-first").map(m=>({...m,dx:0,dy:1})),d=Je(e,(m,k)=>{var $;return e[m][k]===0&&(($=e[m+1])==null?void 0:$[k])!==0},"column-first").map(m=>({...m,dx:0,dy:1}));n.forEach(m=>m.y++),d.forEach(m=>m.x++);const p=hr([...o,...d],(m,k)=>m.x===k.x&&m.y-1===k.y),v=hr([...s,...n],(m,k)=>m.y===k.y&&m.x-1===k.x);return[...p,...v].map(m=>({start:m[0],end:We(m)})).map(m=>({start:vr(m.start,t),end:vr(Vs(m.end,{x:m.start.dx,y:m.start.dy}),t)}))}function wl(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}function bl(e,t){return t.map(n=>wl(e,n)).sort((n,s)=>n-s)}function Js(e,t,n,s){const o=(s.y-n.y)*(t.x-e.x)-(s.x-n.x)*(t.y-e.y);if(o===0)return null;let d=e.y-n.y,p=e.x-n.x;const v=(s.x-n.x)*d-(s.y-n.y)*p,m=(t.x-e.x)*d-(t.y-e.y)*p;return d=v/o,p=m/o,d>0&&d<1&&p>0&&p<1?{x:e.x+d*(t.x-e.x),y:e.y+d*(t.y-e.y)}:null}function wr(e,t,n){const s=[],o=Fs(e,n,1e4);for(const d of t){const p=Js(e,o,d.start,d.end);p&&s.push(p)}return s.length?s.reduce((d,p)=>{const v=Ws(e,p),m=Ws(e,d);return v<m?p:d}):null}function _l(e,t,n){const s=bl(e,n),o=[];for(const d of s){const p=wr(e,t,d-.001),v=wr(e,t,d+.001);p&&o.push(p),v&&o.push(v)}return o}class br{constructor(){this.subscribers=[]}subscribe(t){return this.subscribers.push(t),()=>{this.subscribers=this.subscribers.filter(n=>n!==t)}}publish(t){this.subscribers.forEach(n=>n(t))}clear(){this.subscribers=[]}getSubscriberCount(){return this.subscribers.length}}a.PubSubChannel=br;class xl{constructor(t,n){this.queue=[],this.running=0,this.onProcessed=new br,this.onDrained=new br,this.concurrency=t,this.capacity=n}process(){if(this.running>=this.concurrency)return;const t=this.queue.shift();t&&(this.running++,t().finally(()=>{this.running--,this.process(),this.onProcessed.publish(),this.running===0&&this.onDrained.publish()}))}enqueue(t){if(this.queue.length<this.capacity)return this.queue.push(t),this.process(),Promise.resolve();if(this.onProcessed.getSubscriberCount())throw Error("Queue capacity is full");return new Promise(n=>{this.onProcessed.subscribe(()=>{this.queue.length<this.capacity&&(this.queue.push(t),this.process(),this.onProcessed.clear(),n())})})}drain(){if(this.running===0)return Promise.resolve();if(this.onDrained.getSubscriberCount())throw Error("Already draining");return new Promise(t=>{this.onDrained.subscribe(()=>{this.onDrained.clear(),t()})})}}a.AsyncQueue=xl,a.Binary={hexToUint8Array:Ao,uint8ArrayToHex:Oo,base64ToUint8Array:ko,uint8ArrayToBase64:Eo,base32ToUint8Array:So,uint8ArrayToBase32:To,log2Reduce:Ts,partition:mr,concatBytes:Re,numberToUint8:Cu,uint8ToNumber:Nu,numberToUint16:ju,uint16ToNumber:Du,numberToUint32:Pu,uint32ToNumber:Uu,numberToUint64:pr,uint64ToNumber:Zu,numberToUint256:Ce,uint256ToNumber:Ne,sliceBytes:Bu,keccak256:ie,sha3_256:zu,proximity:Vu,commonPrefix:Fu,setBit:Wu,getBit:Hu,indexOf:qu,equals:Yu,padStart:js,padStartToMultiple:Gu,padEnd:Ds,padEndToMultiple:Ku,xorCypher:Ju},a.Elliptic={privateKeyToPublicKey:Xu,compressPublicKey:el,publicKeyFromCompressed:tl,publicKeyToAddress:rl,signMessage:sl,signHash:Us,verifySignature:al,recoverPublicKey:il,checksumEncode:nl},a.Random={intBetween:Fe,floatBetween:In,chance:Mn,signed:bi,makeSeededRng:Ht,point:xi,procs:ki},a.Arrays={countUnique:hu,makeUnique:fu,splitBySize:lu,splitByCount:xs,index:_s,indexCollection:uu,onlyOrThrow:h,onlyOrNull:g,firstOrThrow:x,firstOrNull:y,shuffle:f,initialize:j,initialize2D:se,rotate2D:ne,containsShape:ze,glue:$a,pluck:Ve,pick:qt,pickMany:Ei,pickManyUnique:Si,pickWeighted:Oi,pickRandomIndices:Oe,pickGuaranteed:Ti,last:We,pipe:$n,makePipe:Ai,sortWeighted:Ii,pushAll:At,unshiftAll:Ia,filterAndRemove:Yo,merge:Hc,empty:qc,pushToBucket:Ta,unshiftAndLimit:Aa,atRolling:Oa,group:hr,createOscillator:Cc,organiseWithLimits:jc,tickPlaybook:ol,getArgument:Pt,getBooleanArgument:ul,getNumberArgument:cl,requireStringArgument:Ls,requireNumberArgument:ll,bringToFront:dl,bringToFrontInPlace:zs,findInstance:Tu,filterInstances:Au,interleave:Ou,toggle:Iu,createHierarchy:$u,multicall:Eu,maxBy:Su},a.System={sleepMillis:l,forever:ji,scheduleMany:Ua,waitFor:Jo,expandError:xa,runAndSetInterval:Di},a.Numbers={make:dr,sum:Ba,average:La,median:za,getDistanceFromMidpoint:Va,clamp:fr,range:Fn,interpolate:Za,createSequence:Rc,increment:zc,decrement:Vc,format:Lc,fromDecimals:Bc,makeStorage:xc,asMegabytes:Pi,convertBytes:Ui,hexToRgb:Zi,rgbToHex:Bi,haversineDistanceToMeters:Li,roundToNearest:kt,formatDistance:zi,triangularNumber:Vi,searchFloat:Fi},a.Promises={raceFulfilled:c,invert:i,runInParallelBatches:u},a.Dates={getTimestamp:ac,getTimeDelta:fs,secondsToHumanTime:oc,countCycles:cc,isoDate:ec,throttle:uc,timeSince:dc,dateTimeSlug:tc,unixTimestamp:Xo,fromUtcString:rc,fromMillis:nc,getProgress:fc,humanizeTime:$t,humanizeProgress:Ko,createTimeDigits:Y,mapDayNumber:hs,getDayInfoFromDate:ur,getDayInfoFromDateTimeString:pc,seconds:mc,minutes:gc,hours:yc,days:vc,make:bc,normalizeTime:sc,absoluteDays:_e},a.Objects={safeParse:$c,deleteDeep:Ri,getDeep:ve,setDeep:we,incrementDeep:Mi,ensureDeep:$i,replaceDeep:Ci,getFirstDeep:Ni,deepMergeInPlace:be,deepMerge2:ka,deepMerge3:Ea,mapAllAsync:Ma,cloneWithJson:Qo,sortObject:ms,sortArray:gs,sortAny:xe,deepEquals:ys,deepEqualsEvery:Mc,runOn:Fc,ifPresent:Wc,zip:Vn,zipSum:Sa,removeEmptyArrays:Gc,removeEmptyValues:Kc,flatten:ou,unflatten:bs,match:cu,sort:Es,map:Qc,mapIterable:Xc,filterKeys:Jc,filterValues:Yc,rethrow:eu,setSomeOnObject:tu,setSomeDeep:ru,flip:nu,getAllPermutations:su,countTruthyValues:iu,transformToArray:pu,setMulti:gu,incrementMulti:mu,createBidirectionalMap:yu,createTemporalBidirectionalMap:vu,pushToBidirectionalMap:Ss,unshiftToBidirectionalMap:wu,addToTemporalBidirectionalMap:bu,getFromTemporalBidirectionalMap:_u,createStatefulToggle:Nc,diffKeys:Dc,pickRandomKey:vs,mapRandomKey:Pc,fromObjectString:Uc,toQueryString:ls,parseQueryString:Lo,hasKey:zo,selectMax:Vo,reposition:Fo,unwrapSingleKey:Wo,parseKeyValues:Ho},a.Types={isFunction:Kt,isObject:ue,isStrictlyObject:Ie,isEmptyArray:Rn,isEmptyObject:Wi,isUndefined:Gt,isString:W,isNumber:le,isBoolean:Cn,isDate:Me,isBlank:Et,isId:Jt,isIntegerString:Nn,isHexString:jn,isUrl:Ln,isNullable:va,asString:Zn,asHexString:sa,asSafeString:ia,asIntegerString:na,asNumber:St,asFunction:aa,asInteger:Xt,asBoolean:oa,asDate:ca,asNullableString:ua,asEmptiableString:la,asId:da,asTime:fa,asArray:ha,asObject:Tt,asNullableObject:pa,asStringMap:ma,asNumericDictionary:ga,asUrl:ya,asNullable:wa,asOptional:ba,enforceObjectShape:zn,enforceArrayShape:_a,isPng:As,isJpg:Os,isWebp:Is,isImage:Ru},a.Strings={tokenizeByCount:du,tokenizeByLength:ks,searchHex:ea,searchSubstring:ta,randomHex:ra,randomLetter:Ji,randomAlphanumeric:Yi,randomRichAscii:Qi,randomUnicode:Xi,includesAny:Fa,slugify:er,normalForm:Ha,enumify:Qa,escapeHtml:eo,decodeHtmlEntities:ro,after:tr,afterLast:Hn,before:Wn,beforeLast:rr,betweenWide:no,betweenNarrow:so,getPreLine:kc,containsWord:or,containsWords:Po,joinUrl:ps,getFuzzyMatchScore:Ot,sortByFuzzyScore:Xa,splitOnce:nr,splitAll:qn,randomize:co,expand:Gn,shrinkTrim:qe,capitalize:It,decapitalize:Kn,csvEscape:mo,parseCsv:Go,surroundInOut:Ya,getExtension:sr,getBasename:ir,normalizeEmail:io,normalizeFilename:ao,parseFilename:oo,camelToTitle:qa,slugToTitle:Ga,slugToCamel:Ka,joinHumanly:Ja,findWeightedPair:ts,extractBlock:rs,extractAllBlocks:vo,replaceBlocks:wo,indexOfEarliest:$e,lastIndexOfBefore:es,parseHtmlAttributes:Uo,readNextWord:Mt,resolveVariables:Zo,resolveVariableWithDefaultSyntax:cs,resolveRemainingVariablesWithDefaults:us,isLetter:Jn,isDigit:Yn,isLetterOrDigit:Ge,isValidObjectPathCharacter:fo,insert:ho,indexOfRegex:Qn,lineMatches:Xn,linesMatchInOrder:po,represent:He,resolveMarkdownLinks:Bo,buildUrl:qo,isChinese:Wa,replaceBetweenStrings:Tc,describeMarkdown:Ac,isBalanced:Oc,textToFormat:Ic,splitFormatting:bo,splitHashtags:_o,splitUrls:xo,route:Io,explodeReplace:ar,generateVariants:Mo,replaceWord:$o,replacePascalCaseWords:Ro,stripHtml:Co,breakLine:os,measureTextWidth:No,toLines:jo,levenshteinDistance:Do},a.Assertions={asEqual:Ra,asTrue:Ca,asTruthy:Na,asFalse:ja,asFalsy:Da,asEither:Pa},a.Cache={get:Ec,invalidate:Sc},a.Vector={addPoint:Vs,subtractPoint:fl,multiplyPoint:vr,normalizePoint:hl,pushPoint:Fs,filterCoordinates:Je,findCorners:yl,findLines:vl,raycast:wr,raycastCircle:_l,getLineIntersectionPoint:Js}})(ii);const C=Pl(ii);C.Arrays;C.Assertions;const L=C.Binary;C.Cache;C.Dates;C.Elliptic;C.Numbers;C.Objects;C.Pagination;C.Promises;C.Random;C.Strings;C.System;C.Types;C.Optional;C.Vector;C.PubSubChannel;C.Chunk;const Ul=C.MerkleTree;C.FixedPointNumber;C.Lazy;C.AsyncLazy;C.AsyncQueue;C.Uint8ArrayReader;C.Uint8ArrayWriter;const Zl=new TextEncoder,Qs=1,Xs=4096,wn=4096,Bl=32;function ai(a,r){return r=typeof r=="number"?I.FeedIndex.fromBigInt(BigInt(r)):r,new I.Identifier(L.keccak256(L.concatBytes(a.toUint8Array(),r.toUint8Array())))}function Ll(a){const r=a.slice(0,I.Span.LENGTH),i=a.slice(I.Span.LENGTH),c=zl(i),u=L.keccak256(L.concatBytes(r,c));return new I.Reference(u)}function zl(a){if(a.length>wn)throw new I.BeeArgumentError(`payload size ${a.length} exceeds maximum chunk payload size ${wn}`,a);const r=new Uint8Array(wn);return r.set(a),L.log2Reduce(L.partition(r,Bl),(i,c)=>L.keccak256(L.concatBytes(i,c)))}function ei(a){if(a instanceof Uint8Array||(a=Zl.encode(a)),a.length<Qs||a.length>Xs)throw new RangeError(`payload size ${a.length} exceeds limits [${Qs}, ${Xs}]`);const r=I.Span.fromBigInt(BigInt(a.length)),i=L.concatBytes(r.toUint8Array(),a);return{data:i,span:r,payload:I.Bytes.fromSlice(i,I.Span.LENGTH),address:Ll(i)}}function Vl(a,r){return new I.Reference(L.keccak256(L.concatBytes(a.toUint8Array(),r.toUint8Array())))}function ti(a,r,i){r=new I.Identifier(r),i=new I.PrivateKey(i);const c=Vl(r,i.publicKey().address()),u=i.sign(L.concatBytes(r.toUint8Array(),a.address.toUint8Array())),l=L.concatBytes(r.toUint8Array(),u.toUint8Array(),a.data),f=I.Span.fromSlice(a.data,0),h=I.Bytes.fromSlice(a.data,I.Span.LENGTH);return{data:l,identifier:r,signature:u,span:f,payload:h,address:c,owner:i.publicKey().address()}}const Fl=q.getInstance(),Wl=X.getInstance();function Hl(a){return new Promise(r=>{setTimeout(r,a)})}function oi(a){return(a.startsWith("0x")?a.slice(2):a).toLowerCase()}async function _n(a,r=3,i=250){return new Promise((c,u)=>{a().then(c).catch(l=>{r>0?(Fl.info(`Retrying... Attempts left: ${r}. Error: ${l.message}`),setTimeout(()=>{_n(a,r-1,i).then(c).catch(u)},i)):(Wl.handleError(l,"Utils.retryAwaitableAsync"),u(l))})})}class ql{constructor(){this.events={},this.on=this.on.bind(this),this.off=this.off.bind(this),this.cleanAll=this.cleanAll.bind(this),this.emit=this.emit.bind(this)}on(r,i){this.events[r]||(this.events[r]=[]),this.events[r].push(i)}off(r,i){if(!this.events[r])return;const c=this.events[r].indexOf(i);c>-1&&this.events[r].splice(c,1)}cleanAll(){this.events={}}emit(r,i){this.events[r]&&this.events[r].forEach(c=>c(i))}}var M;(function(a){a.assertEqual=u=>u;function r(u){}a.assertIs=r;function i(u){throw new Error}a.assertNever=i,a.arrayToEnum=u=>{const l={};for(const f of u)l[f]=f;return l},a.getValidEnumValues=u=>{const l=a.objectKeys(u).filter(h=>typeof u[u[h]]!="number"),f={};for(const h of l)f[h]=u[h];return a.objectValues(f)},a.objectValues=u=>a.objectKeys(u).map(function(l){return u[l]}),a.objectKeys=typeof Object.keys=="function"?u=>Object.keys(u):u=>{const l=[];for(const f in u)Object.prototype.hasOwnProperty.call(u,f)&&l.push(f);return l},a.find=(u,l)=>{for(const f of u)if(l(f))return f},a.isInteger=typeof Number.isInteger=="function"?u=>Number.isInteger(u):u=>typeof u=="number"&&isFinite(u)&&Math.floor(u)===u;function c(u,l=" | "){return u.map(f=>typeof f=="string"?`'${f}'`:f).join(l)}a.joinValues=c,a.jsonStringifyReplacer=(u,l)=>typeof l=="bigint"?l.toString():l})(M||(M={}));var xn;(function(a){a.mergeShapes=(r,i)=>({...r,...i})})(xn||(xn={}));const _=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),oe=a=>{switch(typeof a){case"undefined":return _.undefined;case"string":return _.string;case"number":return isNaN(a)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(a)?_.array:a===null?_.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?_.promise:typeof Map<"u"&&a instanceof Map?_.map:typeof Set<"u"&&a instanceof Set?_.set:typeof Date<"u"&&a instanceof Date?_.date:_.object;default:return _.unknown}},w=M.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Gl=a=>JSON.stringify(a,null,2).replace(/"([^"]+)":/g,"$1:");class F extends Error{get errors(){return this.issues}constructor(r){super(),this.issues=[],this.addIssue=c=>{this.issues=[...this.issues,c]},this.addIssues=(c=[])=>{this.issues=[...this.issues,...c]};const i=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,i):this.__proto__=i,this.name="ZodError",this.issues=r}format(r){const i=r||function(l){return l.message},c={_errors:[]},u=l=>{for(const f of l.issues)if(f.code==="invalid_union")f.unionErrors.map(u);else if(f.code==="invalid_return_type")u(f.returnTypeError);else if(f.code==="invalid_arguments")u(f.argumentsError);else if(f.path.length===0)c._errors.push(i(f));else{let h=c,g=0;for(;g<f.path.length;){const y=f.path[g];g===f.path.length-1?(h[y]=h[y]||{_errors:[]},h[y]._errors.push(i(f))):h[y]=h[y]||{_errors:[]},h=h[y],g++}}};return u(this),c}static assert(r){if(!(r instanceof F))throw new Error(`Not a ZodError: ${r}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(r=i=>i.message){const i={},c=[];for(const u of this.issues)u.path.length>0?(i[u.path[0]]=i[u.path[0]]||[],i[u.path[0]].push(r(u))):c.push(r(u));return{formErrors:c,fieldErrors:i}}get formErrors(){return this.flatten()}}F.create=a=>new F(a);const Ze=(a,r)=>{let i;switch(a.code){case w.invalid_type:a.received===_.undefined?i="Required":i=`Expected ${a.expected}, received ${a.received}`;break;case w.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(a.expected,M.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:i=`Unrecognized key(s) in object: ${M.joinValues(a.keys,", ")}`;break;case w.invalid_union:i="Invalid input";break;case w.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${M.joinValues(a.options)}`;break;case w.invalid_enum_value:i=`Invalid enum value. Expected ${M.joinValues(a.options)}, received '${a.received}'`;break;case w.invalid_arguments:i="Invalid function arguments";break;case w.invalid_return_type:i="Invalid function return type";break;case w.invalid_date:i="Invalid date";break;case w.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(i=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(i=`${i} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?i=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?i=`Invalid input: must end with "${a.validation.endsWith}"`:M.assertNever(a.validation):a.validation!=="regex"?i=`Invalid ${a.validation}`:i="Invalid";break;case w.too_small:a.type==="array"?i=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?i=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?i=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?i=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:i="Invalid input";break;case w.too_big:a.type==="array"?i=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?i=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?i=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?i=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?i=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:i="Invalid input";break;case w.custom:i="Invalid input";break;case w.invalid_intersection_types:i="Intersection results could not be merged";break;case w.not_multiple_of:i=`Number must be a multiple of ${a.multipleOf}`;break;case w.not_finite:i="Number must be finite";break;default:i=r.defaultError,M.assertNever(a)}return{message:i}};let ci=Ze;function Kl(a){ci=a}function Ut(){return ci}const Zt=a=>{const{data:r,path:i,errorMaps:c,issueData:u}=a,l=[...i,...u.path||[]],f={...u,path:l};if(u.message!==void 0)return{...u,path:l,message:u.message};let h="";const g=c.filter(y=>!!y).slice().reverse();for(const y of g)h=y(f,{data:r,defaultError:h}).message;return{...u,path:l,message:h}},Jl=[];function b(a,r){const i=Ut(),c=Zt({issueData:r,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,i,i===Ze?void 0:Ze].filter(u=>!!u)});a.common.issues.push(c)}class z{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(r,i){const c=[];for(const u of i){if(u.status==="aborted")return T;u.status==="dirty"&&r.dirty(),c.push(u.value)}return{status:r.value,value:c}}static async mergeObjectAsync(r,i){const c=[];for(const u of i){const l=await u.key,f=await u.value;c.push({key:l,value:f})}return z.mergeObjectSync(r,c)}static mergeObjectSync(r,i){const c={};for(const u of i){const{key:l,value:f}=u;if(l.status==="aborted"||f.status==="aborted")return T;l.status==="dirty"&&r.dirty(),f.status==="dirty"&&r.dirty(),l.value!=="__proto__"&&(typeof f.value<"u"||u.alwaysSet)&&(c[l.value]=f.value)}return{status:r.value,value:c}}}const T=Object.freeze({status:"aborted"}),Pe=a=>({status:"dirty",value:a}),V=a=>({status:"valid",value:a}),kn=a=>a.status==="aborted",En=a=>a.status==="dirty",Se=a=>a.status==="valid",ut=a=>typeof Promise<"u"&&a instanceof Promise;function Bt(a,r,i,c){if(typeof r=="function"?a!==r||!c:!r.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r.get(a)}function ui(a,r,i,c,u){if(typeof r=="function"?a!==r||!u:!r.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r.set(a,i),i}var E;(function(a){a.errToObj=r=>typeof r=="string"?{message:r}:r||{},a.toString=r=>typeof r=="string"?r:r==null?void 0:r.message})(E||(E={}));var ot,ct;class te{constructor(r,i,c,u){this._cachedPath=[],this.parent=r,this.data=i,this._path=c,this._key=u}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ri=(a,r)=>{if(Se(r))return{success:!0,data:r.value};if(!a.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const i=new F(a.common.issues);return this._error=i,this._error}}};function A(a){if(!a)return{};const{errorMap:r,invalid_type_error:i,required_error:c,description:u}=a;if(r&&(i||c))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return r?{errorMap:r,description:u}:{errorMap:(f,h)=>{var g,y;const{message:x}=a;return f.code==="invalid_enum_value"?{message:x??h.defaultError}:typeof h.data>"u"?{message:(g=x??c)!==null&&g!==void 0?g:h.defaultError}:f.code!=="invalid_type"?{message:h.defaultError}:{message:(y=x??i)!==null&&y!==void 0?y:h.defaultError}},description:u}}class O{get description(){return this._def.description}_getType(r){return oe(r.data)}_getOrReturnCtx(r,i){return i||{common:r.parent.common,data:r.data,parsedType:oe(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}_processInputParams(r){return{status:new z,ctx:{common:r.parent.common,data:r.data,parsedType:oe(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}}_parseSync(r){const i=this._parse(r);if(ut(i))throw new Error("Synchronous parse encountered promise.");return i}_parseAsync(r){const i=this._parse(r);return Promise.resolve(i)}parse(r,i){const c=this.safeParse(r,i);if(c.success)return c.data;throw c.error}safeParse(r,i){var c;const u={common:{issues:[],async:(c=i==null?void 0:i.async)!==null&&c!==void 0?c:!1,contextualErrorMap:i==null?void 0:i.errorMap},path:(i==null?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:oe(r)},l=this._parseSync({data:r,path:u.path,parent:u});return ri(u,l)}"~validate"(r){var i,c;const u={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:oe(r)};if(!this["~standard"].async)try{const l=this._parseSync({data:r,path:[],parent:u});return Se(l)?{value:l.value}:{issues:u.common.issues}}catch(l){!((c=(i=l==null?void 0:l.message)===null||i===void 0?void 0:i.toLowerCase())===null||c===void 0)&&c.includes("encountered")&&(this["~standard"].async=!0),u.common={issues:[],async:!0}}return this._parseAsync({data:r,path:[],parent:u}).then(l=>Se(l)?{value:l.value}:{issues:u.common.issues})}async parseAsync(r,i){const c=await this.safeParseAsync(r,i);if(c.success)return c.data;throw c.error}async safeParseAsync(r,i){const c={common:{issues:[],contextualErrorMap:i==null?void 0:i.errorMap,async:!0},path:(i==null?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:oe(r)},u=this._parse({data:r,path:c.path,parent:c}),l=await(ut(u)?u:Promise.resolve(u));return ri(c,l)}refine(r,i){const c=u=>typeof i=="string"||typeof i>"u"?{message:i}:typeof i=="function"?i(u):i;return this._refinement((u,l)=>{const f=r(u),h=()=>l.addIssue({code:w.custom,...c(u)});return typeof Promise<"u"&&f instanceof Promise?f.then(g=>g?!0:(h(),!1)):f?!0:(h(),!1)})}refinement(r,i){return this._refinement((c,u)=>r(c)?!0:(u.addIssue(typeof i=="function"?i(c,u):i),!1))}_refinement(r){return new J({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:r}})}superRefine(r){return this._refinement(r)}constructor(r){this.spa=this.safeParseAsync,this._def=r,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:i=>this["~validate"](i)}}optional(){return ee.create(this,this._def)}nullable(){return ge.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return K.create(this)}promise(){return Le.create(this,this._def)}or(r){return ht.create([this,r],this._def)}and(r){return pt.create(this,r,this._def)}transform(r){return new J({...A(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:r}})}default(r){const i=typeof r=="function"?r:()=>r;return new wt({...A(this._def),innerType:this,defaultValue:i,typeName:S.ZodDefault})}brand(){return new Tn({typeName:S.ZodBranded,type:this,...A(this._def)})}catch(r){const i=typeof r=="function"?r:()=>r;return new bt({...A(this._def),innerType:this,catchValue:i,typeName:S.ZodCatch})}describe(r){const i=this.constructor;return new i({...this._def,description:r})}pipe(r){return xt.create(this,r)}readonly(){return _t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Yl=/^c[^\s-]{8,}$/i,Ql=/^[0-9a-z]+$/,Xl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ed=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,td=/^[a-z0-9_-]{21}$/i,rd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,sd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,id="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let bn;const ad=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,od=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,cd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ud=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ld=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,dd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,li="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",fd=new RegExp(`^${li}$`);function di(a){let r="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return a.precision?r=`${r}\\.\\d{${a.precision}}`:a.precision==null&&(r=`${r}(\\.\\d+)?`),r}function hd(a){return new RegExp(`^${di(a)}$`)}function fi(a){let r=`${li}T${di(a)}`;const i=[];return i.push(a.local?"Z?":"Z"),a.offset&&i.push("([+-]\\d{2}:?\\d{2})"),r=`${r}(${i.join("|")})`,new RegExp(`^${r}$`)}function pd(a,r){return!!((r==="v4"||!r)&&ad.test(a)||(r==="v6"||!r)&&cd.test(a))}function md(a,r){if(!rd.test(a))return!1;try{const[i]=a.split("."),c=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),u=JSON.parse(atob(c));return!(typeof u!="object"||u===null||!u.typ||!u.alg||r&&u.alg!==r)}catch{return!1}}function gd(a,r){return!!((r==="v4"||!r)&&od.test(a)||(r==="v6"||!r)&&ud.test(a))}class G extends O{_parse(r){if(this._def.coerce&&(r.data=String(r.data)),this._getType(r)!==_.string){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_type,expected:_.string,received:l.parsedType}),T}const c=new z;let u;for(const l of this._def.checks)if(l.kind==="min")r.data.length<l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),c.dirty());else if(l.kind==="max")r.data.length>l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),c.dirty());else if(l.kind==="length"){const f=r.data.length>l.value,h=r.data.length<l.value;(f||h)&&(u=this._getOrReturnCtx(r,u),f?b(u,{code:w.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):h&&b(u,{code:w.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),c.dirty())}else if(l.kind==="email")sd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"email",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="emoji")bn||(bn=new RegExp(id,"u")),bn.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"emoji",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="uuid")ed.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"uuid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="nanoid")td.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"nanoid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid")Yl.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cuid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid2")Ql.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cuid2",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="ulid")Xl.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"ulid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="url")try{new URL(r.data)}catch{u=this._getOrReturnCtx(r,u),b(u,{validation:"url",code:w.invalid_string,message:l.message}),c.dirty()}else l.kind==="regex"?(l.regex.lastIndex=0,l.regex.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"regex",code:w.invalid_string,message:l.message}),c.dirty())):l.kind==="trim"?r.data=r.data.trim():l.kind==="includes"?r.data.includes(l.value,l.position)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),c.dirty()):l.kind==="toLowerCase"?r.data=r.data.toLowerCase():l.kind==="toUpperCase"?r.data=r.data.toUpperCase():l.kind==="startsWith"?r.data.startsWith(l.value)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:{startsWith:l.value},message:l.message}),c.dirty()):l.kind==="endsWith"?r.data.endsWith(l.value)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:{endsWith:l.value},message:l.message}),c.dirty()):l.kind==="datetime"?fi(l).test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:"datetime",message:l.message}),c.dirty()):l.kind==="date"?fd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:"date",message:l.message}),c.dirty()):l.kind==="time"?hd(l).test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:"time",message:l.message}),c.dirty()):l.kind==="duration"?nd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"duration",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="ip"?pd(r.data,l.version)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"ip",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="jwt"?md(r.data,l.alg)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"jwt",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="cidr"?gd(r.data,l.version)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cidr",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="base64"?ld.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"base64",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="base64url"?dd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"base64url",code:w.invalid_string,message:l.message}),c.dirty()):M.assertNever(l);return{status:c.value,value:r.data}}_regex(r,i,c){return this.refinement(u=>r.test(u),{validation:i,code:w.invalid_string,...E.errToObj(c)})}_addCheck(r){return new G({...this._def,checks:[...this._def.checks,r]})}email(r){return this._addCheck({kind:"email",...E.errToObj(r)})}url(r){return this._addCheck({kind:"url",...E.errToObj(r)})}emoji(r){return this._addCheck({kind:"emoji",...E.errToObj(r)})}uuid(r){return this._addCheck({kind:"uuid",...E.errToObj(r)})}nanoid(r){return this._addCheck({kind:"nanoid",...E.errToObj(r)})}cuid(r){return this._addCheck({kind:"cuid",...E.errToObj(r)})}cuid2(r){return this._addCheck({kind:"cuid2",...E.errToObj(r)})}ulid(r){return this._addCheck({kind:"ulid",...E.errToObj(r)})}base64(r){return this._addCheck({kind:"base64",...E.errToObj(r)})}base64url(r){return this._addCheck({kind:"base64url",...E.errToObj(r)})}jwt(r){return this._addCheck({kind:"jwt",...E.errToObj(r)})}ip(r){return this._addCheck({kind:"ip",...E.errToObj(r)})}cidr(r){return this._addCheck({kind:"cidr",...E.errToObj(r)})}datetime(r){var i,c;return typeof r=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:r}):this._addCheck({kind:"datetime",precision:typeof(r==null?void 0:r.precision)>"u"?null:r==null?void 0:r.precision,offset:(i=r==null?void 0:r.offset)!==null&&i!==void 0?i:!1,local:(c=r==null?void 0:r.local)!==null&&c!==void 0?c:!1,...E.errToObj(r==null?void 0:r.message)})}date(r){return this._addCheck({kind:"date",message:r})}time(r){return typeof r=="string"?this._addCheck({kind:"time",precision:null,message:r}):this._addCheck({kind:"time",precision:typeof(r==null?void 0:r.precision)>"u"?null:r==null?void 0:r.precision,...E.errToObj(r==null?void 0:r.message)})}duration(r){return this._addCheck({kind:"duration",...E.errToObj(r)})}regex(r,i){return this._addCheck({kind:"regex",regex:r,...E.errToObj(i)})}includes(r,i){return this._addCheck({kind:"includes",value:r,position:i==null?void 0:i.position,...E.errToObj(i==null?void 0:i.message)})}startsWith(r,i){return this._addCheck({kind:"startsWith",value:r,...E.errToObj(i)})}endsWith(r,i){return this._addCheck({kind:"endsWith",value:r,...E.errToObj(i)})}min(r,i){return this._addCheck({kind:"min",value:r,...E.errToObj(i)})}max(r,i){return this._addCheck({kind:"max",value:r,...E.errToObj(i)})}length(r,i){return this._addCheck({kind:"length",value:r,...E.errToObj(i)})}nonempty(r){return this.min(1,E.errToObj(r))}trim(){return new G({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(r=>r.kind==="datetime")}get isDate(){return!!this._def.checks.find(r=>r.kind==="date")}get isTime(){return!!this._def.checks.find(r=>r.kind==="time")}get isDuration(){return!!this._def.checks.find(r=>r.kind==="duration")}get isEmail(){return!!this._def.checks.find(r=>r.kind==="email")}get isURL(){return!!this._def.checks.find(r=>r.kind==="url")}get isEmoji(){return!!this._def.checks.find(r=>r.kind==="emoji")}get isUUID(){return!!this._def.checks.find(r=>r.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(r=>r.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(r=>r.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(r=>r.kind==="cuid2")}get isULID(){return!!this._def.checks.find(r=>r.kind==="ulid")}get isIP(){return!!this._def.checks.find(r=>r.kind==="ip")}get isCIDR(){return!!this._def.checks.find(r=>r.kind==="cidr")}get isBase64(){return!!this._def.checks.find(r=>r.kind==="base64")}get isBase64url(){return!!this._def.checks.find(r=>r.kind==="base64url")}get minLength(){let r=null;for(const i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxLength(){let r=null;for(const i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}}G.create=a=>{var r;return new G({checks:[],typeName:S.ZodString,coerce:(r=a==null?void 0:a.coerce)!==null&&r!==void 0?r:!1,...A(a)})};function yd(a,r){const i=(a.toString().split(".")[1]||"").length,c=(r.toString().split(".")[1]||"").length,u=i>c?i:c,l=parseInt(a.toFixed(u).replace(".","")),f=parseInt(r.toFixed(u).replace(".",""));return l%f/Math.pow(10,u)}class he extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(r){if(this._def.coerce&&(r.data=Number(r.data)),this._getType(r)!==_.number){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_type,expected:_.number,received:l.parsedType}),T}let c;const u=new z;for(const l of this._def.checks)l.kind==="int"?M.isInteger(r.data)||(c=this._getOrReturnCtx(r,c),b(c,{code:w.invalid_type,expected:"integer",received:"float",message:l.message}),u.dirty()):l.kind==="min"?(l.inclusive?r.data<l.value:r.data<=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_small,minimum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),u.dirty()):l.kind==="max"?(l.inclusive?r.data>l.value:r.data>=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_big,maximum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),u.dirty()):l.kind==="multipleOf"?yd(r.data,l.value)!==0&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.not_multiple_of,multipleOf:l.value,message:l.message}),u.dirty()):l.kind==="finite"?Number.isFinite(r.data)||(c=this._getOrReturnCtx(r,c),b(c,{code:w.not_finite,message:l.message}),u.dirty()):M.assertNever(l);return{status:u.value,value:r.data}}gte(r,i){return this.setLimit("min",r,!0,E.toString(i))}gt(r,i){return this.setLimit("min",r,!1,E.toString(i))}lte(r,i){return this.setLimit("max",r,!0,E.toString(i))}lt(r,i){return this.setLimit("max",r,!1,E.toString(i))}setLimit(r,i,c,u){return new he({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:c,message:E.toString(u)}]})}_addCheck(r){return new he({...this._def,checks:[...this._def.checks,r]})}int(r){return this._addCheck({kind:"int",message:E.toString(r)})}positive(r){return this._addCheck({kind:"min",value:0,inclusive:!1,message:E.toString(r)})}negative(r){return this._addCheck({kind:"max",value:0,inclusive:!1,message:E.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:0,inclusive:!0,message:E.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:0,inclusive:!0,message:E.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:E.toString(i)})}finite(r){return this._addCheck({kind:"finite",message:E.toString(r)})}safe(r){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:E.toString(r)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:E.toString(r)})}get minValue(){let r=null;for(const i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxValue(){let r=null;for(const i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}get isInt(){return!!this._def.checks.find(r=>r.kind==="int"||r.kind==="multipleOf"&&M.isInteger(r.value))}get isFinite(){let r=null,i=null;for(const c of this._def.checks){if(c.kind==="finite"||c.kind==="int"||c.kind==="multipleOf")return!0;c.kind==="min"?(i===null||c.value>i)&&(i=c.value):c.kind==="max"&&(r===null||c.value<r)&&(r=c.value)}return Number.isFinite(i)&&Number.isFinite(r)}}he.create=a=>new he({checks:[],typeName:S.ZodNumber,coerce:(a==null?void 0:a.coerce)||!1,...A(a)});class pe extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(r){if(this._def.coerce)try{r.data=BigInt(r.data)}catch{return this._getInvalidInput(r)}if(this._getType(r)!==_.bigint)return this._getInvalidInput(r);let c;const u=new z;for(const l of this._def.checks)l.kind==="min"?(l.inclusive?r.data<l.value:r.data<=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_small,type:"bigint",minimum:l.value,inclusive:l.inclusive,message:l.message}),u.dirty()):l.kind==="max"?(l.inclusive?r.data>l.value:r.data>=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_big,type:"bigint",maximum:l.value,inclusive:l.inclusive,message:l.message}),u.dirty()):l.kind==="multipleOf"?r.data%l.value!==BigInt(0)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.not_multiple_of,multipleOf:l.value,message:l.message}),u.dirty()):M.assertNever(l);return{status:u.value,value:r.data}}_getInvalidInput(r){const i=this._getOrReturnCtx(r);return b(i,{code:w.invalid_type,expected:_.bigint,received:i.parsedType}),T}gte(r,i){return this.setLimit("min",r,!0,E.toString(i))}gt(r,i){return this.setLimit("min",r,!1,E.toString(i))}lte(r,i){return this.setLimit("max",r,!0,E.toString(i))}lt(r,i){return this.setLimit("max",r,!1,E.toString(i))}setLimit(r,i,c,u){return new pe({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:c,message:E.toString(u)}]})}_addCheck(r){return new pe({...this._def,checks:[...this._def.checks,r]})}positive(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:E.toString(r)})}negative(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:E.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:E.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:E.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:E.toString(i)})}get minValue(){let r=null;for(const i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxValue(){let r=null;for(const i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}}pe.create=a=>{var r;return new pe({checks:[],typeName:S.ZodBigInt,coerce:(r=a==null?void 0:a.coerce)!==null&&r!==void 0?r:!1,...A(a)})};class lt extends O{_parse(r){if(this._def.coerce&&(r.data=!!r.data),this._getType(r)!==_.boolean){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.boolean,received:c.parsedType}),T}return V(r.data)}}lt.create=a=>new lt({typeName:S.ZodBoolean,coerce:(a==null?void 0:a.coerce)||!1,...A(a)});class Te extends O{_parse(r){if(this._def.coerce&&(r.data=new Date(r.data)),this._getType(r)!==_.date){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_type,expected:_.date,received:l.parsedType}),T}if(isNaN(r.data.getTime())){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_date}),T}const c=new z;let u;for(const l of this._def.checks)l.kind==="min"?r.data.getTime()<l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_small,message:l.message,inclusive:!0,exact:!1,minimum:l.value,type:"date"}),c.dirty()):l.kind==="max"?r.data.getTime()>l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_big,message:l.message,inclusive:!0,exact:!1,maximum:l.value,type:"date"}),c.dirty()):M.assertNever(l);return{status:c.value,value:new Date(r.data.getTime())}}_addCheck(r){return new Te({...this._def,checks:[...this._def.checks,r]})}min(r,i){return this._addCheck({kind:"min",value:r.getTime(),message:E.toString(i)})}max(r,i){return this._addCheck({kind:"max",value:r.getTime(),message:E.toString(i)})}get minDate(){let r=null;for(const i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r!=null?new Date(r):null}get maxDate(){let r=null;for(const i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r!=null?new Date(r):null}}Te.create=a=>new Te({checks:[],coerce:(a==null?void 0:a.coerce)||!1,typeName:S.ZodDate,...A(a)});class Lt extends O{_parse(r){if(this._getType(r)!==_.symbol){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.symbol,received:c.parsedType}),T}return V(r.data)}}Lt.create=a=>new Lt({typeName:S.ZodSymbol,...A(a)});class dt extends O{_parse(r){if(this._getType(r)!==_.undefined){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.undefined,received:c.parsedType}),T}return V(r.data)}}dt.create=a=>new dt({typeName:S.ZodUndefined,...A(a)});class ft extends O{_parse(r){if(this._getType(r)!==_.null){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.null,received:c.parsedType}),T}return V(r.data)}}ft.create=a=>new ft({typeName:S.ZodNull,...A(a)});class Be extends O{constructor(){super(...arguments),this._any=!0}_parse(r){return V(r.data)}}Be.create=a=>new Be({typeName:S.ZodAny,...A(a)});class Ee extends O{constructor(){super(...arguments),this._unknown=!0}_parse(r){return V(r.data)}}Ee.create=a=>new Ee({typeName:S.ZodUnknown,...A(a)});class ce extends O{_parse(r){const i=this._getOrReturnCtx(r);return b(i,{code:w.invalid_type,expected:_.never,received:i.parsedType}),T}}ce.create=a=>new ce({typeName:S.ZodNever,...A(a)});class zt extends O{_parse(r){if(this._getType(r)!==_.undefined){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.void,received:c.parsedType}),T}return V(r.data)}}zt.create=a=>new zt({typeName:S.ZodVoid,...A(a)});class K extends O{_parse(r){const{ctx:i,status:c}=this._processInputParams(r),u=this._def;if(i.parsedType!==_.array)return b(i,{code:w.invalid_type,expected:_.array,received:i.parsedType}),T;if(u.exactLength!==null){const f=i.data.length>u.exactLength.value,h=i.data.length<u.exactLength.value;(f||h)&&(b(i,{code:f?w.too_big:w.too_small,minimum:h?u.exactLength.value:void 0,maximum:f?u.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:u.exactLength.message}),c.dirty())}if(u.minLength!==null&&i.data.length<u.minLength.value&&(b(i,{code:w.too_small,minimum:u.minLength.value,type:"array",inclusive:!0,exact:!1,message:u.minLength.message}),c.dirty()),u.maxLength!==null&&i.data.length>u.maxLength.value&&(b(i,{code:w.too_big,maximum:u.maxLength.value,type:"array",inclusive:!0,exact:!1,message:u.maxLength.message}),c.dirty()),i.common.async)return Promise.all([...i.data].map((f,h)=>u.type._parseAsync(new te(i,f,i.path,h)))).then(f=>z.mergeArray(c,f));const l=[...i.data].map((f,h)=>u.type._parseSync(new te(i,f,i.path,h)));return z.mergeArray(c,l)}get element(){return this._def.type}min(r,i){return new K({...this._def,minLength:{value:r,message:E.toString(i)}})}max(r,i){return new K({...this._def,maxLength:{value:r,message:E.toString(i)}})}length(r,i){return new K({...this._def,exactLength:{value:r,message:E.toString(i)}})}nonempty(r){return this.min(1,r)}}K.create=(a,r)=>new K({type:a,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...A(r)});function De(a){if(a instanceof N){const r={};for(const i in a.shape){const c=a.shape[i];r[i]=ee.create(De(c))}return new N({...a._def,shape:()=>r})}else return a instanceof K?new K({...a._def,type:De(a.element)}):a instanceof ee?ee.create(De(a.unwrap())):a instanceof ge?ge.create(De(a.unwrap())):a instanceof re?re.create(a.items.map(r=>De(r))):a}class N extends O{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const r=this._def.shape(),i=M.objectKeys(r);return this._cached={shape:r,keys:i}}_parse(r){if(this._getType(r)!==_.object){const y=this._getOrReturnCtx(r);return b(y,{code:w.invalid_type,expected:_.object,received:y.parsedType}),T}const{status:c,ctx:u}=this._processInputParams(r),{shape:l,keys:f}=this._getCached(),h=[];if(!(this._def.catchall instanceof ce&&this._def.unknownKeys==="strip"))for(const y in u.data)f.includes(y)||h.push(y);const g=[];for(const y of f){const x=l[y],j=u.data[y];g.push({key:{status:"valid",value:y},value:x._parse(new te(u,j,u.path,y)),alwaysSet:y in u.data})}if(this._def.catchall instanceof ce){const y=this._def.unknownKeys;if(y==="passthrough")for(const x of h)g.push({key:{status:"valid",value:x},value:{status:"valid",value:u.data[x]}});else if(y==="strict")h.length>0&&(b(u,{code:w.unrecognized_keys,keys:h}),c.dirty());else if(y!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const y=this._def.catchall;for(const x of h){const j=u.data[x];g.push({key:{status:"valid",value:x},value:y._parse(new te(u,j,u.path,x)),alwaysSet:x in u.data})}}return u.common.async?Promise.resolve().then(async()=>{const y=[];for(const x of g){const j=await x.key,ne=await x.value;y.push({key:j,value:ne,alwaysSet:x.alwaysSet})}return y}).then(y=>z.mergeObjectSync(c,y)):z.mergeObjectSync(c,g)}get shape(){return this._def.shape()}strict(r){return E.errToObj,new N({...this._def,unknownKeys:"strict",...r!==void 0?{errorMap:(i,c)=>{var u,l,f,h;const g=(f=(l=(u=this._def).errorMap)===null||l===void 0?void 0:l.call(u,i,c).message)!==null&&f!==void 0?f:c.defaultError;return i.code==="unrecognized_keys"?{message:(h=E.errToObj(r).message)!==null&&h!==void 0?h:g}:{message:g}}}:{}})}strip(){return new N({...this._def,unknownKeys:"strip"})}passthrough(){return new N({...this._def,unknownKeys:"passthrough"})}extend(r){return new N({...this._def,shape:()=>({...this._def.shape(),...r})})}merge(r){return new N({unknownKeys:r._def.unknownKeys,catchall:r._def.catchall,shape:()=>({...this._def.shape(),...r._def.shape()}),typeName:S.ZodObject})}setKey(r,i){return this.augment({[r]:i})}catchall(r){return new N({...this._def,catchall:r})}pick(r){const i={};return M.objectKeys(r).forEach(c=>{r[c]&&this.shape[c]&&(i[c]=this.shape[c])}),new N({...this._def,shape:()=>i})}omit(r){const i={};return M.objectKeys(this.shape).forEach(c=>{r[c]||(i[c]=this.shape[c])}),new N({...this._def,shape:()=>i})}deepPartial(){return De(this)}partial(r){const i={};return M.objectKeys(this.shape).forEach(c=>{const u=this.shape[c];r&&!r[c]?i[c]=u:i[c]=u.optional()}),new N({...this._def,shape:()=>i})}required(r){const i={};return M.objectKeys(this.shape).forEach(c=>{if(r&&!r[c])i[c]=this.shape[c];else{let l=this.shape[c];for(;l instanceof ee;)l=l._def.innerType;i[c]=l}}),new N({...this._def,shape:()=>i})}keyof(){return hi(M.objectKeys(this.shape))}}N.create=(a,r)=>new N({shape:()=>a,unknownKeys:"strip",catchall:ce.create(),typeName:S.ZodObject,...A(r)});N.strictCreate=(a,r)=>new N({shape:()=>a,unknownKeys:"strict",catchall:ce.create(),typeName:S.ZodObject,...A(r)});N.lazycreate=(a,r)=>new N({shape:a,unknownKeys:"strip",catchall:ce.create(),typeName:S.ZodObject,...A(r)});class ht extends O{_parse(r){const{ctx:i}=this._processInputParams(r),c=this._def.options;function u(l){for(const h of l)if(h.result.status==="valid")return h.result;for(const h of l)if(h.result.status==="dirty")return i.common.issues.push(...h.ctx.common.issues),h.result;const f=l.map(h=>new F(h.ctx.common.issues));return b(i,{code:w.invalid_union,unionErrors:f}),T}if(i.common.async)return Promise.all(c.map(async l=>{const f={...i,common:{...i.common,issues:[]},parent:null};return{result:await l._parseAsync({data:i.data,path:i.path,parent:f}),ctx:f}})).then(u);{let l;const f=[];for(const g of c){const y={...i,common:{...i.common,issues:[]},parent:null},x=g._parseSync({data:i.data,path:i.path,parent:y});if(x.status==="valid")return x;x.status==="dirty"&&!l&&(l={result:x,ctx:y}),y.common.issues.length&&f.push(y.common.issues)}if(l)return i.common.issues.push(...l.ctx.common.issues),l.result;const h=f.map(g=>new F(g));return b(i,{code:w.invalid_union,unionErrors:h}),T}}get options(){return this._def.options}}ht.create=(a,r)=>new ht({options:a,typeName:S.ZodUnion,...A(r)});const ae=a=>a instanceof gt?ae(a.schema):a instanceof J?ae(a.innerType()):a instanceof yt?[a.value]:a instanceof me?a.options:a instanceof vt?M.objectValues(a.enum):a instanceof wt?ae(a._def.innerType):a instanceof dt?[void 0]:a instanceof ft?[null]:a instanceof ee?[void 0,...ae(a.unwrap())]:a instanceof ge?[null,...ae(a.unwrap())]:a instanceof Tn||a instanceof _t?ae(a.unwrap()):a instanceof bt?ae(a._def.innerType):[];class Wt extends O{_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.object)return b(i,{code:w.invalid_type,expected:_.object,received:i.parsedType}),T;const c=this.discriminator,u=i.data[c],l=this.optionsMap.get(u);return l?i.common.async?l._parseAsync({data:i.data,path:i.path,parent:i}):l._parseSync({data:i.data,path:i.path,parent:i}):(b(i,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[c]}),T)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(r,i,c){const u=new Map;for(const l of i){const f=ae(l.shape[r]);if(!f.length)throw new Error(`A discriminator value for key \`${r}\` could not be extracted from all schema options`);for(const h of f){if(u.has(h))throw new Error(`Discriminator property ${String(r)} has duplicate value ${String(h)}`);u.set(h,l)}}return new Wt({typeName:S.ZodDiscriminatedUnion,discriminator:r,options:i,optionsMap:u,...A(c)})}}function Sn(a,r){const i=oe(a),c=oe(r);if(a===r)return{valid:!0,data:a};if(i===_.object&&c===_.object){const u=M.objectKeys(r),l=M.objectKeys(a).filter(h=>u.indexOf(h)!==-1),f={...a,...r};for(const h of l){const g=Sn(a[h],r[h]);if(!g.valid)return{valid:!1};f[h]=g.data}return{valid:!0,data:f}}else if(i===_.array&&c===_.array){if(a.length!==r.length)return{valid:!1};const u=[];for(let l=0;l<a.length;l++){const f=a[l],h=r[l],g=Sn(f,h);if(!g.valid)return{valid:!1};u.push(g.data)}return{valid:!0,data:u}}else return i===_.date&&c===_.date&&+a==+r?{valid:!0,data:a}:{valid:!1}}class pt extends O{_parse(r){const{status:i,ctx:c}=this._processInputParams(r),u=(l,f)=>{if(kn(l)||kn(f))return T;const h=Sn(l.value,f.value);return h.valid?((En(l)||En(f))&&i.dirty(),{status:i.value,value:h.data}):(b(c,{code:w.invalid_intersection_types}),T)};return c.common.async?Promise.all([this._def.left._parseAsync({data:c.data,path:c.path,parent:c}),this._def.right._parseAsync({data:c.data,path:c.path,parent:c})]).then(([l,f])=>u(l,f)):u(this._def.left._parseSync({data:c.data,path:c.path,parent:c}),this._def.right._parseSync({data:c.data,path:c.path,parent:c}))}}pt.create=(a,r,i)=>new pt({left:a,right:r,typeName:S.ZodIntersection,...A(i)});class re extends O{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.array)return b(c,{code:w.invalid_type,expected:_.array,received:c.parsedType}),T;if(c.data.length<this._def.items.length)return b(c,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T;!this._def.rest&&c.data.length>this._def.items.length&&(b(c,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty());const l=[...c.data].map((f,h)=>{const g=this._def.items[h]||this._def.rest;return g?g._parse(new te(c,f,c.path,h)):null}).filter(f=>!!f);return c.common.async?Promise.all(l).then(f=>z.mergeArray(i,f)):z.mergeArray(i,l)}get items(){return this._def.items}rest(r){return new re({...this._def,rest:r})}}re.create=(a,r)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new re({items:a,typeName:S.ZodTuple,rest:null,...A(r)})};class mt extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.object)return b(c,{code:w.invalid_type,expected:_.object,received:c.parsedType}),T;const u=[],l=this._def.keyType,f=this._def.valueType;for(const h in c.data)u.push({key:l._parse(new te(c,h,c.path,h)),value:f._parse(new te(c,c.data[h],c.path,h)),alwaysSet:h in c.data});return c.common.async?z.mergeObjectAsync(i,u):z.mergeObjectSync(i,u)}get element(){return this._def.valueType}static create(r,i,c){return i instanceof O?new mt({keyType:r,valueType:i,typeName:S.ZodRecord,...A(c)}):new mt({keyType:G.create(),valueType:r,typeName:S.ZodRecord,...A(i)})}}class Vt extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.map)return b(c,{code:w.invalid_type,expected:_.map,received:c.parsedType}),T;const u=this._def.keyType,l=this._def.valueType,f=[...c.data.entries()].map(([h,g],y)=>({key:u._parse(new te(c,h,c.path,[y,"key"])),value:l._parse(new te(c,g,c.path,[y,"value"]))}));if(c.common.async){const h=new Map;return Promise.resolve().then(async()=>{for(const g of f){const y=await g.key,x=await g.value;if(y.status==="aborted"||x.status==="aborted")return T;(y.status==="dirty"||x.status==="dirty")&&i.dirty(),h.set(y.value,x.value)}return{status:i.value,value:h}})}else{const h=new Map;for(const g of f){const y=g.key,x=g.value;if(y.status==="aborted"||x.status==="aborted")return T;(y.status==="dirty"||x.status==="dirty")&&i.dirty(),h.set(y.value,x.value)}return{status:i.value,value:h}}}}Vt.create=(a,r,i)=>new Vt({valueType:r,keyType:a,typeName:S.ZodMap,...A(i)});class Ae extends O{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.set)return b(c,{code:w.invalid_type,expected:_.set,received:c.parsedType}),T;const u=this._def;u.minSize!==null&&c.data.size<u.minSize.value&&(b(c,{code:w.too_small,minimum:u.minSize.value,type:"set",inclusive:!0,exact:!1,message:u.minSize.message}),i.dirty()),u.maxSize!==null&&c.data.size>u.maxSize.value&&(b(c,{code:w.too_big,maximum:u.maxSize.value,type:"set",inclusive:!0,exact:!1,message:u.maxSize.message}),i.dirty());const l=this._def.valueType;function f(g){const y=new Set;for(const x of g){if(x.status==="aborted")return T;x.status==="dirty"&&i.dirty(),y.add(x.value)}return{status:i.value,value:y}}const h=[...c.data.values()].map((g,y)=>l._parse(new te(c,g,c.path,y)));return c.common.async?Promise.all(h).then(g=>f(g)):f(h)}min(r,i){return new Ae({...this._def,minSize:{value:r,message:E.toString(i)}})}max(r,i){return new Ae({...this._def,maxSize:{value:r,message:E.toString(i)}})}size(r,i){return this.min(r,i).max(r,i)}nonempty(r){return this.min(1,r)}}Ae.create=(a,r)=>new Ae({valueType:a,minSize:null,maxSize:null,typeName:S.ZodSet,...A(r)});class Ue extends O{constructor(){super(...arguments),this.validate=this.implement}_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.function)return b(i,{code:w.invalid_type,expected:_.function,received:i.parsedType}),T;function c(h,g){return Zt({data:h,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Ut(),Ze].filter(y=>!!y),issueData:{code:w.invalid_arguments,argumentsError:g}})}function u(h,g){return Zt({data:h,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Ut(),Ze].filter(y=>!!y),issueData:{code:w.invalid_return_type,returnTypeError:g}})}const l={errorMap:i.common.contextualErrorMap},f=i.data;if(this._def.returns instanceof Le){const h=this;return V(async function(...g){const y=new F([]),x=await h._def.args.parseAsync(g,l).catch(se=>{throw y.addIssue(c(g,se)),y}),j=await Reflect.apply(f,this,x);return await h._def.returns._def.type.parseAsync(j,l).catch(se=>{throw y.addIssue(u(j,se)),y})})}else{const h=this;return V(function(...g){const y=h._def.args.safeParse(g,l);if(!y.success)throw new F([c(g,y.error)]);const x=Reflect.apply(f,this,y.data),j=h._def.returns.safeParse(x,l);if(!j.success)throw new F([u(x,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...r){return new Ue({...this._def,args:re.create(r).rest(Ee.create())})}returns(r){return new Ue({...this._def,returns:r})}implement(r){return this.parse(r)}strictImplement(r){return this.parse(r)}static create(r,i,c){return new Ue({args:r||re.create([]).rest(Ee.create()),returns:i||Ee.create(),typeName:S.ZodFunction,...A(c)})}}class gt extends O{get schema(){return this._def.getter()}_parse(r){const{ctx:i}=this._processInputParams(r);return this._def.getter()._parse({data:i.data,path:i.path,parent:i})}}gt.create=(a,r)=>new gt({getter:a,typeName:S.ZodLazy,...A(r)});class yt extends O{_parse(r){if(r.data!==this._def.value){const i=this._getOrReturnCtx(r);return b(i,{received:i.data,code:w.invalid_literal,expected:this._def.value}),T}return{status:"valid",value:r.data}}get value(){return this._def.value}}yt.create=(a,r)=>new yt({value:a,typeName:S.ZodLiteral,...A(r)});function hi(a,r){return new me({values:a,typeName:S.ZodEnum,...A(r)})}class me extends O{constructor(){super(...arguments),ot.set(this,void 0)}_parse(r){if(typeof r.data!="string"){const i=this._getOrReturnCtx(r),c=this._def.values;return b(i,{expected:M.joinValues(c),received:i.parsedType,code:w.invalid_type}),T}if(Bt(this,ot)||ui(this,ot,new Set(this._def.values)),!Bt(this,ot).has(r.data)){const i=this._getOrReturnCtx(r),c=this._def.values;return b(i,{received:i.data,code:w.invalid_enum_value,options:c}),T}return V(r.data)}get options(){return this._def.values}get enum(){const r={};for(const i of this._def.values)r[i]=i;return r}get Values(){const r={};for(const i of this._def.values)r[i]=i;return r}get Enum(){const r={};for(const i of this._def.values)r[i]=i;return r}extract(r,i=this._def){return me.create(r,{...this._def,...i})}exclude(r,i=this._def){return me.create(this.options.filter(c=>!r.includes(c)),{...this._def,...i})}}ot=new WeakMap;me.create=hi;class vt extends O{constructor(){super(...arguments),ct.set(this,void 0)}_parse(r){const i=M.getValidEnumValues(this._def.values),c=this._getOrReturnCtx(r);if(c.parsedType!==_.string&&c.parsedType!==_.number){const u=M.objectValues(i);return b(c,{expected:M.joinValues(u),received:c.parsedType,code:w.invalid_type}),T}if(Bt(this,ct)||ui(this,ct,new Set(M.getValidEnumValues(this._def.values))),!Bt(this,ct).has(r.data)){const u=M.objectValues(i);return b(c,{received:c.data,code:w.invalid_enum_value,options:u}),T}return V(r.data)}get enum(){return this._def.values}}ct=new WeakMap;vt.create=(a,r)=>new vt({values:a,typeName:S.ZodNativeEnum,...A(r)});class Le extends O{unwrap(){return this._def.type}_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.promise&&i.common.async===!1)return b(i,{code:w.invalid_type,expected:_.promise,received:i.parsedType}),T;const c=i.parsedType===_.promise?i.data:Promise.resolve(i.data);return V(c.then(u=>this._def.type.parseAsync(u,{path:i.path,errorMap:i.common.contextualErrorMap})))}}Le.create=(a,r)=>new Le({type:a,typeName:S.ZodPromise,...A(r)});class J extends O{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(r){const{status:i,ctx:c}=this._processInputParams(r),u=this._def.effect||null,l={addIssue:f=>{b(c,f),f.fatal?i.abort():i.dirty()},get path(){return c.path}};if(l.addIssue=l.addIssue.bind(l),u.type==="preprocess"){const f=u.transform(c.data,l);if(c.common.async)return Promise.resolve(f).then(async h=>{if(i.value==="aborted")return T;const g=await this._def.schema._parseAsync({data:h,path:c.path,parent:c});return g.status==="aborted"?T:g.status==="dirty"||i.value==="dirty"?Pe(g.value):g});{if(i.value==="aborted")return T;const h=this._def.schema._parseSync({data:f,path:c.path,parent:c});return h.status==="aborted"?T:h.status==="dirty"||i.value==="dirty"?Pe(h.value):h}}if(u.type==="refinement"){const f=h=>{const g=u.refinement(h,l);if(c.common.async)return Promise.resolve(g);if(g instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return h};if(c.common.async===!1){const h=this._def.schema._parseSync({data:c.data,path:c.path,parent:c});return h.status==="aborted"?T:(h.status==="dirty"&&i.dirty(),f(h.value),{status:i.value,value:h.value})}else return this._def.schema._parseAsync({data:c.data,path:c.path,parent:c}).then(h=>h.status==="aborted"?T:(h.status==="dirty"&&i.dirty(),f(h.value).then(()=>({status:i.value,value:h.value}))))}if(u.type==="transform")if(c.common.async===!1){const f=this._def.schema._parseSync({data:c.data,path:c.path,parent:c});if(!Se(f))return f;const h=u.transform(f.value,l);if(h instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:h}}else return this._def.schema._parseAsync({data:c.data,path:c.path,parent:c}).then(f=>Se(f)?Promise.resolve(u.transform(f.value,l)).then(h=>({status:i.value,value:h})):f);M.assertNever(u)}}J.create=(a,r,i)=>new J({schema:a,typeName:S.ZodEffects,effect:r,...A(i)});J.createWithPreprocess=(a,r,i)=>new J({schema:r,effect:{type:"preprocess",transform:a},typeName:S.ZodEffects,...A(i)});class ee extends O{_parse(r){return this._getType(r)===_.undefined?V(void 0):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}ee.create=(a,r)=>new ee({innerType:a,typeName:S.ZodOptional,...A(r)});class ge extends O{_parse(r){return this._getType(r)===_.null?V(null):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}ge.create=(a,r)=>new ge({innerType:a,typeName:S.ZodNullable,...A(r)});class wt extends O{_parse(r){const{ctx:i}=this._processInputParams(r);let c=i.data;return i.parsedType===_.undefined&&(c=this._def.defaultValue()),this._def.innerType._parse({data:c,path:i.path,parent:i})}removeDefault(){return this._def.innerType}}wt.create=(a,r)=>new wt({innerType:a,typeName:S.ZodDefault,defaultValue:typeof r.default=="function"?r.default:()=>r.default,...A(r)});class bt extends O{_parse(r){const{ctx:i}=this._processInputParams(r),c={...i,common:{...i.common,issues:[]}},u=this._def.innerType._parse({data:c.data,path:c.path,parent:{...c}});return ut(u)?u.then(l=>({status:"valid",value:l.status==="valid"?l.value:this._def.catchValue({get error(){return new F(c.common.issues)},input:c.data})})):{status:"valid",value:u.status==="valid"?u.value:this._def.catchValue({get error(){return new F(c.common.issues)},input:c.data})}}removeCatch(){return this._def.innerType}}bt.create=(a,r)=>new bt({innerType:a,typeName:S.ZodCatch,catchValue:typeof r.catch=="function"?r.catch:()=>r.catch,...A(r)});class Ft extends O{_parse(r){if(this._getType(r)!==_.nan){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.nan,received:c.parsedType}),T}return{status:"valid",value:r.data}}}Ft.create=a=>new Ft({typeName:S.ZodNaN,...A(a)});const vd=Symbol("zod_brand");class Tn extends O{_parse(r){const{ctx:i}=this._processInputParams(r),c=i.data;return this._def.type._parse({data:c,path:i.path,parent:i})}unwrap(){return this._def.type}}class xt extends O{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.common.async)return(async()=>{const l=await this._def.in._parseAsync({data:c.data,path:c.path,parent:c});return l.status==="aborted"?T:l.status==="dirty"?(i.dirty(),Pe(l.value)):this._def.out._parseAsync({data:l.value,path:c.path,parent:c})})();{const u=this._def.in._parseSync({data:c.data,path:c.path,parent:c});return u.status==="aborted"?T:u.status==="dirty"?(i.dirty(),{status:"dirty",value:u.value}):this._def.out._parseSync({data:u.value,path:c.path,parent:c})}}static create(r,i){return new xt({in:r,out:i,typeName:S.ZodPipeline})}}class _t extends O{_parse(r){const i=this._def.innerType._parse(r),c=u=>(Se(u)&&(u.value=Object.freeze(u.value)),u);return ut(i)?i.then(u=>c(u)):c(i)}unwrap(){return this._def.innerType}}_t.create=(a,r)=>new _t({innerType:a,typeName:S.ZodReadonly,...A(r)});function pi(a,r={},i){return a?Be.create().superRefine((c,u)=>{var l,f;if(!a(c)){const h=typeof r=="function"?r(c):typeof r=="string"?{message:r}:r,g=(f=(l=h.fatal)!==null&&l!==void 0?l:i)!==null&&f!==void 0?f:!0,y=typeof h=="string"?{message:h}:h;u.addIssue({code:"custom",...y,fatal:g})}}):Be.create()}const wd={object:N.lazycreate};var S;(function(a){a.ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly"})(S||(S={}));const bd=(a,r={message:`Input not instance of ${a.name}`})=>pi(i=>i instanceof a,r),mi=G.create,gi=he.create,_d=Ft.create,xd=pe.create,yi=lt.create,kd=Te.create,Ed=Lt.create,Sd=dt.create,Td=ft.create,Ad=Be.create,Od=Ee.create,Id=ce.create,Md=zt.create,$d=K.create,Rd=N.create,Cd=N.strictCreate,Nd=ht.create,jd=Wt.create,Dd=pt.create,Pd=re.create,Ud=mt.create,Zd=Vt.create,Bd=Ae.create,Ld=Ue.create,zd=gt.create,Vd=yt.create,Fd=me.create,Wd=vt.create,Hd=Le.create,ni=J.create,qd=ee.create,Gd=ge.create,Kd=J.createWithPreprocess,Jd=xt.create,Yd=()=>mi().optional(),Qd=()=>gi().optional(),Xd=()=>yi().optional(),ef={string:a=>G.create({...a,coerce:!0}),number:a=>he.create({...a,coerce:!0}),boolean:a=>lt.create({...a,coerce:!0}),bigint:a=>pe.create({...a,coerce:!0}),date:a=>Te.create({...a,coerce:!0})},tf=T;var D=Object.freeze({__proto__:null,defaultErrorMap:Ze,setErrorMap:Kl,getErrorMap:Ut,makeIssue:Zt,EMPTY_PATH:Jl,addIssueToContext:b,ParseStatus:z,INVALID:T,DIRTY:Pe,OK:V,isAborted:kn,isDirty:En,isValid:Se,isAsync:ut,get util(){return M},get objectUtil(){return xn},ZodParsedType:_,getParsedType:oe,ZodType:O,datetimeRegex:fi,ZodString:G,ZodNumber:he,ZodBigInt:pe,ZodBoolean:lt,ZodDate:Te,ZodSymbol:Lt,ZodUndefined:dt,ZodNull:ft,ZodAny:Be,ZodUnknown:Ee,ZodNever:ce,ZodVoid:zt,ZodArray:K,ZodObject:N,ZodUnion:ht,ZodDiscriminatedUnion:Wt,ZodIntersection:pt,ZodTuple:re,ZodRecord:mt,ZodMap:Vt,ZodSet:Ae,ZodFunction:Ue,ZodLazy:gt,ZodLiteral:yt,ZodEnum:me,ZodNativeEnum:vt,ZodPromise:Le,ZodEffects:J,ZodTransformer:J,ZodOptional:ee,ZodNullable:ge,ZodDefault:wt,ZodCatch:bt,ZodNaN:Ft,BRAND:vd,ZodBranded:Tn,ZodPipeline:xt,ZodReadonly:_t,custom:pi,Schema:O,ZodSchema:O,late:wd,get ZodFirstPartyTypeKind(){return S},coerce:ef,any:Ad,array:$d,bigint:xd,boolean:yi,date:kd,discriminatedUnion:jd,effect:ni,enum:Fd,function:Ld,instanceof:bd,intersection:Dd,lazy:zd,literal:Vd,map:Zd,nan:_d,nativeEnum:Wd,never:Id,null:Td,nullable:Gd,number:gi,object:Rd,oboolean:Xd,onumber:Qd,optional:qd,ostring:Yd,pipeline:Jd,preprocess:Kd,promise:Hd,record:Ud,set:Bd,strictObject:Cd,string:mi,symbol:Ed,transformer:ni,tuple:Pd,undefined:Sd,union:Nd,unknown:Od,void:Md,NEVER:tf,ZodIssueCode:w,quotelessJson:Gl,ZodError:F}),An=(a=>(a.TEXT="text",a.THREAD="thread",a.REACTION="reaction",a))(An||{});const ye=q.getInstance(),rf=["id","targetMessageId","type","message","username","address","timestamp","signature","index","chatTopic","userTopic","additionalProps"],On=D.object({id:D.string(),targetMessageId:D.string().optional(),type:D.nativeEnum(An),message:D.string(),username:D.string(),address:D.string(),timestamp:D.number(),signature:D.string(),index:D.number(),chatTopic:D.string(),userTopic:D.string(),additionalProps:D.record(D.any()).optional()}).refine(a=>!a.additionalProps||Object.keys(a.additionalProps).length===0?!0:cf(a.additionalProps).isValid,{message:"Invalid additional properties in message"}),nf=D.object({reference:D.string(),timestamp:D.number()}),sf=D.object({message:On,messageStateRefs:D.array(nf).nullable()});function vi(a){const r=sf.safeParse(a);return r.success?wi(a.message)?!0:(ye.warn("Invalid main message signature"),!1):(ye.warn("GSOC message validation failed:",r.error.format()),!1)}function af(a){if(!Array.isArray(a))return ye.warn("Message state must be an array"),!1;for(const r of a)if(!of(r))return ye.warn("Invalid message in message state:",r.id),!1;return!0}function of(a){const r=On.safeParse(a);return r.success?wi(a)?!0:(ye.warn("Invalid message signature"),!1):(ye.warn("Message data validation failed:",r.error.format()),!1)}function wi(a){try{const r={username:a.username,address:a.address,timestamp:a.timestamp,message:a.message},i=new TextEncoder,c=L.concatBytes(i.encode(`Ethereum Signed Message:
11
- 32`),L.keccak256(i.encode(JSON.stringify(r))));if(new I.Signature(a.signature).isValid(c,a.address))throw new Error("Signature verification failed!");return!0}catch(r){return ye.warn("Error in validateUserSignature",r),!1}}function cf(a){const r=[];if(a==null)return{isValid:!0,errors:[]};if(typeof a!="object"||Array.isArray(a))return r.push("Additional properties must be a plain object"),{isValid:!1,errors:r};for(const g of Object.keys(a))rf.includes(g)&&r.push(`Property '${g}' is reserved and cannot be overridden`);const i=JSON.stringify(a),c=new TextEncoder().encode(i).length,u=1*1024;c>u&&r.push(`Additional properties too large: ${c} bytes (max: ${u} bytes)`);const l=5;function f(g,y=0){if(y>l)return!1;if(typeof g=="object"&&g!==null&&!Array.isArray(g)){for(const x of Object.values(g))if(!f(x,y+1))return!1}return!0}f(a)||r.push(`Additional properties nested too deeply (max depth: ${l})`);for(const[g,y]of Object.entries(a))if(g.length>100&&r.push(`Property key '${g}' too long (max: 100 characters)`),typeof y=="string"&&y.length>1e3&&r.push(`Property '${g}' value too long (max: 1000 characters)`),typeof y=="string"){const x=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/data:text\/html/gi,/vbscript:/gi,/on\w+\s*=/gi];for(const j of x)if(j.test(y)){r.push(`Property '${g}' contains potentially dangerous content`);break}}const h=20;return Object.keys(a).length>h&&r.push(`Too many additional properties: ${Object.keys(a).length} (max: ${h})`),{isValid:r.length===0,errors:r}}function uf(a){const r=On.safeParse(a);if(!r.success){const i=r.error.issues.map(c=>c.path.length>0?`${c.path.join(".")}: ${c.message}`:c.message);return ye.warn("Message validation failed:",r.error.format()),{isValid:!1,errors:i}}return{isValid:!0,errors:[]}}const H={LOADING_INIT:"loadingInit",LOADING_PREVIOUS_MESSAGES:"loadingPreviousMessages",MESSAGE_RECEIVED:"messageReceived",MESSAGE_REQUEST_INITIATED:"messageRequestInitiated",MESSAGE_REQUEST_UPLOADED:"messageRequestUploaded",MESSAGE_REQUEST_ERROR:"messageRequestError",CRITICAL_ERROR:"criticalError"};class lf{constructor(r,i){this.utils=r,this.emitter=i,this.logger=q.getInstance(),this.errorHandler=X.getInstance(),this.processedRefs=new Set,this.refRetryCount=new Map,this.bannedRefs=new Set,this.latestStatefulMessage=null,this.MAX_RETRIES=3,this.RETRY_DELAY=1e3}async init(){try{const{data:r,index:i}=await this.utils.fetchLatestChatMessage();this.latestStatefulMessage=r;try{await this.initMessageState(r)}catch(c){this.errorHandler.handleError(c,"SwarmHistory.initMessageState")}return i}catch(r){return this.errorHandler.handleError(r,"SwarmHistory.init"),I.FeedIndex.fromBigInt(0n)}}async initMessageState(r){try{if(!vi(r)){this.logger.warn("Invalid GSOC message during message state initialization");return}if(!r.messageStateRefs||r.messageStateRefs.length===0){this.logger.debug("No message state refs to initialize");return}const i=this.findLatestRef(r.messageStateRefs);if(!i){this.logger.warn("No valid latest reference found");return}this.logger.debug("Initializing message state with latest ref:",i.reference),await this.processMessageRefWithRetry(i.reference)}catch(i){if(this.utils.isNotFoundError(i)){this.logger.debug("No latest GSOC message found for message state initialization");return}this.errorHandler.handleError(i,"SwarmHistory.init")}}async fetchPreviousMessageState(){let r=this.latestStatefulMessage;if(!r){const{data:c}=await this.utils.fetchLatestChatMessage();r=c,this.latestStatefulMessage=c}if(!r.messageStateRefs||r.messageStateRefs.length===0){this.logger.debug("No message state refs to fetch");return}const i=[...r.messageStateRefs].sort((c,u)=>c.timestamp-u.timestamp);for(const c of i)!this.processedRefs.has(c.reference)&&!this.bannedRefs.has(c.reference)&&(this.logger.debug("Fetching previous message ref:",c.reference),await this.processMessageRefWithRetry(c.reference))}findLatestRef(r){return r.length===0?null:r.reduce((i,c)=>c.timestamp>i.timestamp?c:i)}async processMessageRefWithRetry(r){if(!(this.processedRefs.has(r)||this.bannedRefs.has(r)))try{await this.processMessageRef(r)}catch(i){await this.handleRefError(r,i)}}async processMessageRef(r){const i=await this.utils.downloadObjectFromBee(r);if(!af(i))throw new Error(`Invalid message state for ref: ${r}`);this.processedRefs.add(r),this.refRetryCount.delete(r);for(const u of i)this.emitter.emit(H.MESSAGE_RECEIVED,u)}async handleRefError(r,i){const c=this.refRetryCount.get(r)||0,u=c+1;if(this.logger.warn(`Error processing ref ${r} (attempt ${u}/${this.MAX_RETRIES}):`,i),u>=this.MAX_RETRIES)this.bannedRefs.add(r),this.refRetryCount.delete(r),this.logger.error(`Ref ${r} has been banned after ${this.MAX_RETRIES} failed attempts`),this.errorHandler.handleError(i,"SwarmHistory.processMessageRef");else{this.refRetryCount.set(r,u);const l=this.RETRY_DELAY*Math.pow(2,c);this.logger.debug(`Retrying ref ${r} after ${l}ms delay`),await Hl(l),await this.processMessageRefWithRetry(r)}}hasPreviousMessages(){return!!this.latestStatefulMessage&&!!this.latestStatefulMessage.messageStateRefs&&this.latestStatefulMessage.messageStateRefs.length>1}cleanup(){this.processedRefs.clear(),this.refRetryCount.clear(),this.bannedRefs.clear(),this.latestStatefulMessage=null}}class df{constructor(r,i){this.userDetails=r,this.swarmSettings=i,this.depth=26,this.errorHandler=X.getInstance()}generateUserOwnedFeedId(r,i){return`${r}_EthercastChat_${i}`}isNotFoundError(r){return r.stack.includes("404")||r.message.includes("Not Found")||r.message.includes("404")||r.code===404}async writeOwnFeedDataByIndex(r,i){const{enveloped:c,stamp:u}=this.swarmSettings;if(!c)await this.writeOwnFeedDataByIndexOwned(r,i);else if(u)await this.writeOwnFeedDataByIndexEnvelope(r,i);else throw new Error("Enveloped mode is enabled, but stamp is not provided")}async writeOwnFeedDataByIndexOwned(r,i){const{bee:c,stamp:u,chatTopic:l}=this.swarmSettings,{privateKey:f,ownAddress:h}=this.userDetails,g=this.generateUserOwnedFeedId(l,h),y=I.Topic.fromString(g);await c.makeFeedWriter(y,new I.PrivateKey(f)).uploadPayload(u,JSON.stringify(i),{index:r})}async writeOwnFeedDataByIndexEnvelope(r,i){const{bee:c,stamp:u,chatTopic:l}=this.swarmSettings,{privateKey:f,ownAddress:h}=this.userDetails,g=new I.PrivateKey(f),y=I.Stamper.fromBlank(f,u,this.depth),x=this.generateUserOwnedFeedId(l,h),j=I.Topic.fromString(x),ne=ai(j,r),se=ei(i),ze=ti(se,ne,g),Oe={hash:()=>ze.address.toUint8Array()},Ve=y.stamp(Oe),{upload:Ht}=c.makeSOCWriter(g),Fe=I.Bytes.fromUtf8(i);return(await Ht(Ve,ne,Fe.toUint8Array())).reference.toHex()}orderMessages(r){return r.sort((i,c)=>i.timestamp-c.timestamp)}async downloadObjectFromBee(r){try{const{bee:i}=this.swarmSettings,c=await i.downloadData(r);return c?c.toJSON():null}catch(i){return this.errorHandler.handleError(i,"Utils.downloadObjectFromBee"),null}}async uploadObjectToBee(r){const{enveloped:i,stamp:c}=this.swarmSettings;if(i){if(c)return this.uploadObjectToBeeEnvelope(r);throw new Error("Enveloped mode is enabled, but stamp is not provided")}else return this.uploadObjectToBeeOwn(r)}async uploadObjectToBeeOwn(r){try{const{bee:i,stamp:c}=this.swarmSettings;return(await i.uploadData(c,JSON.stringify(r),{redundancyLevel:4})).reference.toString()}catch(i){return this.errorHandler.handleError(i,"Utils.uploadObjectToBee"),null}}async uploadObjectToBeeEnvelope(r){try{const{bee:i,stamp:c}=this.swarmSettings,{privateKey:u}=this.userDetails,l=I.Stamper.fromBlank(u,c,this.depth),f=I.Bytes.fromUtf8(JSON.stringify(r)),h=new Ul(async y=>{await i.uploadChunk(l.stamp(y),y.build())});await h.append(f.toUint8Array());const g=await h.finalize();return L.uint8ArrayToHex(g.hash())}catch(i){return this.errorHandler.handleError(i,"Utils.uploadObjectToBee"),null}}async getOwnLatestFeedIndex(){try{const{bee:r,chatTopic:i,feedReadTimeout:c}=this.swarmSettings,{ownAddress:u}=this.userDetails,l=this.generateUserOwnedFeedId(i,u),f=I.Topic.fromString(l),g=await r.makeFeedReader(f,u,{timeout:c}).downloadPayload(),y=Number(g.feedIndex.toBigInt()),x=y+1;return{latestIndex:y,nextIndex:x}}catch(r){if(this.isNotFoundError(r))return{latestIndex:-1,nextIndex:0};throw r}}async fetchLatestChatMessage(){const{bee:r,chatTopic:i,chatAddress:c,feedReadTimeout:u}=this.swarmSettings,f=await r.makeFeedReader(I.Topic.fromString(i),oi(c),{timeout:u}).downloadPayload();return{data:f.payload.toJSON(),index:f.feedIndex}}async sendMessageToGsoc(r){const{enveloped:i,stamp:c}=this.swarmSettings;if(!i)await this.sendMessageToGsocOwn(r);else if(c)await this.sendMessageToGsocEnvelope(r);else throw new Error("Enveloped mode is enabled, but stamp is not provided")}async rawSocDownload(r,i){const{beeUrl:c,socReadTimeout:u}=this.swarmSettings,l=new AbortController,f=setTimeout(()=>l.abort(),u);try{const h=await fetch(`${c}/soc/${r}/${i}`,{headers:{"swarm-chunk-retrieval-timeout":"2000ms"},signal:l.signal});if(!h.ok){const g=new Error(`Failed to fetch: ${r}/${i} [${h.status}]`);throw g.status=h.status,g}return await h.text()}catch(h){throw h.name==="AbortError"?new Error(`Request timeout: ${r}/${i}`):h}finally{clearTimeout(f)}}async sendMessageToGsocOwn(r){const{bee:i,stamp:c,gsocTopic:u,gsocResourceId:l,gsocWriteTimeout:f}=this.swarmSettings,h=new I.PrivateKey(l),g=I.Identifier.fromString(u),y=I.Bytes.fromUtf8(r),{upload:x}=i.makeSOCWriter(h,{timeout:f});await x(c,g,y.toUint8Array())}async sendMessageToGsocEnvelope(r){const{bee:i,stamp:c,gsocTopic:u,gsocResourceId:l,gsocWriteTimeout:f}=this.swarmSettings,{privateKey:h}=this.userDetails,g=I.Stamper.fromBlank(h,c,this.depth),y=new I.PrivateKey(l),x=I.Identifier.fromString(u),j=I.Bytes.fromUtf8(r),ne=ei(j.toUint8Array()),se=ti(ne,x,y),ze={hash:()=>se.address.toUint8Array()},Oe=g.stamp(ze),{upload:Ve}=i.makeSOCWriter(y,{timeout:f});await Ve(Oe,x,j.toUint8Array())}}class ff{constructor(r,i){this.fallbackTransport=null,this.logger=q.getInstance(),this.errorHandler=X.getInstance(),this.gsocIndex=null;const c=new I.PrivateKey(oi(r.user.privateKey));this.userDetails={privateKey:r.user.privateKey,ownAddress:c.publicKey().address().toString(),nickname:r.user.nickname,ownIndex:-1},this.swarmSettings={bee:new I.Bee(r.infra.beeUrl),beeUrl:r.infra.beeUrl,stamp:r.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:r.infra.enveloped,gsocTopic:r.infra.gsocTopic,gsocResourceId:r.infra.gsocResourceId,chatTopic:r.infra.chatTopic,chatAddress:r.infra.chatAddress,feedReadTimeout:r.infra.feedReadTimeout||12e3,gsocWriteTimeout:r.infra.gsocWriteTimeout||2e3,socReadTimeout:r.infra.socReadTimeout||5e3},this.emitter=new ql,this.utils=new df(this.userDetails,this.swarmSettings),this.history=new lf(this.utils,this.emitter);const u=r.infra.pollingInterval||1e3;i?(this.transport=i,r.infra.enableFallbackPolling&&(this.logger.info(`Fallback polling enabled with interval: ${u}ms`),this.fallbackTransport=this.createDefaultPollingTransport(u),this.fallbackTransport.onMessage(l=>{this.emitter.emit(H.MESSAGE_RECEIVED,l)}))):this.transport=this.createDefaultPollingTransport(u),this.transport.onMessage(l=>{this.emitter.emit(H.MESSAGE_RECEIVED,l)})}createDefaultPollingTransport(r){return new si({fetchMessage:async()=>{try{if(!this.gsocIndex)return null;const i=I.Topic.fromString(this.swarmSettings.chatTopic),c=ai(i,this.gsocIndex),u=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,c.toString()),l=JSON.parse(u);return vi(l)?(this.gsocIndex=this.gsocIndex.next(),l.message):(this.logger.warn("Invalid GSOC message during fetching"),null)}catch(i){if(this.utils.isNotFoundError(i))return null;throw i}},pollingInterval:r||1e3})}async start(){await this.init(),await this.transport.start(),this.fallbackTransport&&await this.fallbackTransport.start()}async stop(){this.emitter.cleanAll(),this.history.cleanup(),await this.transport.stop(),this.fallbackTransport&&await this.fallbackTransport.stop()}getEmitter(){return this.emitter}orderMessages(r){return this.utils.orderMessages(r)}async sendMessage(r,i,c,u,l){const f=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,h={id:u||Dl(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(r),timestamp:Date.now(),index:f,type:i,targetMessageId:c,message:r,additionalProps:l},g=uf(h);if(!g.isValid){const y=`Invalid message: ${g.errors.join(", ")}`;throw this.logger.error(y),new Error(y)}try{this.emitter.emit(H.MESSAGE_REQUEST_INITIATED,h),await this.utils.writeOwnFeedDataByIndex(f,JSON.stringify(h)),this.userDetails.ownIndex=f,this.emitter.emit(H.MESSAGE_REQUEST_UPLOADED,h),await this.broadcastUserMessage(h)}catch(y){this.emitter.emit(H.MESSAGE_REQUEST_ERROR,h),this.errorHandler.handleError(y,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(H.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(H.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(r){this.sendMessage(r.message,r.type,r.targetMessageId,r.id,r.additionalProps)}async retryBroadcastUserMessage(r){await this.broadcastUserMessage(r)}async init(){try{this.emitter.emit(H.LOADING_INIT,!0);const[r,i]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(r.status==="rejected")throw r.reason;i.status==="fulfilled"&&(this.gsocIndex=i.value),this.emitter.emit(H.LOADING_INIT,!1)}catch(r){this.errorHandler.handleError(r,"Chat.initSelfState"),this.emitter.emit(H.CRITICAL_ERROR,r)}}async initOwnIndex(){const{latestIndex:c}=await _n(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=c}async broadcastUserMessage(r){try{return _n(()=>this.utils.sendMessageToGsoc(JSON.stringify(r)))}catch(i){this.errorHandler.handleError(i,"Chat.broadcastUserMessage")}}getSignature(r){const{ownAddress:i,privateKey:c,nickname:u}=this.userDetails,l=new I.EthAddress(i).toString(),f=new I.PrivateKey(c);if(f.publicKey().address().toString()!==l)throw new Error("The provided address does not match the address derived from the private key");const g=Date.now();return f.sign(JSON.stringify({username:u,address:l,message:r,timestamp:g})).toHex()}}exports.EVENTS=H;exports.MessageType=An;exports.PollingTransport=si;exports.SwarmChat=ff;
10
+ `),e=e.replace(/(\w+)\((.+)\)/g,(t,n,s)=>`${n}(${s.replaceAll(",","&comma;")})`),e=e.replace(/(,)(\s+})/g,"$2"),e=e.replace(/\.\.\..+?,/g,""),e=e.replace(/({\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/(,\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/:(.+)\?(.+):/g,(t,n,s)=>`: (${n.trim()} && ${s.trim()}) ||`),e=e.replace(/([a-zA-Z0-9]+)( ?: ?{)/g,'"$1"$2'),e=e.replace(/([a-zA-Z0-9]+) ?: ?(.+?)(,|\n|})/g,(t,n,s,o)=>`"${n}":"${s.trim()}"${o}`),e=e.replace(/("'|'")/g,'"'),e=e.replaceAll("&comma;",","),JSON.parse(e)}const de=[1e3,1e6,1e9,1e12,1e15,1e18,1e21,1e24,1e27,1e30,1e9,1e16,1e18,1e18,1e18,1e33],Zc=["thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion","gwei","bzz","btc","eth","dai","decillion"],ws=["K","M","B","T","Qa","Qi","Sx","Sp","O","N","gwei","bzz","eth","btc","dai","D"];function Bc(e,t,n){let s=e.length-t;if(s<=0)return"0."+"0".repeat(-s)+e+(n?" "+n:"");let o=e.substring(0,s),d=e.substring(s);return o===""&&(o="0"),o+"."+d+(n?" "+n:"")}function Lc(e,t){const n=(t==null?void 0:t.longForm)??!1,s=t!=null&&t.unit?` ${t.unit}`:"",o=n?Zc:ws,d=(t==null?void 0:t.precision)??1;if(e<de[0])return`${e}${s}`;for(let p=0;p<de.length-1;p++)if(e<de[p+1])return`${(e/de[p]).toFixed(d)}${n?" ":""}${o[p]}${s}`;return`${(e/de[de.length-1]).toFixed(d)}${n?" ":""}${o[de.length-1]}${s}`}function dr(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeNumber got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim(),s=ws.findIndex(o=>o.toLowerCase()===n.toLowerCase());return s===-1?t:t*de[s]}function fr(e,t,n){return e<t?t:e>n?n:e}function zc(e,t,n){const s=e+t;return s>n?n:s}function Vc(e,t,n){const s=e-t;return s<n?n:s}function Fc(e,t){return t(e),e}function Wc(e,t){e&&t(e)}function Hc(e,t){const n=Object.keys(t);for(const s of n)Array.isArray(t[s])&&Array.isArray(e[s])&&At(e[s],t[s])}function qc(e){return e.splice(0,e.length),e}function Gc(e){for(const t of Object.keys(e))(Rn(e[t])||Array.isArray(e[t])&&e[t].every(n=>n==null))&&delete e[t];return e}function Kc(e){for(const t of Object.entries(e))(t[1]===null||t[1]===void 0||W(t[1])&&Et(t[1]))&&delete e[t[0]];return e}function Jc(e,t){const n={};for(const[s,o]of Object.entries(e))t(s)&&(n[s]=o);return n}function Yc(e,t){const n={};for(const[s,o]of Object.entries(e))t(o)&&(n[s]=o);return n}function Qc(e,t){const n={};for(const s of Object.entries(e))n[s[0]]=t(s[1]);return n}function Xc(e,t){const n=[];let s=0;for(const o of e)n.push(t(o,s++));return n}async function eu(e,t){try{return await e()}catch{throw t}}function tu(e,t,n){n!=null&&(e[t]=n)}function ru(e,t,n,s){const o=ve(n,s);o!=null&&we(e,t,o)}function nu(e){const t={};for(const[n,s]of Object.entries(e))t[s]=n;return t}function su(e){const t=Object.keys(e),n=t.map(v=>e[v].length),s=n.reduce((v,m)=>v*=m);let o=1;const d=[1];for(let v=0;v<n.length-1;v++)o*=n[v],d.push(o);const p=[];for(let v=0;v<s;v++){const m={};for(let k=0;k<t.length;k++){const $=e[t[k]],U=Math.floor(v/d[k])%$.length;m[t[k]]=$[U]}p.push(m)}return p}function iu(e){return Object.values(e).filter(t=>t).length}function au(e,t,n){return e+(n?"["+t+"]":(e.length?".":"")+t)}function Rt(e,t,n,s,o){if(!ue(t))return t;for(const[d,p]of Object.entries(t)){const v=au(n,d,s);Array.isArray(p)?o?Rt(e,p,v,!0,o):e[v]=p.map(m=>Rt(Array.isArray(m)?[]:{},m,"",!1,o)):ue(p)?Rt(e,p,v,!1,o):e[v]=p}return e}function ou(e,t=!1,n){return Rt({},e,n||"",!1,t)}function bs(e){if(!ue(e))return e;const t=Array.isArray(e)?[]:{};for(const[n,s]of Object.entries(e))Array.isArray(s)?we(t,n,s.map(o=>bs(o))):we(t,n,s);return t}function cu(e,t,n){return t[e]?t[e]:n}function _s(e,t){const n={};for(const s of e){const o=t(s);n[o]=s}return n}function uu(e,t){const n={};for(const s of e){const o=t(s);n[o]||(n[o]=[]),n[o].push(s)}return n}function lu(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function xs(e,t){const n=Math.ceil(e.length/t),s=[];for(let o=0;o<e.length;o+=n)s.push(e.slice(o,o+n));return s}function ks(e,t){const n=[],s=Math.ceil(e.length/t);for(let o=0;o<s;o++)n.push(e.slice(o*t,o*t+t));return n}function du(e,t){const n=Math.ceil(e.length/t);return ks(e,n)}function fu(e,t){return Object.values(_s(e,t))}function hu(e,t,n,s,o){const d=t?e.map(t):e,p={};for(const m of d)p[m]=(p[m]||0)+1;const v=s?Es(p,o?(m,k)=>m[1]-k[1]:(m,k)=>k[1]-m[1]):p;return n?Object.keys(v):v}function Es(e,t){return Object.fromEntries(Object.entries(e).sort(t))}function pu(e){const t=[],n=Object.keys(e),s=e[n[0]].length;for(let o=0;o<s;o++){const d={};for(const p of n)d[p]=e[p][o];t.push(d)}return t}function mu(e,t,n=1){for(const s of e)s[t]+=n}function gu(e,t,n){for(const s of e)s[t]=n}function hr(e,t){const n=[];let s=[];return e.forEach((o,d)=>{(d===0||!t(o,e[d-1]))&&(s=[],n.push(s)),s.push(o)}),n}function yu(){return{map:new Map,keys:[]}}function vu(){return{map:new Map,keys:[]}}function Ss(e,t,n,s=100){if(e.map.has(t)){const o=e.keys.indexOf(t);e.keys.splice(o,1)}if(e.map.set(t,n),e.keys.push(t),e.keys.length>s){const o=e.keys.shift();o&&e.map.delete(o)}}function wu(e,t,n,s=100){if(e.map.has(t)){const o=e.keys.indexOf(t);e.keys.splice(o,1)}if(e.map.set(t,n),e.keys.unshift(t),e.keys.length>s){const o=e.keys.shift();o&&e.map.delete(o)}}function bu(e,t,n,s,o=100){Ss(e,t,{validUntil:Date.now()+s,data:n},o)}function _u(e,t){const n=e.map.get(t);return n&&n.validUntil>Date.now()?n.data:null}class fe{constructor(t){this.value=t}static of(t){return new fe(t)}static empty(){return new fe(null)}map(t){return new fe(this.value!==null&&this.value!==void 0?t(this.value):null)}mapAsync(t){return this.value!==null&&this.value!==void 0?t(this.value).then(n=>fe.of(n)):Promise.resolve(fe.empty())}ifPresent(t){return this.value!==null&&this.value!==void 0&&t(this.value),this}ifPresentAsync(t){return this.value!==null&&this.value!==void 0?t(this.value).then(()=>this):Promise.resolve(this)}ifAbsent(t){return(this.value===null||this.value===void 0)&&t(),this}ifAbsentAsync(t){return this.value===null||this.value===void 0?t().then(()=>this):Promise.resolve(this)}getOrFallback(t){return this.value??t()}getOrFallbackAsync(t){return this.value!==null&&this.value!==void 0?Promise.resolve(this.value):t()}getOrThrow(){if(this.value===null||this.value===void 0)throw Error("Optional.value is empty");return this.value}}a.Optional=fe;class xu{constructor(t){this.supplier=t,this.value=null}get(){return this.value||(this.value=this.supplier()),this.value}}a.Lazy=xu;class ku{constructor(t){this.supplier=t,this.value=null}async get(){return this.value||(this.value=await this.supplier()),this.value}}a.AsyncLazy=ku;function Eu(e){return()=>e.forEach(t=>t())}function Su(e,t){return e.reduce((n,s)=>t(n)>t(s)?n:s)}function Tu(e,t){const n=e.find(s=>s instanceof t);return fe.of(n)}function Au(e,t){return e.filter(n=>n instanceof t)}function Ou(e,t){const n=[],s=Math.max(e.length,t.length);for(let o=0;o<s;o++)e[o]&&n.push(e[o]),t[o]&&n.push(t[o]);return n}function Iu(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}class Mu{constructor(t){this.value=t,this.children=[]}}function $u(e,t,n,s,o=!1){const d=new Map,p=[];e.forEach(m=>{const k=new Mu(m);d.set(m[t],k)}),e.forEach(m=>{const k=d.get(m[t]);if(!k)return;const $=m[n];if($){const U=d.get($);U&&U.children.push(k)}else p.push(k)});const v=m=>{m.children.sort((k,$)=>{const U=k.value[s],je=$.value[s];return o?je-U:U-je}),m.children.forEach(v)};return p.forEach(v),p}function Ts(e,t){if(Math.log2(e.length)%1!==0)throw new Error("Array length must be a power of 2");let n=[...e];for(;n.length>1;){const s=[];for(let o=0;o<n.length;o+=2){const d=n[o+1];s.push(t(n[o],d))}n=s}return n[0]}function Re(...e){const t=e.reduce((o,d)=>o+d.length,0),n=new Uint8Array(t);let s=0;return e.forEach(o=>{n.set(o,s),s+=o.length}),n}function As(e){return e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}function Os(e){return e[0]===255&&e[1]===216}function Is(e){return e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function Ru(e){return As(e)||Os(e)||Is(e)}function Cu(e){return new Uint8Array([e])}function Nu(e){return e[0]}function ju(e,t){const n=new ArrayBuffer(2);return new DataView(n).setUint16(0,e,t==="LE"),new Uint8Array(n)}function Du(e,t){return new DataView(e.buffer).getUint16(e.byteOffset,t==="LE")}function Pu(e,t){const n=new ArrayBuffer(4);return new DataView(n).setUint32(0,e,t==="LE"),new Uint8Array(n)}function Uu(e,t){return new DataView(e.buffer).getUint32(e.byteOffset,t==="LE")}function pr(e,t){const n=new ArrayBuffer(8);return new DataView(n).setBigUint64(0,BigInt(e),t==="LE"),new Uint8Array(n)}function Zu(e,t){return new DataView(e.buffer).getBigUint64(e.byteOffset,t==="LE")}function Ce(e,t){const n=new Uint8Array(32);let s=e;if(t==="LE"){for(let o=0;o<32;o++)n[o]=Number(s&0xffn),s>>=8n;return n}for(let o=31;o>=0;o--)n[o]=Number(s&0xffn),s>>=8n;return n}function Ne(e,t){let n=0n;if(t==="LE"){for(let s=31;s>=0;s--)n=n<<8n|BigInt(e[s]);return n}for(let s=0;s<32;s++)n=n<<8n|BigInt(e[s]);return n}function Bu(e,t){const n=[];let s=0;for(const o of t)n.push(e.subarray(s,s+o)),s+=o;return n}function mr(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.subarray(s,s+t));return n}const Ms=[0,1,0,32898,2147483648,32906,2147483648,2147516416,0,32907,0,2147483649,2147483648,2147516545,2147483648,32777,0,138,0,136,0,2147516425,0,2147483658,0,2147516555,2147483648,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,0,32778,2147483648,2147483658,2147483648,2147516545,2147483648,32896,0,2147483649,2147483648,2147516424];function Lu(e){for(let t=0;t<24;t++){const n=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],d=e[3]^e[13]^e[23]^e[33]^e[43],p=e[4]^e[14]^e[24]^e[34]^e[44],v=e[5]^e[15]^e[25]^e[35]^e[45],m=e[6]^e[16]^e[26]^e[36]^e[46],k=e[7]^e[17]^e[27]^e[37]^e[47],$=e[8]^e[18]^e[28]^e[38]^e[48],U=e[9]^e[19]^e[29]^e[39]^e[49],je=o<<1|d>>>31,kl=d<<1|o>>>31,Ye=$^je,Qe=U^kl,El=p<<1|v>>>31,Sl=v<<1|p>>>31,Xe=n^El,et=s^Sl,Tl=m<<1|k>>>31,Al=k<<1|m>>>31,tt=o^Tl,rt=d^Al,Ol=$<<1|U>>>31,Il=U<<1|$>>>31,nt=p^Ol,st=v^Il,Ml=n<<1|s>>>31,$l=s<<1|n>>>31,it=m^Ml,at=k^$l;e[0]^=Ye,e[1]^=Qe,e[2]^=Xe,e[3]^=et,e[4]^=tt,e[5]^=rt,e[6]^=nt,e[7]^=st,e[8]^=it,e[9]^=at,e[10]^=Ye,e[11]^=Qe,e[12]^=Xe,e[13]^=et,e[14]^=tt,e[15]^=rt,e[16]^=nt,e[17]^=st,e[18]^=it,e[19]^=at,e[20]^=Ye,e[21]^=Qe,e[22]^=Xe,e[23]^=et,e[24]^=tt,e[25]^=rt,e[26]^=nt,e[27]^=st,e[28]^=it,e[29]^=at,e[30]^=Ye,e[31]^=Qe,e[32]^=Xe,e[33]^=et,e[34]^=tt,e[35]^=rt,e[36]^=nt,e[37]^=st,e[38]^=it,e[39]^=at,e[40]^=Ye,e[41]^=Qe,e[42]^=Xe,e[43]^=et,e[44]^=tt,e[45]^=rt,e[46]^=nt,e[47]^=st,e[48]^=it,e[49]^=at;const _r=e[0],xr=e[1],kr=e[2]<<1|e[3]>>>31,Er=e[3]<<1|e[2]>>>31,Sr=e[5]<<30|e[4]>>>2,Tr=e[4]<<30|e[5]>>>2,Ar=e[6]<<28|e[7]>>>4,Or=e[7]<<28|e[6]>>>4,Ir=e[8]<<27|e[9]>>>5,Mr=e[9]<<27|e[8]>>>5,$r=e[11]<<4|e[10]>>>28,Rr=e[10]<<4|e[11]>>>28,Cr=e[13]<<12|e[12]>>>20,Nr=e[12]<<12|e[13]>>>20,jr=e[14]<<6|e[15]>>>26,Dr=e[15]<<6|e[14]>>>26,Pr=e[17]<<23|e[16]>>>9,Ur=e[16]<<23|e[17]>>>9,Zr=e[18]<<20|e[19]>>>12,Br=e[19]<<20|e[18]>>>12,Lr=e[20]<<3|e[21]>>>29,zr=e[21]<<3|e[20]>>>29,Vr=e[22]<<10|e[23]>>>22,Fr=e[23]<<10|e[22]>>>22,Wr=e[25]<<11|e[24]>>>21,Hr=e[24]<<11|e[25]>>>21,qr=e[26]<<25|e[27]>>>7,Gr=e[27]<<25|e[26]>>>7,Kr=e[29]<<7|e[28]>>>25,Jr=e[28]<<7|e[29]>>>25,Yr=e[31]<<9|e[30]>>>23,Qr=e[30]<<9|e[31]>>>23,Xr=e[33]<<13|e[32]>>>19,en=e[32]<<13|e[33]>>>19,tn=e[34]<<15|e[35]>>>17,rn=e[35]<<15|e[34]>>>17,nn=e[36]<<21|e[37]>>>11,sn=e[37]<<21|e[36]>>>11,an=e[38]<<8|e[39]>>>24,on=e[39]<<8|e[38]>>>24,cn=e[40]<<18|e[41]>>>14,un=e[41]<<18|e[40]>>>14,ln=e[42]<<2|e[43]>>>30,dn=e[43]<<2|e[42]>>>30,fn=e[45]<<29|e[44]>>>3,hn=e[44]<<29|e[45]>>>3,pn=e[47]<<24|e[46]>>>8,mn=e[46]<<24|e[47]>>>8,gn=e[48]<<14|e[49]>>>18,yn=e[49]<<14|e[48]>>>18;e[0]=_r^~Cr&Wr,e[1]=xr^~Nr&Hr,e[2]=Cr^~Wr&nn,e[3]=Nr^~Hr&sn,e[4]=Wr^~nn&gn,e[5]=Hr^~sn&yn,e[6]=nn^~gn&_r,e[7]=sn^~yn&xr,e[8]=gn^~_r&Cr,e[9]=yn^~xr&Nr,e[10]=Ar^~Zr&Lr,e[11]=Or^~Br&zr,e[12]=Zr^~Lr&Xr,e[13]=Br^~zr&en,e[14]=Lr^~Xr&fn,e[15]=zr^~en&hn,e[16]=Xr^~fn&Ar,e[17]=en^~hn&Or,e[18]=fn^~Ar&Zr,e[19]=hn^~Or&Br,e[20]=kr^~jr&qr,e[21]=Er^~Dr&Gr,e[22]=jr^~qr&an,e[23]=Dr^~Gr&on,e[24]=qr^~an&cn,e[25]=Gr^~on&un,e[26]=an^~cn&kr,e[27]=on^~un&Er,e[28]=cn^~kr&jr,e[29]=un^~Er&Dr,e[30]=Ir^~$r&Vr,e[31]=Mr^~Rr&Fr,e[32]=$r^~Vr&tn,e[33]=Rr^~Fr&rn,e[34]=Vr^~tn&pn,e[35]=Fr^~rn&mn,e[36]=tn^~pn&Ir,e[37]=rn^~mn&Mr,e[38]=pn^~Ir&$r,e[39]=mn^~Mr&Rr,e[40]=Sr^~Pr&Kr,e[41]=Tr^~Ur&Jr,e[42]=Pr^~Kr&Yr,e[43]=Ur^~Jr&Qr,e[44]=Kr^~Yr&ln,e[45]=Jr^~Qr&dn,e[46]=Yr^~ln&Sr,e[47]=Qr^~dn&Tr,e[48]=ln^~Sr&Pr,e[49]=dn^~Tr&Ur,e[0]^=Ms[t*2],e[1]^=Ms[t*2+1]}}function $s(e){const t=[];for(let n=0;n<e.length;n+=4)t.push(e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24);return t}function Rs(e,t){if(!e.length){const o=new Uint8Array(136);return o[0]=t,o[135]=128,[$s(o)]}const n=mr(e,136),s=n[n.length-1];if(s.length<136){const o=new Uint8Array(136);o.set(s),o[s.length]=t,o[135]|=128,n[n.length-1]=o}if(s.length===136){const o=new Uint8Array(136);o[0]=t,o[135]=128,n.push(o)}return n.map($s)}function Cs(e,t){for(const n of t){for(let s=0;s<34;s+=2)e[s]^=n[s+1],e[s+1]^=n[s];Lu(e)}return e}function Ns(e){return new Uint8Array([e[1],e[1]>>-24,e[1]>>-16,e[1]>>-8,e[0],e[0]>>8,e[0]>>16,e[0]>>24,e[3],e[3]>>-24,e[3]>>-16,e[3]>>-8,e[2],e[2]>>8,e[2]>>16,e[2]>>24,e[5],e[5]>>-24,e[5]>>-16,e[5]>>-8,e[4],e[4]>>8,e[4]>>16,e[4]>>24,e[7],e[7]>>-24,e[7]>>-16,e[7]>>-8,e[6],e[6]>>8,e[6]>>16,e[6]>>24])}function ie(e){return Ns(Cs(new Array(50).fill(0),Rs(e,1)))}function zu(e){return Ns(Cs(new Array(50).fill(0),Rs(e,6)))}function Vu(e,t,n){const s=Math.min(e.length,t.length,n/8+1);for(let o=0;o<s;o++){const d=e[o]^t[o];for(let p=0;p<8;p++)if(d>>7-p&1)return o*8+p}return n}function Fu(e,t){const n=Math.min(e.length,t.length);for(let s=0;s<n;s++)if(e[s]!==t[s])return e.subarray(0,s);return e.subarray(0,n)}function Wu(e,t,n,s){const o=Math.floor(t/8),d=t%8;n===1?e[o]|=1<<(s==="BE"?7-d:d):e[o]&=~(1<<(s==="BE"?7-d:d))}function Hu(e,t,n){const s=Math.floor(t/8),o=t%8;return e[s]>>(n==="BE"?7-o:o)&1}function qu(e,t,n=0){for(let s=n;s<e.length;s++)for(let o=0;o<t.length&&e[s+o]===t[o];o++)if(o===t.length-1)return s;return-1}function js(e,t,n=0){if(e.length>=t)return e;const s=new Uint8Array(t);return s.fill(n),s.set(e,t-e.length),s}function Gu(e,t,n=0){const s=e.length%t;return s===0?e:js(e,e.length+t-s,n)}function Ds(e,t,n=0){if(e.length>=t)return e;const s=new Uint8Array(t);return s.fill(n),s.set(e,0),s}function Ku(e,t,n=0){const s=e.length%t;return s===0?e:Ds(e,e.length+t-s,n)}function Ju(e,t){const n=new Uint8Array(e.length);for(let s=0;s<e.length;s++)n[s]=e[s]^t[s%t.length];return n}function Yu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function R(e,t){return(e%t+t)%t}function Ke(e,t){e=R(e,t);let[n,s]=[0n,1n],[o,d]=[t,e];for(;d!==0n;){const p=o/d;[n,s]=[s,n-p*s],[o,d]=[d,o-p*d]}if(o>1n)throw new Error("a is not invertible");return n<0n&&(n+=t),n}function Qu(e,t,n){let s=1n;for(e=R(e,n);t>0;)t%2n===1n&&(s=R(s*e,n)),e=R(e*e,n),t=t/2n;return s}function Ps(e,t){return R(e,t)===0n?0n:t%4n===3n?Qu(e,(t+1n)/4n,t):null}const B=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,P=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Ct=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Nt=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;function gr(e,t,n){if(t===0n)return[0n,0n];const s=R(3n*e*e*Ke(2n*t,n),n),o=R(s*s-2n*e,n),d=R(s*(e-o)-t,n);return[o,d]}function jt(e,t,n,s,o){if(e===0n&&t===0n)return[n,s];if(n===0n&&s===0n)return[e,t];if(e===n&&t===R(-s,o))return[0n,0n];if(e===n&&t===s)return gr(e,t,o);const d=R((s-t)*Ke(n-e,o),o),p=R(d*d-e-n,o),v=R(d*(e-p)-t,o);return[p,v]}function Xu(e){if(e<=0n||e>=P)throw new Error("Invalid private key");return ke(Ct,Nt,e,B)}function el(e){const t=e[1]%2n===0n?2:3;return new Uint8Array([t,...Ce(e[0],"BE")])}function tl(e){if(e.length!==33||e[0]!==2&&e[0]!==3)throw new Error("Invalid compressed public key");const t=Ne(e.slice(1),"BE"),n=Ps(R(t**3n+7n,B),B);if(!n)throw Error("Invalid x: does not correspond to a valid curve point");const s=R(-n,B),o=n%2n===0n;return[t,e[0]===2?o?n:s:o?s:n]}function rl(e){const t=new Uint8Array(20),n=ie(Re(Ce(e[0],"BE"),Ce(e[1],"BE")));return t.set(n.subarray(12)),t}function nl(e){const t=a.Binary.uint8ArrayToHex(e),n=a.Binary.uint8ArrayToHex(a.Binary.keccak256(new Uint8Array([...t].map(o=>o.charCodeAt(0)))));let s="0x";for(let o=0;o<t.length;o++)parseInt(n[o],16)>7?s+=t[o].toUpperCase():s+=t[o];return s}function ke(e,t,n,s){let o=[0n,0n],d=[e,t];const p=n.toString(2);for(const v of p)v==="0"?(d=jt(o[0],o[1],d[0],d[1],s),o=gr(o[0],o[1],s)):(o=jt(o[0],o[1],d[0],d[1],s),d=gr(d[0],d[1],s));return o}function sl(e,t,n){return Us(Ne(ie(e),"BE"),t,n)}function Us(e,t,n){if(t<=0n||t>=P)throw new Error("Invalid private key");if(n||(n=R(Ne(ie(Re(ie(Ce(t,"BE")),Ce(e,"BE"))),"BE"),P)),n<=0n||n>=P)throw new Error("Invalid nonce");const s=R(e,P),o=ke(Ct,Nt,n,B),d=R(o[0],P);let p=R((s+R(d,P)*t)*Ke(n,P),P);if(d===0n||p===0n)throw new Error("Invalid r or s value");let v=o[1]%2n===0n?27n:28n;return p>P/2n&&(p=P-p,v=v===27n?28n:27n),[d,p,v]}function il(e,t,n,s){const o=Ps(R(t**3n+7n,B),B);if(!o)throw new Error("Invalid r: does not correspond to a valid curve point");const d=s===27n?0n:1n,p=o%2n===d?o:B-o,v=R(Ne(ie(e),"BE"),P),m=ke(t,p,n,B),k=ke(Ct,Nt,v,B),$=jt(m[0],m[1],k[0],R(-k[1],B),B);return ke($[0],$[1],Ke(t,P),B)}function al(e,t,n,s){const o=R(Ne(ie(e),"BE"),P),d=Ke(s,P),p=R(o*d,P),v=R(n*d,P),m=ke(Ct,Nt,p,B),k=ke(t[0],t[1],v,B),$=jt(m[0],m[1],k[0],k[1],B);return n===R($[0],P)}class Zs{constructor(t){this.cursor=0,this.buffer=t}read(t){const n=this.buffer.subarray(this.cursor,this.cursor+t);return this.cursor+=t,n}max(){return this.buffer.length-this.cursor}}a.Uint8ArrayReader=Zs;class Bs{constructor(t){this.buffer=t,this.cursor=0}write(t){const n=Math.min(this.max(),t.max());return this.buffer.set(t.read(n),this.cursor),this.cursor+=n,n}max(){return this.buffer.length-this.cursor}}a.Uint8ArrayWriter=Bs;class Dt{constructor(t,n=0n){this.span=n,this.writer=new Bs(new Uint8Array(t))}build(){return Re(pr(this.span,"LE"),this.writer.buffer)}hash(){const t=Ts(mr(this.writer.buffer,32),(n,s)=>ie(Re(n,s)));return ie(Re(pr(this.span,"LE"),t))}}a.Chunk=Dt;class yr{constructor(t,n=4096){this.counters=[1],this.capacity=n,this.chunks=[new Dt(n)],this.onChunk=t}static async root(t,n=4096){const s=new r(r.NOOP,n);return await s.append(t),s.finalize()}async append(t,n=0,s=0n){const o=new Zs(t);for(;o.max()>0;){this.chunks[n].writer.max()===0&&await this.elevate(n);const d=this.chunks[n].writer.write(o);s?this.chunks[n].span+=s:this.chunks[0].span+=BigInt(d)}}async elevate(t){this.counters[t]=++this.counters[t]%(this.capacity/32),this.chunks[t+1]||(this.chunks.push(new Dt(this.capacity)),this.counters.push(1)),await this.append(this.chunks[t].hash(),t+1,this.chunks[t].span),await this.onChunk(this.chunks[t]),this.chunks[t]=new Dt(this.capacity)}async finalize(t=0){return this.chunks[t+1]?this.counters[t]===1?(await this.elevate(t+1),this.chunks[t+1]=this.chunks[t],this.finalize(t+1)):(await this.elevate(t),this.finalize(t+1)):(await this.onChunk(this.chunks[t]),this.chunks[t])}}a.MerkleTree=yr,r=yr,yr.NOOP=async e=>{};class Q{constructor(t,n){if(n<0)throw Error("Scale must be non-negative");this.value=BigInt(t),this.scale=n}static fromDecimalString(t,n){let[s,o]=t.split(".");return o=(o||"").padEnd(n,"0").slice(0,n),new Q(BigInt(s+o),n)}add(t){return this.assertSameScale(t),new Q(this.value+t.value,this.scale)}subtract(t){return this.assertSameScale(t),new Q(this.value-t.value,this.scale)}multiply(t){return new Q(this.value*t,this.scale)}divmod(t){if(t===0n)throw new Error("Division by zero is not allowed");const n=this.value/t,s=this.value%t;return[new Q(n,this.scale),new Q(s,this.scale)]}exchange(t,n,s){if(t==="*"){const d=this.value*n.value/10n**BigInt(this.scale);return new Q(d,s)}this.assertSameScale(n);const o=this.value*10n**BigInt(s)/n.value;return new Q(o,s)}compare(t){return this.assertSameScale(t),this.value>t.value?1:this.value<t.value?-1:0}toDecimalString(){if(this.scale===0)return this.value.toString();const t=this.value.toString(),n=t.slice(0,-this.scale)||"0",s=t.slice(-this.scale).padStart(this.scale,"0");return`${n}.${s}`}toString(){return this.value.toString()}toJSON(){return this.toString()}assertSameScale(t){if(this.scale!==t.scale)throw new Error(`Scale mismatch: expected ${this.scale}, but got ${t.scale}`)}}a.FixedPointNumber=Q;function ol(e){if(e.length===0)return null;const t=e[0];return t.ttlMax?--t.ttl<=0&&e.shift():t.ttlMax=t.ttl,{progress:(t.ttlMax-t.ttl)/t.ttlMax,data:t.data}}function Pt(e,t,n,s){const o=e.findIndex(v=>v===`--${t}`||v.startsWith(`--${t}=`)),d=e[o];if(!d)return(n||{})[s||t||""]||null;if(d.includes("="))return d.split("=")[1];const p=e[o+1];return p&&!p.startsWith("-")?p:(n||{})[s||t||""]||null}function cl(e,t,n,s){const o=Pt(e,t,n,s);if(!o)return null;try{return dr(o)}catch{throw new Error(`Invalid number argument ${t}: ${o}`)}}function ul(e,t,n,s){const o=e.some(m=>m.endsWith("-"+t)),d=Pt(e,t,n,s);if(!d&&o)return!0;if(!d&&!o)return null;const p=["true","1","yes","y","on"],v=["false","0","no","n","off"];if(p.includes(d.toLowerCase()))return!0;if(v.includes(d.toLowerCase()))return!1;throw Error(`Invalid boolean argument ${t}: ${d}`)}function Ls(e,t,n,s){const o=Pt(e,t,n,s);if(!o)throw new Error(`Missing argument ${t}`);return o}function ll(e,t,n,s){const o=Ls(e,t,n,s);try{return dr(o)}catch{throw new Error(`Invalid argument ${t}: ${o}`)}}function zs(e,t){const n=e[t];e.splice(t,1),e.unshift(n)}function dl(e,t){const n=[...e];return zs(n,t),n}function Vs(e,t){return{x:e.x+t.x,y:e.y+t.y}}function fl(e,t){return{x:e.x-t.x,y:e.y-t.y}}function vr(e,t){return{x:e.x*t,y:e.y*t}}function hl(e){const t=Math.sqrt(e.x*e.x+e.y*e.y);return{x:e.x/t,y:e.y/t}}function Fs(e,t,n){return{x:e.x+Math.cos(t)*n,y:e.y+Math.sin(t)*n}}function Ws(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Je(e,t,n="row-first"){const s=[];if(n==="column-first")for(let o=0;o<e.length;o++)for(let d=0;d<e[0].length;d++)t(o,d)&&s.push({x:o,y:d});else for(let o=0;o<e[0].length;o++)for(let d=0;d<e.length;d++)t(d,o)&&s.push({x:d,y:o});return s}function pl(e,t,n){var s,o;return((s=e[t+1])==null?void 0:s[n])&&((o=e[t-1])==null?void 0:o[n])&&!e[t][n-1]&&!e[t][n+1]}function ml(e,t,n){var s,o;return e[t][n+1]&&e[t][n-1]&&!((s=e[t-1])!=null&&s[n])&&!((o=e[t+1])!=null&&o[n])}function Hs(e,t,n){var s;return!((s=e[t-1])!=null&&s[n])}function qs(e,t,n){var s;return!((s=e[t+1])!=null&&s[n])}function Gs(e,t,n){return!e[t][n-1]}function Ks(e,t,n){return!e[t][n+1]}function gl(e,t,n){var o,d,p,v,m,k,$,U;const s=[];return e[t][n]?pl(e,t,n)||ml(e,t,n)?[]:(!((o=e[t-1])!=null&&o[n-1])&&Hs(e,t,n)&&Gs(e,t,n)&&s.push({x:t,y:n}),!((d=e[t+1])!=null&&d[n-1])&&qs(e,t,n)&&Gs(e,t,n)&&s.push({x:t+1,y:n}),!((p=e[t-1])!=null&&p[n+1])&&Hs(e,t,n)&&Ks(e,t,n)&&s.push({x:t,y:n+1}),!((v=e[t+1])!=null&&v[n+1])&&qs(e,t,n)&&Ks(e,t,n)&&s.push({x:t+1,y:n+1}),s):((m=e[t-1])!=null&&m[n]&&e[t][n-1]&&s.push({x:t,y:n}),(k=e[t+1])!=null&&k[n]&&e[t][n-1]&&s.push({x:t+1,y:n}),($=e[t-1])!=null&&$[n]&&e[t][n+1]&&s.push({x:t,y:n+1}),(U=e[t+1])!=null&&U[n]&&e[t][n+1]&&s.push({x:t+1,y:n+1}),s)}function yl(e,t,n,s){const o=[{x:0,y:0},{x:n,y:0},{x:0,y:s},{x:n,y:s}];for(let d=0;d<e.length;d++)for(let p=0;p<e[0].length;p++){const v=gl(e,d,p);for(const m of v)o.some(k=>k.x===m.x&&k.y===m.y)||o.push(m)}return o.map(d=>({x:d.x*t,y:d.y*t}))}function vl(e,t){const n=Je(e,(m,k)=>e[m][k]===0&&e[m][k+1]!==0,"row-first").map(m=>({...m,dx:1,dy:0})),s=Je(e,(m,k)=>e[m][k]===0&&e[m][k-1]!==0,"row-first").map(m=>({...m,dx:1,dy:0})),o=Je(e,(m,k)=>{var $;return e[m][k]===0&&(($=e[m-1])==null?void 0:$[k])!==0},"column-first").map(m=>({...m,dx:0,dy:1})),d=Je(e,(m,k)=>{var $;return e[m][k]===0&&(($=e[m+1])==null?void 0:$[k])!==0},"column-first").map(m=>({...m,dx:0,dy:1}));n.forEach(m=>m.y++),d.forEach(m=>m.x++);const p=hr([...o,...d],(m,k)=>m.x===k.x&&m.y-1===k.y),v=hr([...s,...n],(m,k)=>m.y===k.y&&m.x-1===k.x);return[...p,...v].map(m=>({start:m[0],end:We(m)})).map(m=>({start:vr(m.start,t),end:vr(Vs(m.end,{x:m.start.dx,y:m.start.dy}),t)}))}function wl(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}function bl(e,t){return t.map(n=>wl(e,n)).sort((n,s)=>n-s)}function Js(e,t,n,s){const o=(s.y-n.y)*(t.x-e.x)-(s.x-n.x)*(t.y-e.y);if(o===0)return null;let d=e.y-n.y,p=e.x-n.x;const v=(s.x-n.x)*d-(s.y-n.y)*p,m=(t.x-e.x)*d-(t.y-e.y)*p;return d=v/o,p=m/o,d>0&&d<1&&p>0&&p<1?{x:e.x+d*(t.x-e.x),y:e.y+d*(t.y-e.y)}:null}function wr(e,t,n){const s=[],o=Fs(e,n,1e4);for(const d of t){const p=Js(e,o,d.start,d.end);p&&s.push(p)}return s.length?s.reduce((d,p)=>{const v=Ws(e,p),m=Ws(e,d);return v<m?p:d}):null}function _l(e,t,n){const s=bl(e,n),o=[];for(const d of s){const p=wr(e,t,d-.001),v=wr(e,t,d+.001);p&&o.push(p),v&&o.push(v)}return o}class br{constructor(){this.subscribers=[]}subscribe(t){return this.subscribers.push(t),()=>{this.subscribers=this.subscribers.filter(n=>n!==t)}}publish(t){this.subscribers.forEach(n=>n(t))}clear(){this.subscribers=[]}getSubscriberCount(){return this.subscribers.length}}a.PubSubChannel=br;class xl{constructor(t,n){this.queue=[],this.running=0,this.onProcessed=new br,this.onDrained=new br,this.concurrency=t,this.capacity=n}process(){if(this.running>=this.concurrency)return;const t=this.queue.shift();t&&(this.running++,t().finally(()=>{this.running--,this.process(),this.onProcessed.publish(),this.running===0&&this.onDrained.publish()}))}enqueue(t){if(this.queue.length<this.capacity)return this.queue.push(t),this.process(),Promise.resolve();if(this.onProcessed.getSubscriberCount())throw Error("Queue capacity is full");return new Promise(n=>{this.onProcessed.subscribe(()=>{this.queue.length<this.capacity&&(this.queue.push(t),this.process(),this.onProcessed.clear(),n())})})}drain(){if(this.running===0)return Promise.resolve();if(this.onDrained.getSubscriberCount())throw Error("Already draining");return new Promise(t=>{this.onDrained.subscribe(()=>{this.onDrained.clear(),t()})})}}a.AsyncQueue=xl,a.Binary={hexToUint8Array:Ao,uint8ArrayToHex:Oo,base64ToUint8Array:ko,uint8ArrayToBase64:Eo,base32ToUint8Array:So,uint8ArrayToBase32:To,log2Reduce:Ts,partition:mr,concatBytes:Re,numberToUint8:Cu,uint8ToNumber:Nu,numberToUint16:ju,uint16ToNumber:Du,numberToUint32:Pu,uint32ToNumber:Uu,numberToUint64:pr,uint64ToNumber:Zu,numberToUint256:Ce,uint256ToNumber:Ne,sliceBytes:Bu,keccak256:ie,sha3_256:zu,proximity:Vu,commonPrefix:Fu,setBit:Wu,getBit:Hu,indexOf:qu,equals:Yu,padStart:js,padStartToMultiple:Gu,padEnd:Ds,padEndToMultiple:Ku,xorCypher:Ju},a.Elliptic={privateKeyToPublicKey:Xu,compressPublicKey:el,publicKeyFromCompressed:tl,publicKeyToAddress:rl,signMessage:sl,signHash:Us,verifySignature:al,recoverPublicKey:il,checksumEncode:nl},a.Random={intBetween:Fe,floatBetween:In,chance:Mn,signed:bi,makeSeededRng:Ht,point:xi,procs:ki},a.Arrays={countUnique:hu,makeUnique:fu,splitBySize:lu,splitByCount:xs,index:_s,indexCollection:uu,onlyOrThrow:h,onlyOrNull:g,firstOrThrow:x,firstOrNull:y,shuffle:f,initialize:j,initialize2D:se,rotate2D:ne,containsShape:ze,glue:$a,pluck:Ve,pick:qt,pickMany:Ei,pickManyUnique:Si,pickWeighted:Oi,pickRandomIndices:Oe,pickGuaranteed:Ti,last:We,pipe:$n,makePipe:Ai,sortWeighted:Ii,pushAll:At,unshiftAll:Ia,filterAndRemove:Yo,merge:Hc,empty:qc,pushToBucket:Ta,unshiftAndLimit:Aa,atRolling:Oa,group:hr,createOscillator:Cc,organiseWithLimits:jc,tickPlaybook:ol,getArgument:Pt,getBooleanArgument:ul,getNumberArgument:cl,requireStringArgument:Ls,requireNumberArgument:ll,bringToFront:dl,bringToFrontInPlace:zs,findInstance:Tu,filterInstances:Au,interleave:Ou,toggle:Iu,createHierarchy:$u,multicall:Eu,maxBy:Su},a.System={sleepMillis:l,forever:ji,scheduleMany:Ua,waitFor:Jo,expandError:xa,runAndSetInterval:Di},a.Numbers={make:dr,sum:Ba,average:La,median:za,getDistanceFromMidpoint:Va,clamp:fr,range:Fn,interpolate:Za,createSequence:Rc,increment:zc,decrement:Vc,format:Lc,fromDecimals:Bc,makeStorage:xc,asMegabytes:Pi,convertBytes:Ui,hexToRgb:Zi,rgbToHex:Bi,haversineDistanceToMeters:Li,roundToNearest:kt,formatDistance:zi,triangularNumber:Vi,searchFloat:Fi},a.Promises={raceFulfilled:c,invert:i,runInParallelBatches:u},a.Dates={getTimestamp:ac,getTimeDelta:fs,secondsToHumanTime:oc,countCycles:cc,isoDate:ec,throttle:uc,timeSince:dc,dateTimeSlug:tc,unixTimestamp:Xo,fromUtcString:rc,fromMillis:nc,getProgress:fc,humanizeTime:$t,humanizeProgress:Ko,createTimeDigits:Y,mapDayNumber:hs,getDayInfoFromDate:ur,getDayInfoFromDateTimeString:pc,seconds:mc,minutes:gc,hours:yc,days:vc,make:bc,normalizeTime:sc,absoluteDays:_e},a.Objects={safeParse:$c,deleteDeep:Ri,getDeep:ve,setDeep:we,incrementDeep:Mi,ensureDeep:$i,replaceDeep:Ci,getFirstDeep:Ni,deepMergeInPlace:be,deepMerge2:ka,deepMerge3:Ea,mapAllAsync:Ma,cloneWithJson:Qo,sortObject:ms,sortArray:gs,sortAny:xe,deepEquals:ys,deepEqualsEvery:Mc,runOn:Fc,ifPresent:Wc,zip:Vn,zipSum:Sa,removeEmptyArrays:Gc,removeEmptyValues:Kc,flatten:ou,unflatten:bs,match:cu,sort:Es,map:Qc,mapIterable:Xc,filterKeys:Jc,filterValues:Yc,rethrow:eu,setSomeOnObject:tu,setSomeDeep:ru,flip:nu,getAllPermutations:su,countTruthyValues:iu,transformToArray:pu,setMulti:gu,incrementMulti:mu,createBidirectionalMap:yu,createTemporalBidirectionalMap:vu,pushToBidirectionalMap:Ss,unshiftToBidirectionalMap:wu,addToTemporalBidirectionalMap:bu,getFromTemporalBidirectionalMap:_u,createStatefulToggle:Nc,diffKeys:Dc,pickRandomKey:vs,mapRandomKey:Pc,fromObjectString:Uc,toQueryString:ls,parseQueryString:Lo,hasKey:zo,selectMax:Vo,reposition:Fo,unwrapSingleKey:Wo,parseKeyValues:Ho},a.Types={isFunction:Kt,isObject:ue,isStrictlyObject:Ie,isEmptyArray:Rn,isEmptyObject:Wi,isUndefined:Gt,isString:W,isNumber:le,isBoolean:Cn,isDate:Me,isBlank:Et,isId:Jt,isIntegerString:Nn,isHexString:jn,isUrl:Ln,isNullable:va,asString:Zn,asHexString:sa,asSafeString:ia,asIntegerString:na,asNumber:St,asFunction:aa,asInteger:Xt,asBoolean:oa,asDate:ca,asNullableString:ua,asEmptiableString:la,asId:da,asTime:fa,asArray:ha,asObject:Tt,asNullableObject:pa,asStringMap:ma,asNumericDictionary:ga,asUrl:ya,asNullable:wa,asOptional:ba,enforceObjectShape:zn,enforceArrayShape:_a,isPng:As,isJpg:Os,isWebp:Is,isImage:Ru},a.Strings={tokenizeByCount:du,tokenizeByLength:ks,searchHex:ea,searchSubstring:ta,randomHex:ra,randomLetter:Ji,randomAlphanumeric:Yi,randomRichAscii:Qi,randomUnicode:Xi,includesAny:Fa,slugify:er,normalForm:Ha,enumify:Qa,escapeHtml:eo,decodeHtmlEntities:ro,after:tr,afterLast:Hn,before:Wn,beforeLast:rr,betweenWide:no,betweenNarrow:so,getPreLine:kc,containsWord:or,containsWords:Po,joinUrl:ps,getFuzzyMatchScore:Ot,sortByFuzzyScore:Xa,splitOnce:nr,splitAll:qn,randomize:co,expand:Gn,shrinkTrim:qe,capitalize:It,decapitalize:Kn,csvEscape:mo,parseCsv:Go,surroundInOut:Ya,getExtension:sr,getBasename:ir,normalizeEmail:io,normalizeFilename:ao,parseFilename:oo,camelToTitle:qa,slugToTitle:Ga,slugToCamel:Ka,joinHumanly:Ja,findWeightedPair:ts,extractBlock:rs,extractAllBlocks:vo,replaceBlocks:wo,indexOfEarliest:$e,lastIndexOfBefore:es,parseHtmlAttributes:Uo,readNextWord:Mt,resolveVariables:Zo,resolveVariableWithDefaultSyntax:cs,resolveRemainingVariablesWithDefaults:us,isLetter:Jn,isDigit:Yn,isLetterOrDigit:Ge,isValidObjectPathCharacter:fo,insert:ho,indexOfRegex:Qn,lineMatches:Xn,linesMatchInOrder:po,represent:He,resolveMarkdownLinks:Bo,buildUrl:qo,isChinese:Wa,replaceBetweenStrings:Tc,describeMarkdown:Ac,isBalanced:Oc,textToFormat:Ic,splitFormatting:bo,splitHashtags:_o,splitUrls:xo,route:Io,explodeReplace:ar,generateVariants:Mo,replaceWord:$o,replacePascalCaseWords:Ro,stripHtml:Co,breakLine:os,measureTextWidth:No,toLines:jo,levenshteinDistance:Do},a.Assertions={asEqual:Ra,asTrue:Ca,asTruthy:Na,asFalse:ja,asFalsy:Da,asEither:Pa},a.Cache={get:Ec,invalidate:Sc},a.Vector={addPoint:Vs,subtractPoint:fl,multiplyPoint:vr,normalizePoint:hl,pushPoint:Fs,filterCoordinates:Je,findCorners:yl,findLines:vl,raycast:wr,raycastCircle:_l,getLineIntersectionPoint:Js}})(ii);const C=Pl(ii);C.Arrays;C.Assertions;const L=C.Binary;C.Cache;C.Dates;C.Elliptic;C.Numbers;C.Objects;C.Pagination;C.Promises;C.Random;C.Strings;C.System;C.Types;C.Optional;C.Vector;C.PubSubChannel;C.Chunk;const Ul=C.MerkleTree;C.FixedPointNumber;C.Lazy;C.AsyncLazy;C.AsyncQueue;C.Uint8ArrayReader;C.Uint8ArrayWriter;const Zl=new TextEncoder,Qs=1,Xs=4096,wn=4096,Bl=32;function ai(a,r){return r=typeof r=="number"?I.FeedIndex.fromBigInt(BigInt(r)):r,new I.Identifier(L.keccak256(L.concatBytes(a.toUint8Array(),r.toUint8Array())))}function Ll(a){const r=a.slice(0,I.Span.LENGTH),i=a.slice(I.Span.LENGTH),c=zl(i),u=L.keccak256(L.concatBytes(r,c));return new I.Reference(u)}function zl(a){if(a.length>wn)throw new I.BeeArgumentError(`payload size ${a.length} exceeds maximum chunk payload size ${wn}`,a);const r=new Uint8Array(wn);return r.set(a),L.log2Reduce(L.partition(r,Bl),(i,c)=>L.keccak256(L.concatBytes(i,c)))}function ei(a){if(a instanceof Uint8Array||(a=Zl.encode(a)),a.length<Qs||a.length>Xs)throw new RangeError(`payload size ${a.length} exceeds limits [${Qs}, ${Xs}]`);const r=I.Span.fromBigInt(BigInt(a.length)),i=L.concatBytes(r.toUint8Array(),a);return{data:i,span:r,payload:I.Bytes.fromSlice(i,I.Span.LENGTH),address:Ll(i)}}function Vl(a,r){return new I.Reference(L.keccak256(L.concatBytes(a.toUint8Array(),r.toUint8Array())))}function ti(a,r,i){r=new I.Identifier(r),i=new I.PrivateKey(i);const c=Vl(r,i.publicKey().address()),u=i.sign(L.concatBytes(r.toUint8Array(),a.address.toUint8Array())),l=L.concatBytes(r.toUint8Array(),u.toUint8Array(),a.data),f=I.Span.fromSlice(a.data,0),h=I.Bytes.fromSlice(a.data,I.Span.LENGTH);return{data:l,identifier:r,signature:u,span:f,payload:h,address:c,owner:i.publicKey().address()}}const Fl=q.getInstance(),Wl=X.getInstance();function Hl(a){return new Promise(r=>{setTimeout(r,a)})}function oi(a){return(a.startsWith("0x")?a.slice(2):a).toLowerCase()}async function _n(a,r=3,i=250){return new Promise((c,u)=>{a().then(c).catch(l=>{r>0?(Fl.info(`Retrying... Attempts left: ${r}. Error: ${l.message}`),setTimeout(()=>{_n(a,r-1,i).then(c).catch(u)},i)):(Wl.handleError(l,"Utils.retryAwaitableAsync"),u(l))})})}async function ql(a,r,i="Operation timed out"){return Promise.race([a,new Promise((c,u)=>setTimeout(()=>u(new Error(i)),r))])}class Gl{constructor(){this.events={},this.on=this.on.bind(this),this.off=this.off.bind(this),this.cleanAll=this.cleanAll.bind(this),this.emit=this.emit.bind(this)}on(r,i){this.events[r]||(this.events[r]=[]),this.events[r].push(i)}off(r,i){if(!this.events[r])return;const c=this.events[r].indexOf(i);c>-1&&this.events[r].splice(c,1)}cleanAll(){this.events={}}emit(r,i){this.events[r]&&this.events[r].forEach(c=>c(i))}}var M;(function(a){a.assertEqual=u=>u;function r(u){}a.assertIs=r;function i(u){throw new Error}a.assertNever=i,a.arrayToEnum=u=>{const l={};for(const f of u)l[f]=f;return l},a.getValidEnumValues=u=>{const l=a.objectKeys(u).filter(h=>typeof u[u[h]]!="number"),f={};for(const h of l)f[h]=u[h];return a.objectValues(f)},a.objectValues=u=>a.objectKeys(u).map(function(l){return u[l]}),a.objectKeys=typeof Object.keys=="function"?u=>Object.keys(u):u=>{const l=[];for(const f in u)Object.prototype.hasOwnProperty.call(u,f)&&l.push(f);return l},a.find=(u,l)=>{for(const f of u)if(l(f))return f},a.isInteger=typeof Number.isInteger=="function"?u=>Number.isInteger(u):u=>typeof u=="number"&&isFinite(u)&&Math.floor(u)===u;function c(u,l=" | "){return u.map(f=>typeof f=="string"?`'${f}'`:f).join(l)}a.joinValues=c,a.jsonStringifyReplacer=(u,l)=>typeof l=="bigint"?l.toString():l})(M||(M={}));var xn;(function(a){a.mergeShapes=(r,i)=>({...r,...i})})(xn||(xn={}));const _=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),oe=a=>{switch(typeof a){case"undefined":return _.undefined;case"string":return _.string;case"number":return isNaN(a)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(a)?_.array:a===null?_.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?_.promise:typeof Map<"u"&&a instanceof Map?_.map:typeof Set<"u"&&a instanceof Set?_.set:typeof Date<"u"&&a instanceof Date?_.date:_.object;default:return _.unknown}},w=M.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Kl=a=>JSON.stringify(a,null,2).replace(/"([^"]+)":/g,"$1:");class F extends Error{get errors(){return this.issues}constructor(r){super(),this.issues=[],this.addIssue=c=>{this.issues=[...this.issues,c]},this.addIssues=(c=[])=>{this.issues=[...this.issues,...c]};const i=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,i):this.__proto__=i,this.name="ZodError",this.issues=r}format(r){const i=r||function(l){return l.message},c={_errors:[]},u=l=>{for(const f of l.issues)if(f.code==="invalid_union")f.unionErrors.map(u);else if(f.code==="invalid_return_type")u(f.returnTypeError);else if(f.code==="invalid_arguments")u(f.argumentsError);else if(f.path.length===0)c._errors.push(i(f));else{let h=c,g=0;for(;g<f.path.length;){const y=f.path[g];g===f.path.length-1?(h[y]=h[y]||{_errors:[]},h[y]._errors.push(i(f))):h[y]=h[y]||{_errors:[]},h=h[y],g++}}};return u(this),c}static assert(r){if(!(r instanceof F))throw new Error(`Not a ZodError: ${r}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(r=i=>i.message){const i={},c=[];for(const u of this.issues)u.path.length>0?(i[u.path[0]]=i[u.path[0]]||[],i[u.path[0]].push(r(u))):c.push(r(u));return{formErrors:c,fieldErrors:i}}get formErrors(){return this.flatten()}}F.create=a=>new F(a);const Ze=(a,r)=>{let i;switch(a.code){case w.invalid_type:a.received===_.undefined?i="Required":i=`Expected ${a.expected}, received ${a.received}`;break;case w.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(a.expected,M.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:i=`Unrecognized key(s) in object: ${M.joinValues(a.keys,", ")}`;break;case w.invalid_union:i="Invalid input";break;case w.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${M.joinValues(a.options)}`;break;case w.invalid_enum_value:i=`Invalid enum value. Expected ${M.joinValues(a.options)}, received '${a.received}'`;break;case w.invalid_arguments:i="Invalid function arguments";break;case w.invalid_return_type:i="Invalid function return type";break;case w.invalid_date:i="Invalid date";break;case w.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(i=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(i=`${i} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?i=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?i=`Invalid input: must end with "${a.validation.endsWith}"`:M.assertNever(a.validation):a.validation!=="regex"?i=`Invalid ${a.validation}`:i="Invalid";break;case w.too_small:a.type==="array"?i=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?i=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?i=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?i=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:i="Invalid input";break;case w.too_big:a.type==="array"?i=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?i=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?i=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?i=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?i=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:i="Invalid input";break;case w.custom:i="Invalid input";break;case w.invalid_intersection_types:i="Intersection results could not be merged";break;case w.not_multiple_of:i=`Number must be a multiple of ${a.multipleOf}`;break;case w.not_finite:i="Number must be finite";break;default:i=r.defaultError,M.assertNever(a)}return{message:i}};let ci=Ze;function Jl(a){ci=a}function Ut(){return ci}const Zt=a=>{const{data:r,path:i,errorMaps:c,issueData:u}=a,l=[...i,...u.path||[]],f={...u,path:l};if(u.message!==void 0)return{...u,path:l,message:u.message};let h="";const g=c.filter(y=>!!y).slice().reverse();for(const y of g)h=y(f,{data:r,defaultError:h}).message;return{...u,path:l,message:h}},Yl=[];function b(a,r){const i=Ut(),c=Zt({issueData:r,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,i,i===Ze?void 0:Ze].filter(u=>!!u)});a.common.issues.push(c)}class z{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(r,i){const c=[];for(const u of i){if(u.status==="aborted")return T;u.status==="dirty"&&r.dirty(),c.push(u.value)}return{status:r.value,value:c}}static async mergeObjectAsync(r,i){const c=[];for(const u of i){const l=await u.key,f=await u.value;c.push({key:l,value:f})}return z.mergeObjectSync(r,c)}static mergeObjectSync(r,i){const c={};for(const u of i){const{key:l,value:f}=u;if(l.status==="aborted"||f.status==="aborted")return T;l.status==="dirty"&&r.dirty(),f.status==="dirty"&&r.dirty(),l.value!=="__proto__"&&(typeof f.value<"u"||u.alwaysSet)&&(c[l.value]=f.value)}return{status:r.value,value:c}}}const T=Object.freeze({status:"aborted"}),Pe=a=>({status:"dirty",value:a}),V=a=>({status:"valid",value:a}),kn=a=>a.status==="aborted",En=a=>a.status==="dirty",Se=a=>a.status==="valid",ut=a=>typeof Promise<"u"&&a instanceof Promise;function Bt(a,r,i,c){if(typeof r=="function"?a!==r||!c:!r.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r.get(a)}function ui(a,r,i,c,u){if(typeof r=="function"?a!==r||!u:!r.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r.set(a,i),i}var E;(function(a){a.errToObj=r=>typeof r=="string"?{message:r}:r||{},a.toString=r=>typeof r=="string"?r:r==null?void 0:r.message})(E||(E={}));var ot,ct;class te{constructor(r,i,c,u){this._cachedPath=[],this.parent=r,this.data=i,this._path=c,this._key=u}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ri=(a,r)=>{if(Se(r))return{success:!0,data:r.value};if(!a.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const i=new F(a.common.issues);return this._error=i,this._error}}};function A(a){if(!a)return{};const{errorMap:r,invalid_type_error:i,required_error:c,description:u}=a;if(r&&(i||c))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return r?{errorMap:r,description:u}:{errorMap:(f,h)=>{var g,y;const{message:x}=a;return f.code==="invalid_enum_value"?{message:x??h.defaultError}:typeof h.data>"u"?{message:(g=x??c)!==null&&g!==void 0?g:h.defaultError}:f.code!=="invalid_type"?{message:h.defaultError}:{message:(y=x??i)!==null&&y!==void 0?y:h.defaultError}},description:u}}class O{get description(){return this._def.description}_getType(r){return oe(r.data)}_getOrReturnCtx(r,i){return i||{common:r.parent.common,data:r.data,parsedType:oe(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}_processInputParams(r){return{status:new z,ctx:{common:r.parent.common,data:r.data,parsedType:oe(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}}_parseSync(r){const i=this._parse(r);if(ut(i))throw new Error("Synchronous parse encountered promise.");return i}_parseAsync(r){const i=this._parse(r);return Promise.resolve(i)}parse(r,i){const c=this.safeParse(r,i);if(c.success)return c.data;throw c.error}safeParse(r,i){var c;const u={common:{issues:[],async:(c=i==null?void 0:i.async)!==null&&c!==void 0?c:!1,contextualErrorMap:i==null?void 0:i.errorMap},path:(i==null?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:oe(r)},l=this._parseSync({data:r,path:u.path,parent:u});return ri(u,l)}"~validate"(r){var i,c;const u={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:oe(r)};if(!this["~standard"].async)try{const l=this._parseSync({data:r,path:[],parent:u});return Se(l)?{value:l.value}:{issues:u.common.issues}}catch(l){!((c=(i=l==null?void 0:l.message)===null||i===void 0?void 0:i.toLowerCase())===null||c===void 0)&&c.includes("encountered")&&(this["~standard"].async=!0),u.common={issues:[],async:!0}}return this._parseAsync({data:r,path:[],parent:u}).then(l=>Se(l)?{value:l.value}:{issues:u.common.issues})}async parseAsync(r,i){const c=await this.safeParseAsync(r,i);if(c.success)return c.data;throw c.error}async safeParseAsync(r,i){const c={common:{issues:[],contextualErrorMap:i==null?void 0:i.errorMap,async:!0},path:(i==null?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:oe(r)},u=this._parse({data:r,path:c.path,parent:c}),l=await(ut(u)?u:Promise.resolve(u));return ri(c,l)}refine(r,i){const c=u=>typeof i=="string"||typeof i>"u"?{message:i}:typeof i=="function"?i(u):i;return this._refinement((u,l)=>{const f=r(u),h=()=>l.addIssue({code:w.custom,...c(u)});return typeof Promise<"u"&&f instanceof Promise?f.then(g=>g?!0:(h(),!1)):f?!0:(h(),!1)})}refinement(r,i){return this._refinement((c,u)=>r(c)?!0:(u.addIssue(typeof i=="function"?i(c,u):i),!1))}_refinement(r){return new J({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:r}})}superRefine(r){return this._refinement(r)}constructor(r){this.spa=this.safeParseAsync,this._def=r,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:i=>this["~validate"](i)}}optional(){return ee.create(this,this._def)}nullable(){return ge.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return K.create(this)}promise(){return Le.create(this,this._def)}or(r){return ht.create([this,r],this._def)}and(r){return pt.create(this,r,this._def)}transform(r){return new J({...A(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:r}})}default(r){const i=typeof r=="function"?r:()=>r;return new wt({...A(this._def),innerType:this,defaultValue:i,typeName:S.ZodDefault})}brand(){return new Tn({typeName:S.ZodBranded,type:this,...A(this._def)})}catch(r){const i=typeof r=="function"?r:()=>r;return new bt({...A(this._def),innerType:this,catchValue:i,typeName:S.ZodCatch})}describe(r){const i=this.constructor;return new i({...this._def,description:r})}pipe(r){return xt.create(this,r)}readonly(){return _t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ql=/^c[^\s-]{8,}$/i,Xl=/^[0-9a-z]+$/,ed=/^[0-9A-HJKMNP-TV-Z]{26}$/i,td=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,rd=/^[a-z0-9_-]{21}$/i,nd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,id=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ad="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let bn;const od=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,cd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ud=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ld=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,dd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,li="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",hd=new RegExp(`^${li}$`);function di(a){let r="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return a.precision?r=`${r}\\.\\d{${a.precision}}`:a.precision==null&&(r=`${r}(\\.\\d+)?`),r}function pd(a){return new RegExp(`^${di(a)}$`)}function fi(a){let r=`${li}T${di(a)}`;const i=[];return i.push(a.local?"Z?":"Z"),a.offset&&i.push("([+-]\\d{2}:?\\d{2})"),r=`${r}(${i.join("|")})`,new RegExp(`^${r}$`)}function md(a,r){return!!((r==="v4"||!r)&&od.test(a)||(r==="v6"||!r)&&ud.test(a))}function gd(a,r){if(!nd.test(a))return!1;try{const[i]=a.split("."),c=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),u=JSON.parse(atob(c));return!(typeof u!="object"||u===null||!u.typ||!u.alg||r&&u.alg!==r)}catch{return!1}}function yd(a,r){return!!((r==="v4"||!r)&&cd.test(a)||(r==="v6"||!r)&&ld.test(a))}class G extends O{_parse(r){if(this._def.coerce&&(r.data=String(r.data)),this._getType(r)!==_.string){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_type,expected:_.string,received:l.parsedType}),T}const c=new z;let u;for(const l of this._def.checks)if(l.kind==="min")r.data.length<l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),c.dirty());else if(l.kind==="max")r.data.length>l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),c.dirty());else if(l.kind==="length"){const f=r.data.length>l.value,h=r.data.length<l.value;(f||h)&&(u=this._getOrReturnCtx(r,u),f?b(u,{code:w.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):h&&b(u,{code:w.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),c.dirty())}else if(l.kind==="email")id.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"email",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="emoji")bn||(bn=new RegExp(ad,"u")),bn.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"emoji",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="uuid")td.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"uuid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="nanoid")rd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"nanoid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid")Ql.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cuid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid2")Xl.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cuid2",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="ulid")ed.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"ulid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="url")try{new URL(r.data)}catch{u=this._getOrReturnCtx(r,u),b(u,{validation:"url",code:w.invalid_string,message:l.message}),c.dirty()}else l.kind==="regex"?(l.regex.lastIndex=0,l.regex.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"regex",code:w.invalid_string,message:l.message}),c.dirty())):l.kind==="trim"?r.data=r.data.trim():l.kind==="includes"?r.data.includes(l.value,l.position)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),c.dirty()):l.kind==="toLowerCase"?r.data=r.data.toLowerCase():l.kind==="toUpperCase"?r.data=r.data.toUpperCase():l.kind==="startsWith"?r.data.startsWith(l.value)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:{startsWith:l.value},message:l.message}),c.dirty()):l.kind==="endsWith"?r.data.endsWith(l.value)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:{endsWith:l.value},message:l.message}),c.dirty()):l.kind==="datetime"?fi(l).test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:"datetime",message:l.message}),c.dirty()):l.kind==="date"?hd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:"date",message:l.message}),c.dirty()):l.kind==="time"?pd(l).test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:"time",message:l.message}),c.dirty()):l.kind==="duration"?sd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"duration",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="ip"?md(r.data,l.version)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"ip",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="jwt"?gd(r.data,l.alg)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"jwt",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="cidr"?yd(r.data,l.version)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cidr",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="base64"?dd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"base64",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="base64url"?fd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"base64url",code:w.invalid_string,message:l.message}),c.dirty()):M.assertNever(l);return{status:c.value,value:r.data}}_regex(r,i,c){return this.refinement(u=>r.test(u),{validation:i,code:w.invalid_string,...E.errToObj(c)})}_addCheck(r){return new G({...this._def,checks:[...this._def.checks,r]})}email(r){return this._addCheck({kind:"email",...E.errToObj(r)})}url(r){return this._addCheck({kind:"url",...E.errToObj(r)})}emoji(r){return this._addCheck({kind:"emoji",...E.errToObj(r)})}uuid(r){return this._addCheck({kind:"uuid",...E.errToObj(r)})}nanoid(r){return this._addCheck({kind:"nanoid",...E.errToObj(r)})}cuid(r){return this._addCheck({kind:"cuid",...E.errToObj(r)})}cuid2(r){return this._addCheck({kind:"cuid2",...E.errToObj(r)})}ulid(r){return this._addCheck({kind:"ulid",...E.errToObj(r)})}base64(r){return this._addCheck({kind:"base64",...E.errToObj(r)})}base64url(r){return this._addCheck({kind:"base64url",...E.errToObj(r)})}jwt(r){return this._addCheck({kind:"jwt",...E.errToObj(r)})}ip(r){return this._addCheck({kind:"ip",...E.errToObj(r)})}cidr(r){return this._addCheck({kind:"cidr",...E.errToObj(r)})}datetime(r){var i,c;return typeof r=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:r}):this._addCheck({kind:"datetime",precision:typeof(r==null?void 0:r.precision)>"u"?null:r==null?void 0:r.precision,offset:(i=r==null?void 0:r.offset)!==null&&i!==void 0?i:!1,local:(c=r==null?void 0:r.local)!==null&&c!==void 0?c:!1,...E.errToObj(r==null?void 0:r.message)})}date(r){return this._addCheck({kind:"date",message:r})}time(r){return typeof r=="string"?this._addCheck({kind:"time",precision:null,message:r}):this._addCheck({kind:"time",precision:typeof(r==null?void 0:r.precision)>"u"?null:r==null?void 0:r.precision,...E.errToObj(r==null?void 0:r.message)})}duration(r){return this._addCheck({kind:"duration",...E.errToObj(r)})}regex(r,i){return this._addCheck({kind:"regex",regex:r,...E.errToObj(i)})}includes(r,i){return this._addCheck({kind:"includes",value:r,position:i==null?void 0:i.position,...E.errToObj(i==null?void 0:i.message)})}startsWith(r,i){return this._addCheck({kind:"startsWith",value:r,...E.errToObj(i)})}endsWith(r,i){return this._addCheck({kind:"endsWith",value:r,...E.errToObj(i)})}min(r,i){return this._addCheck({kind:"min",value:r,...E.errToObj(i)})}max(r,i){return this._addCheck({kind:"max",value:r,...E.errToObj(i)})}length(r,i){return this._addCheck({kind:"length",value:r,...E.errToObj(i)})}nonempty(r){return this.min(1,E.errToObj(r))}trim(){return new G({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(r=>r.kind==="datetime")}get isDate(){return!!this._def.checks.find(r=>r.kind==="date")}get isTime(){return!!this._def.checks.find(r=>r.kind==="time")}get isDuration(){return!!this._def.checks.find(r=>r.kind==="duration")}get isEmail(){return!!this._def.checks.find(r=>r.kind==="email")}get isURL(){return!!this._def.checks.find(r=>r.kind==="url")}get isEmoji(){return!!this._def.checks.find(r=>r.kind==="emoji")}get isUUID(){return!!this._def.checks.find(r=>r.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(r=>r.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(r=>r.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(r=>r.kind==="cuid2")}get isULID(){return!!this._def.checks.find(r=>r.kind==="ulid")}get isIP(){return!!this._def.checks.find(r=>r.kind==="ip")}get isCIDR(){return!!this._def.checks.find(r=>r.kind==="cidr")}get isBase64(){return!!this._def.checks.find(r=>r.kind==="base64")}get isBase64url(){return!!this._def.checks.find(r=>r.kind==="base64url")}get minLength(){let r=null;for(const i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxLength(){let r=null;for(const i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}}G.create=a=>{var r;return new G({checks:[],typeName:S.ZodString,coerce:(r=a==null?void 0:a.coerce)!==null&&r!==void 0?r:!1,...A(a)})};function vd(a,r){const i=(a.toString().split(".")[1]||"").length,c=(r.toString().split(".")[1]||"").length,u=i>c?i:c,l=parseInt(a.toFixed(u).replace(".","")),f=parseInt(r.toFixed(u).replace(".",""));return l%f/Math.pow(10,u)}class he extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(r){if(this._def.coerce&&(r.data=Number(r.data)),this._getType(r)!==_.number){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_type,expected:_.number,received:l.parsedType}),T}let c;const u=new z;for(const l of this._def.checks)l.kind==="int"?M.isInteger(r.data)||(c=this._getOrReturnCtx(r,c),b(c,{code:w.invalid_type,expected:"integer",received:"float",message:l.message}),u.dirty()):l.kind==="min"?(l.inclusive?r.data<l.value:r.data<=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_small,minimum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),u.dirty()):l.kind==="max"?(l.inclusive?r.data>l.value:r.data>=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_big,maximum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),u.dirty()):l.kind==="multipleOf"?vd(r.data,l.value)!==0&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.not_multiple_of,multipleOf:l.value,message:l.message}),u.dirty()):l.kind==="finite"?Number.isFinite(r.data)||(c=this._getOrReturnCtx(r,c),b(c,{code:w.not_finite,message:l.message}),u.dirty()):M.assertNever(l);return{status:u.value,value:r.data}}gte(r,i){return this.setLimit("min",r,!0,E.toString(i))}gt(r,i){return this.setLimit("min",r,!1,E.toString(i))}lte(r,i){return this.setLimit("max",r,!0,E.toString(i))}lt(r,i){return this.setLimit("max",r,!1,E.toString(i))}setLimit(r,i,c,u){return new he({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:c,message:E.toString(u)}]})}_addCheck(r){return new he({...this._def,checks:[...this._def.checks,r]})}int(r){return this._addCheck({kind:"int",message:E.toString(r)})}positive(r){return this._addCheck({kind:"min",value:0,inclusive:!1,message:E.toString(r)})}negative(r){return this._addCheck({kind:"max",value:0,inclusive:!1,message:E.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:0,inclusive:!0,message:E.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:0,inclusive:!0,message:E.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:E.toString(i)})}finite(r){return this._addCheck({kind:"finite",message:E.toString(r)})}safe(r){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:E.toString(r)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:E.toString(r)})}get minValue(){let r=null;for(const i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxValue(){let r=null;for(const i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}get isInt(){return!!this._def.checks.find(r=>r.kind==="int"||r.kind==="multipleOf"&&M.isInteger(r.value))}get isFinite(){let r=null,i=null;for(const c of this._def.checks){if(c.kind==="finite"||c.kind==="int"||c.kind==="multipleOf")return!0;c.kind==="min"?(i===null||c.value>i)&&(i=c.value):c.kind==="max"&&(r===null||c.value<r)&&(r=c.value)}return Number.isFinite(i)&&Number.isFinite(r)}}he.create=a=>new he({checks:[],typeName:S.ZodNumber,coerce:(a==null?void 0:a.coerce)||!1,...A(a)});class pe extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(r){if(this._def.coerce)try{r.data=BigInt(r.data)}catch{return this._getInvalidInput(r)}if(this._getType(r)!==_.bigint)return this._getInvalidInput(r);let c;const u=new z;for(const l of this._def.checks)l.kind==="min"?(l.inclusive?r.data<l.value:r.data<=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_small,type:"bigint",minimum:l.value,inclusive:l.inclusive,message:l.message}),u.dirty()):l.kind==="max"?(l.inclusive?r.data>l.value:r.data>=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_big,type:"bigint",maximum:l.value,inclusive:l.inclusive,message:l.message}),u.dirty()):l.kind==="multipleOf"?r.data%l.value!==BigInt(0)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.not_multiple_of,multipleOf:l.value,message:l.message}),u.dirty()):M.assertNever(l);return{status:u.value,value:r.data}}_getInvalidInput(r){const i=this._getOrReturnCtx(r);return b(i,{code:w.invalid_type,expected:_.bigint,received:i.parsedType}),T}gte(r,i){return this.setLimit("min",r,!0,E.toString(i))}gt(r,i){return this.setLimit("min",r,!1,E.toString(i))}lte(r,i){return this.setLimit("max",r,!0,E.toString(i))}lt(r,i){return this.setLimit("max",r,!1,E.toString(i))}setLimit(r,i,c,u){return new pe({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:c,message:E.toString(u)}]})}_addCheck(r){return new pe({...this._def,checks:[...this._def.checks,r]})}positive(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:E.toString(r)})}negative(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:E.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:E.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:E.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:E.toString(i)})}get minValue(){let r=null;for(const i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxValue(){let r=null;for(const i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}}pe.create=a=>{var r;return new pe({checks:[],typeName:S.ZodBigInt,coerce:(r=a==null?void 0:a.coerce)!==null&&r!==void 0?r:!1,...A(a)})};class lt extends O{_parse(r){if(this._def.coerce&&(r.data=!!r.data),this._getType(r)!==_.boolean){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.boolean,received:c.parsedType}),T}return V(r.data)}}lt.create=a=>new lt({typeName:S.ZodBoolean,coerce:(a==null?void 0:a.coerce)||!1,...A(a)});class Te extends O{_parse(r){if(this._def.coerce&&(r.data=new Date(r.data)),this._getType(r)!==_.date){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_type,expected:_.date,received:l.parsedType}),T}if(isNaN(r.data.getTime())){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_date}),T}const c=new z;let u;for(const l of this._def.checks)l.kind==="min"?r.data.getTime()<l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_small,message:l.message,inclusive:!0,exact:!1,minimum:l.value,type:"date"}),c.dirty()):l.kind==="max"?r.data.getTime()>l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_big,message:l.message,inclusive:!0,exact:!1,maximum:l.value,type:"date"}),c.dirty()):M.assertNever(l);return{status:c.value,value:new Date(r.data.getTime())}}_addCheck(r){return new Te({...this._def,checks:[...this._def.checks,r]})}min(r,i){return this._addCheck({kind:"min",value:r.getTime(),message:E.toString(i)})}max(r,i){return this._addCheck({kind:"max",value:r.getTime(),message:E.toString(i)})}get minDate(){let r=null;for(const i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r!=null?new Date(r):null}get maxDate(){let r=null;for(const i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r!=null?new Date(r):null}}Te.create=a=>new Te({checks:[],coerce:(a==null?void 0:a.coerce)||!1,typeName:S.ZodDate,...A(a)});class Lt extends O{_parse(r){if(this._getType(r)!==_.symbol){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.symbol,received:c.parsedType}),T}return V(r.data)}}Lt.create=a=>new Lt({typeName:S.ZodSymbol,...A(a)});class dt extends O{_parse(r){if(this._getType(r)!==_.undefined){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.undefined,received:c.parsedType}),T}return V(r.data)}}dt.create=a=>new dt({typeName:S.ZodUndefined,...A(a)});class ft extends O{_parse(r){if(this._getType(r)!==_.null){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.null,received:c.parsedType}),T}return V(r.data)}}ft.create=a=>new ft({typeName:S.ZodNull,...A(a)});class Be extends O{constructor(){super(...arguments),this._any=!0}_parse(r){return V(r.data)}}Be.create=a=>new Be({typeName:S.ZodAny,...A(a)});class Ee extends O{constructor(){super(...arguments),this._unknown=!0}_parse(r){return V(r.data)}}Ee.create=a=>new Ee({typeName:S.ZodUnknown,...A(a)});class ce extends O{_parse(r){const i=this._getOrReturnCtx(r);return b(i,{code:w.invalid_type,expected:_.never,received:i.parsedType}),T}}ce.create=a=>new ce({typeName:S.ZodNever,...A(a)});class zt extends O{_parse(r){if(this._getType(r)!==_.undefined){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.void,received:c.parsedType}),T}return V(r.data)}}zt.create=a=>new zt({typeName:S.ZodVoid,...A(a)});class K extends O{_parse(r){const{ctx:i,status:c}=this._processInputParams(r),u=this._def;if(i.parsedType!==_.array)return b(i,{code:w.invalid_type,expected:_.array,received:i.parsedType}),T;if(u.exactLength!==null){const f=i.data.length>u.exactLength.value,h=i.data.length<u.exactLength.value;(f||h)&&(b(i,{code:f?w.too_big:w.too_small,minimum:h?u.exactLength.value:void 0,maximum:f?u.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:u.exactLength.message}),c.dirty())}if(u.minLength!==null&&i.data.length<u.minLength.value&&(b(i,{code:w.too_small,minimum:u.minLength.value,type:"array",inclusive:!0,exact:!1,message:u.minLength.message}),c.dirty()),u.maxLength!==null&&i.data.length>u.maxLength.value&&(b(i,{code:w.too_big,maximum:u.maxLength.value,type:"array",inclusive:!0,exact:!1,message:u.maxLength.message}),c.dirty()),i.common.async)return Promise.all([...i.data].map((f,h)=>u.type._parseAsync(new te(i,f,i.path,h)))).then(f=>z.mergeArray(c,f));const l=[...i.data].map((f,h)=>u.type._parseSync(new te(i,f,i.path,h)));return z.mergeArray(c,l)}get element(){return this._def.type}min(r,i){return new K({...this._def,minLength:{value:r,message:E.toString(i)}})}max(r,i){return new K({...this._def,maxLength:{value:r,message:E.toString(i)}})}length(r,i){return new K({...this._def,exactLength:{value:r,message:E.toString(i)}})}nonempty(r){return this.min(1,r)}}K.create=(a,r)=>new K({type:a,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...A(r)});function De(a){if(a instanceof N){const r={};for(const i in a.shape){const c=a.shape[i];r[i]=ee.create(De(c))}return new N({...a._def,shape:()=>r})}else return a instanceof K?new K({...a._def,type:De(a.element)}):a instanceof ee?ee.create(De(a.unwrap())):a instanceof ge?ge.create(De(a.unwrap())):a instanceof re?re.create(a.items.map(r=>De(r))):a}class N extends O{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const r=this._def.shape(),i=M.objectKeys(r);return this._cached={shape:r,keys:i}}_parse(r){if(this._getType(r)!==_.object){const y=this._getOrReturnCtx(r);return b(y,{code:w.invalid_type,expected:_.object,received:y.parsedType}),T}const{status:c,ctx:u}=this._processInputParams(r),{shape:l,keys:f}=this._getCached(),h=[];if(!(this._def.catchall instanceof ce&&this._def.unknownKeys==="strip"))for(const y in u.data)f.includes(y)||h.push(y);const g=[];for(const y of f){const x=l[y],j=u.data[y];g.push({key:{status:"valid",value:y},value:x._parse(new te(u,j,u.path,y)),alwaysSet:y in u.data})}if(this._def.catchall instanceof ce){const y=this._def.unknownKeys;if(y==="passthrough")for(const x of h)g.push({key:{status:"valid",value:x},value:{status:"valid",value:u.data[x]}});else if(y==="strict")h.length>0&&(b(u,{code:w.unrecognized_keys,keys:h}),c.dirty());else if(y!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const y=this._def.catchall;for(const x of h){const j=u.data[x];g.push({key:{status:"valid",value:x},value:y._parse(new te(u,j,u.path,x)),alwaysSet:x in u.data})}}return u.common.async?Promise.resolve().then(async()=>{const y=[];for(const x of g){const j=await x.key,ne=await x.value;y.push({key:j,value:ne,alwaysSet:x.alwaysSet})}return y}).then(y=>z.mergeObjectSync(c,y)):z.mergeObjectSync(c,g)}get shape(){return this._def.shape()}strict(r){return E.errToObj,new N({...this._def,unknownKeys:"strict",...r!==void 0?{errorMap:(i,c)=>{var u,l,f,h;const g=(f=(l=(u=this._def).errorMap)===null||l===void 0?void 0:l.call(u,i,c).message)!==null&&f!==void 0?f:c.defaultError;return i.code==="unrecognized_keys"?{message:(h=E.errToObj(r).message)!==null&&h!==void 0?h:g}:{message:g}}}:{}})}strip(){return new N({...this._def,unknownKeys:"strip"})}passthrough(){return new N({...this._def,unknownKeys:"passthrough"})}extend(r){return new N({...this._def,shape:()=>({...this._def.shape(),...r})})}merge(r){return new N({unknownKeys:r._def.unknownKeys,catchall:r._def.catchall,shape:()=>({...this._def.shape(),...r._def.shape()}),typeName:S.ZodObject})}setKey(r,i){return this.augment({[r]:i})}catchall(r){return new N({...this._def,catchall:r})}pick(r){const i={};return M.objectKeys(r).forEach(c=>{r[c]&&this.shape[c]&&(i[c]=this.shape[c])}),new N({...this._def,shape:()=>i})}omit(r){const i={};return M.objectKeys(this.shape).forEach(c=>{r[c]||(i[c]=this.shape[c])}),new N({...this._def,shape:()=>i})}deepPartial(){return De(this)}partial(r){const i={};return M.objectKeys(this.shape).forEach(c=>{const u=this.shape[c];r&&!r[c]?i[c]=u:i[c]=u.optional()}),new N({...this._def,shape:()=>i})}required(r){const i={};return M.objectKeys(this.shape).forEach(c=>{if(r&&!r[c])i[c]=this.shape[c];else{let l=this.shape[c];for(;l instanceof ee;)l=l._def.innerType;i[c]=l}}),new N({...this._def,shape:()=>i})}keyof(){return hi(M.objectKeys(this.shape))}}N.create=(a,r)=>new N({shape:()=>a,unknownKeys:"strip",catchall:ce.create(),typeName:S.ZodObject,...A(r)});N.strictCreate=(a,r)=>new N({shape:()=>a,unknownKeys:"strict",catchall:ce.create(),typeName:S.ZodObject,...A(r)});N.lazycreate=(a,r)=>new N({shape:a,unknownKeys:"strip",catchall:ce.create(),typeName:S.ZodObject,...A(r)});class ht extends O{_parse(r){const{ctx:i}=this._processInputParams(r),c=this._def.options;function u(l){for(const h of l)if(h.result.status==="valid")return h.result;for(const h of l)if(h.result.status==="dirty")return i.common.issues.push(...h.ctx.common.issues),h.result;const f=l.map(h=>new F(h.ctx.common.issues));return b(i,{code:w.invalid_union,unionErrors:f}),T}if(i.common.async)return Promise.all(c.map(async l=>{const f={...i,common:{...i.common,issues:[]},parent:null};return{result:await l._parseAsync({data:i.data,path:i.path,parent:f}),ctx:f}})).then(u);{let l;const f=[];for(const g of c){const y={...i,common:{...i.common,issues:[]},parent:null},x=g._parseSync({data:i.data,path:i.path,parent:y});if(x.status==="valid")return x;x.status==="dirty"&&!l&&(l={result:x,ctx:y}),y.common.issues.length&&f.push(y.common.issues)}if(l)return i.common.issues.push(...l.ctx.common.issues),l.result;const h=f.map(g=>new F(g));return b(i,{code:w.invalid_union,unionErrors:h}),T}}get options(){return this._def.options}}ht.create=(a,r)=>new ht({options:a,typeName:S.ZodUnion,...A(r)});const ae=a=>a instanceof gt?ae(a.schema):a instanceof J?ae(a.innerType()):a instanceof yt?[a.value]:a instanceof me?a.options:a instanceof vt?M.objectValues(a.enum):a instanceof wt?ae(a._def.innerType):a instanceof dt?[void 0]:a instanceof ft?[null]:a instanceof ee?[void 0,...ae(a.unwrap())]:a instanceof ge?[null,...ae(a.unwrap())]:a instanceof Tn||a instanceof _t?ae(a.unwrap()):a instanceof bt?ae(a._def.innerType):[];class Wt extends O{_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.object)return b(i,{code:w.invalid_type,expected:_.object,received:i.parsedType}),T;const c=this.discriminator,u=i.data[c],l=this.optionsMap.get(u);return l?i.common.async?l._parseAsync({data:i.data,path:i.path,parent:i}):l._parseSync({data:i.data,path:i.path,parent:i}):(b(i,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[c]}),T)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(r,i,c){const u=new Map;for(const l of i){const f=ae(l.shape[r]);if(!f.length)throw new Error(`A discriminator value for key \`${r}\` could not be extracted from all schema options`);for(const h of f){if(u.has(h))throw new Error(`Discriminator property ${String(r)} has duplicate value ${String(h)}`);u.set(h,l)}}return new Wt({typeName:S.ZodDiscriminatedUnion,discriminator:r,options:i,optionsMap:u,...A(c)})}}function Sn(a,r){const i=oe(a),c=oe(r);if(a===r)return{valid:!0,data:a};if(i===_.object&&c===_.object){const u=M.objectKeys(r),l=M.objectKeys(a).filter(h=>u.indexOf(h)!==-1),f={...a,...r};for(const h of l){const g=Sn(a[h],r[h]);if(!g.valid)return{valid:!1};f[h]=g.data}return{valid:!0,data:f}}else if(i===_.array&&c===_.array){if(a.length!==r.length)return{valid:!1};const u=[];for(let l=0;l<a.length;l++){const f=a[l],h=r[l],g=Sn(f,h);if(!g.valid)return{valid:!1};u.push(g.data)}return{valid:!0,data:u}}else return i===_.date&&c===_.date&&+a==+r?{valid:!0,data:a}:{valid:!1}}class pt extends O{_parse(r){const{status:i,ctx:c}=this._processInputParams(r),u=(l,f)=>{if(kn(l)||kn(f))return T;const h=Sn(l.value,f.value);return h.valid?((En(l)||En(f))&&i.dirty(),{status:i.value,value:h.data}):(b(c,{code:w.invalid_intersection_types}),T)};return c.common.async?Promise.all([this._def.left._parseAsync({data:c.data,path:c.path,parent:c}),this._def.right._parseAsync({data:c.data,path:c.path,parent:c})]).then(([l,f])=>u(l,f)):u(this._def.left._parseSync({data:c.data,path:c.path,parent:c}),this._def.right._parseSync({data:c.data,path:c.path,parent:c}))}}pt.create=(a,r,i)=>new pt({left:a,right:r,typeName:S.ZodIntersection,...A(i)});class re extends O{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.array)return b(c,{code:w.invalid_type,expected:_.array,received:c.parsedType}),T;if(c.data.length<this._def.items.length)return b(c,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T;!this._def.rest&&c.data.length>this._def.items.length&&(b(c,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty());const l=[...c.data].map((f,h)=>{const g=this._def.items[h]||this._def.rest;return g?g._parse(new te(c,f,c.path,h)):null}).filter(f=>!!f);return c.common.async?Promise.all(l).then(f=>z.mergeArray(i,f)):z.mergeArray(i,l)}get items(){return this._def.items}rest(r){return new re({...this._def,rest:r})}}re.create=(a,r)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new re({items:a,typeName:S.ZodTuple,rest:null,...A(r)})};class mt extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.object)return b(c,{code:w.invalid_type,expected:_.object,received:c.parsedType}),T;const u=[],l=this._def.keyType,f=this._def.valueType;for(const h in c.data)u.push({key:l._parse(new te(c,h,c.path,h)),value:f._parse(new te(c,c.data[h],c.path,h)),alwaysSet:h in c.data});return c.common.async?z.mergeObjectAsync(i,u):z.mergeObjectSync(i,u)}get element(){return this._def.valueType}static create(r,i,c){return i instanceof O?new mt({keyType:r,valueType:i,typeName:S.ZodRecord,...A(c)}):new mt({keyType:G.create(),valueType:r,typeName:S.ZodRecord,...A(i)})}}class Vt extends O{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.map)return b(c,{code:w.invalid_type,expected:_.map,received:c.parsedType}),T;const u=this._def.keyType,l=this._def.valueType,f=[...c.data.entries()].map(([h,g],y)=>({key:u._parse(new te(c,h,c.path,[y,"key"])),value:l._parse(new te(c,g,c.path,[y,"value"]))}));if(c.common.async){const h=new Map;return Promise.resolve().then(async()=>{for(const g of f){const y=await g.key,x=await g.value;if(y.status==="aborted"||x.status==="aborted")return T;(y.status==="dirty"||x.status==="dirty")&&i.dirty(),h.set(y.value,x.value)}return{status:i.value,value:h}})}else{const h=new Map;for(const g of f){const y=g.key,x=g.value;if(y.status==="aborted"||x.status==="aborted")return T;(y.status==="dirty"||x.status==="dirty")&&i.dirty(),h.set(y.value,x.value)}return{status:i.value,value:h}}}}Vt.create=(a,r,i)=>new Vt({valueType:r,keyType:a,typeName:S.ZodMap,...A(i)});class Ae extends O{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.set)return b(c,{code:w.invalid_type,expected:_.set,received:c.parsedType}),T;const u=this._def;u.minSize!==null&&c.data.size<u.minSize.value&&(b(c,{code:w.too_small,minimum:u.minSize.value,type:"set",inclusive:!0,exact:!1,message:u.minSize.message}),i.dirty()),u.maxSize!==null&&c.data.size>u.maxSize.value&&(b(c,{code:w.too_big,maximum:u.maxSize.value,type:"set",inclusive:!0,exact:!1,message:u.maxSize.message}),i.dirty());const l=this._def.valueType;function f(g){const y=new Set;for(const x of g){if(x.status==="aborted")return T;x.status==="dirty"&&i.dirty(),y.add(x.value)}return{status:i.value,value:y}}const h=[...c.data.values()].map((g,y)=>l._parse(new te(c,g,c.path,y)));return c.common.async?Promise.all(h).then(g=>f(g)):f(h)}min(r,i){return new Ae({...this._def,minSize:{value:r,message:E.toString(i)}})}max(r,i){return new Ae({...this._def,maxSize:{value:r,message:E.toString(i)}})}size(r,i){return this.min(r,i).max(r,i)}nonempty(r){return this.min(1,r)}}Ae.create=(a,r)=>new Ae({valueType:a,minSize:null,maxSize:null,typeName:S.ZodSet,...A(r)});class Ue extends O{constructor(){super(...arguments),this.validate=this.implement}_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.function)return b(i,{code:w.invalid_type,expected:_.function,received:i.parsedType}),T;function c(h,g){return Zt({data:h,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Ut(),Ze].filter(y=>!!y),issueData:{code:w.invalid_arguments,argumentsError:g}})}function u(h,g){return Zt({data:h,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Ut(),Ze].filter(y=>!!y),issueData:{code:w.invalid_return_type,returnTypeError:g}})}const l={errorMap:i.common.contextualErrorMap},f=i.data;if(this._def.returns instanceof Le){const h=this;return V(async function(...g){const y=new F([]),x=await h._def.args.parseAsync(g,l).catch(se=>{throw y.addIssue(c(g,se)),y}),j=await Reflect.apply(f,this,x);return await h._def.returns._def.type.parseAsync(j,l).catch(se=>{throw y.addIssue(u(j,se)),y})})}else{const h=this;return V(function(...g){const y=h._def.args.safeParse(g,l);if(!y.success)throw new F([c(g,y.error)]);const x=Reflect.apply(f,this,y.data),j=h._def.returns.safeParse(x,l);if(!j.success)throw new F([u(x,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...r){return new Ue({...this._def,args:re.create(r).rest(Ee.create())})}returns(r){return new Ue({...this._def,returns:r})}implement(r){return this.parse(r)}strictImplement(r){return this.parse(r)}static create(r,i,c){return new Ue({args:r||re.create([]).rest(Ee.create()),returns:i||Ee.create(),typeName:S.ZodFunction,...A(c)})}}class gt extends O{get schema(){return this._def.getter()}_parse(r){const{ctx:i}=this._processInputParams(r);return this._def.getter()._parse({data:i.data,path:i.path,parent:i})}}gt.create=(a,r)=>new gt({getter:a,typeName:S.ZodLazy,...A(r)});class yt extends O{_parse(r){if(r.data!==this._def.value){const i=this._getOrReturnCtx(r);return b(i,{received:i.data,code:w.invalid_literal,expected:this._def.value}),T}return{status:"valid",value:r.data}}get value(){return this._def.value}}yt.create=(a,r)=>new yt({value:a,typeName:S.ZodLiteral,...A(r)});function hi(a,r){return new me({values:a,typeName:S.ZodEnum,...A(r)})}class me extends O{constructor(){super(...arguments),ot.set(this,void 0)}_parse(r){if(typeof r.data!="string"){const i=this._getOrReturnCtx(r),c=this._def.values;return b(i,{expected:M.joinValues(c),received:i.parsedType,code:w.invalid_type}),T}if(Bt(this,ot)||ui(this,ot,new Set(this._def.values)),!Bt(this,ot).has(r.data)){const i=this._getOrReturnCtx(r),c=this._def.values;return b(i,{received:i.data,code:w.invalid_enum_value,options:c}),T}return V(r.data)}get options(){return this._def.values}get enum(){const r={};for(const i of this._def.values)r[i]=i;return r}get Values(){const r={};for(const i of this._def.values)r[i]=i;return r}get Enum(){const r={};for(const i of this._def.values)r[i]=i;return r}extract(r,i=this._def){return me.create(r,{...this._def,...i})}exclude(r,i=this._def){return me.create(this.options.filter(c=>!r.includes(c)),{...this._def,...i})}}ot=new WeakMap;me.create=hi;class vt extends O{constructor(){super(...arguments),ct.set(this,void 0)}_parse(r){const i=M.getValidEnumValues(this._def.values),c=this._getOrReturnCtx(r);if(c.parsedType!==_.string&&c.parsedType!==_.number){const u=M.objectValues(i);return b(c,{expected:M.joinValues(u),received:c.parsedType,code:w.invalid_type}),T}if(Bt(this,ct)||ui(this,ct,new Set(M.getValidEnumValues(this._def.values))),!Bt(this,ct).has(r.data)){const u=M.objectValues(i);return b(c,{received:c.data,code:w.invalid_enum_value,options:u}),T}return V(r.data)}get enum(){return this._def.values}}ct=new WeakMap;vt.create=(a,r)=>new vt({values:a,typeName:S.ZodNativeEnum,...A(r)});class Le extends O{unwrap(){return this._def.type}_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.promise&&i.common.async===!1)return b(i,{code:w.invalid_type,expected:_.promise,received:i.parsedType}),T;const c=i.parsedType===_.promise?i.data:Promise.resolve(i.data);return V(c.then(u=>this._def.type.parseAsync(u,{path:i.path,errorMap:i.common.contextualErrorMap})))}}Le.create=(a,r)=>new Le({type:a,typeName:S.ZodPromise,...A(r)});class J extends O{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(r){const{status:i,ctx:c}=this._processInputParams(r),u=this._def.effect||null,l={addIssue:f=>{b(c,f),f.fatal?i.abort():i.dirty()},get path(){return c.path}};if(l.addIssue=l.addIssue.bind(l),u.type==="preprocess"){const f=u.transform(c.data,l);if(c.common.async)return Promise.resolve(f).then(async h=>{if(i.value==="aborted")return T;const g=await this._def.schema._parseAsync({data:h,path:c.path,parent:c});return g.status==="aborted"?T:g.status==="dirty"||i.value==="dirty"?Pe(g.value):g});{if(i.value==="aborted")return T;const h=this._def.schema._parseSync({data:f,path:c.path,parent:c});return h.status==="aborted"?T:h.status==="dirty"||i.value==="dirty"?Pe(h.value):h}}if(u.type==="refinement"){const f=h=>{const g=u.refinement(h,l);if(c.common.async)return Promise.resolve(g);if(g instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return h};if(c.common.async===!1){const h=this._def.schema._parseSync({data:c.data,path:c.path,parent:c});return h.status==="aborted"?T:(h.status==="dirty"&&i.dirty(),f(h.value),{status:i.value,value:h.value})}else return this._def.schema._parseAsync({data:c.data,path:c.path,parent:c}).then(h=>h.status==="aborted"?T:(h.status==="dirty"&&i.dirty(),f(h.value).then(()=>({status:i.value,value:h.value}))))}if(u.type==="transform")if(c.common.async===!1){const f=this._def.schema._parseSync({data:c.data,path:c.path,parent:c});if(!Se(f))return f;const h=u.transform(f.value,l);if(h instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:h}}else return this._def.schema._parseAsync({data:c.data,path:c.path,parent:c}).then(f=>Se(f)?Promise.resolve(u.transform(f.value,l)).then(h=>({status:i.value,value:h})):f);M.assertNever(u)}}J.create=(a,r,i)=>new J({schema:a,typeName:S.ZodEffects,effect:r,...A(i)});J.createWithPreprocess=(a,r,i)=>new J({schema:r,effect:{type:"preprocess",transform:a},typeName:S.ZodEffects,...A(i)});class ee extends O{_parse(r){return this._getType(r)===_.undefined?V(void 0):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}ee.create=(a,r)=>new ee({innerType:a,typeName:S.ZodOptional,...A(r)});class ge extends O{_parse(r){return this._getType(r)===_.null?V(null):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}ge.create=(a,r)=>new ge({innerType:a,typeName:S.ZodNullable,...A(r)});class wt extends O{_parse(r){const{ctx:i}=this._processInputParams(r);let c=i.data;return i.parsedType===_.undefined&&(c=this._def.defaultValue()),this._def.innerType._parse({data:c,path:i.path,parent:i})}removeDefault(){return this._def.innerType}}wt.create=(a,r)=>new wt({innerType:a,typeName:S.ZodDefault,defaultValue:typeof r.default=="function"?r.default:()=>r.default,...A(r)});class bt extends O{_parse(r){const{ctx:i}=this._processInputParams(r),c={...i,common:{...i.common,issues:[]}},u=this._def.innerType._parse({data:c.data,path:c.path,parent:{...c}});return ut(u)?u.then(l=>({status:"valid",value:l.status==="valid"?l.value:this._def.catchValue({get error(){return new F(c.common.issues)},input:c.data})})):{status:"valid",value:u.status==="valid"?u.value:this._def.catchValue({get error(){return new F(c.common.issues)},input:c.data})}}removeCatch(){return this._def.innerType}}bt.create=(a,r)=>new bt({innerType:a,typeName:S.ZodCatch,catchValue:typeof r.catch=="function"?r.catch:()=>r.catch,...A(r)});class Ft extends O{_parse(r){if(this._getType(r)!==_.nan){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.nan,received:c.parsedType}),T}return{status:"valid",value:r.data}}}Ft.create=a=>new Ft({typeName:S.ZodNaN,...A(a)});const wd=Symbol("zod_brand");class Tn extends O{_parse(r){const{ctx:i}=this._processInputParams(r),c=i.data;return this._def.type._parse({data:c,path:i.path,parent:i})}unwrap(){return this._def.type}}class xt extends O{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.common.async)return(async()=>{const l=await this._def.in._parseAsync({data:c.data,path:c.path,parent:c});return l.status==="aborted"?T:l.status==="dirty"?(i.dirty(),Pe(l.value)):this._def.out._parseAsync({data:l.value,path:c.path,parent:c})})();{const u=this._def.in._parseSync({data:c.data,path:c.path,parent:c});return u.status==="aborted"?T:u.status==="dirty"?(i.dirty(),{status:"dirty",value:u.value}):this._def.out._parseSync({data:u.value,path:c.path,parent:c})}}static create(r,i){return new xt({in:r,out:i,typeName:S.ZodPipeline})}}class _t extends O{_parse(r){const i=this._def.innerType._parse(r),c=u=>(Se(u)&&(u.value=Object.freeze(u.value)),u);return ut(i)?i.then(u=>c(u)):c(i)}unwrap(){return this._def.innerType}}_t.create=(a,r)=>new _t({innerType:a,typeName:S.ZodReadonly,...A(r)});function pi(a,r={},i){return a?Be.create().superRefine((c,u)=>{var l,f;if(!a(c)){const h=typeof r=="function"?r(c):typeof r=="string"?{message:r}:r,g=(f=(l=h.fatal)!==null&&l!==void 0?l:i)!==null&&f!==void 0?f:!0,y=typeof h=="string"?{message:h}:h;u.addIssue({code:"custom",...y,fatal:g})}}):Be.create()}const bd={object:N.lazycreate};var S;(function(a){a.ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly"})(S||(S={}));const _d=(a,r={message:`Input not instance of ${a.name}`})=>pi(i=>i instanceof a,r),mi=G.create,gi=he.create,xd=Ft.create,kd=pe.create,yi=lt.create,Ed=Te.create,Sd=Lt.create,Td=dt.create,Ad=ft.create,Od=Be.create,Id=Ee.create,Md=ce.create,$d=zt.create,Rd=K.create,Cd=N.create,Nd=N.strictCreate,jd=ht.create,Dd=Wt.create,Pd=pt.create,Ud=re.create,Zd=mt.create,Bd=Vt.create,Ld=Ae.create,zd=Ue.create,Vd=gt.create,Fd=yt.create,Wd=me.create,Hd=vt.create,qd=Le.create,ni=J.create,Gd=ee.create,Kd=ge.create,Jd=J.createWithPreprocess,Yd=xt.create,Qd=()=>mi().optional(),Xd=()=>gi().optional(),ef=()=>yi().optional(),tf={string:a=>G.create({...a,coerce:!0}),number:a=>he.create({...a,coerce:!0}),boolean:a=>lt.create({...a,coerce:!0}),bigint:a=>pe.create({...a,coerce:!0}),date:a=>Te.create({...a,coerce:!0})},rf=T;var D=Object.freeze({__proto__:null,defaultErrorMap:Ze,setErrorMap:Jl,getErrorMap:Ut,makeIssue:Zt,EMPTY_PATH:Yl,addIssueToContext:b,ParseStatus:z,INVALID:T,DIRTY:Pe,OK:V,isAborted:kn,isDirty:En,isValid:Se,isAsync:ut,get util(){return M},get objectUtil(){return xn},ZodParsedType:_,getParsedType:oe,ZodType:O,datetimeRegex:fi,ZodString:G,ZodNumber:he,ZodBigInt:pe,ZodBoolean:lt,ZodDate:Te,ZodSymbol:Lt,ZodUndefined:dt,ZodNull:ft,ZodAny:Be,ZodUnknown:Ee,ZodNever:ce,ZodVoid:zt,ZodArray:K,ZodObject:N,ZodUnion:ht,ZodDiscriminatedUnion:Wt,ZodIntersection:pt,ZodTuple:re,ZodRecord:mt,ZodMap:Vt,ZodSet:Ae,ZodFunction:Ue,ZodLazy:gt,ZodLiteral:yt,ZodEnum:me,ZodNativeEnum:vt,ZodPromise:Le,ZodEffects:J,ZodTransformer:J,ZodOptional:ee,ZodNullable:ge,ZodDefault:wt,ZodCatch:bt,ZodNaN:Ft,BRAND:wd,ZodBranded:Tn,ZodPipeline:xt,ZodReadonly:_t,custom:pi,Schema:O,ZodSchema:O,late:bd,get ZodFirstPartyTypeKind(){return S},coerce:tf,any:Od,array:Rd,bigint:kd,boolean:yi,date:Ed,discriminatedUnion:Dd,effect:ni,enum:Wd,function:zd,instanceof:_d,intersection:Pd,lazy:Vd,literal:Fd,map:Bd,nan:xd,nativeEnum:Hd,never:Md,null:Ad,nullable:Kd,number:gi,object:Cd,oboolean:ef,onumber:Xd,optional:Gd,ostring:Qd,pipeline:Yd,preprocess:Jd,promise:qd,record:Zd,set:Ld,strictObject:Nd,string:mi,symbol:Sd,transformer:ni,tuple:Ud,undefined:Td,union:jd,unknown:Id,void:$d,NEVER:rf,ZodIssueCode:w,quotelessJson:Kl,ZodError:F}),An=(a=>(a.TEXT="text",a.THREAD="thread",a.REACTION="reaction",a))(An||{});const ye=q.getInstance(),nf=["id","targetMessageId","type","message","username","address","timestamp","signature","index","chatTopic","userTopic","additionalProps"],On=D.object({id:D.string(),targetMessageId:D.string().optional(),type:D.nativeEnum(An),message:D.string(),username:D.string(),address:D.string(),timestamp:D.number(),signature:D.string(),index:D.number(),chatTopic:D.string(),userTopic:D.string(),additionalProps:D.record(D.any()).optional()}).refine(a=>!a.additionalProps||Object.keys(a.additionalProps).length===0?!0:uf(a.additionalProps).isValid,{message:"Invalid additional properties in message"}),sf=D.object({reference:D.string(),timestamp:D.number()}),af=D.object({message:On,messageStateRefs:D.array(sf).nullable()});function vi(a){const r=af.safeParse(a);return r.success?wi(a.message)?!0:(ye.warn("Invalid main message signature"),!1):(ye.warn("GSOC message validation failed:",r.error.format()),!1)}function of(a){if(!Array.isArray(a))return ye.warn("Message state must be an array"),!1;for(const r of a)if(!cf(r))return ye.warn("Invalid message in message state:",r.id),!1;return!0}function cf(a){const r=On.safeParse(a);return r.success?wi(a)?!0:(ye.warn("Invalid message signature"),!1):(ye.warn("Message data validation failed:",r.error.format()),!1)}function wi(a){try{const r={username:a.username,address:a.address,timestamp:a.timestamp,message:a.message},i=new TextEncoder,c=L.concatBytes(i.encode(`Ethereum Signed Message:
11
+ 32`),L.keccak256(i.encode(JSON.stringify(r))));if(new I.Signature(a.signature).isValid(c,a.address))throw new Error("Signature verification failed!");return!0}catch(r){return ye.warn("Error in validateUserSignature",r),!1}}function uf(a){const r=[];if(a==null)return{isValid:!0,errors:[]};if(typeof a!="object"||Array.isArray(a))return r.push("Additional properties must be a plain object"),{isValid:!1,errors:r};for(const g of Object.keys(a))nf.includes(g)&&r.push(`Property '${g}' is reserved and cannot be overridden`);const i=JSON.stringify(a),c=new TextEncoder().encode(i).length,u=1*1024;c>u&&r.push(`Additional properties too large: ${c} bytes (max: ${u} bytes)`);const l=5;function f(g,y=0){if(y>l)return!1;if(typeof g=="object"&&g!==null&&!Array.isArray(g)){for(const x of Object.values(g))if(!f(x,y+1))return!1}return!0}f(a)||r.push(`Additional properties nested too deeply (max depth: ${l})`);for(const[g,y]of Object.entries(a))if(g.length>100&&r.push(`Property key '${g}' too long (max: 100 characters)`),typeof y=="string"&&y.length>1e3&&r.push(`Property '${g}' value too long (max: 1000 characters)`),typeof y=="string"){const x=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/data:text\/html/gi,/vbscript:/gi,/on\w+\s*=/gi];for(const j of x)if(j.test(y)){r.push(`Property '${g}' contains potentially dangerous content`);break}}const h=20;return Object.keys(a).length>h&&r.push(`Too many additional properties: ${Object.keys(a).length} (max: ${h})`),{isValid:r.length===0,errors:r}}function lf(a){const r=On.safeParse(a);if(!r.success){const i=r.error.issues.map(c=>c.path.length>0?`${c.path.join(".")}: ${c.message}`:c.message);return ye.warn("Message validation failed:",r.error.format()),{isValid:!1,errors:i}}return{isValid:!0,errors:[]}}const H={LOADING_INIT:"loadingInit",LOADING_PREVIOUS_MESSAGES:"loadingPreviousMessages",MESSAGE_RECEIVED:"messageReceived",MESSAGE_REQUEST_INITIATED:"messageRequestInitiated",MESSAGE_REQUEST_UPLOADED:"messageRequestUploaded",MESSAGE_REQUEST_ERROR:"messageRequestError",CRITICAL_ERROR:"criticalError"};class df{constructor(r,i){this.utils=r,this.emitter=i,this.logger=q.getInstance(),this.errorHandler=X.getInstance(),this.processedRefs=new Set,this.refRetryCount=new Map,this.bannedRefs=new Set,this.latestStatefulMessage=null,this.MAX_RETRIES=3,this.RETRY_DELAY=1e3}async init(){try{const{data:r,index:i}=await this.utils.fetchLatestChatMessage();this.latestStatefulMessage=r;try{await this.initMessageState(r)}catch(c){this.errorHandler.handleError(c,"SwarmHistory.initMessageState")}return i}catch(r){return this.errorHandler.handleError(r,"SwarmHistory.init"),I.FeedIndex.fromBigInt(0n)}}async initMessageState(r){try{if(!vi(r)){this.logger.warn("Invalid GSOC message during message state initialization");return}if(!r.messageStateRefs||r.messageStateRefs.length===0){this.logger.debug("No message state refs to initialize");return}const i=this.findLatestRef(r.messageStateRefs);if(!i){this.logger.warn("No valid latest reference found");return}this.logger.debug("Initializing message state with latest ref:",i.reference),await this.processMessageRefWithRetry(i.reference)}catch(i){if(this.utils.isNotFoundError(i)){this.logger.debug("No latest GSOC message found for message state initialization");return}this.errorHandler.handleError(i,"SwarmHistory.init")}}async fetchPreviousMessageState(){let r=this.latestStatefulMessage;if(!r){const{data:c}=await this.utils.fetchLatestChatMessage();r=c,this.latestStatefulMessage=c}if(!r.messageStateRefs||r.messageStateRefs.length===0){this.logger.debug("No message state refs to fetch");return}const i=[...r.messageStateRefs].sort((c,u)=>c.timestamp-u.timestamp);for(const c of i)!this.processedRefs.has(c.reference)&&!this.bannedRefs.has(c.reference)&&(this.logger.debug("Fetching previous message ref:",c.reference),await this.processMessageRefWithRetry(c.reference))}findLatestRef(r){return r.length===0?null:r.reduce((i,c)=>c.timestamp>i.timestamp?c:i)}async processMessageRefWithRetry(r){if(!(this.processedRefs.has(r)||this.bannedRefs.has(r)))try{await this.processMessageRef(r)}catch(i){await this.handleRefError(r,i)}}async processMessageRef(r){const i=await this.utils.downloadObjectFromBee(r);if(!of(i))throw new Error(`Invalid message state for ref: ${r}`);this.processedRefs.add(r),this.refRetryCount.delete(r);for(const u of i)this.emitter.emit(H.MESSAGE_RECEIVED,u)}async handleRefError(r,i){const c=this.refRetryCount.get(r)||0,u=c+1;if(this.logger.warn(`Error processing ref ${r} (attempt ${u}/${this.MAX_RETRIES}):`,i),u>=this.MAX_RETRIES)this.bannedRefs.add(r),this.refRetryCount.delete(r),this.logger.error(`Ref ${r} has been banned after ${this.MAX_RETRIES} failed attempts`),this.errorHandler.handleError(i,"SwarmHistory.processMessageRef");else{this.refRetryCount.set(r,u);const l=this.RETRY_DELAY*Math.pow(2,c);this.logger.debug(`Retrying ref ${r} after ${l}ms delay`),await Hl(l),await this.processMessageRefWithRetry(r)}}hasPreviousMessages(){return!!this.latestStatefulMessage&&!!this.latestStatefulMessage.messageStateRefs&&this.latestStatefulMessage.messageStateRefs.length>1}cleanup(){this.processedRefs.clear(),this.refRetryCount.clear(),this.bannedRefs.clear(),this.latestStatefulMessage=null}}class ff{constructor(r,i){this.userDetails=r,this.swarmSettings=i,this.depth=26,this.errorHandler=X.getInstance()}generateUserOwnedFeedId(r,i){return`${r}_EthercastChat_${i}`}isNotFoundError(r){return r.stack.includes("404")||r.message.includes("Not Found")||r.message.includes("404")||r.code===404}async writeOwnFeedDataByIndex(r,i){const{enveloped:c,stamp:u}=this.swarmSettings;if(!c)await this.writeOwnFeedDataByIndexOwned(r,i);else if(u)await this.writeOwnFeedDataByIndexEnvelope(r,i);else throw new Error("Enveloped mode is enabled, but stamp is not provided")}async writeOwnFeedDataByIndexOwned(r,i){const{bee:c,stamp:u,chatTopic:l}=this.swarmSettings,{privateKey:f,ownAddress:h}=this.userDetails,g=this.generateUserOwnedFeedId(l,h),y=I.Topic.fromString(g);await c.makeFeedWriter(y,new I.PrivateKey(f)).uploadPayload(u,JSON.stringify(i),{index:r})}async writeOwnFeedDataByIndexEnvelope(r,i){const{bee:c,stamp:u,chatTopic:l}=this.swarmSettings,{privateKey:f,ownAddress:h}=this.userDetails,g=new I.PrivateKey(f),y=I.Stamper.fromBlank(f,u,this.depth),x=this.generateUserOwnedFeedId(l,h),j=I.Topic.fromString(x),ne=ai(j,r),se=ei(i),ze=ti(se,ne,g),Oe={hash:()=>ze.address.toUint8Array()},Ve=y.stamp(Oe),{upload:Ht}=c.makeSOCWriter(g),Fe=I.Bytes.fromUtf8(i);return(await Ht(Ve,ne,Fe.toUint8Array())).reference.toHex()}orderMessages(r){return r.sort((i,c)=>i.timestamp-c.timestamp)}async downloadObjectFromBee(r){try{const{bee:i}=this.swarmSettings,c=await i.downloadData(r);return c?c.toJSON():null}catch(i){return this.errorHandler.handleError(i,"Utils.downloadObjectFromBee"),null}}async uploadObjectToBee(r){const{enveloped:i,stamp:c}=this.swarmSettings;if(i){if(c)return this.uploadObjectToBeeEnvelope(r);throw new Error("Enveloped mode is enabled, but stamp is not provided")}else return this.uploadObjectToBeeOwn(r)}async uploadObjectToBeeOwn(r){try{const{bee:i,stamp:c}=this.swarmSettings;return(await i.uploadData(c,JSON.stringify(r),{redundancyLevel:4})).reference.toString()}catch(i){return this.errorHandler.handleError(i,"Utils.uploadObjectToBee"),null}}async uploadObjectToBeeEnvelope(r){try{const{bee:i,stamp:c}=this.swarmSettings,{privateKey:u}=this.userDetails,l=I.Stamper.fromBlank(u,c,this.depth),f=I.Bytes.fromUtf8(JSON.stringify(r)),h=new Ul(async y=>{await i.uploadChunk(l.stamp(y),y.build())});await h.append(f.toUint8Array());const g=await h.finalize();return L.uint8ArrayToHex(g.hash())}catch(i){return this.errorHandler.handleError(i,"Utils.uploadObjectToBee"),null}}async getOwnLatestFeedIndex(){try{const{bee:r,chatTopic:i}=this.swarmSettings,{ownAddress:c}=this.userDetails,u=this.generateUserOwnedFeedId(i,c),l=I.Topic.fromString(u),h=await r.makeFeedReader(l,c).downloadPayload(),g=Number(h.feedIndex.toBigInt()),y=g+1;return{latestIndex:g,nextIndex:y}}catch(r){if(this.isNotFoundError(r))return{latestIndex:-1,nextIndex:0};throw r}}async fetchLatestChatMessage(){const{bee:r,chatTopic:i,chatAddress:c}=this.swarmSettings,l=await r.makeFeedReader(I.Topic.fromString(i),oi(c)).downloadPayload();return{data:l.payload.toJSON(),index:l.feedIndex}}async sendMessageToGsoc(r){const{enveloped:i,stamp:c}=this.swarmSettings;if(!i)await this.sendMessageToGsocOwn(r);else if(c)await this.sendMessageToGsocEnvelope(r);else throw new Error("Enveloped mode is enabled, but stamp is not provided")}async rawSocDownload(r,i){const{beeUrl:c,socReadTimeout:u}=this.swarmSettings,l=new AbortController,f=setTimeout(()=>l.abort(),u);try{const h=await fetch(`${c}/soc/${r}/${i}`,{headers:{"swarm-chunk-retrieval-timeout":"2000ms"},signal:l.signal});if(!h.ok){const g=new Error(`Failed to fetch: ${r}/${i} [${h.status}]`);throw g.status=h.status,g}return await h.text()}catch(h){throw h.name==="AbortError"?new Error(`Request timeout: ${r}/${i}`):h}finally{clearTimeout(f)}}async sendMessageToGsocOwn(r){const{bee:i,stamp:c,gsocTopic:u,gsocResourceId:l,gsocWriteTimeout:f}=this.swarmSettings,h=new I.PrivateKey(l),g=I.Identifier.fromString(u),y=I.Bytes.fromUtf8(r),{upload:x}=i.makeSOCWriter(h,{timeout:f});await x(c,g,y.toUint8Array())}async sendMessageToGsocEnvelope(r){const{bee:i,stamp:c,gsocTopic:u,gsocResourceId:l,gsocWriteTimeout:f}=this.swarmSettings,{privateKey:h}=this.userDetails,g=I.Stamper.fromBlank(h,c,this.depth),y=new I.PrivateKey(l),x=I.Identifier.fromString(u),j=I.Bytes.fromUtf8(r),ne=ei(j.toUint8Array()),se=ti(ne,x,y),ze={hash:()=>se.address.toUint8Array()},Oe=g.stamp(ze),{upload:Ve}=i.makeSOCWriter(y,{timeout:f});await Ve(Oe,x,j.toUint8Array())}}class hf{constructor(r,i){this.fallbackTransport=null,this.logger=q.getInstance(),this.errorHandler=X.getInstance(),this.gsocIndex=null;const c=new I.PrivateKey(oi(r.user.privateKey));this.userDetails={privateKey:r.user.privateKey,ownAddress:c.publicKey().address().toString(),nickname:r.user.nickname,ownIndex:-1},this.swarmSettings={bee:new I.Bee(r.infra.beeUrl),beeUrl:r.infra.beeUrl,stamp:r.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:r.infra.enveloped,gsocTopic:r.infra.gsocTopic,gsocResourceId:r.infra.gsocResourceId,chatTopic:r.infra.chatTopic,chatAddress:r.infra.chatAddress,feedReadTimeout:r.infra.feedReadTimeout||12e3,gsocWriteTimeout:r.infra.gsocWriteTimeout||2e3,socReadTimeout:r.infra.socReadTimeout||5e3},this.emitter=new Gl,this.utils=new ff(this.userDetails,this.swarmSettings),this.history=new df(this.utils,this.emitter);const u=r.infra.pollingInterval||1e3;i?(this.transport=i,r.infra.enableFallbackPolling&&(this.logger.info(`Fallback polling enabled with interval: ${u}ms`),this.fallbackTransport=this.createDefaultPollingTransport(u),this.fallbackTransport.onMessage(l=>{this.emitter.emit(H.MESSAGE_RECEIVED,l)}))):this.transport=this.createDefaultPollingTransport(u),this.transport.onMessage(l=>{this.emitter.emit(H.MESSAGE_RECEIVED,l)})}createDefaultPollingTransport(r){return new si({fetchMessage:async()=>{try{if(!this.gsocIndex)return null;const i=I.Topic.fromString(this.swarmSettings.chatTopic),c=ai(i,this.gsocIndex),u=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,c.toString()),l=JSON.parse(u);return vi(l)?(this.gsocIndex=this.gsocIndex.next(),l.message):(this.logger.warn("Invalid GSOC message during fetching"),null)}catch(i){if(this.utils.isNotFoundError(i))return null;throw i}},pollingInterval:r||1e3})}async start(){await this.init(),await this.transport.start(),this.fallbackTransport&&await this.fallbackTransport.start()}async stop(){this.emitter.cleanAll(),this.history.cleanup(),await this.transport.stop(),this.fallbackTransport&&await this.fallbackTransport.stop()}getEmitter(){return this.emitter}orderMessages(r){return this.utils.orderMessages(r)}async sendMessage(r,i,c,u,l){const f=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,h={id:u||Dl(),username:this.userDetails.nickname,address:this.userDetails.ownAddress,chatTopic:this.swarmSettings.chatTopic,userTopic:this.utils.generateUserOwnedFeedId(this.swarmSettings.chatTopic,this.userDetails.ownAddress),signature:this.getSignature(r),timestamp:Date.now(),index:f,type:i,targetMessageId:c,message:r,additionalProps:l},g=lf(h);if(!g.isValid){const y=`Invalid message: ${g.errors.join(", ")}`;throw this.logger.error(y),new Error(y)}try{this.emitter.emit(H.MESSAGE_REQUEST_INITIATED,h),await this.utils.writeOwnFeedDataByIndex(f,JSON.stringify(h)),this.userDetails.ownIndex=f,this.emitter.emit(H.MESSAGE_REQUEST_UPLOADED,h),await this.broadcastUserMessage(h)}catch(y){this.emitter.emit(H.MESSAGE_REQUEST_ERROR,h),this.errorHandler.handleError(y,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(H.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(H.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(r){this.sendMessage(r.message,r.type,r.targetMessageId,r.id,r.additionalProps)}async retryBroadcastUserMessage(r){await this.broadcastUserMessage(r)}async init(){var r,i;try{this.emitter.emit(H.LOADING_INIT,!0);const u=this.swarmSettings.feedReadTimeout-1e3,[l,f]=await ql(Promise.allSettled([this.initOwnIndex(),this.history.init()]),u,"Initialization timed out");if(l.status==="rejected")throw l.reason;f.status==="fulfilled"&&(this.gsocIndex=f.value)}catch(c){this.errorHandler.handleError(c,"Chat.initSelfState"),(r=c.message)!=null&&r.includes("timed out")||(i=c.message)!=null&&i.includes("timeout")?this.userDetails.ownIndex===void 0&&(this.userDetails.ownIndex=-1):this.emitter.emit(H.CRITICAL_ERROR,c)}finally{this.emitter.emit(H.LOADING_INIT,!1)}}async initOwnIndex(){const{latestIndex:c}=await _n(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=c}async broadcastUserMessage(r){try{return _n(()=>this.utils.sendMessageToGsoc(JSON.stringify(r)))}catch(i){this.errorHandler.handleError(i,"Chat.broadcastUserMessage")}}getSignature(r){const{ownAddress:i,privateKey:c,nickname:u}=this.userDetails,l=new I.EthAddress(i).toString(),f=new I.PrivateKey(c);if(f.publicKey().address().toString()!==l)throw new Error("The provided address does not match the address derived from the private key");const g=Date.now();return f.sign(JSON.stringify({username:u,address:l,message:r,timestamp:g})).toHex()}}exports.EVENTS=H;exports.MessageType=An;exports.PollingTransport=si;exports.SwarmChat=hf;