@solarpunkltd/swarm-chat-js 6.2.6 → 6.2.7
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.esm.js +378 -378
- package/dist/index.js +5 -5
- package/dist/lib/core.d.ts.map +1 -1
- package/dist/swarm-chat-umd.js +1 -1
- package/package.json +1 -1
package/dist/lib/core.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../../src/lib/core.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,2BAA2B,EAC3B,YAAY,EAGZ,WAAW,EACX,WAAW,EAEZ,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAKlE,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAQrD,qBAAa,SAAS;IACpB,OAAO,CAAC,SAAS,CAAmB;IACpC,OAAO,CAAC,iBAAiB,CAAiC;IAE1D,OAAO,CAAC,OAAO,CAAe;IAC9B,OAAO,CAAC,KAAK,CAAiB;IAC9B,OAAO,CAAC,OAAO,CAAe;IAC9B,OAAO,CAAC,WAAW,CAAmB;IACtC,OAAO,CAAC,aAAa,CAAoB;IAEzC,OAAO,CAAC,MAAM,CAAwB;IACtC,OAAO,CAAC,YAAY,CAA8B;IAElD,OAAO,CAAC,SAAS,CAA0B;gBAE/B,QAAQ,EAAE,YAAY,EAAE,SAAS,CAAC,EAAE,gBAAgB;IAkDhE,OAAO,CAAC,6BAA6B;IAgCxB,KAAK;IASL,IAAI;IAUV,UAAU;IAIV,aAAa,CAAC,QAAQ,EAAE,GAAG,EAAE;IAIvB,WAAW,CACtB,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,WAAW,EACjB,eAAe,CAAC,EAAE,MAAM,EACxB,EAAE,CAAC,EAAE,MAAM,EACX,eAAe,CAAC,EAAE,2BAA2B,GAC5C,OAAO,CAAC,IAAI,CAAC;IAwCH,qBAAqB;IAW3B,mBAAmB,IAAI,OAAO;IAIxB,gBAAgB,CAAC,OAAO,EAAE,WAAW;IAIrC,yBAAyB,CAAC,OAAO,EAAE,WAAW;YAI7C,IAAI;
|
|
1
|
+
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../../src/lib/core.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,2BAA2B,EAC3B,YAAY,EAGZ,WAAW,EACX,WAAW,EAEZ,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAKlE,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAQrD,qBAAa,SAAS;IACpB,OAAO,CAAC,SAAS,CAAmB;IACpC,OAAO,CAAC,iBAAiB,CAAiC;IAE1D,OAAO,CAAC,OAAO,CAAe;IAC9B,OAAO,CAAC,KAAK,CAAiB;IAC9B,OAAO,CAAC,OAAO,CAAe;IAC9B,OAAO,CAAC,WAAW,CAAmB;IACtC,OAAO,CAAC,aAAa,CAAoB;IAEzC,OAAO,CAAC,MAAM,CAAwB;IACtC,OAAO,CAAC,YAAY,CAA8B;IAElD,OAAO,CAAC,SAAS,CAA0B;gBAE/B,QAAQ,EAAE,YAAY,EAAE,SAAS,CAAC,EAAE,gBAAgB;IAkDhE,OAAO,CAAC,6BAA6B;IAgCxB,KAAK;IASL,IAAI;IAUV,UAAU;IAIV,aAAa,CAAC,QAAQ,EAAE,GAAG,EAAE;IAIvB,WAAW,CACtB,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,WAAW,EACjB,eAAe,CAAC,EAAE,MAAM,EACxB,EAAE,CAAC,EAAE,MAAM,EACX,eAAe,CAAC,EAAE,2BAA2B,GAC5C,OAAO,CAAC,IAAI,CAAC;IAwCH,qBAAqB;IAW3B,mBAAmB,IAAI,OAAO;IAIxB,gBAAgB,CAAC,OAAO,EAAE,WAAW;IAIrC,yBAAyB,CAAC,OAAO,EAAE,WAAW;YAI7C,IAAI;YAuCJ,YAAY;YASZ,oBAAoB;IAQlC,OAAO,CAAC,YAAY;CAiBrB"}
|
package/dist/swarm-chat-umd.js
CHANGED
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
`],s+o.length):e.indexOf(t.opening,s+o.length)}}function Kc(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 Yc(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 Qc(e){const t=[];let n=0;for(;n<e.length;){const s=qc(e,n);if(s===-1){t.push({string:e.slice(n),symbol:null});break}const o=Hc(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 Xc(e){const t=[];let n=0;for(;n<e.length;){const s=Ue(e,["http://","https://"],n);if(s===-1){t.push({string:e.slice(n),symbol:null});break}const o=Ue(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 As="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Os="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function Jc(e){return Is(e,As)}function eu(e){return Ms(e,As)}function tu(e){return Is(e,Os)}function ru(e){return Ms(e,Os)}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 E=t.indexOf(m);if(E===-1)throw new Error(`Invalid character: ${m}`);d=d<<Math.log2(s)|E,o+=Math.log2(s),o>=8&&(o-=8,p.push(d>>o&255))}return new Uint8Array(p)}function Ms(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 nu(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 su(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function iu(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 vr(e,t,n){const s=[];for(const o of n)o!==t&&s.push(e.replace(t,o));return s}function au(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(E=>E!==p.avoid),m=v.find(E=>e.includes(E));if(m&&(Dt(d,vr(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&&(Dt(d,vr(e,v,p.variants)),d.length>=n))break}return d.slice(0,n)}function ou(e,t,n,s=!1){const o=new RegExp(s?`(?<=\\s|^)${t}(?=\\s|$)`:`\\b${t}\\b`,"g");return e.replace(o,n)}function cu(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 uu(e){return e.replace(/<[^>]*>/g,"")}function $s(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 lu(e,t={}){return[...e].reduce((n,s)=>n+(t[s]||1),0)}function du(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:E,rest:$}=$s(o);s.push(E),o=$,d=$.split("").map(U=>n[U]||1).reduce((U,ze)=>U+ze,0)}}return o&&s.push(o),s}function fu(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 wr(e,t){return new RegExp(`\\b${t}\\b`).test(e)}function hu(e,t,n){return n==="any"?t.some(s=>wr(e,s)):t.every(s=>wr(e,s))}function pu(e){const t={},n=e.match(/([a-z\-]+)="([^"]+)"/g);if(n)for(const s of n){const[o,d]=mr(s,"=");t[o]=d.slice(1,d.length-1)}return t}function Zt(e,t,n=[]){let s="";for(;t<e.length&&(dt(e[t])||n.includes(e[t]));)s+=e[t++];return s}function mu(e,t,n="$",s=":"){for(const o in t)e=Rs(e,o,t[o],n,s);return e=Cs(e),e}function Rs(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=Zt(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 Cs(e,t="$",n=":"){let s=e.indexOf(t);for(;s!==-1;){const o=Zt(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=Zt(e,s+o.length+2);e=e.replace(`${t}${o}${n}${d}`,d)}s=e.indexOf(t,s+1)}return e}function gu(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 Ns(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 yu(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 vu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function wu(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 bu(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)=>Nt(p[t])-Nt(v[t])),e.forEach((p,v)=>p[t]=v+1)}function _u(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 xu(e,t=":"){return Object.fromEntries(e.map(n=>mr(n,t)).map(n=>n[0]&&n[1]?[lt(n[0]),lt(n[1])]:null).filter(n=>n))}function ku(e,t,n){return Us(e,t)+Ns(n||{})}function Eu(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 Su(e){return`[${Math.floor(e.progress*100)}%] ${Bt(e.deltaMs)} out of ${Bt(e.totalTimeMs)} (${Bt(e.remainingTimeMs)} left) [${Math.round(e.baseTimeMs)} ms each]`}async function Tu(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 Au(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 Ou(e){return JSON.parse(JSON.stringify(e))}function Iu(e){return Math.ceil((e||Date.now())/1e3)}function Mu(e){return(e||new Date).toISOString().slice(0,10)}function $u(e){return(e||new Date).toISOString().slice(0,19).replace(/T|:/g,"-")}function Ru(e){const t=new Date(e);return new Date(t.getTime()-t.getTimezoneOffset()*6e4)}function Cu(e){return new Date(e)}function re(e){return String(Math.floor(e)).padStart(2,"0")}function Nu(e){let[t,n]=e.split(":");ge(parseInt(t,10))||(t="0"),ge(parseInt(n,10))||(n="0");let s=Er(dr(t),0,23),o=Er(dr(n),0,59);return`${re(s)}:${re(o)}`}function Bt(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?`${re(t)}:${re(n)}:${re(s)}`:`${re(n)}:${re(s)}`}function Te(e){return Math.floor((Pe(e)?e.getTime():e)/864e5)}const ju={today:(e,t)=>re(e)+":"+re(t),yesterday:()=>"Yesterday",monday:()=>"Mon",tuesday:()=>"Tue",wednesday:()=>"Wed",thursday:()=>"Thu",friday:()=>"Fri",saturday:()=>"Sat",sunday:()=>"Sun",weeks:e=>`${e}w`};function Du(e,t){const n=new Date((t==null?void 0:t.now)||Date.now()),s=(t==null?void 0:t.labels)||ju,o=Pe(e)?e:new Date(e);if(Te(n)===Te(o))return s.today(o.getUTCHours(),o.getUTCMinutes(),o.getUTCHours()>12);if(Te(n)-Te(o)===1)return s.yesterday();const d=_r(o);return Te(n)-Te(o)<7?s[d.day]():s.weeks(Math.round((n.getTime()-o.getTime())/6048e5))}const js={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 Ds(e,t){const n=(t==null?void 0:t.now)??Date.now(),s=(t==null?void 0:t.labels)||js,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 Pu(e,t=js){return Ds(0,{now:e*1e3,labels:t})}function Uu(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 br={};function Zu(e,t){return!br[e]||Date.now()>br[e]?(br[e]=Date.now()+t,!0):!1}const Bu={s:1e3,m:6e4,h:36e5,d:864e5};function Lu(e,t,n){return t=Pe(t)?t.getTime():t,n=n?Pe(n)?n.getTime():n:Date.now(),(n-t)/Bu[e]}function zu(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 Vu={0:"sunday",1:"monday",2:"tuesday",3:"wednesday",4:"thursday",5:"friday",6:"saturday"};function Ps(e){return{zeroBasedIndex:e,day:Vu[e]}}function _r(e){return Ps(e.getDay())}function Fu(e){return _r(new Date(e))}function Wu(e){return e*1e3}function Hu(e){return e*6e4}function qu(e){return e*36e5}function Gu(e){return e*864e5}const Ku={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 Yu(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=Ku[n];if(!s)throw Error(`Unknown unit: "${n}"`);return t*s}const Qu={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 Xu(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=Qu[n];if(!s)throw Error(`Unknown unit: "${n}"`);return t*s}function Ju(e){return e.replace(/ +/g," ").replace(/^ /gm,"")}const xr={};async function el(e,t,n){const s=Date.now(),o=xr[e];if(o&&o.validUntil>s)return o.value;const d=await n(),p=s+t;return xr[e]={value:d,validUntil:p},d}function tl(e){delete xr[e]}function Us(...e){return e.filter(t=>t).join("/").replace(new RegExp("(?<!:)\\/+","g"),"/")}function rl(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 nl(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 sl(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 il(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 Zs(e){const t=Object.keys(e).sort((s,o)=>s.localeCompare(o)),n={};for(const s of t)n[s]=Ae(e[s]);return n}function Bs(e){const t=[];return e.sort((n,s)=>JSON.stringify(Ae(n)).localeCompare(JSON.stringify(Ae(s)))).forEach(n=>t.push(Ae(n))),t}function Ae(e){return Array.isArray(e)?Bs(e):me(e)?Zs(e):e}function Ls(e,t){return JSON.stringify(Ae(e))===JSON.stringify(Ae(t))}function al(...e){for(let t=1;t<e.length;t++)if(!Ls(e[t-1],e[t]))return!1;return!0}function ol(e){try{return JSON.parse(e)}catch{return null}}function cl(){let e=0;return{next:()=>e++}}function ul(e){let t=0;return{next:()=>e[t++%e.length]}}function ll(e){let t;return n=>{const s=n===e&&t!==e;return t=n,s}}function dl(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 fl(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 zs(e){const t=Object.keys(e);return t[Math.floor(Math.random()*t.length)]}function hl(e,t){const n=zs(e);return e[n]=t(e[n]),n}function pl(e){return e=e.replace(/\r\n/g,`
|
|
10
10
|
`),e=e.replace(/(\w+)\((.+)\)/g,(t,n,s)=>`${n}(${s.replaceAll(",",",")})`),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(",",","),JSON.parse(e)}const ye=[1e3,1e6,1e9,1e12,1e15,1e18,1e21,1e24,1e27,1e30,1e9,1e16,1e18,1e18,1e18,1e33],ml=["thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion","gwei","bzz","btc","eth","dai","decillion"],Vs=["K","M","B","T","Qa","Qi","Sx","Sp","O","N","gwei","bzz","eth","btc","dai","D"];function gl(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 yl(e,t){const n=(t==null?void 0:t.longForm)??!1,s=t!=null&&t.unit?` ${t.unit}`:"",o=n?ml:Vs,d=(t==null?void 0:t.precision)??1;if(e<ye[0])return`${e}${s}`;for(let p=0;p<ye.length-1;p++)if(e<ye[p+1])return`${(e/ye[p]).toFixed(d)}${n?" ":""}${o[p]}${s}`;return`${(e/ye[ye.length-1]).toFixed(d)}${n?" ":""}${o[ye.length-1]}${s}`}function kr(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeNumber got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim(),s=Vs.findIndex(o=>o.toLowerCase()===n.toLowerCase());return s===-1?t:t*ye[s]}function Er(e,t,n){return e<t?t:e>n?n:e}function vl(e,t,n){const s=e+t;return s>n?n:s}function wl(e,t,n){const s=e-t;return s<n?n:s}function bl(e,t){return t(e),e}function _l(e,t){e&&t(e)}function xl(e,t){const n=Object.keys(t);for(const s of n)Array.isArray(t[s])&&Array.isArray(e[s])&&Dt(e[s],t[s])}function kl(e){return e.splice(0,e.length),e}function El(e){for(const t of Object.keys(e))(rs(e[t])||Array.isArray(e[t])&&e[t].every(n=>n==null))&&delete e[t];return e}function Sl(e){for(const t of Object.entries(e))(t[1]===null||t[1]===void 0||H(t[1])&&Ct(t[1]))&&delete e[t[0]];return e}function Tl(e,t){const n={};for(const[s,o]of Object.entries(e))t(s)&&(n[s]=o);return n}function Al(e,t){const n={};for(const[s,o]of Object.entries(e))t(o)&&(n[s]=o);return n}function Ol(e,t){const n={};for(const s of Object.entries(e))n[s[0]]=t(s[1]);return n}function Il(e,t){const n=[];let s=0;for(const o of e)n.push(t(o,s++));return n}async function Ml(e,t){try{return await e()}catch{throw t}}function $l(e,t,n){n!=null&&(e[t]=n)}function Rl(e,t,n,s){const o=ke(n,s);o!=null&&Ee(e,t,o)}function Cl(e){const t={};for(const[n,s]of Object.entries(e))t[s]=n;return t}function Nl(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 E=0;E<t.length;E++){const $=e[t[E]],U=Math.floor(v/d[E])%$.length;m[t[E]]=$[U]}p.push(m)}return p}function jl(e){return Object.values(e).filter(t=>t).length}function Dl(e,t,n){return e+(n?"["+t+"]":(e.length?".":"")+t)}function Lt(e,t,n,s,o){if(!me(t))return t;for(const[d,p]of Object.entries(t)){const v=Dl(n,d,s);Array.isArray(p)?o?Lt(e,p,v,!0,o):e[v]=p.map(m=>Lt(Array.isArray(m)?[]:{},m,"",!1,o)):me(p)?Lt(e,p,v,!1,o):e[v]=p}return e}function Pl(e,t=!1,n){return Lt({},e,n||"",!1,t)}function Fs(e){if(!me(e))return e;const t=Array.isArray(e)?[]:{};for(const[n,s]of Object.entries(e))Array.isArray(s)?Ee(t,n,s.map(o=>Fs(o))):Ee(t,n,s);return t}function Ul(e,t,n){return t[e]?t[e]:n}function Ws(e,t){const n={};for(const s of e){const o=t(s);n[o]=s}return n}function Zl(e,t){const n={};for(const s of e){const o=t(s);n[o]||(n[o]=[]),n[o].push(s)}return n}function Bl(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function Hs(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 qs(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 Ll(e,t){const n=Math.ceil(e.length/t);return qs(e,n)}function zl(e,t){return Object.values(Ws(e,t))}function Vl(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?Gs(p,o?(m,E)=>m[1]-E[1]:(m,E)=>E[1]-m[1]):p;return n?Object.keys(v):v}function Gs(e,t){return Object.fromEntries(Object.entries(e).sort(t))}function Fl(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 Wl(e,t,n=1){for(const s of e)s[t]+=n}function Hl(e,t,n){for(const s of e)s[t]=n}function Sr(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 ql(){return{map:new Map,keys:[]}}function Gl(){return{map:new Map,keys:[]}}function Ks(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 Kl(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 Yl(e,t,n,s,o=100){Ks(e,t,{validUntil:Date.now()+s,data:n},o)}function Ql(e,t){const n=e.map.get(t);return n&&n.validUntil>Date.now()?n.data:null}class ve{constructor(t){this.value=t}static of(t){return new ve(t)}static empty(){return new ve(null)}map(t){return new ve(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=>ve.of(n)):Promise.resolve(ve.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=ve;class Xl{constructor(t){this.supplier=t,this.value=null}get(){return this.value||(this.value=this.supplier()),this.value}}a.Lazy=Xl;class Jl{constructor(t){this.supplier=t,this.value=null}async get(){return this.value||(this.value=await this.supplier()),this.value}}a.AsyncLazy=Jl;function ed(e){return()=>e.forEach(t=>t())}function td(e,t){return e.reduce((n,s)=>t(n)>t(s)?n:s)}function rd(e,t){const n=e.find(s=>s instanceof t);return ve.of(n)}function nd(e,t){return e.filter(n=>n instanceof t)}function sd(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 id(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}class ad{constructor(t){this.value=t,this.children=[]}}function od(e,t,n,s,o=!1){const d=new Map,p=[];e.forEach(m=>{const E=new ad(m);d.set(m[t],E)}),e.forEach(m=>{const E=d.get(m[t]);if(!E)return;const $=m[n];if($){const U=d.get($);U&&U.children.push(E)}else p.push(E)});const v=m=>{m.children.sort((E,$)=>{const U=E.value[s],ze=$.value[s];return o?ze-U:U-ze}),m.children.forEach(v)};return p.forEach(v),p}function Ys(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 Ze(...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 Qs(e){return e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}function Xs(e){return e[0]===255&&e[1]===216}function Js(e){return e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function cd(e){return Qs(e)||Xs(e)||Js(e)}function ud(e){return new Uint8Array([e])}function ld(e){return e[0]}function dd(e,t){const n=new ArrayBuffer(2);return new DataView(n).setUint16(0,e,t==="LE"),new Uint8Array(n)}function fd(e,t){return new DataView(e.buffer).getUint16(e.byteOffset,t==="LE")}function hd(e,t){const n=new ArrayBuffer(4);return new DataView(n).setUint32(0,e,t==="LE"),new Uint8Array(n)}function pd(e,t){return new DataView(e.buffer).getUint32(e.byteOffset,t==="LE")}function Tr(e,t){const n=new ArrayBuffer(8);return new DataView(n).setBigUint64(0,BigInt(e),t==="LE"),new Uint8Array(n)}function md(e,t){return new DataView(e.buffer).getBigUint64(e.byteOffset,t==="LE")}function Be(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 Le(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 gd(e,t){const n=[];let s=0;for(const o of t)n.push(e.subarray(s,s+o)),s+=o;return n}function Ar(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.subarray(s,s+t));return n}const ei=[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 yd(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],E=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],ze=o<<1|d>>>31,Jd=d<<1|o>>>31,pt=$^ze,mt=U^Jd,ef=p<<1|v>>>31,tf=v<<1|p>>>31,gt=n^ef,yt=s^tf,rf=m<<1|E>>>31,nf=E<<1|m>>>31,vt=o^rf,wt=d^nf,sf=$<<1|U>>>31,af=U<<1|$>>>31,bt=p^sf,_t=v^af,of=n<<1|s>>>31,cf=s<<1|n>>>31,xt=m^of,kt=E^cf;e[0]^=pt,e[1]^=mt,e[2]^=gt,e[3]^=yt,e[4]^=vt,e[5]^=wt,e[6]^=bt,e[7]^=_t,e[8]^=xt,e[9]^=kt,e[10]^=pt,e[11]^=mt,e[12]^=gt,e[13]^=yt,e[14]^=vt,e[15]^=wt,e[16]^=bt,e[17]^=_t,e[18]^=xt,e[19]^=kt,e[20]^=pt,e[21]^=mt,e[22]^=gt,e[23]^=yt,e[24]^=vt,e[25]^=wt,e[26]^=bt,e[27]^=_t,e[28]^=xt,e[29]^=kt,e[30]^=pt,e[31]^=mt,e[32]^=gt,e[33]^=yt,e[34]^=vt,e[35]^=wt,e[36]^=bt,e[37]^=_t,e[38]^=xt,e[39]^=kt,e[40]^=pt,e[41]^=mt,e[42]^=gt,e[43]^=yt,e[44]^=vt,e[45]^=wt,e[46]^=bt,e[47]^=_t,e[48]^=xt,e[49]^=kt;const Cr=e[0],Nr=e[1],jr=e[2]<<1|e[3]>>>31,Dr=e[3]<<1|e[2]>>>31,Pr=e[5]<<30|e[4]>>>2,Ur=e[4]<<30|e[5]>>>2,Zr=e[6]<<28|e[7]>>>4,Br=e[7]<<28|e[6]>>>4,Lr=e[8]<<27|e[9]>>>5,zr=e[9]<<27|e[8]>>>5,Vr=e[11]<<4|e[10]>>>28,Fr=e[10]<<4|e[11]>>>28,Wr=e[13]<<12|e[12]>>>20,Hr=e[12]<<12|e[13]>>>20,qr=e[14]<<6|e[15]>>>26,Gr=e[15]<<6|e[14]>>>26,Kr=e[17]<<23|e[16]>>>9,Yr=e[16]<<23|e[17]>>>9,Qr=e[18]<<20|e[19]>>>12,Xr=e[19]<<20|e[18]>>>12,Jr=e[20]<<3|e[21]>>>29,en=e[21]<<3|e[20]>>>29,tn=e[22]<<10|e[23]>>>22,rn=e[23]<<10|e[22]>>>22,nn=e[25]<<11|e[24]>>>21,sn=e[24]<<11|e[25]>>>21,an=e[26]<<25|e[27]>>>7,on=e[27]<<25|e[26]>>>7,cn=e[29]<<7|e[28]>>>25,un=e[28]<<7|e[29]>>>25,ln=e[31]<<9|e[30]>>>23,dn=e[30]<<9|e[31]>>>23,fn=e[33]<<13|e[32]>>>19,hn=e[32]<<13|e[33]>>>19,pn=e[34]<<15|e[35]>>>17,mn=e[35]<<15|e[34]>>>17,gn=e[36]<<21|e[37]>>>11,yn=e[37]<<21|e[36]>>>11,vn=e[38]<<8|e[39]>>>24,wn=e[39]<<8|e[38]>>>24,bn=e[40]<<18|e[41]>>>14,_n=e[41]<<18|e[40]>>>14,xn=e[42]<<2|e[43]>>>30,kn=e[43]<<2|e[42]>>>30,En=e[45]<<29|e[44]>>>3,Sn=e[44]<<29|e[45]>>>3,Tn=e[47]<<24|e[46]>>>8,An=e[46]<<24|e[47]>>>8,On=e[48]<<14|e[49]>>>18,In=e[49]<<14|e[48]>>>18;e[0]=Cr^~Wr&nn,e[1]=Nr^~Hr&sn,e[2]=Wr^~nn&gn,e[3]=Hr^~sn&yn,e[4]=nn^~gn&On,e[5]=sn^~yn&In,e[6]=gn^~On&Cr,e[7]=yn^~In&Nr,e[8]=On^~Cr&Wr,e[9]=In^~Nr&Hr,e[10]=Zr^~Qr&Jr,e[11]=Br^~Xr&en,e[12]=Qr^~Jr&fn,e[13]=Xr^~en&hn,e[14]=Jr^~fn&En,e[15]=en^~hn&Sn,e[16]=fn^~En&Zr,e[17]=hn^~Sn&Br,e[18]=En^~Zr&Qr,e[19]=Sn^~Br&Xr,e[20]=jr^~qr&an,e[21]=Dr^~Gr&on,e[22]=qr^~an&vn,e[23]=Gr^~on&wn,e[24]=an^~vn&bn,e[25]=on^~wn&_n,e[26]=vn^~bn&jr,e[27]=wn^~_n&Dr,e[28]=bn^~jr&qr,e[29]=_n^~Dr&Gr,e[30]=Lr^~Vr&tn,e[31]=zr^~Fr&rn,e[32]=Vr^~tn&pn,e[33]=Fr^~rn&mn,e[34]=tn^~pn&Tn,e[35]=rn^~mn&An,e[36]=pn^~Tn&Lr,e[37]=mn^~An&zr,e[38]=Tn^~Lr&Vr,e[39]=An^~zr&Fr,e[40]=Pr^~Kr&cn,e[41]=Ur^~Yr&un,e[42]=Kr^~cn&ln,e[43]=Yr^~un&dn,e[44]=cn^~ln&xn,e[45]=un^~dn&kn,e[46]=ln^~xn&Pr,e[47]=dn^~kn&Ur,e[48]=xn^~Pr&Kr,e[49]=kn^~Ur&Yr,e[0]^=ei[t*2],e[1]^=ei[t*2+1]}}function ti(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 ri(e,t){if(!e.length){const o=new Uint8Array(136);return o[0]=t,o[135]=128,[ti(o)]}const n=Ar(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(ti)}function ni(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];yd(e)}return e}function si(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 ue(e){return si(ni(new Array(50).fill(0),ri(e,1)))}function vd(e){return si(ni(new Array(50).fill(0),ri(e,6)))}function wd(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 bd(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 _d(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 xd(e,t,n){const s=Math.floor(t/8),o=t%8;return e[s]>>(n==="BE"?7-o:o)&1}function kd(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 ii(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 Ed(e,t,n=0){const s=e.length%t;return s===0?e:ii(e,e.length+t-s,n)}function ai(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 Sd(e,t,n=0){const s=e.length%t;return s===0?e:ai(e,e.length+t-s,n)}function Td(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 Ad(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 ft(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 Od(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 oi(e,t){return R(e,t)===0n?0n:t%4n===3n?Od(e,(t+1n)/4n,t):null}const z=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,P=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,zt=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Vt=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;function Or(e,t,n){if(t===0n)return[0n,0n];const s=R(3n*e*e*ft(2n*t,n),n),o=R(s*s-2n*e,n),d=R(s*(e-o)-t,n);return[o,d]}function Ft(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 Or(e,t,o);const d=R((s-t)*ft(n-e,o),o),p=R(d*d-e-n,o),v=R(d*(e-p)-t,o);return[p,v]}function Id(e){if(e<=0n||e>=P)throw new Error("Invalid private key");return Oe(zt,Vt,e,z)}function Md(e){const t=e[1]%2n===0n?2:3;return new Uint8Array([t,...Be(e[0],"BE")])}function $d(e){if(e.length!==33||e[0]!==2&&e[0]!==3)throw new Error("Invalid compressed public key");const t=Le(e.slice(1),"BE"),n=oi(R(t**3n+7n,z),z);if(!n)throw Error("Invalid x: does not correspond to a valid curve point");const s=R(-n,z),o=n%2n===0n;return[t,e[0]===2?o?n:s:o?s:n]}function Rd(e){const t=new Uint8Array(20),n=ue(Ze(Be(e[0],"BE"),Be(e[1],"BE")));return t.set(n.subarray(12)),t}function Cd(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 Oe(e,t,n,s){let o=[0n,0n],d=[e,t];const p=n.toString(2);for(const v of p)v==="0"?(d=Ft(o[0],o[1],d[0],d[1],s),o=Or(o[0],o[1],s)):(o=Ft(o[0],o[1],d[0],d[1],s),d=Or(d[0],d[1],s));return o}function Nd(e,t,n){return ci(Le(ue(e),"BE"),t,n)}function ci(e,t,n){if(t<=0n||t>=P)throw new Error("Invalid private key");if(n||(n=R(Le(ue(Ze(ue(Be(t,"BE")),Be(e,"BE"))),"BE"),P)),n<=0n||n>=P)throw new Error("Invalid nonce");const s=R(e,P),o=Oe(zt,Vt,n,z),d=R(o[0],P);let p=R((s+R(d,P)*t)*ft(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 jd(e,t,n,s){const o=oi(R(t**3n+7n,z),z);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:z-o,v=R(Le(ue(e),"BE"),P),m=Oe(t,p,n,z),E=Oe(zt,Vt,v,z),$=Ft(m[0],m[1],E[0],R(-E[1],z),z);return Oe($[0],$[1],ft(t,P),z)}function Dd(e,t,n,s){const o=R(Le(ue(e),"BE"),P),d=ft(s,P),p=R(o*d,P),v=R(n*d,P),m=Oe(zt,Vt,p,z),E=Oe(t[0],t[1],v,z),$=Ft(m[0],m[1],E[0],E[1],z);return n===R($[0],P)}class ui{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=ui;class li{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=li;class Wt{constructor(t,n=0n){this.span=n,this.writer=new li(new Uint8Array(t))}build(){return Ze(Tr(this.span,"LE"),this.writer.buffer)}hash(){const t=Ys(Ar(this.writer.buffer,32),(n,s)=>ue(Ze(n,s)));return ue(Ze(Tr(this.span,"LE"),t))}}a.Chunk=Wt;class Ir{constructor(t,n=4096){this.counters=[1],this.capacity=n,this.chunks=[new Wt(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 ui(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 Wt(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 Wt(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=Ir,r=Ir,Ir.NOOP=async e=>{};class ne{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 ne(BigInt(s+o),n)}add(t){return this.assertSameScale(t),new ne(this.value+t.value,this.scale)}subtract(t){return this.assertSameScale(t),new ne(this.value-t.value,this.scale)}multiply(t){return new ne(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 ne(n,this.scale),new ne(s,this.scale)]}exchange(t,n,s){if(t==="*"){const d=this.value*n.value/10n**BigInt(this.scale);return new ne(d,s)}this.assertSameScale(n);const o=this.value*10n**BigInt(s)/n.value;return new ne(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=ne;function Pd(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 Ht(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 Ud(e,t,n,s){const o=Ht(e,t,n,s);if(!o)return null;try{return kr(o)}catch{throw new Error(`Invalid number argument ${t}: ${o}`)}}function Zd(e,t,n,s){const o=e.some(m=>m.endsWith("-"+t)),d=Ht(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 di(e,t,n,s){const o=Ht(e,t,n,s);if(!o)throw new Error(`Missing argument ${t}`);return o}function Bd(e,t,n,s){const o=di(e,t,n,s);try{return kr(o)}catch{throw new Error(`Invalid argument ${t}: ${o}`)}}function fi(e,t){const n=e[t];e.splice(t,1),e.unshift(n)}function Ld(e,t){const n=[...e];return fi(n,t),n}function hi(e,t){return{x:e.x+t.x,y:e.y+t.y}}function zd(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Mr(e,t){return{x:e.x*t,y:e.y*t}}function Vd(e){const t=Math.sqrt(e.x*e.x+e.y*e.y);return{x:e.x/t,y:e.y/t}}function pi(e,t,n){return{x:e.x+Math.cos(t)*n,y:e.y+Math.sin(t)*n}}function mi(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function ht(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 Fd(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 Wd(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 gi(e,t,n){var s;return!((s=e[t-1])!=null&&s[n])}function yi(e,t,n){var s;return!((s=e[t+1])!=null&&s[n])}function vi(e,t,n){return!e[t][n-1]}function wi(e,t,n){return!e[t][n+1]}function Hd(e,t,n){var o,d,p,v,m,E,$,U;const s=[];return e[t][n]?Fd(e,t,n)||Wd(e,t,n)?[]:(!((o=e[t-1])!=null&&o[n-1])&&gi(e,t,n)&&vi(e,t,n)&&s.push({x:t,y:n}),!((d=e[t+1])!=null&&d[n-1])&&yi(e,t,n)&&vi(e,t,n)&&s.push({x:t+1,y:n}),!((p=e[t-1])!=null&&p[n+1])&&gi(e,t,n)&&wi(e,t,n)&&s.push({x:t,y:n+1}),!((v=e[t+1])!=null&&v[n+1])&&yi(e,t,n)&&wi(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}),(E=e[t+1])!=null&&E[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 qd(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=Hd(e,d,p);for(const m of v)o.some(E=>E.x===m.x&&E.y===m.y)||o.push(m)}return o.map(d=>({x:d.x*t,y:d.y*t}))}function Gd(e,t){const n=ht(e,(m,E)=>e[m][E]===0&&e[m][E+1]!==0,"row-first").map(m=>({...m,dx:1,dy:0})),s=ht(e,(m,E)=>e[m][E]===0&&e[m][E-1]!==0,"row-first").map(m=>({...m,dx:1,dy:0})),o=ht(e,(m,E)=>{var $;return e[m][E]===0&&(($=e[m-1])==null?void 0:$[E])!==0},"column-first").map(m=>({...m,dx:0,dy:1})),d=ht(e,(m,E)=>{var $;return e[m][E]===0&&(($=e[m+1])==null?void 0:$[E])!==0},"column-first").map(m=>({...m,dx:0,dy:1}));n.forEach(m=>m.y++),d.forEach(m=>m.x++);const p=Sr([...o,...d],(m,E)=>m.x===E.x&&m.y-1===E.y),v=Sr([...s,...n],(m,E)=>m.y===E.y&&m.x-1===E.x);return[...p,...v].map(m=>({start:m[0],end:ct(m)})).map(m=>({start:Mr(m.start,t),end:Mr(hi(m.end,{x:m.start.dx,y:m.start.dy}),t)}))}function Kd(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}function Yd(e,t){return t.map(n=>Kd(e,n)).sort((n,s)=>n-s)}function bi(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 $r(e,t,n){const s=[],o=pi(e,n,1e4);for(const d of t){const p=bi(e,o,d.start,d.end);p&&s.push(p)}return s.length?s.reduce((d,p)=>{const v=mi(e,p),m=mi(e,d);return v<m?p:d}):null}function Qd(e,t,n){const s=Yd(e,n),o=[];for(const d of s){const p=$r(e,t,d-.001),v=$r(e,t,d+.001);p&&o.push(p),v&&o.push(v)}return o}class Rr{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=Rr;class Xd{constructor(t,n){this.queue=[],this.running=0,this.onProcessed=new Rr,this.onDrained=new Rr,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=Xd,a.Binary={hexToUint8Array:nu,uint8ArrayToHex:su,base64ToUint8Array:Jc,uint8ArrayToBase64:eu,base32ToUint8Array:tu,uint8ArrayToBase32:ru,log2Reduce:Ys,partition:Ar,concatBytes:Ze,numberToUint8:ud,uint8ToNumber:ld,numberToUint16:dd,uint16ToNumber:fd,numberToUint32:hd,uint32ToNumber:pd,numberToUint64:Tr,uint64ToNumber:md,numberToUint256:Be,uint256ToNumber:Le,sliceBytes:gd,keccak256:ue,sha3_256:vd,proximity:wd,commonPrefix:bd,setBit:_d,getBit:xd,indexOf:kd,equals:Ad,padStart:ii,padStartToMultiple:Ed,padEnd:ai,padEndToMultiple:Sd,xorCypher:Td},a.Elliptic={privateKeyToPublicKey:Id,compressPublicKey:Md,publicKeyFromCompressed:$d,publicKeyToAddress:Rd,signMessage:Nd,signHash:ci,verifySignature:Dd,recoverPublicKey:jd,checksumEncode:Cd},a.Random={intBetween:ot,floatBetween:Jn,chance:es,signed:Ya,makeSeededRng:sr,point:Xa,procs:Ja},a.Arrays={countUnique:Vl,makeUnique:zl,splitBySize:Bl,splitByCount:Hs,index:Ws,indexCollection:Zl,onlyOrThrow:h,onlyOrNull:g,firstOrThrow:k,firstOrNull:y,shuffle:f,initialize:j,initialize2D:ce,rotate2D:oe,containsShape:it,glue:cc,pluck:at,pick:ir,pickMany:eo,pickManyUnique:to,pickWeighted:so,pickRandomIndices:je,pickGuaranteed:ro,last:ct,pipe:ts,makePipe:no,sortWeighted:io,pushAll:Dt,unshiftAll:ac,filterAndRemove:Au,merge:xl,empty:kl,pushToBucket:nc,unshiftAndLimit:sc,atRolling:ic,group:Sr,createOscillator:ul,organiseWithLimits:dl,tickPlaybook:Pd,getArgument:Ht,getBooleanArgument:Zd,getNumberArgument:Ud,requireStringArgument:di,requireNumberArgument:Bd,bringToFront:Ld,bringToFrontInPlace:fi,findInstance:rd,filterInstances:nd,interleave:sd,toggle:id,createHierarchy:od,multicall:ed,maxBy:td},a.System={sleepMillis:l,forever:fo,scheduleMany:mc,waitFor:Tu,expandError:Jo,runAndSetInterval:ho},a.Numbers={make:kr,sum:yc,average:vc,median:wc,getDistanceFromMidpoint:bc,clamp:Er,range:ps,interpolate:gc,createSequence:cl,increment:vl,decrement:wl,format:yl,fromDecimals:gl,makeStorage:Xu,asMegabytes:po,convertBytes:mo,hexToRgb:go,rgbToHex:yo,haversineDistanceToMeters:vo,roundToNearest:Rt,formatDistance:wo,triangularNumber:bo,searchFloat:_o},a.Promises={raceFulfilled:c,invert:i,runInParallelBatches:u},a.Dates={getTimestamp:Du,getTimeDelta:Ds,secondsToHumanTime:Pu,countCycles:Uu,isoDate:Mu,throttle:Zu,timeSince:Lu,dateTimeSlug:$u,unixTimestamp:Iu,fromUtcString:Ru,fromMillis:Cu,getProgress:zu,humanizeTime:Bt,humanizeProgress:Su,createTimeDigits:re,mapDayNumber:Ps,getDayInfoFromDate:_r,getDayInfoFromDateTimeString:Fu,seconds:Wu,minutes:Hu,hours:qu,days:Gu,make:Yu,normalizeTime:Nu,absoluteDays:Te},a.Objects={safeParse:ol,deleteDeep:co,getDeep:ke,setDeep:Ee,incrementDeep:ao,ensureDeep:oo,replaceDeep:uo,getFirstDeep:lo,deepMergeInPlace:Se,deepMerge2:ec,deepMerge3:tc,mapAllAsync:oc,cloneWithJson:Ou,sortObject:Zs,sortArray:Bs,sortAny:Ae,deepEquals:Ls,deepEqualsEvery:al,runOn:bl,ifPresent:_l,zip:hs,zipSum:rc,removeEmptyArrays:El,removeEmptyValues:Sl,flatten:Pl,unflatten:Fs,match:Ul,sort:Gs,map:Ol,mapIterable:Il,filterKeys:Tl,filterValues:Al,rethrow:Ml,setSomeOnObject:$l,setSomeDeep:Rl,flip:Cl,getAllPermutations:Nl,countTruthyValues:jl,transformToArray:Fl,setMulti:Hl,incrementMulti:Wl,createBidirectionalMap:ql,createTemporalBidirectionalMap:Gl,pushToBidirectionalMap:Ks,unshiftToBidirectionalMap:Kl,addToTemporalBidirectionalMap:Yl,getFromTemporalBidirectionalMap:Ql,createStatefulToggle:ll,diffKeys:fl,pickRandomKey:zs,mapRandomKey:hl,fromObjectString:pl,toQueryString:Ns,parseQueryString:yu,hasKey:vu,selectMax:wu,reposition:bu,unwrapSingleKey:_u,parseKeyValues:xu},a.Types={isFunction:or,isObject:me,isStrictlyObject:De,isEmptyArray:rs,isEmptyObject:xo,isUndefined:ar,isString:H,isNumber:ge,isBoolean:ns,isDate:Pe,isBlank:Ct,isId:cr,isIntegerString:ss,isHexString:is,isUrl:ds,isNullable:Ko,asString:us,asHexString:jo,asSafeString:Do,asIntegerString:No,asNumber:Nt,asFunction:Po,asInteger:dr,asBoolean:Uo,asDate:Zo,asNullableString:Bo,asEmptiableString:Lo,asId:zo,asTime:Vo,asArray:Fo,asObject:jt,asNullableObject:Wo,asStringMap:Ho,asNumericDictionary:qo,asUrl:Go,asNullable:Yo,asOptional:Qo,enforceObjectShape:fs,enforceArrayShape:Xo,isPng:Qs,isJpg:Xs,isWebp:Js,isImage:cd},a.Strings={tokenizeByCount:Ll,tokenizeByLength:qs,searchHex:$o,searchSubstring:Ro,randomHex:Co,randomLetter:Ao,randomAlphanumeric:Oo,randomRichAscii:Io,randomUnicode:Mo,includesAny:_c,slugify:fr,normalForm:kc,enumify:Ic,escapeHtml:$c,decodeHtmlEntities:Cc,after:hr,afterLast:gs,before:ms,beforeLast:pr,betweenWide:Nc,betweenNarrow:jc,getPreLine:Ju,containsWord:wr,containsWords:hu,joinUrl:Us,getFuzzyMatchScore:Pt,sortByFuzzyScore:Mc,splitOnce:mr,splitAll:ys,randomize:Zc,expand:vs,shrinkTrim:lt,capitalize:Ut,decapitalize:ws,csvEscape:Wc,parseCsv:Eu,surroundInOut:Oc,getExtension:gr,getBasename:yr,normalizeEmail:Dc,normalizeFilename:Pc,parseFilename:Uc,camelToTitle:Ec,slugToTitle:Sc,slugToCamel:Tc,joinHumanly:Ac,findWeightedPair:Ss,extractBlock:Ts,extractAllBlocks:Gc,replaceBlocks:Kc,indexOfEarliest:Ue,lastIndexOfBefore:Es,parseHtmlAttributes:pu,readNextWord:Zt,resolveVariables:mu,resolveVariableWithDefaultSyntax:Rs,resolveRemainingVariablesWithDefaults:Cs,isLetter:bs,isDigit:_s,isLetterOrDigit:dt,isValidObjectPathCharacter:zc,insert:Vc,indexOfRegex:xs,lineMatches:ks,linesMatchInOrder:Fc,represent:ut,resolveMarkdownLinks:gu,buildUrl:ku,isChinese:xc,replaceBetweenStrings:rl,describeMarkdown:nl,isBalanced:sl,textToFormat:il,splitFormatting:Yc,splitHashtags:Qc,splitUrls:Xc,route:iu,explodeReplace:vr,generateVariants:au,replaceWord:ou,replacePascalCaseWords:cu,stripHtml:uu,breakLine:$s,measureTextWidth:lu,toLines:du,levenshteinDistance:fu},a.Assertions={asEqual:uc,asTrue:lc,asTruthy:dc,asFalse:fc,asFalsy:hc,asEither:pc},a.Cache={get:el,invalidate:tl},a.Vector={addPoint:hi,subtractPoint:zd,multiplyPoint:Mr,normalizePoint:Vd,pushPoint:pi,filterCoordinates:ht,findCorners:qd,findLines:Gd,raycast:$r,raycastCircle:Qd,getLineIntersectionPoint:bi}})(Rn);const C=Si(Rn);C.Arrays,C.Assertions;const B=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 Ti=C.MerkleTree;C.FixedPointNumber,C.Lazy,C.AsyncLazy,C.AsyncQueue,C.Uint8ArrayReader,C.Uint8ArrayWriter;const Ai=new TextEncoder,Cn=1,Nn=4096,Gt=4096,Oi=32;function jn(a,r){return r=typeof r=="number"?A.FeedIndex.fromBigInt(BigInt(r)):r,new A.Identifier(B.keccak256(B.concatBytes(a.toUint8Array(),r.toUint8Array())))}function Ii(a){const r=a.slice(0,A.Span.LENGTH),i=a.slice(A.Span.LENGTH),c=Mi(i),u=B.keccak256(B.concatBytes(r,c));return new A.Reference(u)}function Mi(a){if(a.length>Gt)throw new A.BeeArgumentError(`payload size ${a.length} exceeds maximum chunk payload size ${Gt}`,a);const r=new Uint8Array(Gt);return r.set(a),B.log2Reduce(B.partition(r,Oi),(i,c)=>B.keccak256(B.concatBytes(i,c)))}function Dn(a){if(a instanceof Uint8Array||(a=Ai.encode(a)),a.length<Cn||a.length>Nn)throw new RangeError(`payload size ${a.length} exceeds limits [${Cn}, ${Nn}]`);const r=A.Span.fromBigInt(BigInt(a.length)),i=B.concatBytes(r.toUint8Array(),a);return{data:i,span:r,payload:A.Bytes.fromSlice(i,A.Span.LENGTH),address:Ii(i)}}function $i(a,r){return new A.Reference(B.keccak256(B.concatBytes(a.toUint8Array(),r.toUint8Array())))}function Pn(a,r,i){r=new A.Identifier(r),i=new A.PrivateKey(i);const c=$i(r,i.publicKey().address()),u=i.sign(B.concatBytes(r.toUint8Array(),a.address.toUint8Array())),l=B.concatBytes(r.toUint8Array(),u.toUint8Array(),a.data),f=A.Span.fromSlice(a.data,0),h=A.Bytes.fromSlice(a.data,A.Span.LENGTH);return{data:l,identifier:r,signature:u,span:f,payload:h,address:c,owner:i.publicKey().address()}}const Ri=q.getInstance(),Ci=X.getInstance();function Ni(a){return new Promise(r=>{setTimeout(r,a)})}function Un(a){return(a.startsWith("0x")?a.slice(2):a).toLowerCase()}async function Kt(a,r=3,i=250){return new Promise((c,u)=>{a().then(c).catch(l=>{r>0?(Ri.info(`Retrying... Attempts left: ${r}. Error: ${l.message}`),setTimeout(()=>{Kt(a,r-1,i).then(c).catch(u)},i)):(Ci.handleError(l,"Utils.retryAwaitableAsync"),u(l))})})}async function ji(a,r,i="Operation timed out"){return Promise.race([a,new Promise((c,u)=>setTimeout(()=>u(new Error(i)),r))])}class Di{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 Yt;(function(a){a.mergeShapes=(r,i)=>({...r,...i})})(Yt||(Yt={}));const _=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),se=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"]),Pi=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 Ie=(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 Zn=Ie;function Ui(a){Zn=a}function Et(){return Zn}const St=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}},Zi=[];function b(a,r){const i=Et(),c=St({issueData:r,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,i,i===Ie?void 0:Ie].filter(u=>!!u)});a.common.issues.push(c)}class L{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 L.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"}),Me=a=>({status:"dirty",value:a}),V=a=>({status:"valid",value:a}),Qt=a=>a.status==="aborted",Xt=a=>a.status==="dirty",we=a=>a.status==="valid",Ve=a=>typeof Promise<"u"&&a instanceof Promise;function Tt(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 Bn(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}typeof SuppressedError=="function"&&SuppressedError;var x;(function(a){a.errToObj=r=>typeof r=="string"?{message:r}:r||{},a.toString=r=>typeof r=="string"?r:r==null?void 0:r.message})(x||(x={}));var Fe,We;class J{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 Ln=(a,r)=>{if(we(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 O(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:k}=a;return f.code==="invalid_enum_value"?{message:k??h.defaultError}:typeof h.data>"u"?{message:(g=k??c)!==null&&g!==void 0?g:h.defaultError}:f.code!=="invalid_type"?{message:h.defaultError}:{message:(y=k??i)!==null&&y!==void 0?y:h.defaultError}},description:u}}class I{get description(){return this._def.description}_getType(r){return se(r.data)}_getOrReturnCtx(r,i){return i||{common:r.parent.common,data:r.data,parsedType:se(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}_processInputParams(r){return{status:new L,ctx:{common:r.parent.common,data:r.data,parsedType:se(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}}_parseSync(r){const i=this._parse(r);if(Ve(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:se(r)},l=this._parseSync({data:r,path:u.path,parent:u});return Ln(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:se(r)};if(!this["~standard"].async)try{const l=this._parseSync({data:r,path:[],parent:u});return we(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=>we(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:se(r)},u=this._parse({data:r,path:c.path,parent:c}),l=await(Ve(u)?u:Promise.resolve(u));return Ln(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 Y({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 te.create(this,this._def)}nullable(){return he.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return K.create(this)}promise(){return Ne.create(this,this._def)}or(r){return Ke.create([this,r],this._def)}and(r){return Ye.create(this,r,this._def)}transform(r){return new Y({...O(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:r}})}default(r){const i=typeof r=="function"?r:()=>r;return new tt({...O(this._def),innerType:this,defaultValue:i,typeName:S.ZodDefault})}brand(){return new tr({typeName:S.ZodBranded,type:this,...O(this._def)})}catch(r){const i=typeof r=="function"?r:()=>r;return new rt({...O(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 nt.create(this,r)}readonly(){return st.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Bi=/^c[^\s-]{8,}$/i,Li=/^[0-9a-z]+$/,zi=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Vi=/^[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,Fi=/^[a-z0-9_-]{21}$/i,Wi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hi=/^[-+]?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)?)??$/,qi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Gi="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Jt;const Ki=/^(?:(?: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])$/,Yi=/^(?:(?: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])$/,Qi=/^(([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]))$/,Xi=/^(([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])$/,Ji=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ea=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zn="((\\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])))",ta=new RegExp(`^${zn}$`);function Vn(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 ra(a){return new RegExp(`^${Vn(a)}$`)}function Fn(a){let r=`${zn}T${Vn(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 na(a,r){return!!((r==="v4"||!r)&&Ki.test(a)||(r==="v6"||!r)&&Qi.test(a))}function sa(a,r){if(!Wi.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 ia(a,r){return!!((r==="v4"||!r)&&Yi.test(a)||(r==="v6"||!r)&&Xi.test(a))}class G extends I{_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 L;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")qi.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")Jt||(Jt=new RegExp(Gi,"u")),Jt.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")Vi.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")Fi.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")Bi.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")Li.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")zi.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"?Fn(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"?ta.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:"date",message:l.message}),c.dirty()):l.kind==="time"?ra(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"?Hi.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"duration",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="ip"?na(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"?sa(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"?ia(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"?Ji.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"base64",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="base64url"?ea.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,...x.errToObj(c)})}_addCheck(r){return new G({...this._def,checks:[...this._def.checks,r]})}email(r){return this._addCheck({kind:"email",...x.errToObj(r)})}url(r){return this._addCheck({kind:"url",...x.errToObj(r)})}emoji(r){return this._addCheck({kind:"emoji",...x.errToObj(r)})}uuid(r){return this._addCheck({kind:"uuid",...x.errToObj(r)})}nanoid(r){return this._addCheck({kind:"nanoid",...x.errToObj(r)})}cuid(r){return this._addCheck({kind:"cuid",...x.errToObj(r)})}cuid2(r){return this._addCheck({kind:"cuid2",...x.errToObj(r)})}ulid(r){return this._addCheck({kind:"ulid",...x.errToObj(r)})}base64(r){return this._addCheck({kind:"base64",...x.errToObj(r)})}base64url(r){return this._addCheck({kind:"base64url",...x.errToObj(r)})}jwt(r){return this._addCheck({kind:"jwt",...x.errToObj(r)})}ip(r){return this._addCheck({kind:"ip",...x.errToObj(r)})}cidr(r){return this._addCheck({kind:"cidr",...x.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,...x.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,...x.errToObj(r==null?void 0:r.message)})}duration(r){return this._addCheck({kind:"duration",...x.errToObj(r)})}regex(r,i){return this._addCheck({kind:"regex",regex:r,...x.errToObj(i)})}includes(r,i){return this._addCheck({kind:"includes",value:r,position:i==null?void 0:i.position,...x.errToObj(i==null?void 0:i.message)})}startsWith(r,i){return this._addCheck({kind:"startsWith",value:r,...x.errToObj(i)})}endsWith(r,i){return this._addCheck({kind:"endsWith",value:r,...x.errToObj(i)})}min(r,i){return this._addCheck({kind:"min",value:r,...x.errToObj(i)})}max(r,i){return this._addCheck({kind:"max",value:r,...x.errToObj(i)})}length(r,i){return this._addCheck({kind:"length",value:r,...x.errToObj(i)})}nonempty(r){return this.min(1,x.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,...O(a)})};function aa(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 le extends I{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 L;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"?aa(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,x.toString(i))}gt(r,i){return this.setLimit("min",r,!1,x.toString(i))}lte(r,i){return this.setLimit("max",r,!0,x.toString(i))}lt(r,i){return this.setLimit("max",r,!1,x.toString(i))}setLimit(r,i,c,u){return new le({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:c,message:x.toString(u)}]})}_addCheck(r){return new le({...this._def,checks:[...this._def.checks,r]})}int(r){return this._addCheck({kind:"int",message:x.toString(r)})}positive(r){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(r)})}negative(r){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:x.toString(i)})}finite(r){return this._addCheck({kind:"finite",message:x.toString(r)})}safe(r){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(r)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.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)}}le.create=a=>new le({checks:[],typeName:S.ZodNumber,coerce:(a==null?void 0:a.coerce)||!1,...O(a)});class de extends I{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 L;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,x.toString(i))}gt(r,i){return this.setLimit("min",r,!1,x.toString(i))}lte(r,i){return this.setLimit("max",r,!0,x.toString(i))}lt(r,i){return this.setLimit("max",r,!1,x.toString(i))}setLimit(r,i,c,u){return new de({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:c,message:x.toString(u)}]})}_addCheck(r){return new de({...this._def,checks:[...this._def.checks,r]})}positive(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(r)})}negative(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:x.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}}de.create=a=>{var r;return new de({checks:[],typeName:S.ZodBigInt,coerce:(r=a==null?void 0:a.coerce)!==null&&r!==void 0?r:!1,...O(a)})};class He extends I{_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)}}He.create=a=>new He({typeName:S.ZodBoolean,coerce:(a==null?void 0:a.coerce)||!1,...O(a)});class be extends I{_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 L;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 be({...this._def,checks:[...this._def.checks,r]})}min(r,i){return this._addCheck({kind:"min",value:r.getTime(),message:x.toString(i)})}max(r,i){return this._addCheck({kind:"max",value:r.getTime(),message:x.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}}be.create=a=>new be({checks:[],coerce:(a==null?void 0:a.coerce)||!1,typeName:S.ZodDate,...O(a)});class At extends I{_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)}}At.create=a=>new At({typeName:S.ZodSymbol,...O(a)});class qe extends I{_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)}}qe.create=a=>new qe({typeName:S.ZodUndefined,...O(a)});class Ge extends I{_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)}}Ge.create=a=>new Ge({typeName:S.ZodNull,...O(a)});class $e extends I{constructor(){super(...arguments),this._any=!0}_parse(r){return V(r.data)}}$e.create=a=>new $e({typeName:S.ZodAny,...O(a)});class _e extends I{constructor(){super(...arguments),this._unknown=!0}_parse(r){return V(r.data)}}_e.create=a=>new _e({typeName:S.ZodUnknown,...O(a)});class ie extends I{_parse(r){const i=this._getOrReturnCtx(r);return b(i,{code:w.invalid_type,expected:_.never,received:i.parsedType}),T}}ie.create=a=>new ie({typeName:S.ZodNever,...O(a)});class Ot extends I{_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)}}Ot.create=a=>new Ot({typeName:S.ZodVoid,...O(a)});class K extends I{_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 J(i,f,i.path,h)))).then(f=>L.mergeArray(c,f));const l=[...i.data].map((f,h)=>u.type._parseSync(new J(i,f,i.path,h)));return L.mergeArray(c,l)}get element(){return this._def.type}min(r,i){return new K({...this._def,minLength:{value:r,message:x.toString(i)}})}max(r,i){return new K({...this._def,maxLength:{value:r,message:x.toString(i)}})}length(r,i){return new K({...this._def,exactLength:{value:r,message:x.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,...O(r)});function Re(a){if(a instanceof N){const r={};for(const i in a.shape){const c=a.shape[i];r[i]=te.create(Re(c))}return new N({...a._def,shape:()=>r})}else return a instanceof K?new K({...a._def,type:Re(a.element)}):a instanceof te?te.create(Re(a.unwrap())):a instanceof he?he.create(Re(a.unwrap())):a instanceof ee?ee.create(a.items.map(r=>Re(r))):a}class N extends I{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 ie&&this._def.unknownKeys==="strip"))for(const y in u.data)f.includes(y)||h.push(y);const g=[];for(const y of f){const k=l[y],j=u.data[y];g.push({key:{status:"valid",value:y},value:k._parse(new J(u,j,u.path,y)),alwaysSet:y in u.data})}if(this._def.catchall instanceof ie){const y=this._def.unknownKeys;if(y==="passthrough")for(const k of h)g.push({key:{status:"valid",value:k},value:{status:"valid",value:u.data[k]}});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 k of h){const j=u.data[k];g.push({key:{status:"valid",value:k},value:y._parse(new J(u,j,u.path,k)),alwaysSet:k in u.data})}}return u.common.async?Promise.resolve().then(async()=>{const y=[];for(const k of g){const j=await k.key,oe=await k.value;y.push({key:j,value:oe,alwaysSet:k.alwaysSet})}return y}).then(y=>L.mergeObjectSync(c,y)):L.mergeObjectSync(c,g)}get shape(){return this._def.shape()}strict(r){return x.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=x.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 Re(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 te;)l=l._def.innerType;i[c]=l}}),new N({...this._def,shape:()=>i})}keyof(){return Wn(M.objectKeys(this.shape))}}N.create=(a,r)=>new N({shape:()=>a,unknownKeys:"strip",catchall:ie.create(),typeName:S.ZodObject,...O(r)}),N.strictCreate=(a,r)=>new N({shape:()=>a,unknownKeys:"strict",catchall:ie.create(),typeName:S.ZodObject,...O(r)}),N.lazycreate=(a,r)=>new N({shape:a,unknownKeys:"strip",catchall:ie.create(),typeName:S.ZodObject,...O(r)});class Ke extends I{_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},k=g._parseSync({data:i.data,path:i.path,parent:y});if(k.status==="valid")return k;k.status==="dirty"&&!l&&(l={result:k,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}}Ke.create=(a,r)=>new Ke({options:a,typeName:S.ZodUnion,...O(r)});const ae=a=>a instanceof Xe?ae(a.schema):a instanceof Y?ae(a.innerType()):a instanceof Je?[a.value]:a instanceof fe?a.options:a instanceof et?M.objectValues(a.enum):a instanceof tt?ae(a._def.innerType):a instanceof qe?[void 0]:a instanceof Ge?[null]:a instanceof te?[void 0,...ae(a.unwrap())]:a instanceof he?[null,...ae(a.unwrap())]:a instanceof tr||a instanceof st?ae(a.unwrap()):a instanceof rt?ae(a._def.innerType):[];class It extends I{_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 It({typeName:S.ZodDiscriminatedUnion,discriminator:r,options:i,optionsMap:u,...O(c)})}}function er(a,r){const i=se(a),c=se(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=er(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=er(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 Ye extends I{_parse(r){const{status:i,ctx:c}=this._processInputParams(r),u=(l,f)=>{if(Qt(l)||Qt(f))return T;const h=er(l.value,f.value);return h.valid?((Xt(l)||Xt(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}))}}Ye.create=(a,r,i)=>new Ye({left:a,right:r,typeName:S.ZodIntersection,...O(i)});class ee extends I{_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 J(c,f,c.path,h)):null}).filter(f=>!!f);return c.common.async?Promise.all(l).then(f=>L.mergeArray(i,f)):L.mergeArray(i,l)}get items(){return this._def.items}rest(r){return new ee({...this._def,rest:r})}}ee.create=(a,r)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ee({items:a,typeName:S.ZodTuple,rest:null,...O(r)})};class Qe extends I{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 J(c,h,c.path,h)),value:f._parse(new J(c,c.data[h],c.path,h)),alwaysSet:h in c.data});return c.common.async?L.mergeObjectAsync(i,u):L.mergeObjectSync(i,u)}get element(){return this._def.valueType}static create(r,i,c){return i instanceof I?new Qe({keyType:r,valueType:i,typeName:S.ZodRecord,...O(c)}):new Qe({keyType:G.create(),valueType:r,typeName:S.ZodRecord,...O(i)})}}class Mt extends I{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 J(c,h,c.path,[y,"key"])),value:l._parse(new J(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,k=await g.value;if(y.status==="aborted"||k.status==="aborted")return T;(y.status==="dirty"||k.status==="dirty")&&i.dirty(),h.set(y.value,k.value)}return{status:i.value,value:h}})}else{const h=new Map;for(const g of f){const y=g.key,k=g.value;if(y.status==="aborted"||k.status==="aborted")return T;(y.status==="dirty"||k.status==="dirty")&&i.dirty(),h.set(y.value,k.value)}return{status:i.value,value:h}}}}Mt.create=(a,r,i)=>new Mt({valueType:r,keyType:a,typeName:S.ZodMap,...O(i)});class xe extends I{_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 k of g){if(k.status==="aborted")return T;k.status==="dirty"&&i.dirty(),y.add(k.value)}return{status:i.value,value:y}}const h=[...c.data.values()].map((g,y)=>l._parse(new J(c,g,c.path,y)));return c.common.async?Promise.all(h).then(g=>f(g)):f(h)}min(r,i){return new xe({...this._def,minSize:{value:r,message:x.toString(i)}})}max(r,i){return new xe({...this._def,maxSize:{value:r,message:x.toString(i)}})}size(r,i){return this.min(r,i).max(r,i)}nonempty(r){return this.min(1,r)}}xe.create=(a,r)=>new xe({valueType:a,minSize:null,maxSize:null,typeName:S.ZodSet,...O(r)});class Ce extends I{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 St({data:h,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Et(),Ie].filter(y=>!!y),issueData:{code:w.invalid_arguments,argumentsError:g}})}function u(h,g){return St({data:h,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Et(),Ie].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 Ne){const h=this;return V(async function(...g){const y=new F([]),k=await h._def.args.parseAsync(g,l).catch(ce=>{throw y.addIssue(c(g,ce)),y}),j=await Reflect.apply(f,this,k);return await h._def.returns._def.type.parseAsync(j,l).catch(ce=>{throw y.addIssue(u(j,ce)),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 k=Reflect.apply(f,this,y.data),j=h._def.returns.safeParse(k,l);if(!j.success)throw new F([u(k,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...r){return new Ce({...this._def,args:ee.create(r).rest(_e.create())})}returns(r){return new Ce({...this._def,returns:r})}implement(r){return this.parse(r)}strictImplement(r){return this.parse(r)}static create(r,i,c){return new Ce({args:r||ee.create([]).rest(_e.create()),returns:i||_e.create(),typeName:S.ZodFunction,...O(c)})}}class Xe extends I{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})}}Xe.create=(a,r)=>new Xe({getter:a,typeName:S.ZodLazy,...O(r)});class Je extends I{_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}}Je.create=(a,r)=>new Je({value:a,typeName:S.ZodLiteral,...O(r)});function Wn(a,r){return new fe({values:a,typeName:S.ZodEnum,...O(r)})}class fe extends I{constructor(){super(...arguments),Fe.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(Tt(this,Fe)||Bn(this,Fe,new Set(this._def.values)),!Tt(this,Fe).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 fe.create(r,{...this._def,...i})}exclude(r,i=this._def){return fe.create(this.options.filter(c=>!r.includes(c)),{...this._def,...i})}}Fe=new WeakMap,fe.create=Wn;class et extends I{constructor(){super(...arguments),We.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(Tt(this,We)||Bn(this,We,new Set(M.getValidEnumValues(this._def.values))),!Tt(this,We).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}}We=new WeakMap,et.create=(a,r)=>new et({values:a,typeName:S.ZodNativeEnum,...O(r)});class Ne extends I{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})))}}Ne.create=(a,r)=>new Ne({type:a,typeName:S.ZodPromise,...O(r)});class Y extends I{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"?Me(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"?Me(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(!we(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=>we(f)?Promise.resolve(u.transform(f.value,l)).then(h=>({status:i.value,value:h})):f);M.assertNever(u)}}Y.create=(a,r,i)=>new Y({schema:a,typeName:S.ZodEffects,effect:r,...O(i)}),Y.createWithPreprocess=(a,r,i)=>new Y({schema:r,effect:{type:"preprocess",transform:a},typeName:S.ZodEffects,...O(i)});class te extends I{_parse(r){return this._getType(r)===_.undefined?V(void 0):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}te.create=(a,r)=>new te({innerType:a,typeName:S.ZodOptional,...O(r)});class he extends I{_parse(r){return this._getType(r)===_.null?V(null):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}he.create=(a,r)=>new he({innerType:a,typeName:S.ZodNullable,...O(r)});class tt extends I{_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}}tt.create=(a,r)=>new tt({innerType:a,typeName:S.ZodDefault,defaultValue:typeof r.default=="function"?r.default:()=>r.default,...O(r)});class rt extends I{_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 Ve(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}}rt.create=(a,r)=>new rt({innerType:a,typeName:S.ZodCatch,catchValue:typeof r.catch=="function"?r.catch:()=>r.catch,...O(r)});class $t extends I{_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}}}$t.create=a=>new $t({typeName:S.ZodNaN,...O(a)});const oa=Symbol("zod_brand");class tr extends I{_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 nt extends I{_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(),Me(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 nt({in:r,out:i,typeName:S.ZodPipeline})}}class st extends I{_parse(r){const i=this._def.innerType._parse(r),c=u=>(we(u)&&(u.value=Object.freeze(u.value)),u);return Ve(i)?i.then(u=>c(u)):c(i)}unwrap(){return this._def.innerType}}st.create=(a,r)=>new st({innerType:a,typeName:S.ZodReadonly,...O(r)});function Hn(a,r={},i){return a?$e.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})}}):$e.create()}const ca={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 ua=(a,r={message:`Input not instance of ${a.name}`})=>Hn(i=>i instanceof a,r),qn=G.create,Gn=le.create,la=$t.create,da=de.create,Kn=He.create,fa=be.create,ha=At.create,pa=qe.create,ma=Ge.create,ga=$e.create,ya=_e.create,va=ie.create,wa=Ot.create,ba=K.create,_a=N.create,xa=N.strictCreate,ka=Ke.create,Ea=It.create,Sa=Ye.create,Ta=ee.create,Aa=Qe.create,Oa=Mt.create,Ia=xe.create,Ma=Ce.create,$a=Xe.create,Ra=Je.create,Ca=fe.create,Na=et.create,ja=Ne.create,Yn=Y.create,Da=te.create,Pa=he.create,Ua=Y.createWithPreprocess,Za=nt.create;var D=Object.freeze({__proto__:null,defaultErrorMap:Ie,setErrorMap:Ui,getErrorMap:Et,makeIssue:St,EMPTY_PATH:Zi,addIssueToContext:b,ParseStatus:L,INVALID:T,DIRTY:Me,OK:V,isAborted:Qt,isDirty:Xt,isValid:we,isAsync:Ve,get util(){return M},get objectUtil(){return Yt},ZodParsedType:_,getParsedType:se,ZodType:I,datetimeRegex:Fn,ZodString:G,ZodNumber:le,ZodBigInt:de,ZodBoolean:He,ZodDate:be,ZodSymbol:At,ZodUndefined:qe,ZodNull:Ge,ZodAny:$e,ZodUnknown:_e,ZodNever:ie,ZodVoid:Ot,ZodArray:K,ZodObject:N,ZodUnion:Ke,ZodDiscriminatedUnion:It,ZodIntersection:Ye,ZodTuple:ee,ZodRecord:Qe,ZodMap:Mt,ZodSet:xe,ZodFunction:Ce,ZodLazy:Xe,ZodLiteral:Je,ZodEnum:fe,ZodNativeEnum:et,ZodPromise:Ne,ZodEffects:Y,ZodTransformer:Y,ZodOptional:te,ZodNullable:he,ZodDefault:tt,ZodCatch:rt,ZodNaN:$t,BRAND:oa,ZodBranded:tr,ZodPipeline:nt,ZodReadonly:st,custom:Hn,Schema:I,ZodSchema:I,late:ca,get ZodFirstPartyTypeKind(){return S},coerce:{string:a=>G.create({...a,coerce:!0}),number:a=>le.create({...a,coerce:!0}),boolean:a=>He.create({...a,coerce:!0}),bigint:a=>de.create({...a,coerce:!0}),date:a=>be.create({...a,coerce:!0})},any:ga,array:ba,bigint:da,boolean:Kn,date:fa,discriminatedUnion:Ea,effect:Yn,enum:Ca,function:Ma,instanceof:ua,intersection:Sa,lazy:$a,literal:Ra,map:Oa,nan:la,nativeEnum:Na,never:va,null:ma,nullable:Pa,number:Gn,object:_a,oboolean:()=>Kn().optional(),onumber:()=>Gn().optional(),optional:Da,ostring:()=>qn().optional(),pipeline:Za,preprocess:Ua,promise:ja,record:Aa,set:Ia,strictObject:xa,string:qn,symbol:ha,transformer:Yn,tuple:Ta,undefined:pa,union:ka,unknown:ya,void:wa,NEVER:T,ZodIssueCode:w,quotelessJson:Pi,ZodError:F}),rr=(a=>(a.TEXT="text",a.THREAD="thread",a.REACTION="reaction",a))(rr||{});const pe=q.getInstance(),Ba=["id","targetMessageId","type","message","username","address","timestamp","signature","index","chatTopic","userTopic","additionalProps"],nr=D.object({id:D.string(),targetMessageId:D.string().optional(),type:D.nativeEnum(rr),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:Wa(a.additionalProps).isValid,{message:"Invalid additional properties in message"}),La=D.object({reference:D.string(),timestamp:D.number()}),za=D.object({message:nr,messageStateRefs:D.array(La).nullable()});function Qn(a){const r=za.safeParse(a);return r.success?Xn(a.message)?!0:(pe.warn("Invalid main message signature"),!1):(pe.warn("GSOC message validation failed:",r.error.format()),!1)}function Va(a){if(!Array.isArray(a))return pe.warn("Message state must be an array"),!1;for(const r of a)if(!Fa(r))return pe.warn("Invalid message in message state:",r.id),!1;return!0}function Fa(a){const r=nr.safeParse(a);return r.success?Xn(a)?!0:(pe.warn("Invalid message signature"),!1):(pe.warn("Message data validation failed:",r.error.format()),!1)}function Xn(a){try{const r={username:a.username,address:a.address,timestamp:a.timestamp,message:a.message},i=new TextEncoder,c=B.concatBytes(i.encode(`Ethereum Signed Message:
|
|
11
|
-
32`),B.keccak256(i.encode(JSON.stringify(r))));if(new A.Signature(a.signature).isValid(c,a.address))throw new Error("Signature verification failed!");return!0}catch(r){return pe.warn("Error in validateUserSignature",r),!1}}function Wa(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))Ba.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 k of Object.values(g))if(!f(k,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 k=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/data:text\/html/gi,/vbscript:/gi,/on\w+\s*=/gi];for(const j of k)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 Ha(a){const r=nr.safeParse(a);if(!r.success){const i=r.error.issues.map(c=>c.path.length>0?`${c.path.join(".")}: ${c.message}`:c.message);return pe.warn("Message validation failed:",r.error.format()),{isValid:!1,errors:i}}return{isValid:!0,errors:[]}}const W={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 qa{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"),A.FeedIndex.fromBigInt(0n)}}async initMessageState(r){try{if(!Qn(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(!Va(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(W.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 Ni(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 Ga{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=A.Topic.fromString(g);await c.makeFeedWriter(y,new A.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 A.PrivateKey(f),y=A.Stamper.fromBlank(f,u,this.depth),k=this.generateUserOwnedFeedId(l,h),j=A.Topic.fromString(k),oe=jn(j,r),ce=Dn(i),it=Pn(ce,oe,g),je={hash:()=>it.address.toUint8Array()},at=y.stamp(je),{upload:sr}=c.makeSOCWriter(g),ot=A.Bytes.fromUtf8(i);return(await sr(at,oe,ot.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=A.Stamper.fromBlank(u,c,this.depth),f=A.Bytes.fromUtf8(JSON.stringify(r)),h=new Ti(async y=>{await i.uploadChunk(l.stamp(y),y.build())});await h.append(f.toUint8Array());const g=await h.finalize();return B.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=A.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(A.Topic.fromString(i),Un(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 A.PrivateKey(l),g=A.Identifier.fromString(u),y=A.Bytes.fromUtf8(r),{upload:k}=i.makeSOCWriter(h,{timeout:f});await k(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=A.Stamper.fromBlank(h,c,this.depth),y=new A.PrivateKey(l),k=A.Identifier.fromString(u),j=A.Bytes.fromUtf8(r),oe=Dn(j.toUint8Array()),ce=Pn(oe,k,y),it={hash:()=>ce.address.toUint8Array()},je=g.stamp(it),{upload:at}=i.makeSOCWriter(y,{timeout:f});await at(je,k,j.toUint8Array())}}class Ka{constructor(r,i){this.fallbackTransport=null,this.logger=q.getInstance(),this.errorHandler=X.getInstance(),this.gsocIndex=null;const c=new A.PrivateKey(Un(r.user.privateKey));this.userDetails={privateKey:r.user.privateKey,ownAddress:c.publicKey().address().toString(),nickname:r.user.nickname,ownIndex:-1},this.swarmSettings={bee:new A.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 Di,this.utils=new Ga(this.userDetails,this.swarmSettings),this.history=new qa(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(W.MESSAGE_RECEIVED,l)}))):this.transport=this.createDefaultPollingTransport(u),this.transport.onMessage(l=>{this.emitter.emit(W.MESSAGE_RECEIVED,l)})}createDefaultPollingTransport(r){return new $n({fetchMessage:async()=>{try{if(!this.gsocIndex)return null;const i=A.Topic.fromString(this.swarmSettings.chatTopic),c=jn(i,this.gsocIndex),u=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,c.toString()),l=JSON.parse(u);return Qn(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||Ei(),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=Ha(h);if(!g.isValid){const y=`Invalid message: ${g.errors.join(", ")}`;throw this.logger.error(y),new Error(y)}try{this.emitter.emit(W.MESSAGE_REQUEST_INITIATED,h),await this.utils.writeOwnFeedDataByIndex(f,JSON.stringify(h)),this.userDetails.ownIndex=f,this.emitter.emit(W.MESSAGE_REQUEST_UPLOADED,h),await this.broadcastUserMessage(h)}catch(y){this.emitter.emit(W.MESSAGE_REQUEST_ERROR,h),this.errorHandler.handleError(y,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(W.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(W.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(W.LOADING_INIT,!0);const u=this.swarmSettings.feedReadTimeout-1e3,[l,f]=await ji(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(W.CRITICAL_ERROR,c)}finally{this.emitter.emit(W.LOADING_INIT,!1)}}async initOwnIndex(){const{latestIndex:c}=await Kt(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=c}async broadcastUserMessage(r){try{return Kt(()=>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 A.EthAddress(i).toString(),f=new A.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()}}Q.EVENTS=W,Q.MessageType=rr,Q.PollingTransport=$n,Q.SwarmChat=Ka,Object.defineProperty(Q,Symbol.toStringTag,{value:"Module"})});
|
|
11
|
+
32`),B.keccak256(i.encode(JSON.stringify(r))));if(new A.Signature(a.signature).isValid(c,a.address))throw new Error("Signature verification failed!");return!0}catch(r){return pe.warn("Error in validateUserSignature",r),!1}}function Wa(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))Ba.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 k of Object.values(g))if(!f(k,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 k=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/data:text\/html/gi,/vbscript:/gi,/on\w+\s*=/gi];for(const j of k)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 Ha(a){const r=nr.safeParse(a);if(!r.success){const i=r.error.issues.map(c=>c.path.length>0?`${c.path.join(".")}: ${c.message}`:c.message);return pe.warn("Message validation failed:",r.error.format()),{isValid:!1,errors:i}}return{isValid:!0,errors:[]}}const W={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 qa{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"),A.FeedIndex.fromBigInt(0n)}}async initMessageState(r){try{if(!Qn(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(!Va(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(W.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 Ni(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 Ga{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=A.Topic.fromString(g);await c.makeFeedWriter(y,new A.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 A.PrivateKey(f),y=A.Stamper.fromBlank(f,u,this.depth),k=this.generateUserOwnedFeedId(l,h),j=A.Topic.fromString(k),oe=jn(j,r),ce=Dn(i),it=Pn(ce,oe,g),je={hash:()=>it.address.toUint8Array()},at=y.stamp(je),{upload:sr}=c.makeSOCWriter(g),ot=A.Bytes.fromUtf8(i);return(await sr(at,oe,ot.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=A.Stamper.fromBlank(u,c,this.depth),f=A.Bytes.fromUtf8(JSON.stringify(r)),h=new Ti(async y=>{await i.uploadChunk(l.stamp(y),y.build())});await h.append(f.toUint8Array());const g=await h.finalize();return B.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=A.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(A.Topic.fromString(i),Un(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 A.PrivateKey(l),g=A.Identifier.fromString(u),y=A.Bytes.fromUtf8(r),{upload:k}=i.makeSOCWriter(h,{timeout:f});await k(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=A.Stamper.fromBlank(h,c,this.depth),y=new A.PrivateKey(l),k=A.Identifier.fromString(u),j=A.Bytes.fromUtf8(r),oe=Dn(j.toUint8Array()),ce=Pn(oe,k,y),it={hash:()=>ce.address.toUint8Array()},je=g.stamp(it),{upload:at}=i.makeSOCWriter(y,{timeout:f});await at(je,k,j.toUint8Array())}}class Ka{constructor(r,i){this.fallbackTransport=null,this.logger=q.getInstance(),this.errorHandler=X.getInstance(),this.gsocIndex=null;const c=new A.PrivateKey(Un(r.user.privateKey));this.userDetails={privateKey:r.user.privateKey,ownAddress:c.publicKey().address().toString(),nickname:r.user.nickname,ownIndex:-1},this.swarmSettings={bee:new A.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 Di,this.utils=new Ga(this.userDetails,this.swarmSettings),this.history=new qa(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(W.MESSAGE_RECEIVED,l)}))):this.transport=this.createDefaultPollingTransport(u),this.transport.onMessage(l=>{this.emitter.emit(W.MESSAGE_RECEIVED,l)})}createDefaultPollingTransport(r){return new $n({fetchMessage:async()=>{try{if(!this.gsocIndex)return null;const i=A.Topic.fromString(this.swarmSettings.chatTopic),c=jn(i,this.gsocIndex),u=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,c.toString()),l=JSON.parse(u);return Qn(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||Ei(),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=Ha(h);if(!g.isValid){const y=`Invalid message: ${g.errors.join(", ")}`;throw this.logger.error(y),new Error(y)}try{this.emitter.emit(W.MESSAGE_REQUEST_INITIATED,h),await this.utils.writeOwnFeedDataByIndex(f,JSON.stringify(h)),this.userDetails.ownIndex=f,this.emitter.emit(W.MESSAGE_REQUEST_UPLOADED,h),await this.broadcastUserMessage(h)}catch(y){this.emitter.emit(W.MESSAGE_REQUEST_ERROR,h),this.errorHandler.handleError(y,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(W.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(W.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(W.LOADING_INIT,!0);const u=this.swarmSettings.feedReadTimeout-1e3,[l,f]=await ji(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:this.gsocIndex=A.FeedIndex.fromBigInt(0n)}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.gsocIndex||(this.gsocIndex=A.FeedIndex.fromBigInt(0n))):this.emitter.emit(W.CRITICAL_ERROR,c)}finally{this.emitter.emit(W.LOADING_INIT,!1)}}async initOwnIndex(){const{latestIndex:c}=await Kt(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=c}async broadcastUserMessage(r){try{return Kt(()=>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 A.EthAddress(i).toString(),f=new A.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()}}Q.EVENTS=W,Q.MessageType=rr,Q.PollingTransport=$n,Q.SwarmChat=Ka,Object.defineProperty(Q,Symbol.toStringTag,{value:"Module"})});
|