@solarpunkltd/swarm-chat-js 4.2.2 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- (function(ue,A){typeof exports=="object"&&typeof module<"u"?A(exports,require("@ethersphere/bee-js")):typeof define=="function"&&define.amd?define(["exports","@ethersphere/bee-js"],A):(ue=typeof globalThis<"u"?globalThis:ue||self,A(ue.SwarmChatJs={},ue.BeeJs))})(this,function(ue,A){"use strict";const P=[];for(let a=0;a<256;++a)P.push((a+256).toString(16).slice(1));function gi(a,n=0){return(P[a[n+0]]+P[a[n+1]]+P[a[n+2]]+P[a[n+3]]+"-"+P[a[n+4]]+P[a[n+5]]+"-"+P[a[n+6]]+P[a[n+7]]+"-"+P[a[n+8]]+P[a[n+9]]+"-"+P[a[n+10]]+P[a[n+11]]+P[a[n+12]]+P[a[n+13]]+P[a[n+14]]+P[a[n+15]]).toLowerCase()}let Wt;const yi=new Uint8Array(16);function vi(){if(!Wt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Wt=crypto.getRandomValues.bind(crypto)}return Wt(yi)}const On={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function wi(a,n,i){if(On.randomUUID&&!n&&!a)return On.randomUUID();a=a||{};const c=a.random||(a.rng||vi)();return c[6]=c[6]&15|64,c[8]=c[8]&63|128,gi(c)}function _i(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var In={};(function(a){var n;Object.defineProperty(a,"__esModule",{value:!0}),a.Vector=a.Cache=a.Assertions=a.Strings=a.Types=a.Objects=a.Dates=a.Promises=a.Numbers=a.System=a.Arrays=a.Random=a.Elliptic=a.Binary=a.AsyncQueue=a.PubSubChannel=a.FixedPointNumber=a.MerkleTree=a.Chunk=a.Uint8ArrayWriter=a.Uint8ArrayReader=a.AsyncLazy=a.Lazy=a.Optional=void 0;async function i(e){return new Promise((t,r)=>e.then(r,t))}async function c(e){return i(Promise.all(e.map(i)))}async function u(e,t=1){const r=Ls(e,t),s=[],o=r.map(async d=>{for(const f of d)s.push(await f())});return await Promise.all(o),s}async function l(e){return new Promise(t=>setTimeout(()=>{t(!0)},e))}function h(e,t=Math.random){for(let r=e.length-1;r>0;r--){const s=Math.floor(t()*(r+1)),o=e[r];e[r]=e[s],e[s]=o}return e}function p(e){if(e.length===1)return e[0];throw Error(`Expected exactly one element, actual: ${e.length}`)}function w(e){return e.length===1?e[0]:null}function v(e){return e.length>0?e[0]:null}function E(e){if(!e.length)throw Error("Received empty array");return e[0]}function j(e,t){const r=[];for(let s=0;s<e;s++)r.push(t(s));return r}function ae(e){const t=[];for(let r=0;r<e[0].length;r++){t.push([]);for(let s=0;s<e.length;s++)t[r].push(e[s][r])}return t}function oe(e,t,r){const s=[];for(let o=0;o<e;o++){s.push([]);for(let d=0;d<t;d++)s[o].push(r)}return s}function st(e,t,r,s){if(r<0||s<0||s+t[0].length>e[0].length||r+t.length>e.length)return!1;for(let o=0;o<t.length;o++)for(let d=0;d<t[o].length;d++)if(t[o][d]!==void 0&&e[r+o][s+d]!==t[o][d])return!1;return!0}function Re(e,t,r=Math.random){return h(us(0,e.length-1),r).slice(0,t)}function tr(e,t){return e.map(r=>r[t])}function rr(e){let t=e,r=3405648695,s=3735928559;return function(){return t+=r,r^=t<<7,t*=s,s^=t<<13,t^=r^s,(t>>>0)/4294967296}}function it(e,t,r=Math.random){return Math.floor(r()*(t-e+1))+e}function Gn(e,t,r=Math.random){return r()*(t-e)+e}function Za(){return Math.random()*2-1}function Ba(e,t,r){return t>=e.x&&t<e.x+e.width&&r>=e.y&&r<e.y+e.height}function La(e,t,r,s=Math.random){let o,d;do o=it(0,e-1,s),d=it(0,t-1,s);while(r&&Ba(r,o,d));return[o,d]}function za(e,t=Math.random){const r=Math.floor(e),s=e-r;return Kn(s,t)?r+1:r}function Kn(e,t=Math.random){return t()<e}function nr(e,t=Math.random){return e[Math.floor(e.length*t())]}function Fa(e,t,r=Math.random){if(t>e.length)throw new Error(`Count (${t}) is greater than array length (${e.length})`);return Re(e,t,r).map(s=>e[s])}function Va(e,t,r,s=Math.random){if(t>e.length)throw new Error(`Count (${t}) is greater than array length (${e.length})`);const o=[];for(;o.length<t;){const d=nr(e,s);o.some(f=>r(f,d))||o.push(d)}return o}function Wa(e,t,r,s,o,d=Math.random){const f=e.filter(m=>m!==t&&m!==r),g=[];for(t!==null&&g.push(t);f.length&&g.length<s;){const m=a.Random.intBetween(0,f.length-1,d);o(f[m],g)&&g.push(f[m]),f.splice(m,1)}return h(g,d),{values:g,indexOfGuaranteed:t!==null?g.indexOf(t):-1}}function at(e){if(!e.length)throw Error("Received empty array");return e[e.length-1]}function Yn(e,t,r){return r(t.reduce((s,o)=>o(s),e))}function Ha(e,t){return r=>Yn(r,e,t)}function qa(e,t,r){if(r===void 0&&(r=Math.random()),e.length!==t.length)throw new Error("Array length mismatch");let s=t.reduce((d,f)=>d+f,0);const o=r*s;for(let d=0;d<e.length-1;d++)if(s-=t[d],o>=s)return e[d];return at(e)}function Ga(e,t,r=Math.random){const s=t.map(d=>r()*d),o=[];for(let d=0;d<e.length;d++)o.push([e[d],s[d]]);return o.sort((d,f)=>f[1]-d[1]).map(d=>d[0])}function xe(e,t){if(e==null)return null;const r=t.split(".");let s=e;for(const o of r){if(s[o]===null||s[o]===void 0)return null;s=s[o]}return s}function ke(e,t,r){const s=t.split(/\.|\[/);let o=e;for(let d=0;d<s.length;d++){const f=s[d],g=d<s.length-1&&s[d+1].includes("]"),m=f.includes("]")?f.replace(/\[|\]/g,""):f;if(d===s.length-1)return o[m]=r,r;pe(o[m])||(g?o[m]=[]:o[m]={}),o=o[m]}return r}function Ka(e,t,r=1){const s=xe(e,t)||0;return ke(e,t,s+r),s}function Ya(e,t,r){return xe(e,t)||ke(e,t,r)}function Qa(e,t){const r=fr(t,"."),s=ds(t,".");if(!r||!s)return;const o=xe(e,r);delete o[s]}function Xa(e,t,r){const s=xe(e,t);if(!s)throw new Error("Key '"+t+"' does not exist.");return ke(e,t,r),s}function Ja(e,t,r){for(const s of t){const o=xe(e,s);if(o)return o}if(r){const s=Object.values(e);if(s.length)return s[0]}return null}async function eo(e,t,r){for(;;){try{await e()}catch(s){r&&r("Error in forever",s)}await l(t)}}function to(e,t){e();const r=setInterval(()=>{e()},t);return()=>clearInterval(r)}function ro(e){return e/1024/1024}function no(e){return e>=1024*1024*1024*1024?(e/1024/1024/1024/1024).toFixed(3)+" TB":e>=1024*1024*1024?(e/1024/1024/1024).toFixed(3)+" GB":e>=1024*1024?(e/1024/1024).toFixed(3)+" MB":e>=1024?(e/1024).toFixed(3)+" KB":e+" B"}function so(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e.toLowerCase());if(!t)throw new Error("Invalid hex color: "+e);return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}function io(e){return"#"+e.map(t=>t.toString(16).padStart(2,"0")).join("")}function ao(e,t,r,s){const o=e*Math.PI/180,d=r*Math.PI/180,f=(r-e)*Math.PI/180,g=(s-t)*Math.PI/180,m=Math.sin(f/2)*Math.sin(f/2)+Math.cos(o)*Math.cos(d)*Math.sin(g/2)*Math.sin(g/2);return 6371e3*(2*Math.atan2(Math.sqrt(m),Math.sqrt(1-m)))}function $t(e,t){return Math.round(e/t)*t}function oo(e){return e>1e3?(e/1e3).toFixed(0)+" km":e>=500?$t(e,100)+" m":e>=100?$t(e,50)+" m":$t(e,10)+" m"}function co(e){return e*(e+1)/2}function uo(e){const t=e.match(/-?\d+(\.\d+)?/);if(!t)throw Error("No float found in "+e);return parseFloat(t[0])}function pe(e,t=!0){return!e||t&&!sr(e._readableState)||t&&e.constructor&&(e.constructor.isBuffer||e.constructor.name=="Uint8Array"||e.constructor.name==="ArrayBuffer"||e.constructor.name==="ReadableStream")?!1:typeof e=="object"}function je(e){return pe(e)&&!Array.isArray(e)}function Qn(e){return Array.isArray(e)&&e.length===0}function lo(e){return je(e)&&Object.keys(e).length===0}function sr(e){return e===void 0}function ir(e){return Object.prototype.toString.call(e)==="[object Function]"||Object.prototype.toString.call(e)==="[object AsyncFunction]"}function V(e){return Object.prototype.toString.call(e)==="[object String]"}function me(e){return typeof e=="number"&&isFinite(e)}function Xn(e){return e===!0||e===!1}function De(e){return Object.prototype.toString.call(e)==="[object Date]"}function Mt(e){return!V(e)||e.trim().length===0}function ar(e){return me(e)&&Number.isInteger(e)&&e>=1}function Jn(e){return V(e)&&e.match(/^-?\d+$/)!==null}function es(e){return V(e)&&e.match(/^(0x)?[0-9a-f]+$/i)!==null}const fo="!@#$%^&*()_+-=[]{}|;:<>?,./",ho="!@#$%^&*()_+-=[]{}|;:<>?,./".split(""),or="abcdefghijklmnopqrstuvwxyz",po="ABCDEFGHIJKLMNOPQRSTUVWXYZ",mo="1234567890",cr=or+po+mo,ts=cr+fo,rs=["—","\\","東","京","都","𝖆","𝖇","𝖈","👾","🙇","💁","🙅","ᚠ","ᛇ","ᚻ","ᛦ"],ns="0123456789abcdef";function go(e,t=Math.random){let r="";for(let s=0;s<e;s++)r+=or[Math.floor(t()*or.length)];return r}function yo(e,t=Math.random){let r="";for(let s=0;s<e;s++)r+=cr[Math.floor(t()*cr.length)];return r}function vo(e,t=Math.random){let r="";for(let s=0;s<e;s++)r+=ts[Math.floor(t()*ts.length)];return r}function wo(e,t=Math.random){let r="";for(let s=0;s<e;s++)r+=rs[Math.floor(t()*rs.length)];return r}function _o(e,t){const r=new RegExp(`[0-9a-f]{${t}}`,"i"),s=e.match(r);return s?s[0]:null}function bo(e,t,r=ho){const s=fs(e,r);for(const o of s)if(t(o))return o;return null}function xo(e,t=Math.random){let r="";for(let s=0;s<e;s++)r+=ns[Math.floor(t()*ns.length)];return r}function ko(e,t){if(!Jn(e))throw new TypeError(`Expected integer string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);const r=BigInt(e);if(t&&(t.min&&r<t.min||t.max&&r>t.max))throw RangeError(`Expected integer string${t!=null&&t.name?` for ${t.name}`:""} in range: ${t.min??"-inf"}..${t.max??"inf"}; got: `+r);return e}function ss(e,t){if(Mt(e))throw new TypeError(`Expected string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);if(t&&(t.min!==void 0&&e.length<t.min||t.max!==void 0&&e.length>t.max))throw RangeError(`Expected string${t!=null&&t.name?` for ${t.name}`:""} length in range: ${t.min??"-inf"}..${t.max??"inf"}; got: ${e.length}`);return e}function Eo(e,t){if(!es(e))throw new TypeError(`Expected hex string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);const r=e.replace(/^0x/,"");if(t&&t.byteLength&&r.length!==t.byteLength*2)throw RangeError(`Expected hex string${t!=null&&t.name?` for ${t.name}`:""} of byte length ${t.byteLength}; got: `+r);return r}function So(e,t){if(!ss(e,t).split("").every(r=>r==="_"||ut(r)))throw new TypeError(`Expected safe string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function is(e,t){if(t.min!==void 0&&e<t.min||t.max!==void 0&&e>t.max)throw RangeError(`Expected value${t!=null&&t.name?` for ${t.name}`:""} in range: ${t.min??"-inf"}..${t.max??"inf"}; got: ${e}`)}function To(e,t){if(!ir(e))throw new TypeError(`Expected function${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Ct(e,t){if(me(e))return t&&is(e,t),e;if(!V(e)||!e.match(/^-?\d+(\.\d+)?$/))throw new TypeError(`Expected number${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);const r=parseFloat(e);return t&&is(r,t),r}function ur(e,t){return Ct(e,t)|0}function Ao(e,t){if(e==="true")return!0;if(e==="false")return!1;if(!Xn(e))throw new TypeError(`Expected boolean${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Oo(e,t){if(!De(e))throw new TypeError(`Expected date${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Io(e){return Mt(e)?null:e}function $o(e,t){if(!V(e))throw new TypeError(`Expected string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Mo(e,t){if(ar(e))return e;const r=parseInt(e,10);if(!ar(r))throw new TypeError(`Expected id${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return r}function Co(e,t){if(!V(e))throw new TypeError(`Expected time${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);const r=e.split(":");if(r.length!==2)throw new TypeError(`Expected time${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);const s=parseInt(r[0],10),o=parseInt(r[1],10);if(!me(s)||!me(o)||s<0||s>23||o<0||o>59)throw new TypeError(`Expected time, got${t!=null&&t.name?` for ${t.name}`:""}: `+e);return`${String(s).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function No(e,t){if(!Array.isArray(e))throw new TypeError(`Expected array${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Nt(e,t){if(!je(e))throw new TypeError(`Expected object${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Ro(e,t){return e===null?null:Nt(e,t)}function jo(e,t){const r=Nt(e,t);for(const s of Object.keys(r))if(!V(r[s]))throw new TypeError(`Expected string map${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return r}function Do(e,t){const r=Nt(e),s=Object.keys(r),o=Object.values(r);if(!s.every(V)||!o.every(me))throw new TypeError(`Expected numeric dictionary${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return r}function as(e){return V(e)&&e.match(/^https?:\/\/.+/)!==null}function Uo(e,t){if(!as(e))throw new TypeError(`Expected url${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Po(e,t){return t==null?!0:e(t)}function Zo(e,t){return t==null?null:e(t)}function Bo(e,t){return t==null?void 0:e(t)}function os(e,t){for(const[r,s]of Object.entries(t))if(!s(e[r]))throw TypeError(`${r} in value does not exist or match shape`);for(const r of Object.keys(e))if(!t[r])throw TypeError(`${r} exists in value but not in shape`);return!0}function Lo(e,t){return e.every(r=>os(r,t))}function ot(e,t="json",r=0){if(pe(e,!1)){if(r>1)return"[object Object]";if(t==="json"){if(Array.isArray(e)){const o=e.map(d=>ot(d,"json",r+1));return r===0?JSON.stringify(o):o}const s={};e.message&&(s.message=ot(e.message,"json",r+1));for(const[o,d]of Object.entries(e))s[o]=ot(d,"json",r+1);return r===0?JSON.stringify(s):s}else if(t==="key-value"){const s=Object.keys(e);return e.message&&!s.includes("message")&&s.unshift("message"),s.map(o=>`${o}=${JSON.stringify(ot(e[o],"json",r+1))}`).join(" ")}}return sr(e)&&(e="undefined"),r===0?JSON.stringify(e):e}function zo(e,t){if(V(e))return e;const r=Object.keys(e);e.message&&!r.includes("message")&&r.push("message");const s=r.map(o=>`${o}: ${e[o]}`).join("; ");return t&&e.stack?s+`
2
- `+e.stack:s}function Ee(e,t){if(je(e)&&je(t))for(const r in t)je(t[r])?(e[r]||(e[r]={}),Ee(e[r],t[r])):Array.isArray(t[r])?e[r]=[...t[r]]:(t[r]!==null&&t[r]!==void 0||e[r]===null||e[r]===void 0)&&(e[r]=t[r]);return e}function Fo(e,t){const r={};return Ee(r,e),Ee(r,t),r}function Vo(e,t,r){const s={};return Ee(s,e),Ee(s,t),Ee(s,r),s}function cs(e,t){const r={};for(const s of e)for(const o of Object.keys(s))r[o]?r[o]=t(r[o],s[o]):r[o]=s[o];return r}function Wo(e){return cs(e,(t,r)=>t+r)}function Ho(e,t,r){e[t]||(e[t]=[]),e[t].push(r)}function qo(e,t,r){for(e.unshift(t);e.length>r;)e.pop()}function Go(e,t){let r=t%e.length;return r<0&&(r+=e.length),e[r]}function Rt(e,t){Array.prototype.push.apply(e,t)}function Ko(e,t){Array.prototype.unshift.apply(e,t)}async function Yo(e,t){const r=[];for(const s of e)r.push(await t(s));return r}function Qo(e,t){const r=[];for(let s=0;s<e.length;s++)r.push(e[s]),s<e.length-1&&(ir(t)?r.push(t()):r.push(t));return r}function Xo(e,t){if(e!==t)throw Error(`Expected [${e}] to equal [${t}]`);return[e,t]}function Jo(e){if(e!==!0)throw Error(`Expected [true], got: [${e}]`);return e}function ec(e){if(!e)throw Error(`Expected truthy value, got: [${e}]`);return e}function tc(e){if(e!==!1)throw Error(`Expected [false], got: [${e}]`);return e}function rc(e){if(e)throw Error(`Expected falsy value, got: [${e}]`);return e}function nc(e,t){if(!t.includes(e))throw Error(`Expected any of [${t.join(", ")}], got: [${e}]`);return e}function sc(e,t){for(let r=0;r<e.length;r++){const s=e[r],o=t[r],d=Math.max(0,o.getTime()-Date.now());setTimeout(s,d)}}function ic(e,t,r){return e+(t-e)*r}function ac(e){return e.reduce((t,r)=>t+r,0)}function oc(e){return e.reduce((t,r)=>t+r,0)/e.length}function cc(e){const t=[...e].sort((s,o)=>s-o),r=Math.floor(t.length/2);return t.length%2===0?(t[r]+t[r-1])/2:t[r]}function uc(e,t){return e-(t-1)/2}function us(e,t){const r=[];for(let s=e;s<=t;s++)r.push(s);return r}function lc(e,t){return t.some(r=>e.includes(r))}function dc(e){return/^[\u4E00-\u9FA5]+$/.test(e)}function lr(e,t=()=>!1){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").split("").map(r=>/[a-z0-9]/.test(r)||t(r)?r:"-").join("").replace(/-+/g,"-").replace(/^-|-$/g,"")}function fc(e){return lr(e).replaceAll("-","")}function hc(e){return Dt(e.replace(/([A-Z])/g," $1"))}function pc(e){return e.split("-").map(Dt).join(" ")}function mc(e){return ps(e.split("-").map(Dt).join(""))}function gc(e,t=", ",r=" and "){return!e||!e.length?"":e.length===1?e[0]:e.length===2?`${e[0]}${r}${e[1]}`:`${e.slice(0,e.length-1).join(t)}${r}${e[e.length-1]}`}function yc(e,t){return t+e.split("").join(t)+t}function vc(e){return lr(e).replace(/-/g,"_").toUpperCase()}function jt(e,t){if(t.length===0)return 0;const r=e.toLowerCase(),s=t.toLowerCase();return e===t?1e4:r.startsWith(s)?1e4-e.length:r.includes(s)?5e3-e.length:new RegExp(".*"+s.split("").join(".*")+".*").test(r)?1e3-e.length:0}function wc(e,t){return e.filter(r=>jt(r,t)).sort((r,s)=>jt(s,t)-jt(r,t))}function _c(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}const bc={"&amp;":"&","&quot;":'"',"&apos;":"'","&gt;":">","&lt;":"<"};function xc(e){let t=e.replace(/&#(\d+);/g,(r,s)=>String.fromCharCode(s)).replace(/&#x(\d+);/g,(r,s)=>String.fromCharCode(parseInt(s,16)));for(const[r,s]of Object.entries(bc))t=t.replaceAll(r,s);return t}function ls(e,t){const r=e.indexOf(t);return r===-1?null:e.slice(0,r)}function dr(e,t){const r=e.indexOf(t);return r===-1?null:e.slice(r+t.length)}function fr(e,t){const r=e.lastIndexOf(t);return r===-1?null:e.slice(0,r)}function ds(e,t){const r=e.lastIndexOf(t);return r===-1?null:e.slice(r+t.length)}function kc(e,t,r){const s=fr(e,r);return s?dr(s,t):null}function Ec(e,t,r){const s=dr(e,t);return s?ls(s,r):null}function hr(e,t,r=!1){const s=r?e.lastIndexOf(t):e.indexOf(t);return s===-1?r?[null,e]:[e,null]:[e.slice(0,s),e.slice(s+t.length)]}function fs(e,t){let r=[e];for(const s of t)r=r.flatMap(o=>o.split(s));return r.filter(s=>s)}function pr(e){const t=at(e.split(/\\|\//g)),r=t.lastIndexOf(".",t.length-1);return r<=0?"":t.slice(r+1)}function mr(e){const t=at(e.split(/\\|\//g)),r=t.lastIndexOf(".",t.length-1);return r<=0?t:t.slice(0,r)}function Sc(e){let[t,r]=e.split("@");t=ct(t.replaceAll(".","").toLowerCase()).replaceAll(" ","");const[s]=t.split("+");if(!s||!r||r.indexOf(".")===-1||r.indexOf(".")===r.length-1)throw new Error("Invalid email");return r=ct(r.toLowerCase()).replaceAll(" ",""),`${s}@${r}`}function Tc(e){const t=mr(e),r=pr(e);return r?`${t}.${r}`:t}function Ac(e){const t=mr(e),r=pr(e);return{basename:t,extension:r,filename:r?`${t}.${r}`:t}}function Oc(e,t=Math.random){return e.replace(/\{(.+?)\}/g,(r,s)=>nr(s.split("|"),t))}function hs(e){const t=/\{(.+?)\}/,r=e.match(t);if(!r||!r.index)return[e];const s=r[1].split(","),o=e.slice(0,r.index),d=e.slice(r.index+r[0].length);let f=[];for(const g of s){const m=hs(o+g+d);f=f.concat(m)}return f}function ct(e){return e.split(`
1
+ (function(re,A){typeof exports=="object"&&typeof module<"u"?A(exports,require("@ethersphere/bee-js")):typeof define=="function"&&define.amd?define(["exports","@ethersphere/bee-js"],A):(re=typeof globalThis<"u"?globalThis:re||self,A(re.SwarmChatJs={},re.BeeJs))})(this,function(re,A){"use strict";const P=[];for(let a=0;a<256;++a)P.push((a+256).toString(16).slice(1));function _i(a,r=0){return(P[a[r+0]]+P[a[r+1]]+P[a[r+2]]+P[a[r+3]]+"-"+P[a[r+4]]+P[a[r+5]]+"-"+P[a[r+6]]+P[a[r+7]]+"-"+P[a[r+8]]+P[a[r+9]]+"-"+P[a[r+10]]+P[a[r+11]]+P[a[r+12]]+P[a[r+13]]+P[a[r+14]]+P[a[r+15]]).toLowerCase()}let Ht;const bi=new Uint8Array(16);function xi(){if(!Ht){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ht=crypto.getRandomValues.bind(crypto)}return Ht(bi)}const Mn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ki(a,r,i){if(Mn.randomUUID&&!r&&!a)return Mn.randomUUID();a=a||{};const c=a.random||(a.rng||xi)();return c[6]=c[6]&15|64,c[8]=c[8]&63|128,_i(c)}function Ei(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var $n={};(function(a){var r;Object.defineProperty(a,"__esModule",{value:!0}),a.Vector=a.Cache=a.Assertions=a.Strings=a.Types=a.Objects=a.Dates=a.Promises=a.Numbers=a.System=a.Arrays=a.Random=a.Elliptic=a.Binary=a.AsyncQueue=a.PubSubChannel=a.FixedPointNumber=a.MerkleTree=a.Chunk=a.Uint8ArrayWriter=a.Uint8ArrayReader=a.AsyncLazy=a.Lazy=a.Optional=void 0;async function i(e){return new Promise((t,n)=>e.then(n,t))}async function c(e){return i(Promise.all(e.map(i)))}async function u(e,t=1){const n=Ws(e,t),s=[],o=n.map(async d=>{for(const f of d)s.push(await f())});return await Promise.all(o),s}async function l(e){return new Promise(t=>setTimeout(()=>{t(!0)},e))}function h(e,t=Math.random){for(let n=e.length-1;n>0;n--){const s=Math.floor(t()*(n+1)),o=e[n];e[n]=e[s],e[s]=o}return e}function m(e){if(e.length===1)return e[0];throw Error(`Expected exactly one element, actual: ${e.length}`)}function w(e){return e.length===1?e[0]:null}function v(e){return e.length>0?e[0]:null}function E(e){if(!e.length)throw Error("Received empty array");return e[0]}function j(e,t){const n=[];for(let s=0;s<e;s++)n.push(t(s));return n}function oe(e){const t=[];for(let n=0;n<e[0].length;n++){t.push([]);for(let s=0;s<e.length;s++)t[n].push(e[s][n])}return t}function ce(e,t,n){const s=[];for(let o=0;o<e;o++){s.push([]);for(let d=0;d<t;d++)s[o].push(n)}return s}function it(e,t,n,s){if(n<0||s<0||s+t[0].length>e[0].length||n+t.length>e.length)return!1;for(let o=0;o<t.length;o++)for(let d=0;d<t[o].length;d++)if(t[o][d]!==void 0&&e[n+o][s+d]!==t[o][d])return!1;return!0}function je(e,t,n=Math.random){return h(hs(0,e.length-1),n).slice(0,t)}function nr(e,t){return e.map(n=>n[t])}function sr(e){let t=e,n=3405648695,s=3735928559;return function(){return t+=n,n^=t<<7,t*=s,s^=t<<13,t^=n^s,(t>>>0)/4294967296}}function at(e,t,n=Math.random){return Math.floor(n()*(t-e+1))+e}function Xn(e,t,n=Math.random){return n()*(t-e)+e}function Wa(){return Math.random()*2-1}function Ha(e,t,n){return t>=e.x&&t<e.x+e.width&&n>=e.y&&n<e.y+e.height}function qa(e,t,n,s=Math.random){let o,d;do o=at(0,e-1,s),d=at(0,t-1,s);while(n&&Ha(n,o,d));return[o,d]}function Ga(e,t=Math.random){const n=Math.floor(e),s=e-n;return Jn(s,t)?n+1:n}function Jn(e,t=Math.random){return t()<e}function ir(e,t=Math.random){return e[Math.floor(e.length*t())]}function Ka(e,t,n=Math.random){if(t>e.length)throw new Error(`Count (${t}) is greater than array length (${e.length})`);return je(e,t,n).map(s=>e[s])}function Ya(e,t,n,s=Math.random){if(t>e.length)throw new Error(`Count (${t}) is greater than array length (${e.length})`);const o=[];for(;o.length<t;){const d=ir(e,s);o.some(f=>n(f,d))||o.push(d)}return o}function Qa(e,t,n,s,o,d=Math.random){const f=e.filter(p=>p!==t&&p!==n),g=[];for(t!==null&&g.push(t);f.length&&g.length<s;){const p=a.Random.intBetween(0,f.length-1,d);o(f[p],g)&&g.push(f[p]),f.splice(p,1)}return h(g,d),{values:g,indexOfGuaranteed:t!==null?g.indexOf(t):-1}}function ot(e){if(!e.length)throw Error("Received empty array");return e[e.length-1]}function es(e,t,n){return n(t.reduce((s,o)=>o(s),e))}function Xa(e,t){return n=>es(n,e,t)}function Ja(e,t,n){if(n===void 0&&(n=Math.random()),e.length!==t.length)throw new Error("Array length mismatch");let s=t.reduce((d,f)=>d+f,0);const o=n*s;for(let d=0;d<e.length-1;d++)if(s-=t[d],o>=s)return e[d];return ot(e)}function eo(e,t,n=Math.random){const s=t.map(d=>n()*d),o=[];for(let d=0;d<e.length;d++)o.push([e[d],s[d]]);return o.sort((d,f)=>f[1]-d[1]).map(d=>d[0])}function ke(e,t){if(e==null)return null;const n=t.split(".");let s=e;for(const o of n){if(s[o]===null||s[o]===void 0)return null;s=s[o]}return s}function Ee(e,t,n){const s=t.split(/\.|\[/);let o=e;for(let d=0;d<s.length;d++){const f=s[d],g=d<s.length-1&&s[d+1].includes("]"),p=f.includes("]")?f.replace(/\[|\]/g,""):f;if(d===s.length-1)return o[p]=n,n;me(o[p])||(g?o[p]=[]:o[p]={}),o=o[p]}return n}function to(e,t,n=1){const s=ke(e,t)||0;return Ee(e,t,s+n),s}function ro(e,t,n){return ke(e,t)||Ee(e,t,n)}function no(e,t){const n=mr(t,"."),s=ps(t,".");if(!n||!s)return;const o=ke(e,n);delete o[s]}function so(e,t,n){const s=ke(e,t);if(!s)throw new Error("Key '"+t+"' does not exist.");return Ee(e,t,n),s}function io(e,t,n){for(const s of t){const o=ke(e,s);if(o)return o}if(n){const s=Object.values(e);if(s.length)return s[0]}return null}async function ao(e,t,n){for(;;){try{await e()}catch(s){n&&n("Error in forever",s)}await l(t)}}function oo(e,t){e();const n=setInterval(()=>{e()},t);return()=>clearInterval(n)}function co(e){return e/1024/1024}function uo(e){return e>=1024*1024*1024*1024?(e/1024/1024/1024/1024).toFixed(3)+" TB":e>=1024*1024*1024?(e/1024/1024/1024).toFixed(3)+" GB":e>=1024*1024?(e/1024/1024).toFixed(3)+" MB":e>=1024?(e/1024).toFixed(3)+" KB":e+" B"}function lo(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e.toLowerCase());if(!t)throw new Error("Invalid hex color: "+e);return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}function fo(e){return"#"+e.map(t=>t.toString(16).padStart(2,"0")).join("")}function ho(e,t,n,s){const o=e*Math.PI/180,d=n*Math.PI/180,f=(n-e)*Math.PI/180,g=(s-t)*Math.PI/180,p=Math.sin(f/2)*Math.sin(f/2)+Math.cos(o)*Math.cos(d)*Math.sin(g/2)*Math.sin(g/2);return 6371e3*(2*Math.atan2(Math.sqrt(p),Math.sqrt(1-p)))}function $t(e,t){return Math.round(e/t)*t}function mo(e){return e>1e3?(e/1e3).toFixed(0)+" km":e>=500?$t(e,100)+" m":e>=100?$t(e,50)+" m":$t(e,10)+" m"}function po(e){return e*(e+1)/2}function go(e){const t=e.match(/-?\d+(\.\d+)?/);if(!t)throw Error("No float found in "+e);return parseFloat(t[0])}function me(e,t=!0){return!e||t&&!ar(e._readableState)||t&&e.constructor&&(e.constructor.isBuffer||e.constructor.name=="Uint8Array"||e.constructor.name==="ArrayBuffer"||e.constructor.name==="ReadableStream")?!1:typeof e=="object"}function De(e){return me(e)&&!Array.isArray(e)}function ts(e){return Array.isArray(e)&&e.length===0}function yo(e){return De(e)&&Object.keys(e).length===0}function ar(e){return e===void 0}function or(e){return Object.prototype.toString.call(e)==="[object Function]"||Object.prototype.toString.call(e)==="[object AsyncFunction]"}function W(e){return Object.prototype.toString.call(e)==="[object String]"}function pe(e){return typeof e=="number"&&isFinite(e)}function rs(e){return e===!0||e===!1}function Ue(e){return Object.prototype.toString.call(e)==="[object Date]"}function Rt(e){return!W(e)||e.trim().length===0}function cr(e){return pe(e)&&Number.isInteger(e)&&e>=1}function ns(e){return W(e)&&e.match(/^-?\d+$/)!==null}function ss(e){return W(e)&&e.match(/^(0x)?[0-9a-f]+$/i)!==null}const vo="!@#$%^&*()_+-=[]{}|;:<>?,./",wo="!@#$%^&*()_+-=[]{}|;:<>?,./".split(""),ur="abcdefghijklmnopqrstuvwxyz",_o="ABCDEFGHIJKLMNOPQRSTUVWXYZ",bo="1234567890",lr=ur+_o+bo,is=lr+vo,as=["—","\\","東","京","都","𝖆","𝖇","𝖈","👾","🙇","💁","🙅","ᚠ","ᛇ","ᚻ","ᛦ"],os="0123456789abcdef";function xo(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=ur[Math.floor(t()*ur.length)];return n}function ko(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=lr[Math.floor(t()*lr.length)];return n}function Eo(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=is[Math.floor(t()*is.length)];return n}function So(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=as[Math.floor(t()*as.length)];return n}function To(e,t){const n=new RegExp(`[0-9a-f]{${t}}`,"i"),s=e.match(n);return s?s[0]:null}function Ao(e,t,n=wo){const s=gs(e,n);for(const o of s)if(t(o))return o;return null}function Oo(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=os[Math.floor(t()*os.length)];return n}function Io(e,t){if(!ns(e))throw new TypeError(`Expected integer string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);const n=BigInt(e);if(t&&(t.min&&n<t.min||t.max&&n>t.max))throw RangeError(`Expected integer string${t!=null&&t.name?` for ${t.name}`:""} in range: ${t.min??"-inf"}..${t.max??"inf"}; got: `+n);return e}function cs(e,t){if(Rt(e))throw new TypeError(`Expected string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);if(t&&(t.min!==void 0&&e.length<t.min||t.max!==void 0&&e.length>t.max))throw RangeError(`Expected string${t!=null&&t.name?` for ${t.name}`:""} length in range: ${t.min??"-inf"}..${t.max??"inf"}; got: ${e.length}`);return e}function Mo(e,t){if(!ss(e))throw new TypeError(`Expected hex string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);const n=e.replace(/^0x/,"");if(t&&t.byteLength&&n.length!==t.byteLength*2)throw RangeError(`Expected hex string${t!=null&&t.name?` for ${t.name}`:""} of byte length ${t.byteLength}; got: `+n);return n}function $o(e,t){if(!cs(e,t).split("").every(n=>n==="_"||lt(n)))throw new TypeError(`Expected safe string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function us(e,t){if(t.min!==void 0&&e<t.min||t.max!==void 0&&e>t.max)throw RangeError(`Expected value${t!=null&&t.name?` for ${t.name}`:""} in range: ${t.min??"-inf"}..${t.max??"inf"}; got: ${e}`)}function Ro(e,t){if(!or(e))throw new TypeError(`Expected function${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Ct(e,t){if(pe(e))return t&&us(e,t),e;if(!W(e)||!e.match(/^-?\d+(\.\d+)?$/))throw new TypeError(`Expected number${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);const n=parseFloat(e);return t&&us(n,t),n}function dr(e,t){return Ct(e,t)|0}function Co(e,t){if(e==="true")return!0;if(e==="false")return!1;if(!rs(e))throw new TypeError(`Expected boolean${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function No(e,t){if(!Ue(e))throw new TypeError(`Expected date${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function jo(e){return Rt(e)?null:e}function Do(e,t){if(!W(e))throw new TypeError(`Expected string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Uo(e,t){if(cr(e))return e;const n=parseInt(e,10);if(!cr(n))throw new TypeError(`Expected id${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return n}function Po(e,t){if(!W(e))throw new TypeError(`Expected time${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);const n=e.split(":");if(n.length!==2)throw new TypeError(`Expected time${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);const s=parseInt(n[0],10),o=parseInt(n[1],10);if(!pe(s)||!pe(o)||s<0||s>23||o<0||o>59)throw new TypeError(`Expected time, got${t!=null&&t.name?` for ${t.name}`:""}: `+e);return`${String(s).padStart(2,"0")}:${String(o).padStart(2,"0")}`}function Zo(e,t){if(!Array.isArray(e))throw new TypeError(`Expected array${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Nt(e,t){if(!De(e))throw new TypeError(`Expected object${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Bo(e,t){return e===null?null:Nt(e,t)}function Lo(e,t){const n=Nt(e,t);for(const s of Object.keys(n))if(!W(n[s]))throw new TypeError(`Expected string map${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return n}function zo(e,t){const n=Nt(e),s=Object.keys(n),o=Object.values(n);if(!s.every(W)||!o.every(pe))throw new TypeError(`Expected numeric dictionary${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return n}function ls(e){return W(e)&&e.match(/^https?:\/\/.+/)!==null}function Fo(e,t){if(!ls(e))throw new TypeError(`Expected url${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Vo(e,t){return t==null?!0:e(t)}function Wo(e,t){return t==null?null:e(t)}function Ho(e,t){return t==null?void 0:e(t)}function ds(e,t){for(const[n,s]of Object.entries(t))if(!s(e[n]))throw TypeError(`${n} in value does not exist or match shape`);for(const n of Object.keys(e))if(!t[n])throw TypeError(`${n} exists in value but not in shape`);return!0}function qo(e,t){return e.every(n=>ds(n,t))}function ct(e,t="json",n=0){if(me(e,!1)){if(n>1)return"[object Object]";if(t==="json"){if(Array.isArray(e)){const o=e.map(d=>ct(d,"json",n+1));return n===0?JSON.stringify(o):o}const s={};e.message&&(s.message=ct(e.message,"json",n+1));for(const[o,d]of Object.entries(e))s[o]=ct(d,"json",n+1);return n===0?JSON.stringify(s):s}else if(t==="key-value"){const s=Object.keys(e);return e.message&&!s.includes("message")&&s.unshift("message"),s.map(o=>`${o}=${JSON.stringify(ct(e[o],"json",n+1))}`).join(" ")}}return ar(e)&&(e="undefined"),n===0?JSON.stringify(e):e}function Go(e,t){if(W(e))return e;const n=Object.keys(e);e.message&&!n.includes("message")&&n.push("message");const s=n.map(o=>`${o}: ${e[o]}`).join("; ");return t&&e.stack?s+`
2
+ `+e.stack:s}function Se(e,t){if(De(e)&&De(t))for(const n in t)De(t[n])?(e[n]||(e[n]={}),Se(e[n],t[n])):Array.isArray(t[n])?e[n]=[...t[n]]:(t[n]!==null&&t[n]!==void 0||e[n]===null||e[n]===void 0)&&(e[n]=t[n]);return e}function Ko(e,t){const n={};return Se(n,e),Se(n,t),n}function Yo(e,t,n){const s={};return Se(s,e),Se(s,t),Se(s,n),s}function fs(e,t){const n={};for(const s of e)for(const o of Object.keys(s))n[o]?n[o]=t(n[o],s[o]):n[o]=s[o];return n}function Qo(e){return fs(e,(t,n)=>t+n)}function Xo(e,t,n){e[t]||(e[t]=[]),e[t].push(n)}function Jo(e,t,n){for(e.unshift(t);e.length>n;)e.pop()}function ec(e,t){let n=t%e.length;return n<0&&(n+=e.length),e[n]}function jt(e,t){Array.prototype.push.apply(e,t)}function tc(e,t){Array.prototype.unshift.apply(e,t)}async function rc(e,t){const n=[];for(const s of e)n.push(await t(s));return n}function nc(e,t){const n=[];for(let s=0;s<e.length;s++)n.push(e[s]),s<e.length-1&&(or(t)?n.push(t()):n.push(t));return n}function sc(e,t){if(e!==t)throw Error(`Expected [${e}] to equal [${t}]`);return[e,t]}function ic(e){if(e!==!0)throw Error(`Expected [true], got: [${e}]`);return e}function ac(e){if(!e)throw Error(`Expected truthy value, got: [${e}]`);return e}function oc(e){if(e!==!1)throw Error(`Expected [false], got: [${e}]`);return e}function cc(e){if(e)throw Error(`Expected falsy value, got: [${e}]`);return e}function uc(e,t){if(!t.includes(e))throw Error(`Expected any of [${t.join(", ")}], got: [${e}]`);return e}function lc(e,t){for(let n=0;n<e.length;n++){const s=e[n],o=t[n],d=Math.max(0,o.getTime()-Date.now());setTimeout(s,d)}}function dc(e,t,n){return e+(t-e)*n}function fc(e){return e.reduce((t,n)=>t+n,0)}function hc(e){return e.reduce((t,n)=>t+n,0)/e.length}function mc(e){const t=[...e].sort((s,o)=>s-o),n=Math.floor(t.length/2);return t.length%2===0?(t[n]+t[n-1])/2:t[n]}function pc(e,t){return e-(t-1)/2}function hs(e,t){const n=[];for(let s=e;s<=t;s++)n.push(s);return n}function gc(e,t){return t.some(n=>e.includes(n))}function yc(e){return/^[\u4E00-\u9FA5]+$/.test(e)}function fr(e,t=()=>!1){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").split("").map(n=>/[a-z0-9]/.test(n)||t(n)?n:"-").join("").replace(/-+/g,"-").replace(/^-|-$/g,"")}function vc(e){return fr(e).replaceAll("-","")}function wc(e){return Ut(e.replace(/([A-Z])/g," $1"))}function _c(e){return e.split("-").map(Ut).join(" ")}function bc(e){return vs(e.split("-").map(Ut).join(""))}function xc(e,t=", ",n=" and "){return!e||!e.length?"":e.length===1?e[0]:e.length===2?`${e[0]}${n}${e[1]}`:`${e.slice(0,e.length-1).join(t)}${n}${e[e.length-1]}`}function kc(e,t){return t+e.split("").join(t)+t}function Ec(e){return fr(e).replace(/-/g,"_").toUpperCase()}function Dt(e,t){if(t.length===0)return 0;const n=e.toLowerCase(),s=t.toLowerCase();return e===t?1e4:n.startsWith(s)?1e4-e.length:n.includes(s)?5e3-e.length:new RegExp(".*"+s.split("").join(".*")+".*").test(n)?1e3-e.length:0}function Sc(e,t){return e.filter(n=>Dt(n,t)).sort((n,s)=>Dt(s,t)-Dt(n,t))}function Tc(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}const Ac={"&amp;":"&","&quot;":'"',"&apos;":"'","&gt;":">","&lt;":"<"};function Oc(e){let t=e.replace(/&#(\d+);/g,(n,s)=>String.fromCharCode(s)).replace(/&#x(\d+);/g,(n,s)=>String.fromCharCode(parseInt(s,16)));for(const[n,s]of Object.entries(Ac))t=t.replaceAll(n,s);return t}function ms(e,t){const n=e.indexOf(t);return n===-1?null:e.slice(0,n)}function hr(e,t){const n=e.indexOf(t);return n===-1?null:e.slice(n+t.length)}function mr(e,t){const n=e.lastIndexOf(t);return n===-1?null:e.slice(0,n)}function ps(e,t){const n=e.lastIndexOf(t);return n===-1?null:e.slice(n+t.length)}function Ic(e,t,n){const s=mr(e,n);return s?hr(s,t):null}function Mc(e,t,n){const s=hr(e,t);return s?ms(s,n):null}function pr(e,t,n=!1){const s=n?e.lastIndexOf(t):e.indexOf(t);return s===-1?n?[null,e]:[e,null]:[e.slice(0,s),e.slice(s+t.length)]}function gs(e,t){let n=[e];for(const s of t)n=n.flatMap(o=>o.split(s));return n.filter(s=>s)}function gr(e){const t=ot(e.split(/\\|\//g)),n=t.lastIndexOf(".",t.length-1);return n<=0?"":t.slice(n+1)}function yr(e){const t=ot(e.split(/\\|\//g)),n=t.lastIndexOf(".",t.length-1);return n<=0?t:t.slice(0,n)}function $c(e){let[t,n]=e.split("@");t=ut(t.replaceAll(".","").toLowerCase()).replaceAll(" ","");const[s]=t.split("+");if(!s||!n||n.indexOf(".")===-1||n.indexOf(".")===n.length-1)throw new Error("Invalid email");return n=ut(n.toLowerCase()).replaceAll(" ",""),`${s}@${n}`}function Rc(e){const t=yr(e),n=gr(e);return n?`${t}.${n}`:t}function Cc(e){const t=yr(e),n=gr(e);return{basename:t,extension:n,filename:n?`${t}.${n}`:t}}function Nc(e,t=Math.random){return e.replace(/\{(.+?)\}/g,(n,s)=>ir(s.split("|"),t))}function ys(e){const t=/\{(.+?)\}/,n=e.match(t);if(!n||!n.index)return[e];const s=n[1].split(","),o=e.slice(0,n.index),d=e.slice(n.index+n[0].length);let f=[];for(const g of s){const p=ys(o+g+d);f=f.concat(p)}return f}function ut(e){return e.split(`
3
3
  `).map(t=>t.trim().replace(/\s+/g," ")).filter(t=>t.length>0).join(`
4
- `)}function Dt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ps(e){return e.charAt(0).toLowerCase()+e.slice(1)}function ms(e){if(!e)return!1;const t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function gs(e){if(!e)return!1;const t=e.charCodeAt(0);return t>=48&&t<=57}function ut(e){return ms(e)||gs(e)}const Ic=`
5
- \r.,?!:;"'\`(){}[]~@#$%^&*-+=|<>/\\`.split("");function $c(e){return Ic.includes(e)}function Mc(e){return ut(e)||e==="."||e==="["||e==="]"||e==="_"}function Cc(e,t,r,s,o){return e.slice(0,t)+s+e.slice(t,t+r)+o+e.slice(t+r)}function ys(e,t,r=0){const s=t.exec(e.slice(r));return s?{index:s.index,match:s[0]}:null}function vs(e,t,r=!0){if(!r)return t.every(o=>o instanceof RegExp?o.test(e):e.indexOf(o,0)!==-1);let s=0;for(const o of t)if(o instanceof RegExp){const d=ys(e,o,s);if(!d)return!1;s=d.index+d.match.length}else{const d=e.indexOf(o,s);if(d===-1)return!1;s=d+o.length}return!0}function Nc(e,t,r=!0){let s=0;for(const o of t){let d=!1;for(;!d&&s<e.length;)vs(e[s],o,r)&&(d=!0),s++;if(!d)return!1}return!0}function Rc(e){return e.match(/"|,/)?`"${e.replace(/"/g,'""')}"`:e}function Ue(e,t,r=0){let s=-1;for(const o of t){const d=e.indexOf(o,r);d!==-1&&(s===-1||d<s)&&(s=d)}return s}function jc(e,t=0){for(let r=t;r<e.length;r++)if($c(e[r]))return r;return-1}function Dc(e,t=0){for(let r=t;r<e.length;r++)if(e[r]==="#"&&ut(e[r+1]))return r;return-1}function ws(e,t,r=0){return e.slice(0,r).lastIndexOf(t)}function _s(e,t=0,r="{",s="}"){let o=1;for(let d=t;d<e.length;d++)if(e.slice(d,d+s.length)===s){if(--o===0)return d}else e.slice(d,d+r.length)===r&&o++;return-1}function bs(e,t){const r=t.wordBoundary?Ue(e,[`${t.opening} `,`${t.opening}
6
- `],t.start||0):e.indexOf(t.opening,t.start||0);if(r===-1)return null;const s=_s(e,r+t.opening.length,t.opening,t.closing);return s===-1?null:t.exclusive?e.slice(r+t.opening.length,s):e.slice(r,s+t.closing.length)}function Uc(e,t){const r=[];let s=t.wordBoundary?Ue(e,[`${t.opening} `,`${t.opening}
7
- `],t.start||0):e.indexOf(t.opening,t.start||0);for(;;){if(s===-1)return r;const o=bs(e,{...t,start:s});if(!o)return r;r.push(o),s=t.wordBoundary?Ue(e,[`${t.opening} `,`${t.opening}
8
- `],s+o.length):e.indexOf(t.opening,s+o.length)}}function Pc(e,t,r){let s=0;for(;;){const o=a.Strings.extractBlock(e,{...r,start:s});if(!o)return e;const d=t(o);s=e.indexOf(o,s)+d.length,e=e.replace(o,d)}}function Zc(e,t){const r=[];let s=0;for(;s<e.length;){const o=e.indexOf(t,s);if(o===-1){r.push({string:e.slice(s),symbol:null});break}const d=e.indexOf(t,o+t.length);if(o>s&&d!==-1&&r.push({string:e.slice(s,o),symbol:null}),d===-1){r.push({string:e.slice(s),symbol:null});break}r.push({string:e.slice(o+t.length,d),symbol:t}),s=d+t.length}return r}function Bc(e){const t=[];let r=0;for(;r<e.length;){const s=Dc(e,r);if(s===-1){t.push({string:e.slice(r),symbol:null});break}const o=jc(e,s+1);if(o===-1){t.push({string:e.slice(r,s),symbol:null}),t.push({string:e.slice(s+1),symbol:"#"});break}s>r&&t.push({string:e.slice(r,s),symbol:null}),t.push({string:e.slice(s+1,o),symbol:"#"}),r=o}return t}function Lc(e){const t=[];let r=0;for(;r<e.length;){const s=Ue(e,["http://","https://"],r);if(s===-1){t.push({string:e.slice(r),symbol:null});break}const o=Ue(e,[" ",`
9
- `],s);if(o===-1){s>r&&t.push({string:e.slice(r,s),symbol:null}),t.push({string:e.slice(s),symbol:"http"});break}s>r&&t.push({string:e.slice(r,s),symbol:null}),t.push({string:e.slice(s,o),symbol:"http"}),r=o}return t}const xs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ks="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function zc(e){return Es(e,xs)}function Fc(e){return Ss(e,xs)}function Vc(e){return Es(e,ks)}function Wc(e){return Ss(e,ks)}function Es(e,t){const r="=",s=t.length;let o=0,d=0;const f=[];for(let g=0;g<e.length;g++){const m=e[g];if(m===r)break;const k=t.indexOf(m);if(k===-1)throw new Error(`Invalid character: ${m}`);d=d<<Math.log2(s)|k,o+=Math.log2(s),o>=8&&(o-=8,f.push(d>>o&255))}return new Uint8Array(f)}function Ss(e,t){const r=t.length;let s=0,o=0,d="";for(let f=0;f<e.length;f++)for(o=o<<8|e[f],s+=8;s>=Math.log2(r);)s-=Math.log2(r),d+=t[o>>s&r-1];return s>0&&(d+=t[o<<Math.log2(r)-s&r-1]),d.length%4!==0&&(d+="=".repeat(4-d.length%4)),d}function Hc(e){e.startsWith("0x")&&(e=e.slice(2));const t=e.length/2,r=new Uint8Array(t);for(let s=0;s<t;s++){const o=parseInt(e.slice(s*2,s*2+2),16);r[s]=o}return r}function qc(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function Gc(e,t){const r=e.split("/").filter(d=>d),s=t.split("/").filter(d=>d);if(r.length!==s.length)return null;const o={};for(let d=0;d<r.length;d++){const f=r[d];if(f.startsWith(":"))o[f.slice(1)]=s[d];else if(f!==s[d])return null}return o}function gr(e,t,r){const s=[];for(const o of r)o!==t&&s.push(e.replace(t,o));return s}function Kc(e,t,r,s=Math.random){const o=a.Arrays.shuffle(t.map(f=>({variants:a.Arrays.shuffle(f.variants.map(g=>g),s),avoid:f.avoid})),s),d=[];for(const f of o){const g=f.variants.filter(k=>k!==f.avoid),m=g.find(k=>e.includes(k));if(m&&(Rt(d,gr(e,m,g)),d.length>=r))break}if(d.length<r)for(const f of o){const g=f.variants.find(m=>e.includes(m));if(g&&(Rt(d,gr(e,g,f.variants)),d.length>=r))break}return d.slice(0,r)}function Yc(e,t,r,s=!1){const o=new RegExp(s?`(?<=\\s|^)${t}(?=\\s|$)`:`\\b${t}\\b`,"g");return e.replace(o,r)}function Qc(e,t){const r=/\b[A-Z][a-zA-Z0-9]*\b/g;return e.replace(r,s=>s.toUpperCase()===s?s:t(s))}function Xc(e){return e.replace(/<[^>]*>/g,"")}function Ts(e){const t=e.lastIndexOf(" ");if(t===-1)return{line:e,rest:""};const r=e.slice(0,t),s=e.slice(t+1);return{line:r,rest:s}}function Jc(e,t={}){return[...e].reduce((r,s)=>r+(t[s]||1),0)}function eu(e,t,r={}){const s=[];let o="",d=0;for(let f=0;f<e.length;f++){const g=e[f],m=r[g]||1;if(o+=g,d+=m,d>t){const{line:k,rest:M}=Ts(o);s.push(k),o=M,d=M.split("").map(U=>r[U]||1).reduce((U,Le)=>U+Le,0)}}return o&&s.push(o),s}function tu(e,t){const r=[];for(let s=0;s<=e.length;s++)r[s]=[s];for(let s=0;s<=t.length;s++)r[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;r[s][o]=Math.min(r[s-1][o]+1,r[s][o-1]+1,r[s-1][o-1]+d)}return r[e.length][t.length]}function yr(e,t){return new RegExp(`\\b${t}\\b`).test(e)}function ru(e,t,r){return r==="any"?t.some(s=>yr(e,s)):t.every(s=>yr(e,s))}function nu(e){const t={},r=e.match(/([a-z\-]+)="([^"]+)"/g);if(r)for(const s of r){const[o,d]=hr(s,"=");t[o]=d.slice(1,d.length-1)}return t}function Ut(e,t,r=[]){let s="";for(;t<e.length&&(ut(e[t])||r.includes(e[t]));)s+=e[t++];return s}function su(e,t,r="$",s=":"){for(const o in t)e=As(e,o,t[o],r,s);return e=Os(e),e}function As(e,t,r,s="$",o=":"){if(r==="")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}`,r);else{const f=Ut(e,d+t.length+2,["_"]);e=e.replace(`${s}${t}${o}${f}`,r)}else e=e.replace(`${s}${t}`,r);d=e.indexOf(`${s}${t}`,d+r.length)}return e}function Os(e,t="$",r=":"){let s=e.indexOf(t);for(;s!==-1;){const o=Ut(e,s+1);if(e[s+o.length+1]===r)if(e[s+o.length+2]===r)e=e.replace(`${t}${o}${r}${r}`,"");else{const d=Ut(e,s+o.length+2);e=e.replace(`${t}${o}${r}${d}`,d)}s=e.indexOf(t,s+1)}return e}function iu(e,t){let r=e.indexOf("](");for(;r!==-1;){const s=ws(e,"[",r),o=e.indexOf(")",r);if(s!==-1&&o!==-1){const[d,f]=e.slice(s+1,o).split("]("),g=t(d,f);e=e.slice(0,s)+g+e.slice(o+1)}r=e.indexOf("](",r+1)}return e}function Is(e,t=!0){const r=Object.entries(e).filter(([s,o])=>o!=null).map(([s,o])=>`${s}=${encodeURIComponent(o)}`).join("&");return r?(t?"?":"")+r:""}function au(e){const t={},r=e.split("&");for(const s of r){const[o,d]=s.split("=");o&&d&&(t[o]=decodeURIComponent(d))}return t}function ou(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function cu(e,t){let r=null,s=-1/0;for(const[o,d]of Object.entries(e)){const f=t(d);f>s&&(s=f,r=o)}return r?[r,e[r]]:null}function uu(e,t,r,s){const o=e.find(f=>f[t]===r),d=e.find(f=>f[t]===r+s);o&&d?(o[t]=r+s,d[t]=r):o&&(o[t]=r+s),e.sort((f,g)=>Ct(f[t])-Ct(g[t])),e.forEach((f,g)=>f[t]=g+1)}function lu(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 du(e,t=":"){return Object.fromEntries(e.map(r=>hr(r,t)).map(r=>r[0]&&r[1]?[ct(r[0]),ct(r[1])]:null).filter(r=>r))}function fu(e,t,r){return Ns(e,t)+Is(r||{})}function hu(e,t=",",r='"'){const s=[];let o="",d=!1;const f=e.split("");for(const g of f)g===t&&!d?(s.push(o),o=""):g===r&&(!o&&!d||d)?d=!d:o+=g;return s.push(o),s}function pu(e){return`[${Math.floor(e.progress*100)}%] ${Pt(e.deltaMs)} out of ${Pt(e.totalTimeMs)} (${Pt(e.remainingTimeMs)} left) [${Math.round(e.baseTimeMs)} ms each]`}async function mu(e,t,r){for(let s=0;s<r;s++){try{if(await e())return!0}catch{}s<r-1&&await l(t)}return!1}function gu(e,t){const r=[];for(let s=e.length-1;s>=0;s--)t(e[s])&&r.push(e.splice(s,1)[0]);return r}function yu(e){return JSON.parse(JSON.stringify(e))}function vu(e){return Math.ceil((e||Date.now())/1e3)}function wu(e){return(e||new Date).toISOString().slice(0,10)}function _u(e){return(e||new Date).toISOString().slice(0,19).replace(/T|:/g,"-")}function bu(e){const t=new Date(e);return new Date(t.getTime()-t.getTimezoneOffset()*6e4)}function xu(e){return new Date(e)}function ee(e){return String(Math.floor(e)).padStart(2,"0")}function ku(e){let[t,r]=e.split(":");me(parseInt(t,10))||(t="0"),me(parseInt(r,10))||(r="0");let s=xr(ur(t),0,23),o=xr(ur(r),0,59);return`${ee(s)}:${ee(o)}`}function Pt(e){const t=Math.floor(e/36e5);e=e%36e5;const r=Math.floor(e/6e4);e=e%6e4;const s=Math.floor(e/1e3);return t?`${ee(t)}:${ee(r)}:${ee(s)}`:`${ee(r)}:${ee(s)}`}function Se(e){return Math.floor((De(e)?e.getTime():e)/864e5)}const Eu={today:(e,t)=>ee(e)+":"+ee(t),yesterday:()=>"Yesterday",monday:()=>"Mon",tuesday:()=>"Tue",wednesday:()=>"Wed",thursday:()=>"Thu",friday:()=>"Fri",saturday:()=>"Sat",sunday:()=>"Sun",weeks:e=>`${e}w`};function Su(e,t){const r=new Date((t==null?void 0:t.now)||Date.now()),s=(t==null?void 0:t.labels)||Eu,o=De(e)?e:new Date(e);if(Se(r)===Se(o))return s.today(o.getUTCHours(),o.getUTCMinutes(),o.getUTCHours()>12);if(Se(r)-Se(o)===1)return s.yesterday();const d=wr(o);return Se(r)-Se(o)<7?s[d.day]():s.weeks(Math.round((r.getTime()-o.getTime())/6048e5))}const $s={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 Ms(e,t){const r=(t==null?void 0:t.now)??Date.now(),s=(t==null?void 0:t.labels)||$s,o=a.Types.isDate(e)?e.getTime():e;let d=(r-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 Tu(e,t=$s){return Ms(0,{now:e*1e3,labels:t})}function Au(e,t,r){const s=((r==null?void 0:r.now)??Date.now())-e,o=Math.floor(s/t),d=t/((r==null?void 0:r.precision)??1)-Math.ceil(s%t/((r==null?void 0:r.precision)??1));return{cycles:o,remaining:d}}const vr={};function Ou(e,t){return!vr[e]||Date.now()>vr[e]?(vr[e]=Date.now()+t,!0):!1}const Iu={s:1e3,m:6e4,h:36e5,d:864e5};function $u(e,t,r){return t=De(t)?t.getTime():t,r=r?De(r)?r.getTime():r:Date.now(),(r-t)/Iu[e]}function Mu(e,t,r,s){s||(s=Date.now());const o=t/r,d=s-e,f=d/t,g=f*r,m=g-d;return{deltaMs:d,progress:o,baseTimeMs:f,totalTimeMs:g,remainingTimeMs:m}}const Cu={0:"sunday",1:"monday",2:"tuesday",3:"wednesday",4:"thursday",5:"friday",6:"saturday"};function Cs(e){return{zeroBasedIndex:e,day:Cu[e]}}function wr(e){return Cs(e.getDay())}function Nu(e){return wr(new Date(e))}function Ru(e){return e*1e3}function ju(e){return e*6e4}function Du(e){return e*36e5}function Uu(e){return e*864e5}const Pu={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 Zu(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const r=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=Pu[r];if(!s)throw Error(`Unknown unit: "${r}"`);return t*s}const Bu={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 Lu(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const r=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=Bu[r];if(!s)throw Error(`Unknown unit: "${r}"`);return t*s}function zu(e){return e.replace(/ +/g," ").replace(/^ /gm,"")}const _r={};async function Fu(e,t,r){const s=Date.now(),o=_r[e];if(o&&o.validUntil>s)return o.value;const d=await r(),f=s+t;return _r[e]={value:d,validUntil:f},d}function Vu(e){delete _r[e]}function Ns(...e){return e.filter(t=>t).join("/").replace(new RegExp("(?<!:)\\/+","g"),"/")}function Wu(e,t,r,s,o=!0){const d=e.indexOf(t),f=e.indexOf(r,d+t.length);if(d===-1||f===-1)throw Error("Start or end not found");return o?e.substring(0,d+t.length)+s+e.substring(f):e.substring(0,d)+s+e.substring(f+r.length)}function Hu(e){let t="p";e.startsWith("#")?(t="h1",e=e.slice(1).trim()):e.startsWith("-")&&(t="li",e=e.slice(1).trim());const r=e[0]===e[0].toUpperCase(),s=/[.?!]$/.test(e),o=/:$/.test(e);return{type:t,isCapitalized:r,hasPunctuation:s,endsWithColon:o}}function qu(e,t="(",r=")"){let s=0,o=0;for(;o<e.length;)if(e.startsWith(t,o)?(s++,o+=t.length):e.startsWith(r,o)?(s--,o+=r.length):o++,s<0)return!1;return t===r?s%2===0:s===0}function Gu(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 Rs(e){const t=Object.keys(e).sort((s,o)=>s.localeCompare(o)),r={};for(const s of t)r[s]=Te(e[s]);return r}function js(e){const t=[];return e.sort((r,s)=>JSON.stringify(Te(r)).localeCompare(JSON.stringify(Te(s)))).forEach(r=>t.push(Te(r))),t}function Te(e){return Array.isArray(e)?js(e):pe(e)?Rs(e):e}function Ds(e,t){return JSON.stringify(Te(e))===JSON.stringify(Te(t))}function Ku(...e){for(let t=1;t<e.length;t++)if(!Ds(e[t-1],e[t]))return!1;return!0}function Yu(e){try{return JSON.parse(e)}catch{return null}}function Qu(){let e=0;return{next:()=>e++}}function Xu(e){let t=0;return{next:()=>e[t++%e.length]}}function Ju(e){let t;return r=>{const s=r===e&&t!==e;return t=r,s}}function el(e,t,r,s,o){const d={};for(const f of Object.keys(t))d[f]=[];d[s]=[],o&&(e=e.sort(o));for(const f of e){const g=f[r],m=t[g]?g:s;d[m].length>=t[m]?d[s].push(f):d[m].push(f)}return d}function tl(e,t){const r=Object.keys(e),s=Object.keys(t);return{uniqueToA:r.filter(o=>!s.includes(o)),uniqueToB:s.filter(o=>!r.includes(o))}}function Us(e){const t=Object.keys(e);return t[Math.floor(Math.random()*t.length)]}function rl(e,t){const r=Us(e);return e[r]=t(e[r]),r}function nl(e){return e=e.replace(/\r\n/g,`
10
- `),e=e.replace(/(\w+)\((.+)\)/g,(t,r,s)=>`${r}(${s.replaceAll(",","&comma;")})`),e=e.replace(/(,)(\s+})/g,"$2"),e=e.replace(/\.\.\..+?,/g,""),e=e.replace(/({\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/(,\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/:(.+)\?(.+):/g,(t,r,s)=>`: (${r.trim()} && ${s.trim()}) ||`),e=e.replace(/([a-zA-Z0-9]+)( ?: ?{)/g,'"$1"$2'),e=e.replace(/([a-zA-Z0-9]+) ?: ?(.+?)(,|\n|})/g,(t,r,s,o)=>`"${r}":"${s.trim()}"${o}`),e=e.replace(/("'|'")/g,'"'),e=e.replaceAll("&comma;",","),JSON.parse(e)}const ge=[1e3,1e6,1e9,1e12,1e15,1e18,1e21,1e24,1e27,1e30,1e9,1e16,1e18,1e18,1e18,1e33],sl=["thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion","gwei","bzz","btc","eth","dai","decillion"],Ps=["K","M","B","T","Qa","Qi","Sx","Sp","O","N","gwei","bzz","eth","btc","dai","D"];function il(e,t,r){let s=e.length-t;if(s<=0)return"0."+"0".repeat(-s)+e+(r?" "+r:"");let o=e.substring(0,s),d=e.substring(s);return o===""&&(o="0"),o+"."+d+(r?" "+r:"")}function al(e,t){const r=(t==null?void 0:t.longForm)??!1,s=t!=null&&t.unit?` ${t.unit}`:"",o=r?sl:Ps,d=(t==null?void 0:t.precision)??1;if(e<ge[0])return`${e}${s}`;for(let f=0;f<ge.length-1;f++)if(e<ge[f+1])return`${(e/ge[f]).toFixed(d)}${r?" ":""}${o[f]}${s}`;return`${(e/ge[ge.length-1]).toFixed(d)}${r?" ":""}${o[ge.length-1]}${s}`}function br(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeNumber got NaN for input");const r=e.replace(/^-?[0-9.]+/,"").trim(),s=Ps.findIndex(o=>o.toLowerCase()===r.toLowerCase());return s===-1?t:t*ge[s]}function xr(e,t,r){return e<t?t:e>r?r:e}function ol(e,t,r){const s=e+t;return s>r?r:s}function cl(e,t,r){const s=e-t;return s<r?r:s}function ul(e,t){return t(e),e}function ll(e,t){e&&t(e)}function dl(e,t){const r=Object.keys(t);for(const s of r)Array.isArray(t[s])&&Array.isArray(e[s])&&Rt(e[s],t[s])}function fl(e){return e.splice(0,e.length),e}function hl(e){for(const t of Object.keys(e))(Qn(e[t])||Array.isArray(e[t])&&e[t].every(r=>r==null))&&delete e[t];return e}function pl(e){for(const t of Object.entries(e))(t[1]===null||t[1]===void 0||V(t[1])&&Mt(t[1]))&&delete e[t[0]];return e}function ml(e,t){const r={};for(const[s,o]of Object.entries(e))t(s)&&(r[s]=o);return r}function gl(e,t){const r={};for(const[s,o]of Object.entries(e))t(o)&&(r[s]=o);return r}function yl(e,t){const r={};for(const s of Object.entries(e))r[s[0]]=t(s[1]);return r}function vl(e,t){const r=[];let s=0;for(const o of e)r.push(t(o,s++));return r}async function wl(e,t){try{return await e()}catch{throw t}}function _l(e,t,r){r!=null&&(e[t]=r)}function bl(e,t,r,s){const o=xe(r,s);o!=null&&ke(e,t,o)}function xl(e){const t={};for(const[r,s]of Object.entries(e))t[s]=r;return t}function kl(e){const t=Object.keys(e),r=t.map(g=>e[g].length),s=r.reduce((g,m)=>g*=m);let o=1;const d=[1];for(let g=0;g<r.length-1;g++)o*=r[g],d.push(o);const f=[];for(let g=0;g<s;g++){const m={};for(let k=0;k<t.length;k++){const M=e[t[k]],U=Math.floor(g/d[k])%M.length;m[t[k]]=M[U]}f.push(m)}return f}function El(e){return Object.values(e).filter(t=>t).length}function Sl(e,t,r){return e+(r?"["+t+"]":(e.length?".":"")+t)}function Zt(e,t,r,s,o){if(!pe(t))return t;for(const[d,f]of Object.entries(t)){const g=Sl(r,d,s);Array.isArray(f)?o?Zt(e,f,g,!0,o):e[g]=f.map(m=>Zt(Array.isArray(m)?[]:{},m,"",!1,o)):pe(f)?Zt(e,f,g,!1,o):e[g]=f}return e}function Tl(e,t=!1,r){return Zt({},e,r||"",!1,t)}function Zs(e){if(!pe(e))return e;const t=Array.isArray(e)?[]:{};for(const[r,s]of Object.entries(e))Array.isArray(s)?ke(t,r,s.map(o=>Zs(o))):ke(t,r,s);return t}function Al(e,t,r){return t[e]?t[e]:r}function Bs(e,t){const r={};for(const s of e){const o=t(s);r[o]=s}return r}function Ol(e,t){const r={};for(const s of e){const o=t(s);r[o]||(r[o]=[]),r[o].push(s)}return r}function Il(e,t){const r=[];for(let s=0;s<e.length;s+=t)r.push(e.slice(s,s+t));return r}function Ls(e,t){const r=Math.ceil(e.length/t),s=[];for(let o=0;o<e.length;o+=r)s.push(e.slice(o,o+r));return s}function zs(e,t){const r=[],s=Math.ceil(e.length/t);for(let o=0;o<s;o++)r.push(e.slice(o*t,o*t+t));return r}function $l(e,t){const r=Math.ceil(e.length/t);return zs(e,r)}function Ml(e,t){return Object.values(Bs(e,t))}function Cl(e,t,r,s,o){const d=t?e.map(t):e,f={};for(const m of d)f[m]=(f[m]||0)+1;const g=s?Fs(f,o?(m,k)=>m[1]-k[1]:(m,k)=>k[1]-m[1]):f;return r?Object.keys(g):g}function Fs(e,t){return Object.fromEntries(Object.entries(e).sort(t))}function Nl(e){const t=[],r=Object.keys(e),s=e[r[0]].length;for(let o=0;o<s;o++){const d={};for(const f of r)d[f]=e[f][o];t.push(d)}return t}function Rl(e,t,r=1){for(const s of e)s[t]+=r}function jl(e,t,r){for(const s of e)s[t]=r}function kr(e,t){const r=[];let s=[];return e.forEach((o,d)=>{(d===0||!t(o,e[d-1]))&&(s=[],r.push(s)),s.push(o)}),r}function Dl(){return{map:new Map,keys:[]}}function Ul(){return{map:new Map,keys:[]}}function Vs(e,t,r,s=100){if(e.map.has(t)){const o=e.keys.indexOf(t);e.keys.splice(o,1)}if(e.map.set(t,r),e.keys.push(t),e.keys.length>s){const o=e.keys.shift();o&&e.map.delete(o)}}function Pl(e,t,r,s=100){if(e.map.has(t)){const o=e.keys.indexOf(t);e.keys.splice(o,1)}if(e.map.set(t,r),e.keys.unshift(t),e.keys.length>s){const o=e.keys.shift();o&&e.map.delete(o)}}function Zl(e,t,r,s,o=100){Vs(e,t,{validUntil:Date.now()+s,data:r},o)}function Bl(e,t){const r=e.map.get(t);return r&&r.validUntil>Date.now()?r.data:null}class ye{constructor(t){this.value=t}static of(t){return new ye(t)}static empty(){return new ye(null)}map(t){return new ye(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(r=>ye.of(r)):Promise.resolve(ye.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=ye;class Ll{constructor(t){this.supplier=t,this.value=null}get(){return this.value||(this.value=this.supplier()),this.value}}a.Lazy=Ll;class zl{constructor(t){this.supplier=t,this.value=null}async get(){return this.value||(this.value=await this.supplier()),this.value}}a.AsyncLazy=zl;function Fl(e){return()=>e.forEach(t=>t())}function Vl(e,t){return e.reduce((r,s)=>t(r)>t(s)?r:s)}function Wl(e,t){const r=e.find(s=>s instanceof t);return ye.of(r)}function Hl(e,t){return e.filter(r=>r instanceof t)}function ql(e,t){const r=[],s=Math.max(e.length,t.length);for(let o=0;o<s;o++)e[o]&&r.push(e[o]),t[o]&&r.push(t[o]);return r}function Gl(e,t){return e.includes(t)?e.filter(r=>r!==t):[...e,t]}class Kl{constructor(t){this.value=t,this.children=[]}}function Yl(e,t,r,s,o=!1){const d=new Map,f=[];e.forEach(m=>{const k=new Kl(m);d.set(m[t],k)}),e.forEach(m=>{const k=d.get(m[t]);if(!k)return;const M=m[r];if(M){const U=d.get(M);U&&U.children.push(k)}else f.push(k)});const g=m=>{m.children.sort((k,M)=>{const U=k.value[s],Le=M.value[s];return o?Le-U:U-Le}),m.children.forEach(g)};return f.forEach(g),f}function Ws(e,t){if(Math.log2(e.length)%1!==0)throw new Error("Array length must be a power of 2");let r=[...e];for(;r.length>1;){const s=[];for(let o=0;o<r.length;o+=2){const d=r[o+1];s.push(t(r[o],d))}r=s}return r[0]}function Pe(...e){const t=e.reduce((o,d)=>o+d.length,0),r=new Uint8Array(t);let s=0;return e.forEach(o=>{r.set(o,s),s+=o.length}),r}function Hs(e){return e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}function qs(e){return e[0]===255&&e[1]===216}function Gs(e){return e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function Ql(e){return Hs(e)||qs(e)||Gs(e)}function Xl(e){return new Uint8Array([e])}function Jl(e){return e[0]}function ed(e,t){const r=new ArrayBuffer(2);return new DataView(r).setUint16(0,e,t==="LE"),new Uint8Array(r)}function td(e,t){return new DataView(e.buffer).getUint16(e.byteOffset,t==="LE")}function rd(e,t){const r=new ArrayBuffer(4);return new DataView(r).setUint32(0,e,t==="LE"),new Uint8Array(r)}function nd(e,t){return new DataView(e.buffer).getUint32(e.byteOffset,t==="LE")}function Er(e,t){const r=new ArrayBuffer(8);return new DataView(r).setBigUint64(0,BigInt(e),t==="LE"),new Uint8Array(r)}function sd(e,t){return new DataView(e.buffer).getBigUint64(e.byteOffset,t==="LE")}function Ze(e,t){const r=new Uint8Array(32);let s=e;if(t==="LE"){for(let o=0;o<32;o++)r[o]=Number(s&0xffn),s>>=8n;return r}for(let o=31;o>=0;o--)r[o]=Number(s&0xffn),s>>=8n;return r}function Be(e,t){let r=0n;if(t==="LE"){for(let s=31;s>=0;s--)r=r<<8n|BigInt(e[s]);return r}for(let s=0;s<32;s++)r=r<<8n|BigInt(e[s]);return r}function id(e,t){const r=[];let s=0;for(const o of t)r.push(e.subarray(s,s+o)),s+=o;return r}function Sr(e,t){const r=[];for(let s=0;s<e.length;s+=t)r.push(e.subarray(s,s+t));return r}const Ks=[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 ad(e){for(let t=0;t<24;t++){const r=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],f=e[4]^e[14]^e[24]^e[34]^e[44],g=e[5]^e[15]^e[25]^e[35]^e[45],m=e[6]^e[16]^e[26]^e[36]^e[46],k=e[7]^e[17]^e[27]^e[37]^e[47],M=e[8]^e[18]^e[28]^e[38]^e[48],U=e[9]^e[19]^e[29]^e[39]^e[49],Le=o<<1|d>>>31,zd=d<<1|o>>>31,ft=M^Le,ht=U^zd,Fd=f<<1|g>>>31,Vd=g<<1|f>>>31,pt=r^Fd,mt=s^Vd,Wd=m<<1|k>>>31,Hd=k<<1|m>>>31,gt=o^Wd,yt=d^Hd,qd=M<<1|U>>>31,Gd=U<<1|M>>>31,vt=f^qd,wt=g^Gd,Kd=r<<1|s>>>31,Yd=s<<1|r>>>31,_t=m^Kd,bt=k^Yd;e[0]^=ft,e[1]^=ht,e[2]^=pt,e[3]^=mt,e[4]^=gt,e[5]^=yt,e[6]^=vt,e[7]^=wt,e[8]^=_t,e[9]^=bt,e[10]^=ft,e[11]^=ht,e[12]^=pt,e[13]^=mt,e[14]^=gt,e[15]^=yt,e[16]^=vt,e[17]^=wt,e[18]^=_t,e[19]^=bt,e[20]^=ft,e[21]^=ht,e[22]^=pt,e[23]^=mt,e[24]^=gt,e[25]^=yt,e[26]^=vt,e[27]^=wt,e[28]^=_t,e[29]^=bt,e[30]^=ft,e[31]^=ht,e[32]^=pt,e[33]^=mt,e[34]^=gt,e[35]^=yt,e[36]^=vt,e[37]^=wt,e[38]^=_t,e[39]^=bt,e[40]^=ft,e[41]^=ht,e[42]^=pt,e[43]^=mt,e[44]^=gt,e[45]^=yt,e[46]^=vt,e[47]^=wt,e[48]^=_t,e[49]^=bt;const Mr=e[0],Cr=e[1],Nr=e[2]<<1|e[3]>>>31,Rr=e[3]<<1|e[2]>>>31,jr=e[5]<<30|e[4]>>>2,Dr=e[4]<<30|e[5]>>>2,Ur=e[6]<<28|e[7]>>>4,Pr=e[7]<<28|e[6]>>>4,Zr=e[8]<<27|e[9]>>>5,Br=e[9]<<27|e[8]>>>5,Lr=e[11]<<4|e[10]>>>28,zr=e[10]<<4|e[11]>>>28,Fr=e[13]<<12|e[12]>>>20,Vr=e[12]<<12|e[13]>>>20,Wr=e[14]<<6|e[15]>>>26,Hr=e[15]<<6|e[14]>>>26,qr=e[17]<<23|e[16]>>>9,Gr=e[16]<<23|e[17]>>>9,Kr=e[18]<<20|e[19]>>>12,Yr=e[19]<<20|e[18]>>>12,Qr=e[20]<<3|e[21]>>>29,Xr=e[21]<<3|e[20]>>>29,Jr=e[22]<<10|e[23]>>>22,en=e[23]<<10|e[22]>>>22,tn=e[25]<<11|e[24]>>>21,rn=e[24]<<11|e[25]>>>21,nn=e[26]<<25|e[27]>>>7,sn=e[27]<<25|e[26]>>>7,an=e[29]<<7|e[28]>>>25,on=e[28]<<7|e[29]>>>25,cn=e[31]<<9|e[30]>>>23,un=e[30]<<9|e[31]>>>23,ln=e[33]<<13|e[32]>>>19,dn=e[32]<<13|e[33]>>>19,fn=e[34]<<15|e[35]>>>17,hn=e[35]<<15|e[34]>>>17,pn=e[36]<<21|e[37]>>>11,mn=e[37]<<21|e[36]>>>11,gn=e[38]<<8|e[39]>>>24,yn=e[39]<<8|e[38]>>>24,vn=e[40]<<18|e[41]>>>14,wn=e[41]<<18|e[40]>>>14,_n=e[42]<<2|e[43]>>>30,bn=e[43]<<2|e[42]>>>30,xn=e[45]<<29|e[44]>>>3,kn=e[44]<<29|e[45]>>>3,En=e[47]<<24|e[46]>>>8,Sn=e[46]<<24|e[47]>>>8,Tn=e[48]<<14|e[49]>>>18,An=e[49]<<14|e[48]>>>18;e[0]=Mr^~Fr&tn,e[1]=Cr^~Vr&rn,e[2]=Fr^~tn&pn,e[3]=Vr^~rn&mn,e[4]=tn^~pn&Tn,e[5]=rn^~mn&An,e[6]=pn^~Tn&Mr,e[7]=mn^~An&Cr,e[8]=Tn^~Mr&Fr,e[9]=An^~Cr&Vr,e[10]=Ur^~Kr&Qr,e[11]=Pr^~Yr&Xr,e[12]=Kr^~Qr&ln,e[13]=Yr^~Xr&dn,e[14]=Qr^~ln&xn,e[15]=Xr^~dn&kn,e[16]=ln^~xn&Ur,e[17]=dn^~kn&Pr,e[18]=xn^~Ur&Kr,e[19]=kn^~Pr&Yr,e[20]=Nr^~Wr&nn,e[21]=Rr^~Hr&sn,e[22]=Wr^~nn&gn,e[23]=Hr^~sn&yn,e[24]=nn^~gn&vn,e[25]=sn^~yn&wn,e[26]=gn^~vn&Nr,e[27]=yn^~wn&Rr,e[28]=vn^~Nr&Wr,e[29]=wn^~Rr&Hr,e[30]=Zr^~Lr&Jr,e[31]=Br^~zr&en,e[32]=Lr^~Jr&fn,e[33]=zr^~en&hn,e[34]=Jr^~fn&En,e[35]=en^~hn&Sn,e[36]=fn^~En&Zr,e[37]=hn^~Sn&Br,e[38]=En^~Zr&Lr,e[39]=Sn^~Br&zr,e[40]=jr^~qr&an,e[41]=Dr^~Gr&on,e[42]=qr^~an&cn,e[43]=Gr^~on&un,e[44]=an^~cn&_n,e[45]=on^~un&bn,e[46]=cn^~_n&jr,e[47]=un^~bn&Dr,e[48]=_n^~jr&qr,e[49]=bn^~Dr&Gr,e[0]^=Ks[t*2],e[1]^=Ks[t*2+1]}}function Ys(e){const t=[];for(let r=0;r<e.length;r+=4)t.push(e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24);return t}function Qs(e,t){if(!e.length){const o=new Uint8Array(136);return o[0]=t,o[135]=128,[Ys(o)]}const r=Sr(e,136),s=r[r.length-1];if(s.length<136){const o=new Uint8Array(136);o.set(s),o[s.length]=t,o[135]|=128,r[r.length-1]=o}if(s.length===136){const o=new Uint8Array(136);o[0]=t,o[135]=128,r.push(o)}return r.map(Ys)}function Xs(e,t){for(const r of t){for(let s=0;s<34;s+=2)e[s]^=r[s+1],e[s+1]^=r[s];ad(e)}return e}function Js(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 ce(e){return Js(Xs(new Array(50).fill(0),Qs(e,1)))}function od(e){return Js(Xs(new Array(50).fill(0),Qs(e,6)))}function cd(e,t,r){const s=Math.min(e.length,t.length,r/8+1);for(let o=0;o<s;o++){const d=e[o]^t[o];for(let f=0;f<8;f++)if(d>>7-f&1)return o*8+f}return r}function ud(e,t){const r=Math.min(e.length,t.length);for(let s=0;s<r;s++)if(e[s]!==t[s])return e.subarray(0,s);return e.subarray(0,r)}function ld(e,t,r,s){const o=Math.floor(t/8),d=t%8;r===1?e[o]|=1<<(s==="BE"?7-d:d):e[o]&=~(1<<(s==="BE"?7-d:d))}function dd(e,t,r){const s=Math.floor(t/8),o=t%8;return e[s]>>(r==="BE"?7-o:o)&1}function fd(e,t,r=0){for(let s=r;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 ei(e,t,r=0){if(e.length>=t)return e;const s=new Uint8Array(t);return s.fill(r),s.set(e,t-e.length),s}function hd(e,t,r=0){const s=e.length%t;return s===0?e:ei(e,e.length+t-s,r)}function ti(e,t,r=0){if(e.length>=t)return e;const s=new Uint8Array(t);return s.fill(r),s.set(e,0),s}function pd(e,t,r=0){const s=e.length%t;return s===0?e:ti(e,e.length+t-s,r)}function md(e,t){const r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e[s]^t[s%t.length];return r}function gd(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function C(e,t){return(e%t+t)%t}function lt(e,t){e=C(e,t);let[r,s]=[0n,1n],[o,d]=[t,e];for(;d!==0n;){const f=o/d;[r,s]=[s,r-f*s],[o,d]=[d,o-f*d]}if(o>1n)throw new Error("a is not invertible");return r<0n&&(r+=t),r}function yd(e,t,r){let s=1n;for(e=C(e,r);t>0;)t%2n===1n&&(s=C(s*e,r)),e=C(e*e,r),t=t/2n;return s}function ri(e,t){return C(e,t)===0n?0n:t%4n===3n?yd(e,(t+1n)/4n,t):null}const L=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,D=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Bt=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Lt=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;function Tr(e,t,r){if(t===0n)return[0n,0n];const s=C(3n*e*e*lt(2n*t,r),r),o=C(s*s-2n*e,r),d=C(s*(e-o)-t,r);return[o,d]}function zt(e,t,r,s,o){if(e===0n&&t===0n)return[r,s];if(r===0n&&s===0n)return[e,t];if(e===r&&t===C(-s,o))return[0n,0n];if(e===r&&t===s)return Tr(e,t,o);const d=C((s-t)*lt(r-e,o),o),f=C(d*d-e-r,o),g=C(d*(e-f)-t,o);return[f,g]}function vd(e){if(e<=0n||e>=D)throw new Error("Invalid private key");return Ae(Bt,Lt,e,L)}function wd(e){const t=e[1]%2n===0n?2:3;return new Uint8Array([t,...Ze(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=Be(e.slice(1),"BE"),r=ri(C(t**3n+7n,L),L);if(!r)throw Error("Invalid x: does not correspond to a valid curve point");const s=C(-r,L),o=r%2n===0n;return[t,e[0]===2?o?r:s:o?s:r]}function bd(e){const t=new Uint8Array(20),r=ce(Pe(Ze(e[0],"BE"),Ze(e[1],"BE")));return t.set(r.subarray(12)),t}function xd(e){const t=a.Binary.uint8ArrayToHex(e),r=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(r[o],16)>7?s+=t[o].toUpperCase():s+=t[o];return s}function Ae(e,t,r,s){let o=[0n,0n],d=[e,t];const f=r.toString(2);for(const g of f)g==="0"?(d=zt(o[0],o[1],d[0],d[1],s),o=Tr(o[0],o[1],s)):(o=zt(o[0],o[1],d[0],d[1],s),d=Tr(d[0],d[1],s));return o}function kd(e,t,r){return ni(Be(ce(e),"BE"),t,r)}function ni(e,t,r){if(t<=0n||t>=D)throw new Error("Invalid private key");if(r||(r=C(Be(ce(Pe(ce(Ze(t,"BE")),Ze(e,"BE"))),"BE"),D)),r<=0n||r>=D)throw new Error("Invalid nonce");const s=C(e,D),o=Ae(Bt,Lt,r,L),d=C(o[0],D);let f=C((s+C(d,D)*t)*lt(r,D),D);if(d===0n||f===0n)throw new Error("Invalid r or s value");let g=o[1]%2n===0n?27n:28n;return f>D/2n&&(f=D-f,g=g===27n?28n:27n),[d,f,g]}function Ed(e,t,r,s){const o=ri(C(t**3n+7n,L),L);if(!o)throw new Error("Invalid r: does not correspond to a valid curve point");const d=s===27n?0n:1n,f=o%2n===d?o:L-o,g=C(Be(ce(e),"BE"),D),m=Ae(t,f,r,L),k=Ae(Bt,Lt,g,L),M=zt(m[0],m[1],k[0],C(-k[1],L),L);return Ae(M[0],M[1],lt(t,D),L)}function Sd(e,t,r,s){const o=C(Be(ce(e),"BE"),D),d=lt(s,D),f=C(o*d,D),g=C(r*d,D),m=Ae(Bt,Lt,f,L),k=Ae(t[0],t[1],g,L),M=zt(m[0],m[1],k[0],k[1],L);return r===C(M[0],D)}class si{constructor(t){this.cursor=0,this.buffer=t}read(t){const r=this.buffer.subarray(this.cursor,this.cursor+t);return this.cursor+=t,r}max(){return this.buffer.length-this.cursor}}a.Uint8ArrayReader=si;class ii{constructor(t){this.buffer=t,this.cursor=0}write(t){const r=Math.min(this.max(),t.max());return this.buffer.set(t.read(r),this.cursor),this.cursor+=r,r}max(){return this.buffer.length-this.cursor}}a.Uint8ArrayWriter=ii;class Ft{constructor(t,r=0n){this.span=r,this.writer=new ii(new Uint8Array(t))}build(){return Pe(Er(this.span,"LE"),this.writer.buffer)}hash(){const t=Ws(Sr(this.writer.buffer,32),(r,s)=>ce(Pe(r,s)));return ce(Pe(Er(this.span,"LE"),t))}}a.Chunk=Ft;class Ar{constructor(t,r=4096){this.counters=[1],this.capacity=r,this.chunks=[new Ft(r)],this.onChunk=t}static async root(t,r=4096){const s=new n(n.NOOP,r);return await s.append(t),s.finalize()}async append(t,r=0,s=0n){const o=new si(t);for(;o.max()>0;){this.chunks[r].writer.max()===0&&await this.elevate(r);const d=this.chunks[r].writer.write(o);s?this.chunks[r].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 Ft(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 Ft(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=Ar,n=Ar,Ar.NOOP=async e=>{};class te{constructor(t,r){if(r<0)throw Error("Scale must be non-negative");this.value=BigInt(t),this.scale=r}static fromDecimalString(t,r){let[s,o]=t.split(".");return o=(o||"").padEnd(r,"0").slice(0,r),new te(BigInt(s+o),r)}add(t){return this.assertSameScale(t),new te(this.value+t.value,this.scale)}subtract(t){return this.assertSameScale(t),new te(this.value-t.value,this.scale)}multiply(t){return new te(this.value*t,this.scale)}divmod(t){if(t===0n)throw new Error("Division by zero is not allowed");const r=this.value/t,s=this.value%t;return[new te(r,this.scale),new te(s,this.scale)]}exchange(t,r,s){if(t==="*"){const d=this.value*r.value/10n**BigInt(this.scale);return new te(d,s)}this.assertSameScale(r);const o=this.value*10n**BigInt(s)/r.value;return new te(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(),r=t.slice(0,-this.scale)||"0",s=t.slice(-this.scale).padStart(this.scale,"0");return`${r}.${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=te;function Td(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 Vt(e,t,r,s){const o=e.findIndex(g=>g===`--${t}`||g.startsWith(`--${t}=`)),d=e[o];if(!d)return(r||{})[s||t||""]||null;if(d.includes("="))return d.split("=")[1];const f=e[o+1];return f&&!f.startsWith("-")?f:(r||{})[s||t||""]||null}function Ad(e,t,r,s){const o=Vt(e,t,r,s);if(!o)return null;try{return br(o)}catch{throw new Error(`Invalid number argument ${t}: ${o}`)}}function Od(e,t,r,s){const o=e.some(m=>m.endsWith("-"+t)),d=Vt(e,t,r,s);if(!d&&o)return!0;if(!d&&!o)return null;const f=["true","1","yes","y","on"],g=["false","0","no","n","off"];if(f.includes(d.toLowerCase()))return!0;if(g.includes(d.toLowerCase()))return!1;throw Error(`Invalid boolean argument ${t}: ${d}`)}function ai(e,t,r,s){const o=Vt(e,t,r,s);if(!o)throw new Error(`Missing argument ${t}`);return o}function Id(e,t,r,s){const o=ai(e,t,r,s);try{return br(o)}catch{throw new Error(`Invalid argument ${t}: ${o}`)}}function oi(e,t){const r=e[t];e.splice(t,1),e.unshift(r)}function $d(e,t){const r=[...e];return oi(r,t),r}function ci(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Md(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Or(e,t){return{x:e.x*t,y:e.y*t}}function Cd(e){const t=Math.sqrt(e.x*e.x+e.y*e.y);return{x:e.x/t,y:e.y/t}}function ui(e,t,r){return{x:e.x+Math.cos(t)*r,y:e.y+Math.sin(t)*r}}function li(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function dt(e,t,r="row-first"){const s=[];if(r==="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 Nd(e,t,r){var s,o;return((s=e[t+1])==null?void 0:s[r])&&((o=e[t-1])==null?void 0:o[r])&&!e[t][r-1]&&!e[t][r+1]}function Rd(e,t,r){var s,o;return e[t][r+1]&&e[t][r-1]&&!((s=e[t-1])!=null&&s[r])&&!((o=e[t+1])!=null&&o[r])}function di(e,t,r){var s;return!((s=e[t-1])!=null&&s[r])}function fi(e,t,r){var s;return!((s=e[t+1])!=null&&s[r])}function hi(e,t,r){return!e[t][r-1]}function pi(e,t,r){return!e[t][r+1]}function jd(e,t,r){var o,d,f,g,m,k,M,U;const s=[];return e[t][r]?Nd(e,t,r)||Rd(e,t,r)?[]:(!((o=e[t-1])!=null&&o[r-1])&&di(e,t,r)&&hi(e,t,r)&&s.push({x:t,y:r}),!((d=e[t+1])!=null&&d[r-1])&&fi(e,t,r)&&hi(e,t,r)&&s.push({x:t+1,y:r}),!((f=e[t-1])!=null&&f[r+1])&&di(e,t,r)&&pi(e,t,r)&&s.push({x:t,y:r+1}),!((g=e[t+1])!=null&&g[r+1])&&fi(e,t,r)&&pi(e,t,r)&&s.push({x:t+1,y:r+1}),s):((m=e[t-1])!=null&&m[r]&&e[t][r-1]&&s.push({x:t,y:r}),(k=e[t+1])!=null&&k[r]&&e[t][r-1]&&s.push({x:t+1,y:r}),(M=e[t-1])!=null&&M[r]&&e[t][r+1]&&s.push({x:t,y:r+1}),(U=e[t+1])!=null&&U[r]&&e[t][r+1]&&s.push({x:t+1,y:r+1}),s)}function Dd(e,t,r,s){const o=[{x:0,y:0},{x:r,y:0},{x:0,y:s},{x:r,y:s}];for(let d=0;d<e.length;d++)for(let f=0;f<e[0].length;f++){const g=jd(e,d,f);for(const m of g)o.some(k=>k.x===m.x&&k.y===m.y)||o.push(m)}return o.map(d=>({x:d.x*t,y:d.y*t}))}function Ud(e,t){const r=dt(e,(m,k)=>e[m][k]===0&&e[m][k+1]!==0,"row-first").map(m=>({...m,dx:1,dy:0})),s=dt(e,(m,k)=>e[m][k]===0&&e[m][k-1]!==0,"row-first").map(m=>({...m,dx:1,dy:0})),o=dt(e,(m,k)=>{var M;return e[m][k]===0&&((M=e[m-1])==null?void 0:M[k])!==0},"column-first").map(m=>({...m,dx:0,dy:1})),d=dt(e,(m,k)=>{var M;return e[m][k]===0&&((M=e[m+1])==null?void 0:M[k])!==0},"column-first").map(m=>({...m,dx:0,dy:1}));r.forEach(m=>m.y++),d.forEach(m=>m.x++);const f=kr([...o,...d],(m,k)=>m.x===k.x&&m.y-1===k.y),g=kr([...s,...r],(m,k)=>m.y===k.y&&m.x-1===k.x);return[...f,...g].map(m=>({start:m[0],end:at(m)})).map(m=>({start:Or(m.start,t),end:Or(ci(m.end,{x:m.start.dx,y:m.start.dy}),t)}))}function Pd(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}function Zd(e,t){return t.map(r=>Pd(e,r)).sort((r,s)=>r-s)}function mi(e,t,r,s){const o=(s.y-r.y)*(t.x-e.x)-(s.x-r.x)*(t.y-e.y);if(o===0)return null;let d=e.y-r.y,f=e.x-r.x;const g=(s.x-r.x)*d-(s.y-r.y)*f,m=(t.x-e.x)*d-(t.y-e.y)*f;return d=g/o,f=m/o,d>0&&d<1&&f>0&&f<1?{x:e.x+d*(t.x-e.x),y:e.y+d*(t.y-e.y)}:null}function Ir(e,t,r){const s=[],o=ui(e,r,1e4);for(const d of t){const f=mi(e,o,d.start,d.end);f&&s.push(f)}return s.length?s.reduce((d,f)=>{const g=li(e,f),m=li(e,d);return g<m?f:d}):null}function Bd(e,t,r){const s=Zd(e,r),o=[];for(const d of s){const f=Ir(e,t,d-.001),g=Ir(e,t,d+.001);f&&o.push(f),g&&o.push(g)}return o}class $r{constructor(){this.subscribers=[]}subscribe(t){return this.subscribers.push(t),()=>{this.subscribers=this.subscribers.filter(r=>r!==t)}}publish(t){this.subscribers.forEach(r=>r(t))}clear(){this.subscribers=[]}getSubscriberCount(){return this.subscribers.length}}a.PubSubChannel=$r;class Ld{constructor(t,r){this.queue=[],this.running=0,this.onProcessed=new $r,this.onDrained=new $r,this.concurrency=t,this.capacity=r}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(r=>{this.onProcessed.subscribe(()=>{this.queue.length<this.capacity&&(this.queue.push(t),this.process(),this.onProcessed.clear(),r())})})}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=Ld,a.Binary={hexToUint8Array:Hc,uint8ArrayToHex:qc,base64ToUint8Array:zc,uint8ArrayToBase64:Fc,base32ToUint8Array:Vc,uint8ArrayToBase32:Wc,log2Reduce:Ws,partition:Sr,concatBytes:Pe,numberToUint8:Xl,uint8ToNumber:Jl,numberToUint16:ed,uint16ToNumber:td,numberToUint32:rd,uint32ToNumber:nd,numberToUint64:Er,uint64ToNumber:sd,numberToUint256:Ze,uint256ToNumber:Be,sliceBytes:id,keccak256:ce,sha3_256:od,proximity:cd,commonPrefix:ud,setBit:ld,getBit:dd,indexOf:fd,equals:gd,padStart:ei,padStartToMultiple:hd,padEnd:ti,padEndToMultiple:pd,xorCypher:md},a.Elliptic={privateKeyToPublicKey:vd,compressPublicKey:wd,publicKeyFromCompressed:_d,publicKeyToAddress:bd,signMessage:kd,signHash:ni,verifySignature:Sd,recoverPublicKey:Ed,checksumEncode:xd},a.Random={intBetween:it,floatBetween:Gn,chance:Kn,signed:Za,makeSeededRng:rr,point:La,procs:za},a.Arrays={countUnique:Cl,makeUnique:Ml,splitBySize:Il,splitByCount:Ls,index:Bs,indexCollection:Ol,onlyOrThrow:p,onlyOrNull:w,firstOrThrow:E,firstOrNull:v,shuffle:h,initialize:j,initialize2D:oe,rotate2D:ae,containsShape:st,glue:Qo,pluck:tr,pick:nr,pickMany:Fa,pickManyUnique:Va,pickWeighted:qa,pickRandomIndices:Re,pickGuaranteed:Wa,last:at,pipe:Yn,makePipe:Ha,sortWeighted:Ga,pushAll:Rt,unshiftAll:Ko,filterAndRemove:gu,merge:dl,empty:fl,pushToBucket:Ho,unshiftAndLimit:qo,atRolling:Go,group:kr,createOscillator:Xu,organiseWithLimits:el,tickPlaybook:Td,getArgument:Vt,getBooleanArgument:Od,getNumberArgument:Ad,requireStringArgument:ai,requireNumberArgument:Id,bringToFront:$d,bringToFrontInPlace:oi,findInstance:Wl,filterInstances:Hl,interleave:ql,toggle:Gl,createHierarchy:Yl,multicall:Fl,maxBy:Vl},a.System={sleepMillis:l,forever:eo,scheduleMany:sc,waitFor:mu,expandError:zo,runAndSetInterval:to},a.Numbers={make:br,sum:ac,average:oc,median:cc,getDistanceFromMidpoint:uc,clamp:xr,range:us,interpolate:ic,createSequence:Qu,increment:ol,decrement:cl,format:al,fromDecimals:il,makeStorage:Lu,asMegabytes:ro,convertBytes:no,hexToRgb:so,rgbToHex:io,haversineDistanceToMeters:ao,roundToNearest:$t,formatDistance:oo,triangularNumber:co,searchFloat:uo},a.Promises={raceFulfilled:c,invert:i,runInParallelBatches:u},a.Dates={getTimestamp:Su,getTimeDelta:Ms,secondsToHumanTime:Tu,countCycles:Au,isoDate:wu,throttle:Ou,timeSince:$u,dateTimeSlug:_u,unixTimestamp:vu,fromUtcString:bu,fromMillis:xu,getProgress:Mu,humanizeTime:Pt,humanizeProgress:pu,createTimeDigits:ee,mapDayNumber:Cs,getDayInfoFromDate:wr,getDayInfoFromDateTimeString:Nu,seconds:Ru,minutes:ju,hours:Du,days:Uu,make:Zu,normalizeTime:ku,absoluteDays:Se},a.Objects={safeParse:Yu,deleteDeep:Qa,getDeep:xe,setDeep:ke,incrementDeep:Ka,ensureDeep:Ya,replaceDeep:Xa,getFirstDeep:Ja,deepMergeInPlace:Ee,deepMerge2:Fo,deepMerge3:Vo,mapAllAsync:Yo,cloneWithJson:yu,sortObject:Rs,sortArray:js,sortAny:Te,deepEquals:Ds,deepEqualsEvery:Ku,runOn:ul,ifPresent:ll,zip:cs,zipSum:Wo,removeEmptyArrays:hl,removeEmptyValues:pl,flatten:Tl,unflatten:Zs,match:Al,sort:Fs,map:yl,mapIterable:vl,filterKeys:ml,filterValues:gl,rethrow:wl,setSomeOnObject:_l,setSomeDeep:bl,flip:xl,getAllPermutations:kl,countTruthyValues:El,transformToArray:Nl,setMulti:jl,incrementMulti:Rl,createBidirectionalMap:Dl,createTemporalBidirectionalMap:Ul,pushToBidirectionalMap:Vs,unshiftToBidirectionalMap:Pl,addToTemporalBidirectionalMap:Zl,getFromTemporalBidirectionalMap:Bl,createStatefulToggle:Ju,diffKeys:tl,pickRandomKey:Us,mapRandomKey:rl,fromObjectString:nl,toQueryString:Is,parseQueryString:au,hasKey:ou,selectMax:cu,reposition:uu,unwrapSingleKey:lu,parseKeyValues:du},a.Types={isFunction:ir,isObject:pe,isStrictlyObject:je,isEmptyArray:Qn,isEmptyObject:lo,isUndefined:sr,isString:V,isNumber:me,isBoolean:Xn,isDate:De,isBlank:Mt,isId:ar,isIntegerString:Jn,isHexString:es,isUrl:as,isNullable:Po,asString:ss,asHexString:Eo,asSafeString:So,asIntegerString:ko,asNumber:Ct,asFunction:To,asInteger:ur,asBoolean:Ao,asDate:Oo,asNullableString:Io,asEmptiableString:$o,asId:Mo,asTime:Co,asArray:No,asObject:Nt,asNullableObject:Ro,asStringMap:jo,asNumericDictionary:Do,asUrl:Uo,asNullable:Zo,asOptional:Bo,enforceObjectShape:os,enforceArrayShape:Lo,isPng:Hs,isJpg:qs,isWebp:Gs,isImage:Ql},a.Strings={tokenizeByCount:$l,tokenizeByLength:zs,searchHex:_o,searchSubstring:bo,randomHex:xo,randomLetter:go,randomAlphanumeric:yo,randomRichAscii:vo,randomUnicode:wo,includesAny:lc,slugify:lr,normalForm:fc,enumify:vc,escapeHtml:_c,decodeHtmlEntities:xc,after:dr,afterLast:ds,before:ls,beforeLast:fr,betweenWide:kc,betweenNarrow:Ec,getPreLine:zu,containsWord:yr,containsWords:ru,joinUrl:Ns,getFuzzyMatchScore:jt,sortByFuzzyScore:wc,splitOnce:hr,splitAll:fs,randomize:Oc,expand:hs,shrinkTrim:ct,capitalize:Dt,decapitalize:ps,csvEscape:Rc,parseCsv:hu,surroundInOut:yc,getExtension:pr,getBasename:mr,normalizeEmail:Sc,normalizeFilename:Tc,parseFilename:Ac,camelToTitle:hc,slugToTitle:pc,slugToCamel:mc,joinHumanly:gc,findWeightedPair:_s,extractBlock:bs,extractAllBlocks:Uc,replaceBlocks:Pc,indexOfEarliest:Ue,lastIndexOfBefore:ws,parseHtmlAttributes:nu,readNextWord:Ut,resolveVariables:su,resolveVariableWithDefaultSyntax:As,resolveRemainingVariablesWithDefaults:Os,isLetter:ms,isDigit:gs,isLetterOrDigit:ut,isValidObjectPathCharacter:Mc,insert:Cc,indexOfRegex:ys,lineMatches:vs,linesMatchInOrder:Nc,represent:ot,resolveMarkdownLinks:iu,buildUrl:fu,isChinese:dc,replaceBetweenStrings:Wu,describeMarkdown:Hu,isBalanced:qu,textToFormat:Gu,splitFormatting:Zc,splitHashtags:Bc,splitUrls:Lc,route:Gc,explodeReplace:gr,generateVariants:Kc,replaceWord:Yc,replacePascalCaseWords:Qc,stripHtml:Xc,breakLine:Ts,measureTextWidth:Jc,toLines:eu,levenshteinDistance:tu},a.Assertions={asEqual:Xo,asTrue:Jo,asTruthy:ec,asFalse:tc,asFalsy:rc,asEither:nc},a.Cache={get:Fu,invalidate:Vu},a.Vector={addPoint:ci,subtractPoint:Md,multiplyPoint:Or,normalizePoint:Cd,pushPoint:ui,filterCoordinates:dt,findCorners:Dd,findLines:Ud,raycast:Ir,raycastCircle:Bd,getLineIntersectionPoint:mi}})(In);const N=_i(In);N.Arrays,N.Assertions;const Z=N.Binary;N.Cache,N.Dates,N.Elliptic,N.Numbers,N.Objects,N.Pagination,N.Promises,N.Random,N.Strings,N.System,N.Types,N.Optional,N.Vector,N.PubSubChannel,N.Chunk;const bi=N.MerkleTree;N.FixedPointNumber,N.Lazy,N.AsyncLazy,N.AsyncQueue,N.Uint8ArrayReader,N.Uint8ArrayWriter;const xi=new TextEncoder,$n=1,Mn=4096,Ht=4096,ki=32;function Cn(a,n){return n=typeof n=="number"?A.FeedIndex.fromBigInt(BigInt(n)):n,new A.Identifier(Z.keccak256(Z.concatBytes(a.toUint8Array(),n.toUint8Array())))}function Ei(a){const n=a.slice(0,A.Span.LENGTH),i=a.slice(A.Span.LENGTH),c=Si(i),u=Z.keccak256(Z.concatBytes(n,c));return new A.Reference(u)}function Si(a){if(a.length>Ht)throw new A.BeeArgumentError(`payload size ${a.length} exceeds maximum chunk payload size ${Ht}`,a);const n=new Uint8Array(Ht);return n.set(a),Z.log2Reduce(Z.partition(n,ki),(i,c)=>Z.keccak256(Z.concatBytes(i,c)))}function Nn(a){if(a instanceof Uint8Array||(a=xi.encode(a)),a.length<$n||a.length>Mn)throw new RangeError(`payload size ${a.length} exceeds limits [${$n}, ${Mn}]`);const n=A.Span.fromBigInt(BigInt(a.length)),i=Z.concatBytes(n.toUint8Array(),a);return{data:i,span:n,payload:A.Bytes.fromSlice(i,A.Span.LENGTH),address:Ei(i)}}function Ti(a,n){return new A.Reference(Z.keccak256(Z.concatBytes(a.toUint8Array(),n.toUint8Array())))}function Rn(a,n,i){n=new A.Identifier(n),i=new A.PrivateKey(i);const c=Ti(n,i.publicKey().address()),u=i.sign(Z.concatBytes(n.toUint8Array(),a.address.toUint8Array())),l=Z.concatBytes(n.toUint8Array(),u.toUint8Array(),a.data),h=A.Span.fromSlice(a.data,0),p=A.Bytes.fromSlice(a.data,A.Span.LENGTH);return{data:l,identifier:n,signature:u,span:h,payload:p,address:c,owner:i.publicKey().address()}}class K{constructor(){}static getInstance(){return K.instance||(K.instance=new K),K.instance}formatMessage(n,...i){return`[${new Date().toISOString()}] [${n.toUpperCase()}] - ${i.map(u=>typeof u=="object"?JSON.stringify(u):u).join(" ")}`}log(...n){console.log(this.formatMessage("log",...n))}info(...n){console.info(this.formatMessage("info",...n))}warn(...n){console.warn(this.formatMessage("warn",...n))}error(...n){console.error(this.formatMessage("error",...n))}debug(...n){console.debug(this.formatMessage("debug",...n))}}class re{constructor(){this.logger=K.getInstance()}static getInstance(){return re.instance||(re.instance=new re),re.instance}handleError(n,i){const c=n instanceof Error?n.message:"Unknown error occurred",u=n instanceof Error?n.stack:null;this.logger.error(`Error in ${i||"unknown context"}: ${c}`,{stack:u})}}const Ai=K.getInstance(),Oi=re.getInstance();function qt(a){return(a.startsWith("0x")?a.slice(2):a).toLowerCase()}async function Gt(a,n=3,i=250){return new Promise((c,u)=>{a().then(c).catch(l=>{n>0?(Ai.info(`Retrying... Attempts left: ${n}. Error: ${l.message}`),setTimeout(()=>{Gt(a,n-1,i).then(c).catch(u)},i)):(Oi.handleError(l,"Utils.retryAwaitableAsync"),u(l))})})}class Ii{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(n,i){this.events[n]||(this.events[n]=[]),this.events[n].push(i)}off(n,i){if(!this.events[n])return;const c=this.events[n].indexOf(i);c>-1&&this.events[n].splice(c,1)}cleanAll(){this.events={}}emit(n,i){this.events[n]&&this.events[n].forEach(c=>c(i))}}var $;(function(a){a.assertEqual=u=>u;function n(u){}a.assertIs=n;function i(u){throw new Error}a.assertNever=i,a.arrayToEnum=u=>{const l={};for(const h of u)l[h]=h;return l},a.getValidEnumValues=u=>{const l=a.objectKeys(u).filter(p=>typeof u[u[p]]!="number"),h={};for(const p of l)h[p]=u[p];return a.objectValues(h)},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 h in u)Object.prototype.hasOwnProperty.call(u,h)&&l.push(h);return l},a.find=(u,l)=>{for(const h of u)if(l(h))return h},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(h=>typeof h=="string"?`'${h}'`:h).join(l)}a.joinValues=c,a.jsonStringifyReplacer=(u,l)=>typeof l=="bigint"?l.toString():l})($||($={}));var Kt;(function(a){a.mergeShapes=(n,i)=>({...n,...i})})(Kt||(Kt={}));const b=$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ne=a=>{switch(typeof a){case"undefined":return b.undefined;case"string":return b.string;case"number":return isNaN(a)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(a)?b.array:a===null?b.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?b.promise:typeof Map<"u"&&a instanceof Map?b.map:typeof Set<"u"&&a instanceof Set?b.set:typeof Date<"u"&&a instanceof Date?b.date:b.object;default:return b.unknown}},y=$.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"]),$i=a=>JSON.stringify(a,null,2).replace(/"([^"]+)":/g,"$1:");class F extends Error{get errors(){return this.issues}constructor(n){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=n}format(n){const i=n||function(l){return l.message},c={_errors:[]},u=l=>{for(const h of l.issues)if(h.code==="invalid_union")h.unionErrors.map(u);else if(h.code==="invalid_return_type")u(h.returnTypeError);else if(h.code==="invalid_arguments")u(h.argumentsError);else if(h.path.length===0)c._errors.push(i(h));else{let p=c,w=0;for(;w<h.path.length;){const v=h.path[w];w===h.path.length-1?(p[v]=p[v]||{_errors:[]},p[v]._errors.push(i(h))):p[v]=p[v]||{_errors:[]},p=p[v],w++}}};return u(this),c}static assert(n){if(!(n instanceof F))throw new Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=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(n(u))):c.push(n(u));return{formErrors:c,fieldErrors:i}}get formErrors(){return this.flatten()}}F.create=a=>new F(a);const Oe=(a,n)=>{let i;switch(a.code){case y.invalid_type:a.received===b.undefined?i="Required":i=`Expected ${a.expected}, received ${a.received}`;break;case y.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(a.expected,$.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:i=`Unrecognized key(s) in object: ${$.joinValues(a.keys,", ")}`;break;case y.invalid_union:i="Invalid input";break;case y.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${$.joinValues(a.options)}`;break;case y.invalid_enum_value:i=`Invalid enum value. Expected ${$.joinValues(a.options)}, received '${a.received}'`;break;case y.invalid_arguments:i="Invalid function arguments";break;case y.invalid_return_type:i="Invalid function return type";break;case y.invalid_date:i="Invalid date";break;case y.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}"`:$.assertNever(a.validation):a.validation!=="regex"?i=`Invalid ${a.validation}`:i="Invalid";break;case y.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 y.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 y.custom:i="Invalid input";break;case y.invalid_intersection_types:i="Intersection results could not be merged";break;case y.not_multiple_of:i=`Number must be a multiple of ${a.multipleOf}`;break;case y.not_finite:i="Number must be finite";break;default:i=n.defaultError,$.assertNever(a)}return{message:i}};let jn=Oe;function Mi(a){jn=a}function xt(){return jn}const kt=a=>{const{data:n,path:i,errorMaps:c,issueData:u}=a,l=[...i,...u.path||[]],h={...u,path:l};if(u.message!==void 0)return{...u,path:l,message:u.message};let p="";const w=c.filter(v=>!!v).slice().reverse();for(const v of w)p=v(h,{data:n,defaultError:p}).message;return{...u,path:l,message:p}},Ci=[];function _(a,n){const i=xt(),c=kt({issueData:n,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,i,i===Oe?void 0:Oe].filter(u=>!!u)});a.common.issues.push(c)}class B{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(n,i){const c=[];for(const u of i){if(u.status==="aborted")return T;u.status==="dirty"&&n.dirty(),c.push(u.value)}return{status:n.value,value:c}}static async mergeObjectAsync(n,i){const c=[];for(const u of i){const l=await u.key,h=await u.value;c.push({key:l,value:h})}return B.mergeObjectSync(n,c)}static mergeObjectSync(n,i){const c={};for(const u of i){const{key:l,value:h}=u;if(l.status==="aborted"||h.status==="aborted")return T;l.status==="dirty"&&n.dirty(),h.status==="dirty"&&n.dirty(),l.value!=="__proto__"&&(typeof h.value<"u"||u.alwaysSet)&&(c[l.value]=h.value)}return{status:n.value,value:c}}}const T=Object.freeze({status:"aborted"}),Ie=a=>({status:"dirty",value:a}),z=a=>({status:"valid",value:a}),Yt=a=>a.status==="aborted",Qt=a=>a.status==="dirty",ve=a=>a.status==="valid",ze=a=>typeof Promise<"u"&&a instanceof Promise;function Et(a,n,i,c){if(typeof n=="function"?a!==n||!c:!n.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n.get(a)}function Dn(a,n,i,c,u){if(typeof n=="function"?a!==n||!u:!n.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n.set(a,i),i}typeof SuppressedError=="function"&&SuppressedError;var x;(function(a){a.errToObj=n=>typeof n=="string"?{message:n}:n||{},a.toString=n=>typeof n=="string"?n:n==null?void 0:n.message})(x||(x={}));var Fe,Ve;class Y{constructor(n,i,c,u){this._cachedPath=[],this.parent=n,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 Un=(a,n)=>{if(ve(n))return{success:!0,data:n.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:n,invalid_type_error:i,required_error:c,description:u}=a;if(n&&(i||c))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return n?{errorMap:n,description:u}:{errorMap:(h,p)=>{var w,v;const{message:E}=a;return h.code==="invalid_enum_value"?{message:E??p.defaultError}:typeof p.data>"u"?{message:(w=E??c)!==null&&w!==void 0?w:p.defaultError}:h.code!=="invalid_type"?{message:p.defaultError}:{message:(v=E??i)!==null&&v!==void 0?v:p.defaultError}},description:u}}class I{get description(){return this._def.description}_getType(n){return ne(n.data)}_getOrReturnCtx(n,i){return i||{common:n.parent.common,data:n.data,parsedType:ne(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new B,ctx:{common:n.parent.common,data:n.data,parsedType:ne(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){const i=this._parse(n);if(ze(i))throw new Error("Synchronous parse encountered promise.");return i}_parseAsync(n){const i=this._parse(n);return Promise.resolve(i)}parse(n,i){const c=this.safeParse(n,i);if(c.success)return c.data;throw c.error}safeParse(n,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:n,parsedType:ne(n)},l=this._parseSync({data:n,path:u.path,parent:u});return Un(u,l)}"~validate"(n){var i,c;const u={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:ne(n)};if(!this["~standard"].async)try{const l=this._parseSync({data:n,path:[],parent:u});return ve(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:n,path:[],parent:u}).then(l=>ve(l)?{value:l.value}:{issues:u.common.issues})}async parseAsync(n,i){const c=await this.safeParseAsync(n,i);if(c.success)return c.data;throw c.error}async safeParseAsync(n,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:n,parsedType:ne(n)},u=this._parse({data:n,path:c.path,parent:c}),l=await(ze(u)?u:Promise.resolve(u));return Un(c,l)}refine(n,i){const c=u=>typeof i=="string"||typeof i>"u"?{message:i}:typeof i=="function"?i(u):i;return this._refinement((u,l)=>{const h=n(u),p=()=>l.addIssue({code:y.custom,...c(u)});return typeof Promise<"u"&&h instanceof Promise?h.then(w=>w?!0:(p(),!1)):h?!0:(p(),!1)})}refinement(n,i){return this._refinement((c,u)=>n(c)?!0:(u.addIssue(typeof i=="function"?i(c,u):i),!1))}_refinement(n){return new q({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}constructor(n){this.spa=this.safeParseAsync,this._def=n,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 X.create(this,this._def)}nullable(){return he.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return H.create(this)}promise(){return Ne.create(this,this._def)}or(n){return Ge.create([this,n],this._def)}and(n){return Ke.create(this,n,this._def)}transform(n){return new q({...O(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:n}})}default(n){const i=typeof n=="function"?n:()=>n;return new et({...O(this._def),innerType:this,defaultValue:i,typeName:S.ZodDefault})}brand(){return new er({typeName:S.ZodBranded,type:this,...O(this._def)})}catch(n){const i=typeof n=="function"?n:()=>n;return new tt({...O(this._def),innerType:this,catchValue:i,typeName:S.ZodCatch})}describe(n){const i=this.constructor;return new i({...this._def,description:n})}pipe(n){return rt.create(this,n)}readonly(){return nt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ni=/^c[^\s-]{8,}$/i,Ri=/^[0-9a-z]+$/,ji=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Di=/^[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,Ui=/^[a-z0-9_-]{21}$/i,Pi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Zi=/^[-+]?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)?)??$/,Bi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Li="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Xt;const zi=/^(?:(?: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])$/,Fi=/^(?:(?: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])$/,Vi=/^(([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]))$/,Wi=/^(([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])$/,Hi=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,qi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Pn="((\\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])))",Gi=new RegExp(`^${Pn}$`);function Zn(a){let n="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return a.precision?n=`${n}\\.\\d{${a.precision}}`:a.precision==null&&(n=`${n}(\\.\\d+)?`),n}function Ki(a){return new RegExp(`^${Zn(a)}$`)}function Bn(a){let n=`${Pn}T${Zn(a)}`;const i=[];return i.push(a.local?"Z?":"Z"),a.offset&&i.push("([+-]\\d{2}:?\\d{2})"),n=`${n}(${i.join("|")})`,new RegExp(`^${n}$`)}function Yi(a,n){return!!((n==="v4"||!n)&&zi.test(a)||(n==="v6"||!n)&&Vi.test(a))}function Qi(a,n){if(!Pi.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||n&&u.alg!==n)}catch{return!1}}function Xi(a,n){return!!((n==="v4"||!n)&&Fi.test(a)||(n==="v6"||!n)&&Wi.test(a))}class W extends I{_parse(n){if(this._def.coerce&&(n.data=String(n.data)),this._getType(n)!==b.string){const l=this._getOrReturnCtx(n);return _(l,{code:y.invalid_type,expected:b.string,received:l.parsedType}),T}const c=new B;let u;for(const l of this._def.checks)if(l.kind==="min")n.data.length<l.value&&(u=this._getOrReturnCtx(n,u),_(u,{code:y.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),c.dirty());else if(l.kind==="max")n.data.length>l.value&&(u=this._getOrReturnCtx(n,u),_(u,{code:y.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),c.dirty());else if(l.kind==="length"){const h=n.data.length>l.value,p=n.data.length<l.value;(h||p)&&(u=this._getOrReturnCtx(n,u),h?_(u,{code:y.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):p&&_(u,{code:y.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),c.dirty())}else if(l.kind==="email")Bi.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"email",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="emoji")Xt||(Xt=new RegExp(Li,"u")),Xt.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"emoji",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="uuid")Di.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"uuid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="nanoid")Ui.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"nanoid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid")Ni.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"cuid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid2")Ri.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"cuid2",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="ulid")ji.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"ulid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="url")try{new URL(n.data)}catch{u=this._getOrReturnCtx(n,u),_(u,{validation:"url",code:y.invalid_string,message:l.message}),c.dirty()}else l.kind==="regex"?(l.regex.lastIndex=0,l.regex.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"regex",code:y.invalid_string,message:l.message}),c.dirty())):l.kind==="trim"?n.data=n.data.trim():l.kind==="includes"?n.data.includes(l.value,l.position)||(u=this._getOrReturnCtx(n,u),_(u,{code:y.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),c.dirty()):l.kind==="toLowerCase"?n.data=n.data.toLowerCase():l.kind==="toUpperCase"?n.data=n.data.toUpperCase():l.kind==="startsWith"?n.data.startsWith(l.value)||(u=this._getOrReturnCtx(n,u),_(u,{code:y.invalid_string,validation:{startsWith:l.value},message:l.message}),c.dirty()):l.kind==="endsWith"?n.data.endsWith(l.value)||(u=this._getOrReturnCtx(n,u),_(u,{code:y.invalid_string,validation:{endsWith:l.value},message:l.message}),c.dirty()):l.kind==="datetime"?Bn(l).test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{code:y.invalid_string,validation:"datetime",message:l.message}),c.dirty()):l.kind==="date"?Gi.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{code:y.invalid_string,validation:"date",message:l.message}),c.dirty()):l.kind==="time"?Ki(l).test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{code:y.invalid_string,validation:"time",message:l.message}),c.dirty()):l.kind==="duration"?Zi.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"duration",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="ip"?Yi(n.data,l.version)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"ip",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="jwt"?Qi(n.data,l.alg)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"jwt",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="cidr"?Xi(n.data,l.version)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"cidr",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="base64"?Hi.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"base64",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="base64url"?qi.test(n.data)||(u=this._getOrReturnCtx(n,u),_(u,{validation:"base64url",code:y.invalid_string,message:l.message}),c.dirty()):$.assertNever(l);return{status:c.value,value:n.data}}_regex(n,i,c){return this.refinement(u=>n.test(u),{validation:i,code:y.invalid_string,...x.errToObj(c)})}_addCheck(n){return new W({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...x.errToObj(n)})}url(n){return this._addCheck({kind:"url",...x.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...x.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...x.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...x.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...x.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...x.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...x.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...x.errToObj(n)})}base64url(n){return this._addCheck({kind:"base64url",...x.errToObj(n)})}jwt(n){return this._addCheck({kind:"jwt",...x.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...x.errToObj(n)})}cidr(n){return this._addCheck({kind:"cidr",...x.errToObj(n)})}datetime(n){var i,c;return typeof n=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n}):this._addCheck({kind:"datetime",precision:typeof(n==null?void 0:n.precision)>"u"?null:n==null?void 0:n.precision,offset:(i=n==null?void 0:n.offset)!==null&&i!==void 0?i:!1,local:(c=n==null?void 0:n.local)!==null&&c!==void 0?c:!1,...x.errToObj(n==null?void 0:n.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){return typeof n=="string"?this._addCheck({kind:"time",precision:null,message:n}):this._addCheck({kind:"time",precision:typeof(n==null?void 0:n.precision)>"u"?null:n==null?void 0:n.precision,...x.errToObj(n==null?void 0:n.message)})}duration(n){return this._addCheck({kind:"duration",...x.errToObj(n)})}regex(n,i){return this._addCheck({kind:"regex",regex:n,...x.errToObj(i)})}includes(n,i){return this._addCheck({kind:"includes",value:n,position:i==null?void 0:i.position,...x.errToObj(i==null?void 0:i.message)})}startsWith(n,i){return this._addCheck({kind:"startsWith",value:n,...x.errToObj(i)})}endsWith(n,i){return this._addCheck({kind:"endsWith",value:n,...x.errToObj(i)})}min(n,i){return this._addCheck({kind:"min",value:n,...x.errToObj(i)})}max(n,i){return this._addCheck({kind:"max",value:n,...x.errToObj(i)})}length(n,i){return this._addCheck({kind:"length",value:n,...x.errToObj(i)})}nonempty(n){return this.min(1,x.errToObj(n))}trim(){return new W({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new W({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new W({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(n=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find(n=>n.kind==="date")}get isTime(){return!!this._def.checks.find(n=>n.kind==="time")}get isDuration(){return!!this._def.checks.find(n=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find(n=>n.kind==="email")}get isURL(){return!!this._def.checks.find(n=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find(n=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find(n=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(n=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(n=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(n=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find(n=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find(n=>n.kind==="ip")}get isCIDR(){return!!this._def.checks.find(n=>n.kind==="cidr")}get isBase64(){return!!this._def.checks.find(n=>n.kind==="base64")}get isBase64url(){return!!this._def.checks.find(n=>n.kind==="base64url")}get minLength(){let n=null;for(const i of this._def.checks)i.kind==="min"&&(n===null||i.value>n)&&(n=i.value);return n}get maxLength(){let n=null;for(const i of this._def.checks)i.kind==="max"&&(n===null||i.value<n)&&(n=i.value);return n}}W.create=a=>{var n;return new W({checks:[],typeName:S.ZodString,coerce:(n=a==null?void 0:a.coerce)!==null&&n!==void 0?n:!1,...O(a)})};function Ji(a,n){const i=(a.toString().split(".")[1]||"").length,c=(n.toString().split(".")[1]||"").length,u=i>c?i:c,l=parseInt(a.toFixed(u).replace(".","")),h=parseInt(n.toFixed(u).replace(".",""));return l%h/Math.pow(10,u)}class le extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce&&(n.data=Number(n.data)),this._getType(n)!==b.number){const l=this._getOrReturnCtx(n);return _(l,{code:y.invalid_type,expected:b.number,received:l.parsedType}),T}let c;const u=new B;for(const l of this._def.checks)l.kind==="int"?$.isInteger(n.data)||(c=this._getOrReturnCtx(n,c),_(c,{code:y.invalid_type,expected:"integer",received:"float",message:l.message}),u.dirty()):l.kind==="min"?(l.inclusive?n.data<l.value:n.data<=l.value)&&(c=this._getOrReturnCtx(n,c),_(c,{code:y.too_small,minimum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),u.dirty()):l.kind==="max"?(l.inclusive?n.data>l.value:n.data>=l.value)&&(c=this._getOrReturnCtx(n,c),_(c,{code:y.too_big,maximum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),u.dirty()):l.kind==="multipleOf"?Ji(n.data,l.value)!==0&&(c=this._getOrReturnCtx(n,c),_(c,{code:y.not_multiple_of,multipleOf:l.value,message:l.message}),u.dirty()):l.kind==="finite"?Number.isFinite(n.data)||(c=this._getOrReturnCtx(n,c),_(c,{code:y.not_finite,message:l.message}),u.dirty()):$.assertNever(l);return{status:u.value,value:n.data}}gte(n,i){return this.setLimit("min",n,!0,x.toString(i))}gt(n,i){return this.setLimit("min",n,!1,x.toString(i))}lte(n,i){return this.setLimit("max",n,!0,x.toString(i))}lt(n,i){return this.setLimit("max",n,!1,x.toString(i))}setLimit(n,i,c,u){return new le({...this._def,checks:[...this._def.checks,{kind:n,value:i,inclusive:c,message:x.toString(u)}]})}_addCheck(n){return new le({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:x.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(n)})}multipleOf(n,i){return this._addCheck({kind:"multipleOf",value:n,message:x.toString(i)})}finite(n){return this._addCheck({kind:"finite",message:x.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(n)})}get minValue(){let n=null;for(const i of this._def.checks)i.kind==="min"&&(n===null||i.value>n)&&(n=i.value);return n}get maxValue(){let n=null;for(const i of this._def.checks)i.kind==="max"&&(n===null||i.value<n)&&(n=i.value);return n}get isInt(){return!!this._def.checks.find(n=>n.kind==="int"||n.kind==="multipleOf"&&$.isInteger(n.value))}get isFinite(){let n=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"&&(n===null||c.value<n)&&(n=c.value)}return Number.isFinite(i)&&Number.isFinite(n)}}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(n){if(this._def.coerce)try{n.data=BigInt(n.data)}catch{return this._getInvalidInput(n)}if(this._getType(n)!==b.bigint)return this._getInvalidInput(n);let c;const u=new B;for(const l of this._def.checks)l.kind==="min"?(l.inclusive?n.data<l.value:n.data<=l.value)&&(c=this._getOrReturnCtx(n,c),_(c,{code:y.too_small,type:"bigint",minimum:l.value,inclusive:l.inclusive,message:l.message}),u.dirty()):l.kind==="max"?(l.inclusive?n.data>l.value:n.data>=l.value)&&(c=this._getOrReturnCtx(n,c),_(c,{code:y.too_big,type:"bigint",maximum:l.value,inclusive:l.inclusive,message:l.message}),u.dirty()):l.kind==="multipleOf"?n.data%l.value!==BigInt(0)&&(c=this._getOrReturnCtx(n,c),_(c,{code:y.not_multiple_of,multipleOf:l.value,message:l.message}),u.dirty()):$.assertNever(l);return{status:u.value,value:n.data}}_getInvalidInput(n){const i=this._getOrReturnCtx(n);return _(i,{code:y.invalid_type,expected:b.bigint,received:i.parsedType}),T}gte(n,i){return this.setLimit("min",n,!0,x.toString(i))}gt(n,i){return this.setLimit("min",n,!1,x.toString(i))}lte(n,i){return this.setLimit("max",n,!0,x.toString(i))}lt(n,i){return this.setLimit("max",n,!1,x.toString(i))}setLimit(n,i,c,u){return new de({...this._def,checks:[...this._def.checks,{kind:n,value:i,inclusive:c,message:x.toString(u)}]})}_addCheck(n){return new de({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(n)})}multipleOf(n,i){return this._addCheck({kind:"multipleOf",value:n,message:x.toString(i)})}get minValue(){let n=null;for(const i of this._def.checks)i.kind==="min"&&(n===null||i.value>n)&&(n=i.value);return n}get maxValue(){let n=null;for(const i of this._def.checks)i.kind==="max"&&(n===null||i.value<n)&&(n=i.value);return n}}de.create=a=>{var n;return new de({checks:[],typeName:S.ZodBigInt,coerce:(n=a==null?void 0:a.coerce)!==null&&n!==void 0?n:!1,...O(a)})};class We extends I{_parse(n){if(this._def.coerce&&(n.data=!!n.data),this._getType(n)!==b.boolean){const c=this._getOrReturnCtx(n);return _(c,{code:y.invalid_type,expected:b.boolean,received:c.parsedType}),T}return z(n.data)}}We.create=a=>new We({typeName:S.ZodBoolean,coerce:(a==null?void 0:a.coerce)||!1,...O(a)});class we extends I{_parse(n){if(this._def.coerce&&(n.data=new Date(n.data)),this._getType(n)!==b.date){const l=this._getOrReturnCtx(n);return _(l,{code:y.invalid_type,expected:b.date,received:l.parsedType}),T}if(isNaN(n.data.getTime())){const l=this._getOrReturnCtx(n);return _(l,{code:y.invalid_date}),T}const c=new B;let u;for(const l of this._def.checks)l.kind==="min"?n.data.getTime()<l.value&&(u=this._getOrReturnCtx(n,u),_(u,{code:y.too_small,message:l.message,inclusive:!0,exact:!1,minimum:l.value,type:"date"}),c.dirty()):l.kind==="max"?n.data.getTime()>l.value&&(u=this._getOrReturnCtx(n,u),_(u,{code:y.too_big,message:l.message,inclusive:!0,exact:!1,maximum:l.value,type:"date"}),c.dirty()):$.assertNever(l);return{status:c.value,value:new Date(n.data.getTime())}}_addCheck(n){return new we({...this._def,checks:[...this._def.checks,n]})}min(n,i){return this._addCheck({kind:"min",value:n.getTime(),message:x.toString(i)})}max(n,i){return this._addCheck({kind:"max",value:n.getTime(),message:x.toString(i)})}get minDate(){let n=null;for(const i of this._def.checks)i.kind==="min"&&(n===null||i.value>n)&&(n=i.value);return n!=null?new Date(n):null}get maxDate(){let n=null;for(const i of this._def.checks)i.kind==="max"&&(n===null||i.value<n)&&(n=i.value);return n!=null?new Date(n):null}}we.create=a=>new we({checks:[],coerce:(a==null?void 0:a.coerce)||!1,typeName:S.ZodDate,...O(a)});class St extends I{_parse(n){if(this._getType(n)!==b.symbol){const c=this._getOrReturnCtx(n);return _(c,{code:y.invalid_type,expected:b.symbol,received:c.parsedType}),T}return z(n.data)}}St.create=a=>new St({typeName:S.ZodSymbol,...O(a)});class He extends I{_parse(n){if(this._getType(n)!==b.undefined){const c=this._getOrReturnCtx(n);return _(c,{code:y.invalid_type,expected:b.undefined,received:c.parsedType}),T}return z(n.data)}}He.create=a=>new He({typeName:S.ZodUndefined,...O(a)});class qe extends I{_parse(n){if(this._getType(n)!==b.null){const c=this._getOrReturnCtx(n);return _(c,{code:y.invalid_type,expected:b.null,received:c.parsedType}),T}return z(n.data)}}qe.create=a=>new qe({typeName:S.ZodNull,...O(a)});class $e extends I{constructor(){super(...arguments),this._any=!0}_parse(n){return z(n.data)}}$e.create=a=>new $e({typeName:S.ZodAny,...O(a)});class _e extends I{constructor(){super(...arguments),this._unknown=!0}_parse(n){return z(n.data)}}_e.create=a=>new _e({typeName:S.ZodUnknown,...O(a)});class se extends I{_parse(n){const i=this._getOrReturnCtx(n);return _(i,{code:y.invalid_type,expected:b.never,received:i.parsedType}),T}}se.create=a=>new se({typeName:S.ZodNever,...O(a)});class Tt extends I{_parse(n){if(this._getType(n)!==b.undefined){const c=this._getOrReturnCtx(n);return _(c,{code:y.invalid_type,expected:b.void,received:c.parsedType}),T}return z(n.data)}}Tt.create=a=>new Tt({typeName:S.ZodVoid,...O(a)});class H extends I{_parse(n){const{ctx:i,status:c}=this._processInputParams(n),u=this._def;if(i.parsedType!==b.array)return _(i,{code:y.invalid_type,expected:b.array,received:i.parsedType}),T;if(u.exactLength!==null){const h=i.data.length>u.exactLength.value,p=i.data.length<u.exactLength.value;(h||p)&&(_(i,{code:h?y.too_big:y.too_small,minimum:p?u.exactLength.value:void 0,maximum:h?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&&(_(i,{code:y.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&&(_(i,{code:y.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((h,p)=>u.type._parseAsync(new Y(i,h,i.path,p)))).then(h=>B.mergeArray(c,h));const l=[...i.data].map((h,p)=>u.type._parseSync(new Y(i,h,i.path,p)));return B.mergeArray(c,l)}get element(){return this._def.type}min(n,i){return new H({...this._def,minLength:{value:n,message:x.toString(i)}})}max(n,i){return new H({...this._def,maxLength:{value:n,message:x.toString(i)}})}length(n,i){return new H({...this._def,exactLength:{value:n,message:x.toString(i)}})}nonempty(n){return this.min(1,n)}}H.create=(a,n)=>new H({type:a,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...O(n)});function Me(a){if(a instanceof R){const n={};for(const i in a.shape){const c=a.shape[i];n[i]=X.create(Me(c))}return new R({...a._def,shape:()=>n})}else return a instanceof H?new H({...a._def,type:Me(a.element)}):a instanceof X?X.create(Me(a.unwrap())):a instanceof he?he.create(Me(a.unwrap())):a instanceof Q?Q.create(a.items.map(n=>Me(n))):a}class R 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 n=this._def.shape(),i=$.objectKeys(n);return this._cached={shape:n,keys:i}}_parse(n){if(this._getType(n)!==b.object){const v=this._getOrReturnCtx(n);return _(v,{code:y.invalid_type,expected:b.object,received:v.parsedType}),T}const{status:c,ctx:u}=this._processInputParams(n),{shape:l,keys:h}=this._getCached(),p=[];if(!(this._def.catchall instanceof se&&this._def.unknownKeys==="strip"))for(const v in u.data)h.includes(v)||p.push(v);const w=[];for(const v of h){const E=l[v],j=u.data[v];w.push({key:{status:"valid",value:v},value:E._parse(new Y(u,j,u.path,v)),alwaysSet:v in u.data})}if(this._def.catchall instanceof se){const v=this._def.unknownKeys;if(v==="passthrough")for(const E of p)w.push({key:{status:"valid",value:E},value:{status:"valid",value:u.data[E]}});else if(v==="strict")p.length>0&&(_(u,{code:y.unrecognized_keys,keys:p}),c.dirty());else if(v!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const v=this._def.catchall;for(const E of p){const j=u.data[E];w.push({key:{status:"valid",value:E},value:v._parse(new Y(u,j,u.path,E)),alwaysSet:E in u.data})}}return u.common.async?Promise.resolve().then(async()=>{const v=[];for(const E of w){const j=await E.key,ae=await E.value;v.push({key:j,value:ae,alwaysSet:E.alwaysSet})}return v}).then(v=>B.mergeObjectSync(c,v)):B.mergeObjectSync(c,w)}get shape(){return this._def.shape()}strict(n){return x.errToObj,new R({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(i,c)=>{var u,l,h,p;const w=(h=(l=(u=this._def).errorMap)===null||l===void 0?void 0:l.call(u,i,c).message)!==null&&h!==void 0?h:c.defaultError;return i.code==="unrecognized_keys"?{message:(p=x.errToObj(n).message)!==null&&p!==void 0?p:w}:{message:w}}}:{}})}strip(){return new R({...this._def,unknownKeys:"strip"})}passthrough(){return new R({...this._def,unknownKeys:"passthrough"})}extend(n){return new R({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new R({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:S.ZodObject})}setKey(n,i){return this.augment({[n]:i})}catchall(n){return new R({...this._def,catchall:n})}pick(n){const i={};return $.objectKeys(n).forEach(c=>{n[c]&&this.shape[c]&&(i[c]=this.shape[c])}),new R({...this._def,shape:()=>i})}omit(n){const i={};return $.objectKeys(this.shape).forEach(c=>{n[c]||(i[c]=this.shape[c])}),new R({...this._def,shape:()=>i})}deepPartial(){return Me(this)}partial(n){const i={};return $.objectKeys(this.shape).forEach(c=>{const u=this.shape[c];n&&!n[c]?i[c]=u:i[c]=u.optional()}),new R({...this._def,shape:()=>i})}required(n){const i={};return $.objectKeys(this.shape).forEach(c=>{if(n&&!n[c])i[c]=this.shape[c];else{let l=this.shape[c];for(;l instanceof X;)l=l._def.innerType;i[c]=l}}),new R({...this._def,shape:()=>i})}keyof(){return Ln($.objectKeys(this.shape))}}R.create=(a,n)=>new R({shape:()=>a,unknownKeys:"strip",catchall:se.create(),typeName:S.ZodObject,...O(n)}),R.strictCreate=(a,n)=>new R({shape:()=>a,unknownKeys:"strict",catchall:se.create(),typeName:S.ZodObject,...O(n)}),R.lazycreate=(a,n)=>new R({shape:a,unknownKeys:"strip",catchall:se.create(),typeName:S.ZodObject,...O(n)});class Ge extends I{_parse(n){const{ctx:i}=this._processInputParams(n),c=this._def.options;function u(l){for(const p of l)if(p.result.status==="valid")return p.result;for(const p of l)if(p.result.status==="dirty")return i.common.issues.push(...p.ctx.common.issues),p.result;const h=l.map(p=>new F(p.ctx.common.issues));return _(i,{code:y.invalid_union,unionErrors:h}),T}if(i.common.async)return Promise.all(c.map(async l=>{const h={...i,common:{...i.common,issues:[]},parent:null};return{result:await l._parseAsync({data:i.data,path:i.path,parent:h}),ctx:h}})).then(u);{let l;const h=[];for(const w of c){const v={...i,common:{...i.common,issues:[]},parent:null},E=w._parseSync({data:i.data,path:i.path,parent:v});if(E.status==="valid")return E;E.status==="dirty"&&!l&&(l={result:E,ctx:v}),v.common.issues.length&&h.push(v.common.issues)}if(l)return i.common.issues.push(...l.ctx.common.issues),l.result;const p=h.map(w=>new F(w));return _(i,{code:y.invalid_union,unionErrors:p}),T}}get options(){return this._def.options}}Ge.create=(a,n)=>new Ge({options:a,typeName:S.ZodUnion,...O(n)});const ie=a=>a instanceof Qe?ie(a.schema):a instanceof q?ie(a.innerType()):a instanceof Xe?[a.value]:a instanceof fe?a.options:a instanceof Je?$.objectValues(a.enum):a instanceof et?ie(a._def.innerType):a instanceof He?[void 0]:a instanceof qe?[null]:a instanceof X?[void 0,...ie(a.unwrap())]:a instanceof he?[null,...ie(a.unwrap())]:a instanceof er||a instanceof nt?ie(a.unwrap()):a instanceof tt?ie(a._def.innerType):[];class At extends I{_parse(n){const{ctx:i}=this._processInputParams(n);if(i.parsedType!==b.object)return _(i,{code:y.invalid_type,expected:b.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}):(_(i,{code:y.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(n,i,c){const u=new Map;for(const l of i){const h=ie(l.shape[n]);if(!h.length)throw new Error(`A discriminator value for key \`${n}\` could not be extracted from all schema options`);for(const p of h){if(u.has(p))throw new Error(`Discriminator property ${String(n)} has duplicate value ${String(p)}`);u.set(p,l)}}return new At({typeName:S.ZodDiscriminatedUnion,discriminator:n,options:i,optionsMap:u,...O(c)})}}function Jt(a,n){const i=ne(a),c=ne(n);if(a===n)return{valid:!0,data:a};if(i===b.object&&c===b.object){const u=$.objectKeys(n),l=$.objectKeys(a).filter(p=>u.indexOf(p)!==-1),h={...a,...n};for(const p of l){const w=Jt(a[p],n[p]);if(!w.valid)return{valid:!1};h[p]=w.data}return{valid:!0,data:h}}else if(i===b.array&&c===b.array){if(a.length!==n.length)return{valid:!1};const u=[];for(let l=0;l<a.length;l++){const h=a[l],p=n[l],w=Jt(h,p);if(!w.valid)return{valid:!1};u.push(w.data)}return{valid:!0,data:u}}else return i===b.date&&c===b.date&&+a==+n?{valid:!0,data:a}:{valid:!1}}class Ke extends I{_parse(n){const{status:i,ctx:c}=this._processInputParams(n),u=(l,h)=>{if(Yt(l)||Yt(h))return T;const p=Jt(l.value,h.value);return p.valid?((Qt(l)||Qt(h))&&i.dirty(),{status:i.value,value:p.data}):(_(c,{code:y.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,h])=>u(l,h)):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}))}}Ke.create=(a,n,i)=>new Ke({left:a,right:n,typeName:S.ZodIntersection,...O(i)});class Q extends I{_parse(n){const{status:i,ctx:c}=this._processInputParams(n);if(c.parsedType!==b.array)return _(c,{code:y.invalid_type,expected:b.array,received:c.parsedType}),T;if(c.data.length<this._def.items.length)return _(c,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T;!this._def.rest&&c.data.length>this._def.items.length&&(_(c,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty());const l=[...c.data].map((h,p)=>{const w=this._def.items[p]||this._def.rest;return w?w._parse(new Y(c,h,c.path,p)):null}).filter(h=>!!h);return c.common.async?Promise.all(l).then(h=>B.mergeArray(i,h)):B.mergeArray(i,l)}get items(){return this._def.items}rest(n){return new Q({...this._def,rest:n})}}Q.create=(a,n)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Q({items:a,typeName:S.ZodTuple,rest:null,...O(n)})};class Ye extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){const{status:i,ctx:c}=this._processInputParams(n);if(c.parsedType!==b.object)return _(c,{code:y.invalid_type,expected:b.object,received:c.parsedType}),T;const u=[],l=this._def.keyType,h=this._def.valueType;for(const p in c.data)u.push({key:l._parse(new Y(c,p,c.path,p)),value:h._parse(new Y(c,c.data[p],c.path,p)),alwaysSet:p in c.data});return c.common.async?B.mergeObjectAsync(i,u):B.mergeObjectSync(i,u)}get element(){return this._def.valueType}static create(n,i,c){return i instanceof I?new Ye({keyType:n,valueType:i,typeName:S.ZodRecord,...O(c)}):new Ye({keyType:W.create(),valueType:n,typeName:S.ZodRecord,...O(i)})}}class Ot extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){const{status:i,ctx:c}=this._processInputParams(n);if(c.parsedType!==b.map)return _(c,{code:y.invalid_type,expected:b.map,received:c.parsedType}),T;const u=this._def.keyType,l=this._def.valueType,h=[...c.data.entries()].map(([p,w],v)=>({key:u._parse(new Y(c,p,c.path,[v,"key"])),value:l._parse(new Y(c,w,c.path,[v,"value"]))}));if(c.common.async){const p=new Map;return Promise.resolve().then(async()=>{for(const w of h){const v=await w.key,E=await w.value;if(v.status==="aborted"||E.status==="aborted")return T;(v.status==="dirty"||E.status==="dirty")&&i.dirty(),p.set(v.value,E.value)}return{status:i.value,value:p}})}else{const p=new Map;for(const w of h){const v=w.key,E=w.value;if(v.status==="aborted"||E.status==="aborted")return T;(v.status==="dirty"||E.status==="dirty")&&i.dirty(),p.set(v.value,E.value)}return{status:i.value,value:p}}}}Ot.create=(a,n,i)=>new Ot({valueType:n,keyType:a,typeName:S.ZodMap,...O(i)});class be extends I{_parse(n){const{status:i,ctx:c}=this._processInputParams(n);if(c.parsedType!==b.set)return _(c,{code:y.invalid_type,expected:b.set,received:c.parsedType}),T;const u=this._def;u.minSize!==null&&c.data.size<u.minSize.value&&(_(c,{code:y.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&&(_(c,{code:y.too_big,maximum:u.maxSize.value,type:"set",inclusive:!0,exact:!1,message:u.maxSize.message}),i.dirty());const l=this._def.valueType;function h(w){const v=new Set;for(const E of w){if(E.status==="aborted")return T;E.status==="dirty"&&i.dirty(),v.add(E.value)}return{status:i.value,value:v}}const p=[...c.data.values()].map((w,v)=>l._parse(new Y(c,w,c.path,v)));return c.common.async?Promise.all(p).then(w=>h(w)):h(p)}min(n,i){return new be({...this._def,minSize:{value:n,message:x.toString(i)}})}max(n,i){return new be({...this._def,maxSize:{value:n,message:x.toString(i)}})}size(n,i){return this.min(n,i).max(n,i)}nonempty(n){return this.min(1,n)}}be.create=(a,n)=>new be({valueType:a,minSize:null,maxSize:null,typeName:S.ZodSet,...O(n)});class Ce extends I{constructor(){super(...arguments),this.validate=this.implement}_parse(n){const{ctx:i}=this._processInputParams(n);if(i.parsedType!==b.function)return _(i,{code:y.invalid_type,expected:b.function,received:i.parsedType}),T;function c(p,w){return kt({data:p,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,xt(),Oe].filter(v=>!!v),issueData:{code:y.invalid_arguments,argumentsError:w}})}function u(p,w){return kt({data:p,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,xt(),Oe].filter(v=>!!v),issueData:{code:y.invalid_return_type,returnTypeError:w}})}const l={errorMap:i.common.contextualErrorMap},h=i.data;if(this._def.returns instanceof Ne){const p=this;return z(async function(...w){const v=new F([]),E=await p._def.args.parseAsync(w,l).catch(oe=>{throw v.addIssue(c(w,oe)),v}),j=await Reflect.apply(h,this,E);return await p._def.returns._def.type.parseAsync(j,l).catch(oe=>{throw v.addIssue(u(j,oe)),v})})}else{const p=this;return z(function(...w){const v=p._def.args.safeParse(w,l);if(!v.success)throw new F([c(w,v.error)]);const E=Reflect.apply(h,this,v.data),j=p._def.returns.safeParse(E,l);if(!j.success)throw new F([u(E,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...n){return new Ce({...this._def,args:Q.create(n).rest(_e.create())})}returns(n){return new Ce({...this._def,returns:n})}implement(n){return this.parse(n)}strictImplement(n){return this.parse(n)}static create(n,i,c){return new Ce({args:n||Q.create([]).rest(_e.create()),returns:i||_e.create(),typeName:S.ZodFunction,...O(c)})}}class Qe extends I{get schema(){return this._def.getter()}_parse(n){const{ctx:i}=this._processInputParams(n);return this._def.getter()._parse({data:i.data,path:i.path,parent:i})}}Qe.create=(a,n)=>new Qe({getter:a,typeName:S.ZodLazy,...O(n)});class Xe extends I{_parse(n){if(n.data!==this._def.value){const i=this._getOrReturnCtx(n);return _(i,{received:i.data,code:y.invalid_literal,expected:this._def.value}),T}return{status:"valid",value:n.data}}get value(){return this._def.value}}Xe.create=(a,n)=>new Xe({value:a,typeName:S.ZodLiteral,...O(n)});function Ln(a,n){return new fe({values:a,typeName:S.ZodEnum,...O(n)})}class fe extends I{constructor(){super(...arguments),Fe.set(this,void 0)}_parse(n){if(typeof n.data!="string"){const i=this._getOrReturnCtx(n),c=this._def.values;return _(i,{expected:$.joinValues(c),received:i.parsedType,code:y.invalid_type}),T}if(Et(this,Fe)||Dn(this,Fe,new Set(this._def.values)),!Et(this,Fe).has(n.data)){const i=this._getOrReturnCtx(n),c=this._def.values;return _(i,{received:i.data,code:y.invalid_enum_value,options:c}),T}return z(n.data)}get options(){return this._def.values}get enum(){const n={};for(const i of this._def.values)n[i]=i;return n}get Values(){const n={};for(const i of this._def.values)n[i]=i;return n}get Enum(){const n={};for(const i of this._def.values)n[i]=i;return n}extract(n,i=this._def){return fe.create(n,{...this._def,...i})}exclude(n,i=this._def){return fe.create(this.options.filter(c=>!n.includes(c)),{...this._def,...i})}}Fe=new WeakMap,fe.create=Ln;class Je extends I{constructor(){super(...arguments),Ve.set(this,void 0)}_parse(n){const i=$.getValidEnumValues(this._def.values),c=this._getOrReturnCtx(n);if(c.parsedType!==b.string&&c.parsedType!==b.number){const u=$.objectValues(i);return _(c,{expected:$.joinValues(u),received:c.parsedType,code:y.invalid_type}),T}if(Et(this,Ve)||Dn(this,Ve,new Set($.getValidEnumValues(this._def.values))),!Et(this,Ve).has(n.data)){const u=$.objectValues(i);return _(c,{received:c.data,code:y.invalid_enum_value,options:u}),T}return z(n.data)}get enum(){return this._def.values}}Ve=new WeakMap,Je.create=(a,n)=>new Je({values:a,typeName:S.ZodNativeEnum,...O(n)});class Ne extends I{unwrap(){return this._def.type}_parse(n){const{ctx:i}=this._processInputParams(n);if(i.parsedType!==b.promise&&i.common.async===!1)return _(i,{code:y.invalid_type,expected:b.promise,received:i.parsedType}),T;const c=i.parsedType===b.promise?i.data:Promise.resolve(i.data);return z(c.then(u=>this._def.type.parseAsync(u,{path:i.path,errorMap:i.common.contextualErrorMap})))}}Ne.create=(a,n)=>new Ne({type:a,typeName:S.ZodPromise,...O(n)});class q extends I{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){const{status:i,ctx:c}=this._processInputParams(n),u=this._def.effect||null,l={addIssue:h=>{_(c,h),h.fatal?i.abort():i.dirty()},get path(){return c.path}};if(l.addIssue=l.addIssue.bind(l),u.type==="preprocess"){const h=u.transform(c.data,l);if(c.common.async)return Promise.resolve(h).then(async p=>{if(i.value==="aborted")return T;const w=await this._def.schema._parseAsync({data:p,path:c.path,parent:c});return w.status==="aborted"?T:w.status==="dirty"||i.value==="dirty"?Ie(w.value):w});{if(i.value==="aborted")return T;const p=this._def.schema._parseSync({data:h,path:c.path,parent:c});return p.status==="aborted"?T:p.status==="dirty"||i.value==="dirty"?Ie(p.value):p}}if(u.type==="refinement"){const h=p=>{const w=u.refinement(p,l);if(c.common.async)return Promise.resolve(w);if(w instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return p};if(c.common.async===!1){const p=this._def.schema._parseSync({data:c.data,path:c.path,parent:c});return p.status==="aborted"?T:(p.status==="dirty"&&i.dirty(),h(p.value),{status:i.value,value:p.value})}else return this._def.schema._parseAsync({data:c.data,path:c.path,parent:c}).then(p=>p.status==="aborted"?T:(p.status==="dirty"&&i.dirty(),h(p.value).then(()=>({status:i.value,value:p.value}))))}if(u.type==="transform")if(c.common.async===!1){const h=this._def.schema._parseSync({data:c.data,path:c.path,parent:c});if(!ve(h))return h;const p=u.transform(h.value,l);if(p instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:p}}else return this._def.schema._parseAsync({data:c.data,path:c.path,parent:c}).then(h=>ve(h)?Promise.resolve(u.transform(h.value,l)).then(p=>({status:i.value,value:p})):h);$.assertNever(u)}}q.create=(a,n,i)=>new q({schema:a,typeName:S.ZodEffects,effect:n,...O(i)}),q.createWithPreprocess=(a,n,i)=>new q({schema:n,effect:{type:"preprocess",transform:a},typeName:S.ZodEffects,...O(i)});class X extends I{_parse(n){return this._getType(n)===b.undefined?z(void 0):this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}X.create=(a,n)=>new X({innerType:a,typeName:S.ZodOptional,...O(n)});class he extends I{_parse(n){return this._getType(n)===b.null?z(null):this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}he.create=(a,n)=>new he({innerType:a,typeName:S.ZodNullable,...O(n)});class et extends I{_parse(n){const{ctx:i}=this._processInputParams(n);let c=i.data;return i.parsedType===b.undefined&&(c=this._def.defaultValue()),this._def.innerType._parse({data:c,path:i.path,parent:i})}removeDefault(){return this._def.innerType}}et.create=(a,n)=>new et({innerType:a,typeName:S.ZodDefault,defaultValue:typeof n.default=="function"?n.default:()=>n.default,...O(n)});class tt extends I{_parse(n){const{ctx:i}=this._processInputParams(n),c={...i,common:{...i.common,issues:[]}},u=this._def.innerType._parse({data:c.data,path:c.path,parent:{...c}});return ze(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}}tt.create=(a,n)=>new tt({innerType:a,typeName:S.ZodCatch,catchValue:typeof n.catch=="function"?n.catch:()=>n.catch,...O(n)});class It extends I{_parse(n){if(this._getType(n)!==b.nan){const c=this._getOrReturnCtx(n);return _(c,{code:y.invalid_type,expected:b.nan,received:c.parsedType}),T}return{status:"valid",value:n.data}}}It.create=a=>new It({typeName:S.ZodNaN,...O(a)});const ea=Symbol("zod_brand");class er extends I{_parse(n){const{ctx:i}=this._processInputParams(n),c=i.data;return this._def.type._parse({data:c,path:i.path,parent:i})}unwrap(){return this._def.type}}class rt extends I{_parse(n){const{status:i,ctx:c}=this._processInputParams(n);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(),Ie(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(n,i){return new rt({in:n,out:i,typeName:S.ZodPipeline})}}class nt extends I{_parse(n){const i=this._def.innerType._parse(n),c=u=>(ve(u)&&(u.value=Object.freeze(u.value)),u);return ze(i)?i.then(u=>c(u)):c(i)}unwrap(){return this._def.innerType}}nt.create=(a,n)=>new nt({innerType:a,typeName:S.ZodReadonly,...O(n)});function zn(a,n={},i){return a?$e.create().superRefine((c,u)=>{var l,h;if(!a(c)){const p=typeof n=="function"?n(c):typeof n=="string"?{message:n}:n,w=(h=(l=p.fatal)!==null&&l!==void 0?l:i)!==null&&h!==void 0?h:!0,v=typeof p=="string"?{message:p}:p;u.addIssue({code:"custom",...v,fatal:w})}}):$e.create()}const ta={object:R.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 ra=(a,n={message:`Input not instance of ${a.name}`})=>zn(i=>i instanceof a,n),Fn=W.create,Vn=le.create,na=It.create,sa=de.create,Wn=We.create,ia=we.create,aa=St.create,oa=He.create,ca=qe.create,ua=$e.create,la=_e.create,da=se.create,fa=Tt.create,ha=H.create,pa=R.create,ma=R.strictCreate,ga=Ge.create,ya=At.create,va=Ke.create,wa=Q.create,_a=Ye.create,ba=Ot.create,xa=be.create,ka=Ce.create,Ea=Qe.create,Sa=Xe.create,Ta=fe.create,Aa=Je.create,Oa=Ne.create,Hn=q.create,Ia=X.create,$a=he.create,Ma=q.createWithPreprocess,Ca=rt.create;var J=Object.freeze({__proto__:null,defaultErrorMap:Oe,setErrorMap:Mi,getErrorMap:xt,makeIssue:kt,EMPTY_PATH:Ci,addIssueToContext:_,ParseStatus:B,INVALID:T,DIRTY:Ie,OK:z,isAborted:Yt,isDirty:Qt,isValid:ve,isAsync:ze,get util(){return $},get objectUtil(){return Kt},ZodParsedType:b,getParsedType:ne,ZodType:I,datetimeRegex:Bn,ZodString:W,ZodNumber:le,ZodBigInt:de,ZodBoolean:We,ZodDate:we,ZodSymbol:St,ZodUndefined:He,ZodNull:qe,ZodAny:$e,ZodUnknown:_e,ZodNever:se,ZodVoid:Tt,ZodArray:H,ZodObject:R,ZodUnion:Ge,ZodDiscriminatedUnion:At,ZodIntersection:Ke,ZodTuple:Q,ZodRecord:Ye,ZodMap:Ot,ZodSet:be,ZodFunction:Ce,ZodLazy:Qe,ZodLiteral:Xe,ZodEnum:fe,ZodNativeEnum:Je,ZodPromise:Ne,ZodEffects:q,ZodTransformer:q,ZodOptional:X,ZodNullable:he,ZodDefault:et,ZodCatch:tt,ZodNaN:It,BRAND:ea,ZodBranded:er,ZodPipeline:rt,ZodReadonly:nt,custom:zn,Schema:I,ZodSchema:I,late:ta,get ZodFirstPartyTypeKind(){return S},coerce:{string:a=>W.create({...a,coerce:!0}),number:a=>le.create({...a,coerce:!0}),boolean:a=>We.create({...a,coerce:!0}),bigint:a=>de.create({...a,coerce:!0}),date:a=>we.create({...a,coerce:!0})},any:ua,array:ha,bigint:sa,boolean:Wn,date:ia,discriminatedUnion:ya,effect:Hn,enum:Ta,function:ka,instanceof:ra,intersection:va,lazy:Ea,literal:Sa,map:ba,nan:na,nativeEnum:Aa,never:da,null:ca,nullable:$a,number:Vn,object:pa,oboolean:()=>Wn().optional(),onumber:()=>Vn().optional(),optional:Ia,ostring:()=>Fn().optional(),pipeline:Ca,preprocess:Ma,promise:Oa,record:_a,set:xa,strictObject:ma,string:Fn,symbol:aa,transformer:Hn,tuple:wa,undefined:oa,union:ga,unknown:la,void:fa,NEVER:T,ZodIssueCode:y,quotelessJson:$i,ZodError:F});const qn=K.getInstance(),Na=J.object({id:J.string(),message:J.string(),username:J.string(),address:J.string(),timestamp:J.number(),signature:J.string(),index:J.number(),chatTopic:J.string(),userTopic:J.string()});function Ra(a){const n=Na.safeParse(a);return n.success?ja(a)?!0:(console.warn("Invalid messageSender"),!1):(qn.warn(n.error.format()),!1)}function ja(a){try{const n={username:a.username,address:a.address,timestamp:a.timestamp},i=new TextEncoder,c=Z.concatBytes(i.encode(`Ethereum Signed Message:
11
- 32`),Z.keccak256(i.encode(JSON.stringify(n))));if(new A.Signature(a.signature).isValid(c,a.address))throw new Error("Signature verification failed!");return!0}catch(n){return qn.warn("Error in validateUserSignature",n),!1}}const G={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 Da{constructor(n,i){this.utils=n,this.emitter=i,this.logger=K.getInstance(),this.errorHandler=re.getInstance(),this.historyIndex=null}async init(){try{const n=await this.utils.fetchLatestChatMessage();return this.historyIndex=n.index,await this.fetchPreviousMessages(),n.index}catch(n){return this.errorHandler.handleError(n,"SwarmHistory.init"),A.FeedIndex.fromBigInt(0n)}}async fetchPreviousMessages(n=10){try{if(!this.historyIndex){this.logger.warn("History index is not set. Cannot fetch previous messages.");return}if(this.historyIndex.toBigInt()===0n){this.logger.warn("No previous messages to fetch.");return}const i=this.historyIndex.toBigInt(),c=i>BigInt(n)?i-BigInt(n):0n;for(let u=i-1n;u>=c;u--){const l=await this.utils.fetchChatMessage(A.FeedIndex.fromBigInt(u));if(this.emitter.emit(G.MESSAGE_RECEIVED,l),this.historyIndex=A.FeedIndex.fromBigInt(u),u===0n)break}}catch(i){this.errorHandler.handleError(i,"SwarmHistory.fetchPreviousMessages")}}}class Ua{constructor(n,i){this.userDetails=n,this.swarmSettings=i,this.depth=26,this.errorHandler=re.getInstance(),this.UPLOAD_GSOC_TIMEOUT=2e3}generateUserOwnedFeedId(n,i){return`${n}_EthercastChat_${i}`}isNotFoundError(n){return n.stack.includes("404")||n.message.includes("Not Found")||n.message.includes("404")||n.code===404}async writeOwnFeedDataByIndex(n,i){const{enveloped:c,stamp:u}=this.swarmSettings;if(!c)await this.writeOwnFeedDataByIndexOwned(n,i);else if(u)await this.writeOwnFeedDataByIndexEnvelope(n,i);else throw new Error("Enveloped mode is enabled, but stamp is not provided")}async writeOwnFeedDataByIndexOwned(n,i){const{bee:c,stamp:u,chatTopic:l}=this.swarmSettings,{privateKey:h,ownAddress:p}=this.userDetails,w=this.generateUserOwnedFeedId(l,p),v=A.Topic.fromString(w);await c.makeFeedWriter(v,new A.PrivateKey(h)).uploadPayload(u,JSON.stringify(i),{index:n})}async writeOwnFeedDataByIndexEnvelope(n,i){const{bee:c,stamp:u,chatTopic:l}=this.swarmSettings,{privateKey:h,ownAddress:p}=this.userDetails,w=new A.PrivateKey(h),v=A.Stamper.fromBlank(h,u,this.depth),E=this.generateUserOwnedFeedId(l,p),j=A.Topic.fromString(E),ae=Cn(j,n),oe=Nn(i),st=Rn(oe,ae,w),Re={hash:()=>st.address.toUint8Array()},tr=v.stamp(Re),{upload:rr}=c.makeSOCWriter(w),it=A.Bytes.fromUtf8(i);return(await rr(tr,ae,it.toUint8Array())).reference.toHex()}orderMessages(n){return n.sort((i,c)=>i.timestamp-c.timestamp)}async uploadObjectToBee(n){const{enveloped:i,stamp:c}=this.swarmSettings;if(i){if(c)return this.uploadObjectToBeeEnvelope(n);throw new Error("Enveloped mode is enabled, but stamp is not provided")}else return this.uploadObjectToBeeOwn(n)}async uploadObjectToBeeOwn(n){try{const{bee:i,stamp:c}=this.swarmSettings;return(await i.uploadData(c,JSON.stringify(n),{redundancyLevel:4})).reference.toString()}catch(i){return this.errorHandler.handleError(i,"Utils.uploadObjectToBee"),null}}async uploadObjectToBeeEnvelope(n){try{const{bee:i,stamp:c}=this.swarmSettings,{privateKey:u}=this.userDetails,l=A.Stamper.fromBlank(u,c,this.depth),h=A.Bytes.fromUtf8(JSON.stringify(n)),p=new bi(async v=>{await i.uploadChunk(l.stamp(v),v.build())});await p.append(h.toUint8Array());const w=await p.finalize();return Z.uint8ArrayToHex(w.hash())}catch(i){return this.errorHandler.handleError(i,"Utils.uploadObjectToBee"),null}}async getOwnLatestFeedIndex(){try{const{bee:n,chatTopic:i}=this.swarmSettings,{ownAddress:c}=this.userDetails,u=this.generateUserOwnedFeedId(i,c),l=A.Topic.fromString(u),p=await n.makeFeedReader(l,c).downloadPayload(),w=Number(p.feedIndex.toBigInt()),v=w+1;return{latestIndex:w,nextIndex:v}}catch(n){if(this.isNotFoundError(n))return{latestIndex:-1,nextIndex:0};throw n}}async fetchLatestChatMessage(){const{bee:n,chatTopic:i,chatAddress:c}=this.swarmSettings,l=await n.makeFeedReader(A.Topic.fromString(i),qt(c)).downloadPayload();return{message:l.payload.toJSON(),index:l.feedIndex}}async fetchChatMessage(n){const{bee:i,chatTopic:c,chatAddress:u}=this.swarmSettings;return(await i.makeFeedReader(A.Topic.fromString(c),qt(u)).downloadPayload({index:n})).payload.toJSON()}async sendMessageToGsoc(n){const{enveloped:i,stamp:c}=this.swarmSettings;if(!i)await this.sendMessageToGsocOwn(n);else if(c)await this.sendMessageToGsocEnvelope(n);else throw new Error("Enveloped mode is enabled, but stamp is not provided")}async rawSocDownload(n,i){const{beeUrl:c}=this.swarmSettings,u=await fetch(`${c}/soc/${n}/${i}`,{headers:{"swarm-chunk-retrieval-timeout":"2000ms"}});if(!u.ok){const l=new Error(`Failed to fetch: ${n}/${i} [${u.status}]`);throw l.status=u.status,l}return u.text()}async sendMessageToGsocOwn(n){const{bee:i,stamp:c,gsocTopic:u,gsocResourceId:l}=this.swarmSettings,h=new A.PrivateKey(l),p=A.Identifier.fromString(u),w=A.Bytes.fromUtf8(n),{upload:v}=i.makeSOCWriter(h,{timeout:this.UPLOAD_GSOC_TIMEOUT});await v(c,p,w.toUint8Array())}async sendMessageToGsocEnvelope(n){const{bee:i,stamp:c,gsocTopic:u,gsocResourceId:l}=this.swarmSettings,{privateKey:h}=this.userDetails,p=A.Stamper.fromBlank(h,c,this.depth),w=new A.PrivateKey(l),v=A.Identifier.fromString(u),E=A.Bytes.fromUtf8(n),j=Nn(E.toUint8Array()),ae=Rn(j,v,w),oe={hash:()=>ae.address.toUint8Array()},st=p.stamp(oe),{upload:Re}=i.makeSOCWriter(w,{timeout:this.UPLOAD_GSOC_TIMEOUT});await Re(st,v,E.toUint8Array())}}class Pa{constructor(n){this.logger=K.getInstance(),this.errorHandler=re.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const i=new A.PrivateKey(qt(n.user.privateKey));this.userDetails={privateKey:n.user.privateKey,ownAddress:i.publicKey().address().toString(),nickname:n.user.nickname,ownIndex:-1},this.swarmSettings={bee:new A.Bee(n.infra.beeUrl),beeUrl:n.infra.beeUrl,stamp:n.infra.stamp||"0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",enveloped:n.infra.enveloped,gsocTopic:n.infra.gsocTopic,gsocResourceId:n.infra.gsocResourceId,chatTopic:n.infra.chatTopic,chatAddress:n.infra.chatAddress},this.emitter=new Ii,this.utils=new Ua(this.userDetails,this.swarmSettings),this.history=new Da(this.utils,this.emitter)}start(){this.init(),this.startMessagesFetchProcess()}stop(){this.emitter.cleanAll(),this.stopMessagesFetchProcess()}getEmitter(){return this.emitter}orderMessages(n){return this.utils.orderMessages(n)}async sendMessage(n,i){const c=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,u={id:i||wi(),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(),timestamp:Date.now(),index:c,message:n};try{this.emitter.emit(G.MESSAGE_REQUEST_INITIATED,u),await this.utils.writeOwnFeedDataByIndex(c,JSON.stringify(u)),this.userDetails.ownIndex=c,this.emitter.emit(G.MESSAGE_REQUEST_UPLOADED,u),await this.broadcastUserMessage(u)}catch(l){this.emitter.emit(G.MESSAGE_REQUEST_ERROR,u),this.errorHandler.handleError(l,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(G.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessages()}finally{this.emitter.emit(G.LOADING_PREVIOUS_MESSAGES,!1)}}async retrySendMessage(n){this.sendMessage(n.message,n.id)}async retryBroadcastUserMessage(n){await this.broadcastUserMessage(n)}async init(){try{this.emitter.emit(G.LOADING_INIT,!0);const[n,i]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(n.status==="rejected")throw n.reason;i.status==="fulfilled"&&(this.gsocIndex=i.value),this.emitter.emit(G.LOADING_INIT,!1)}catch(n){this.errorHandler.handleError(n,"Chat.initSelfState"),this.emitter.emit(G.CRITICAL_ERROR,n)}}async initOwnIndex(){const{latestIndex:c}=await Gt(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=c}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const n=A.Topic.fromString(this.swarmSettings.chatTopic),i=Cn(n,this.gsocIndex),c=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,i.toString()),u=JSON.parse(c);if(!Ra(u)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(G.MESSAGE_RECEIVED,u),this.gsocIndex=this.gsocIndex.next()}catch(n){if(this.utils.isNotFoundError(n))return;this.errorHandler.handleError(n,"Chat.fetchLatestMessage")}}async broadcastUserMessage(n){try{return Gt(()=>this.utils.sendMessageToGsoc(JSON.stringify(n)))}catch(i){this.errorHandler.handleError(i,"Chat.broadcastUserMessage")}}getSignature(){const{ownAddress:n,privateKey:i,nickname:c}=this.userDetails,u=new A.EthAddress(n).toString(),l=new A.PrivateKey(i);if(l.publicKey().address().toString()!==u)throw new Error("The provided address does not match the address derived from the private key");const p=Date.now();return l.sign(JSON.stringify({username:c,address:u,timestamp:p})).toHex()}async startMessagesFetchProcess(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const n=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(n,200)};n()}stopMessagesFetchProcess(){this.stopFetch=!0}}ue.EVENTS=G,ue.SwarmChat=Pa,Object.defineProperty(ue,Symbol.toStringTag,{value:"Module"})});
4
+ `)}function Ut(e){return e.charAt(0).toUpperCase()+e.slice(1)}function vs(e){return e.charAt(0).toLowerCase()+e.slice(1)}function ws(e){if(!e)return!1;const t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function _s(e){if(!e)return!1;const t=e.charCodeAt(0);return t>=48&&t<=57}function lt(e){return ws(e)||_s(e)}const jc=`
5
+ \r.,?!:;"'\`(){}[]~@#$%^&*-+=|<>/\\`.split("");function Dc(e){return jc.includes(e)}function Uc(e){return lt(e)||e==="."||e==="["||e==="]"||e==="_"}function Pc(e,t,n,s,o){return e.slice(0,t)+s+e.slice(t,t+n)+o+e.slice(t+n)}function bs(e,t,n=0){const s=t.exec(e.slice(n));return s?{index:s.index,match:s[0]}:null}function xs(e,t,n=!0){if(!n)return t.every(o=>o instanceof RegExp?o.test(e):e.indexOf(o,0)!==-1);let s=0;for(const o of t)if(o instanceof RegExp){const d=bs(e,o,s);if(!d)return!1;s=d.index+d.match.length}else{const d=e.indexOf(o,s);if(d===-1)return!1;s=d+o.length}return!0}function Zc(e,t,n=!0){let s=0;for(const o of t){let d=!1;for(;!d&&s<e.length;)xs(e[s],o,n)&&(d=!0),s++;if(!d)return!1}return!0}function Bc(e){return e.match(/"|,/)?`"${e.replace(/"/g,'""')}"`:e}function Pe(e,t,n=0){let s=-1;for(const o of t){const d=e.indexOf(o,n);d!==-1&&(s===-1||d<s)&&(s=d)}return s}function Lc(e,t=0){for(let n=t;n<e.length;n++)if(Dc(e[n]))return n;return-1}function zc(e,t=0){for(let n=t;n<e.length;n++)if(e[n]==="#"&&lt(e[n+1]))return n;return-1}function ks(e,t,n=0){return e.slice(0,n).lastIndexOf(t)}function Es(e,t=0,n="{",s="}"){let o=1;for(let d=t;d<e.length;d++)if(e.slice(d,d+s.length)===s){if(--o===0)return d}else e.slice(d,d+n.length)===n&&o++;return-1}function Ss(e,t){const n=t.wordBoundary?Pe(e,[`${t.opening} `,`${t.opening}
6
+ `],t.start||0):e.indexOf(t.opening,t.start||0);if(n===-1)return null;const s=Es(e,n+t.opening.length,t.opening,t.closing);return s===-1?null:t.exclusive?e.slice(n+t.opening.length,s):e.slice(n,s+t.closing.length)}function Fc(e,t){const n=[];let s=t.wordBoundary?Pe(e,[`${t.opening} `,`${t.opening}
7
+ `],t.start||0):e.indexOf(t.opening,t.start||0);for(;;){if(s===-1)return n;const o=Ss(e,{...t,start:s});if(!o)return n;n.push(o),s=t.wordBoundary?Pe(e,[`${t.opening} `,`${t.opening}
8
+ `],s+o.length):e.indexOf(t.opening,s+o.length)}}function Vc(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 Wc(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 Hc(e){const t=[];let n=0;for(;n<e.length;){const s=zc(e,n);if(s===-1){t.push({string:e.slice(n),symbol:null});break}const o=Lc(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 qc(e){const t=[];let n=0;for(;n<e.length;){const s=Pe(e,["http://","https://"],n);if(s===-1){t.push({string:e.slice(n),symbol:null});break}const o=Pe(e,[" ",`
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 Ts="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",As="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function Gc(e){return Os(e,Ts)}function Kc(e){return Is(e,Ts)}function Yc(e){return Os(e,As)}function Qc(e){return Is(e,As)}function Os(e,t){const n="=",s=t.length;let o=0,d=0;const f=[];for(let g=0;g<e.length;g++){const p=e[g];if(p===n)break;const k=t.indexOf(p);if(k===-1)throw new Error(`Invalid character: ${p}`);d=d<<Math.log2(s)|k,o+=Math.log2(s),o>=8&&(o-=8,f.push(d>>o&255))}return new Uint8Array(f)}function Is(e,t){const n=t.length;let s=0,o=0,d="";for(let f=0;f<e.length;f++)for(o=o<<8|e[f],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 Xc(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 Jc(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function eu(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 f=n[d];if(f.startsWith(":"))o[f.slice(1)]=s[d];else if(f!==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 tu(e,t,n,s=Math.random){const o=a.Arrays.shuffle(t.map(f=>({variants:a.Arrays.shuffle(f.variants.map(g=>g),s),avoid:f.avoid})),s),d=[];for(const f of o){const g=f.variants.filter(k=>k!==f.avoid),p=g.find(k=>e.includes(k));if(p&&(jt(d,vr(e,p,g)),d.length>=n))break}if(d.length<n)for(const f of o){const g=f.variants.find(p=>e.includes(p));if(g&&(jt(d,vr(e,g,f.variants)),d.length>=n))break}return d.slice(0,n)}function ru(e,t,n,s=!1){const o=new RegExp(s?`(?<=\\s|^)${t}(?=\\s|$)`:`\\b${t}\\b`,"g");return e.replace(o,n)}function nu(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 su(e){return e.replace(/<[^>]*>/g,"")}function Ms(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 iu(e,t={}){return[...e].reduce((n,s)=>n+(t[s]||1),0)}function au(e,t,n={}){const s=[];let o="",d=0;for(let f=0;f<e.length;f++){const g=e[f],p=n[g]||1;if(o+=g,d+=p,d>t){const{line:k,rest:$}=Ms(o);s.push(k),o=$,d=$.split("").map(U=>n[U]||1).reduce((U,ze)=>U+ze,0)}}return o&&s.push(o),s}function ou(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 cu(e,t,n){return n==="any"?t.some(s=>wr(e,s)):t.every(s=>wr(e,s))}function uu(e){const t={},n=e.match(/([a-z\-]+)="([^"]+)"/g);if(n)for(const s of n){const[o,d]=pr(s,"=");t[o]=d.slice(1,d.length-1)}return t}function Pt(e,t,n=[]){let s="";for(;t<e.length&&(lt(e[t])||n.includes(e[t]));)s+=e[t++];return s}function lu(e,t,n="$",s=":"){for(const o in t)e=$s(e,o,t[o],n,s);return e=Rs(e),e}function $s(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 f=Pt(e,d+t.length+2,["_"]);e=e.replace(`${s}${t}${o}${f}`,n)}else e=e.replace(`${s}${t}`,n);d=e.indexOf(`${s}${t}`,d+n.length)}return e}function Rs(e,t="$",n=":"){let s=e.indexOf(t);for(;s!==-1;){const o=Pt(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=Pt(e,s+o.length+2);e=e.replace(`${t}${o}${n}${d}`,d)}s=e.indexOf(t,s+1)}return e}function du(e,t){let n=e.indexOf("](");for(;n!==-1;){const s=ks(e,"[",n),o=e.indexOf(")",n);if(s!==-1&&o!==-1){const[d,f]=e.slice(s+1,o).split("]("),g=t(d,f);e=e.slice(0,s)+g+e.slice(o+1)}n=e.indexOf("](",n+1)}return e}function Cs(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 fu(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 hu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function mu(e,t){let n=null,s=-1/0;for(const[o,d]of Object.entries(e)){const f=t(d);f>s&&(s=f,n=o)}return n?[n,e[n]]:null}function pu(e,t,n,s){const o=e.find(f=>f[t]===n),d=e.find(f=>f[t]===n+s);o&&d?(o[t]=n+s,d[t]=n):o&&(o[t]=n+s),e.sort((f,g)=>Ct(f[t])-Ct(g[t])),e.forEach((f,g)=>f[t]=g+1)}function gu(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 yu(e,t=":"){return Object.fromEntries(e.map(n=>pr(n,t)).map(n=>n[0]&&n[1]?[ut(n[0]),ut(n[1])]:null).filter(n=>n))}function vu(e,t,n){return Us(e,t)+Cs(n||{})}function wu(e,t=",",n='"'){const s=[];let o="",d=!1;const f=e.split("");for(const g of f)g===t&&!d?(s.push(o),o=""):g===n&&(!o&&!d||d)?d=!d:o+=g;return s.push(o),s}function _u(e){return`[${Math.floor(e.progress*100)}%] ${Zt(e.deltaMs)} out of ${Zt(e.totalTimeMs)} (${Zt(e.remainingTimeMs)} left) [${Math.round(e.baseTimeMs)} ms each]`}async function bu(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 xu(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 ku(e){return JSON.parse(JSON.stringify(e))}function Eu(e){return Math.ceil((e||Date.now())/1e3)}function Su(e){return(e||new Date).toISOString().slice(0,10)}function Tu(e){return(e||new Date).toISOString().slice(0,19).replace(/T|:/g,"-")}function Au(e){const t=new Date(e);return new Date(t.getTime()-t.getTimezoneOffset()*6e4)}function Ou(e){return new Date(e)}function ee(e){return String(Math.floor(e)).padStart(2,"0")}function Iu(e){let[t,n]=e.split(":");pe(parseInt(t,10))||(t="0"),pe(parseInt(n,10))||(n="0");let s=Er(dr(t),0,23),o=Er(dr(n),0,59);return`${ee(s)}:${ee(o)}`}function Zt(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?`${ee(t)}:${ee(n)}:${ee(s)}`:`${ee(n)}:${ee(s)}`}function Te(e){return Math.floor((Ue(e)?e.getTime():e)/864e5)}const Mu={today:(e,t)=>ee(e)+":"+ee(t),yesterday:()=>"Yesterday",monday:()=>"Mon",tuesday:()=>"Tue",wednesday:()=>"Wed",thursday:()=>"Thu",friday:()=>"Fri",saturday:()=>"Sat",sunday:()=>"Sun",weeks:e=>`${e}w`};function $u(e,t){const n=new Date((t==null?void 0:t.now)||Date.now()),s=(t==null?void 0:t.labels)||Mu,o=Ue(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=br(o);return Te(n)-Te(o)<7?s[d.day]():s.weeks(Math.round((n.getTime()-o.getTime())/6048e5))}const Ns={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 js(e,t){const n=(t==null?void 0:t.now)??Date.now(),s=(t==null?void 0:t.labels)||Ns,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 Ru(e,t=Ns){return js(0,{now:e*1e3,labels:t})}function Cu(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 _r={};function Nu(e,t){return!_r[e]||Date.now()>_r[e]?(_r[e]=Date.now()+t,!0):!1}const ju={s:1e3,m:6e4,h:36e5,d:864e5};function Du(e,t,n){return t=Ue(t)?t.getTime():t,n=n?Ue(n)?n.getTime():n:Date.now(),(n-t)/ju[e]}function Uu(e,t,n,s){s||(s=Date.now());const o=t/n,d=s-e,f=d/t,g=f*n,p=g-d;return{deltaMs:d,progress:o,baseTimeMs:f,totalTimeMs:g,remainingTimeMs:p}}const Pu={0:"sunday",1:"monday",2:"tuesday",3:"wednesday",4:"thursday",5:"friday",6:"saturday"};function Ds(e){return{zeroBasedIndex:e,day:Pu[e]}}function br(e){return Ds(e.getDay())}function Zu(e){return br(new Date(e))}function Bu(e){return e*1e3}function Lu(e){return e*6e4}function zu(e){return e*36e5}function Fu(e){return e*864e5}const Vu={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 Wu(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=Vu[n];if(!s)throw Error(`Unknown unit: "${n}"`);return t*s}const Hu={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 qu(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=Hu[n];if(!s)throw Error(`Unknown unit: "${n}"`);return t*s}function Gu(e){return e.replace(/ +/g," ").replace(/^ /gm,"")}const xr={};async function Ku(e,t,n){const s=Date.now(),o=xr[e];if(o&&o.validUntil>s)return o.value;const d=await n(),f=s+t;return xr[e]={value:d,validUntil:f},d}function Yu(e){delete xr[e]}function Us(...e){return e.filter(t=>t).join("/").replace(new RegExp("(?<!:)\\/+","g"),"/")}function Qu(e,t,n,s,o=!0){const d=e.indexOf(t),f=e.indexOf(n,d+t.length);if(d===-1||f===-1)throw Error("Start or end not found");return o?e.substring(0,d+t.length)+s+e.substring(f):e.substring(0,d)+s+e.substring(f+n.length)}function Xu(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 Ju(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 el(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 Ps(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 Zs(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)?Zs(e):me(e)?Ps(e):e}function Bs(e,t){return JSON.stringify(Ae(e))===JSON.stringify(Ae(t))}function tl(...e){for(let t=1;t<e.length;t++)if(!Bs(e[t-1],e[t]))return!1;return!0}function rl(e){try{return JSON.parse(e)}catch{return null}}function nl(){let e=0;return{next:()=>e++}}function sl(e){let t=0;return{next:()=>e[t++%e.length]}}function il(e){let t;return n=>{const s=n===e&&t!==e;return t=n,s}}function al(e,t,n,s,o){const d={};for(const f of Object.keys(t))d[f]=[];d[s]=[],o&&(e=e.sort(o));for(const f of e){const g=f[n],p=t[g]?g:s;d[p].length>=t[p]?d[s].push(f):d[p].push(f)}return d}function ol(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 Ls(e){const t=Object.keys(e);return t[Math.floor(Math.random()*t.length)]}function cl(e,t){const n=Ls(e);return e[n]=t(e[n]),n}function ul(e){return e=e.replace(/\r\n/g,`
10
+ `),e=e.replace(/(\w+)\((.+)\)/g,(t,n,s)=>`${n}(${s.replaceAll(",","&comma;")})`),e=e.replace(/(,)(\s+})/g,"$2"),e=e.replace(/\.\.\..+?,/g,""),e=e.replace(/({\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/(,\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/:(.+)\?(.+):/g,(t,n,s)=>`: (${n.trim()} && ${s.trim()}) ||`),e=e.replace(/([a-zA-Z0-9]+)( ?: ?{)/g,'"$1"$2'),e=e.replace(/([a-zA-Z0-9]+) ?: ?(.+?)(,|\n|})/g,(t,n,s,o)=>`"${n}":"${s.trim()}"${o}`),e=e.replace(/("'|'")/g,'"'),e=e.replaceAll("&comma;",","),JSON.parse(e)}const ge=[1e3,1e6,1e9,1e12,1e15,1e18,1e21,1e24,1e27,1e30,1e9,1e16,1e18,1e18,1e18,1e33],ll=["thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion","gwei","bzz","btc","eth","dai","decillion"],zs=["K","M","B","T","Qa","Qi","Sx","Sp","O","N","gwei","bzz","eth","btc","dai","D"];function dl(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 fl(e,t){const n=(t==null?void 0:t.longForm)??!1,s=t!=null&&t.unit?` ${t.unit}`:"",o=n?ll:zs,d=(t==null?void 0:t.precision)??1;if(e<ge[0])return`${e}${s}`;for(let f=0;f<ge.length-1;f++)if(e<ge[f+1])return`${(e/ge[f]).toFixed(d)}${n?" ":""}${o[f]}${s}`;return`${(e/ge[ge.length-1]).toFixed(d)}${n?" ":""}${o[ge.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=zs.findIndex(o=>o.toLowerCase()===n.toLowerCase());return s===-1?t:t*ge[s]}function Er(e,t,n){return e<t?t:e>n?n:e}function hl(e,t,n){const s=e+t;return s>n?n:s}function ml(e,t,n){const s=e-t;return s<n?n:s}function pl(e,t){return t(e),e}function gl(e,t){e&&t(e)}function yl(e,t){const n=Object.keys(t);for(const s of n)Array.isArray(t[s])&&Array.isArray(e[s])&&jt(e[s],t[s])}function vl(e){return e.splice(0,e.length),e}function wl(e){for(const t of Object.keys(e))(ts(e[t])||Array.isArray(e[t])&&e[t].every(n=>n==null))&&delete e[t];return e}function _l(e){for(const t of Object.entries(e))(t[1]===null||t[1]===void 0||W(t[1])&&Rt(t[1]))&&delete e[t[0]];return e}function bl(e,t){const n={};for(const[s,o]of Object.entries(e))t(s)&&(n[s]=o);return n}function xl(e,t){const n={};for(const[s,o]of Object.entries(e))t(o)&&(n[s]=o);return n}function kl(e,t){const n={};for(const s of Object.entries(e))n[s[0]]=t(s[1]);return n}function El(e,t){const n=[];let s=0;for(const o of e)n.push(t(o,s++));return n}async function Sl(e,t){try{return await e()}catch{throw t}}function Tl(e,t,n){n!=null&&(e[t]=n)}function Al(e,t,n,s){const o=ke(n,s);o!=null&&Ee(e,t,o)}function Ol(e){const t={};for(const[n,s]of Object.entries(e))t[s]=n;return t}function Il(e){const t=Object.keys(e),n=t.map(g=>e[g].length),s=n.reduce((g,p)=>g*=p);let o=1;const d=[1];for(let g=0;g<n.length-1;g++)o*=n[g],d.push(o);const f=[];for(let g=0;g<s;g++){const p={};for(let k=0;k<t.length;k++){const $=e[t[k]],U=Math.floor(g/d[k])%$.length;p[t[k]]=$[U]}f.push(p)}return f}function Ml(e){return Object.values(e).filter(t=>t).length}function $l(e,t,n){return e+(n?"["+t+"]":(e.length?".":"")+t)}function Bt(e,t,n,s,o){if(!me(t))return t;for(const[d,f]of Object.entries(t)){const g=$l(n,d,s);Array.isArray(f)?o?Bt(e,f,g,!0,o):e[g]=f.map(p=>Bt(Array.isArray(p)?[]:{},p,"",!1,o)):me(f)?Bt(e,f,g,!1,o):e[g]=f}return e}function Rl(e,t=!1,n){return Bt({},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 Cl(e,t,n){return t[e]?t[e]:n}function Vs(e,t){const n={};for(const s of e){const o=t(s);n[o]=s}return n}function Nl(e,t){const n={};for(const s of e){const o=t(s);n[o]||(n[o]=[]),n[o].push(s)}return n}function jl(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function Ws(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 Hs(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 Dl(e,t){const n=Math.ceil(e.length/t);return Hs(e,n)}function Ul(e,t){return Object.values(Vs(e,t))}function Pl(e,t,n,s,o){const d=t?e.map(t):e,f={};for(const p of d)f[p]=(f[p]||0)+1;const g=s?qs(f,o?(p,k)=>p[1]-k[1]:(p,k)=>k[1]-p[1]):f;return n?Object.keys(g):g}function qs(e,t){return Object.fromEntries(Object.entries(e).sort(t))}function Zl(e){const t=[],n=Object.keys(e),s=e[n[0]].length;for(let o=0;o<s;o++){const d={};for(const f of n)d[f]=e[f][o];t.push(d)}return t}function Bl(e,t,n=1){for(const s of e)s[t]+=n}function Ll(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 zl(){return{map:new Map,keys:[]}}function Fl(){return{map:new Map,keys:[]}}function Gs(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 Vl(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 Wl(e,t,n,s,o=100){Gs(e,t,{validUntil:Date.now()+s,data:n},o)}function Hl(e,t){const n=e.map.get(t);return n&&n.validUntil>Date.now()?n.data:null}class ye{constructor(t){this.value=t}static of(t){return new ye(t)}static empty(){return new ye(null)}map(t){return new ye(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=>ye.of(n)):Promise.resolve(ye.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=ye;class ql{constructor(t){this.supplier=t,this.value=null}get(){return this.value||(this.value=this.supplier()),this.value}}a.Lazy=ql;class Gl{constructor(t){this.supplier=t,this.value=null}async get(){return this.value||(this.value=await this.supplier()),this.value}}a.AsyncLazy=Gl;function Kl(e){return()=>e.forEach(t=>t())}function Yl(e,t){return e.reduce((n,s)=>t(n)>t(s)?n:s)}function Ql(e,t){const n=e.find(s=>s instanceof t);return ye.of(n)}function Xl(e,t){return e.filter(n=>n instanceof t)}function Jl(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 ed(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}class td{constructor(t){this.value=t,this.children=[]}}function rd(e,t,n,s,o=!1){const d=new Map,f=[];e.forEach(p=>{const k=new td(p);d.set(p[t],k)}),e.forEach(p=>{const k=d.get(p[t]);if(!k)return;const $=p[n];if($){const U=d.get($);U&&U.children.push(k)}else f.push(k)});const g=p=>{p.children.sort((k,$)=>{const U=k.value[s],ze=$.value[s];return o?ze-U:U-ze}),p.children.forEach(g)};return f.forEach(g),f}function Ks(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 Ys(e){return e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}function Qs(e){return e[0]===255&&e[1]===216}function Xs(e){return e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function nd(e){return Ys(e)||Qs(e)||Xs(e)}function sd(e){return new Uint8Array([e])}function id(e){return e[0]}function ad(e,t){const n=new ArrayBuffer(2);return new DataView(n).setUint16(0,e,t==="LE"),new Uint8Array(n)}function od(e,t){return new DataView(e.buffer).getUint16(e.byteOffset,t==="LE")}function cd(e,t){const n=new ArrayBuffer(4);return new DataView(n).setUint32(0,e,t==="LE"),new Uint8Array(n)}function ud(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 ld(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 dd(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 Js=[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 fd(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],f=e[4]^e[14]^e[24]^e[34]^e[44],g=e[5]^e[15]^e[25]^e[35]^e[45],p=e[6]^e[16]^e[26]^e[36]^e[46],k=e[7]^e[17]^e[27]^e[37]^e[47],$=e[8]^e[18]^e[28]^e[38]^e[48],U=e[9]^e[19]^e[29]^e[39]^e[49],ze=o<<1|d>>>31,Gd=d<<1|o>>>31,ht=$^ze,mt=U^Gd,Kd=f<<1|g>>>31,Yd=g<<1|f>>>31,pt=n^Kd,gt=s^Yd,Qd=p<<1|k>>>31,Xd=k<<1|p>>>31,yt=o^Qd,vt=d^Xd,Jd=$<<1|U>>>31,ef=U<<1|$>>>31,wt=f^Jd,_t=g^ef,tf=n<<1|s>>>31,rf=s<<1|n>>>31,bt=p^tf,xt=k^rf;e[0]^=ht,e[1]^=mt,e[2]^=pt,e[3]^=gt,e[4]^=yt,e[5]^=vt,e[6]^=wt,e[7]^=_t,e[8]^=bt,e[9]^=xt,e[10]^=ht,e[11]^=mt,e[12]^=pt,e[13]^=gt,e[14]^=yt,e[15]^=vt,e[16]^=wt,e[17]^=_t,e[18]^=bt,e[19]^=xt,e[20]^=ht,e[21]^=mt,e[22]^=pt,e[23]^=gt,e[24]^=yt,e[25]^=vt,e[26]^=wt,e[27]^=_t,e[28]^=bt,e[29]^=xt,e[30]^=ht,e[31]^=mt,e[32]^=pt,e[33]^=gt,e[34]^=yt,e[35]^=vt,e[36]^=wt,e[37]^=_t,e[38]^=bt,e[39]^=xt,e[40]^=ht,e[41]^=mt,e[42]^=pt,e[43]^=gt,e[44]^=yt,e[45]^=vt,e[46]^=wt,e[47]^=_t,e[48]^=bt,e[49]^=xt;const Cr=e[0],Nr=e[1],jr=e[2]<<1|e[3]>>>31,Dr=e[3]<<1|e[2]>>>31,Ur=e[5]<<30|e[4]>>>2,Pr=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,Fr=e[11]<<4|e[10]>>>28,Vr=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,mn=e[34]<<15|e[35]>>>17,pn=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,_n=e[40]<<18|e[41]>>>14,bn=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&_n,e[25]=on^~wn&bn,e[26]=vn^~_n&jr,e[27]=wn^~bn&Dr,e[28]=_n^~jr&qr,e[29]=bn^~Dr&Gr,e[30]=Lr^~Fr&tn,e[31]=zr^~Vr&rn,e[32]=Fr^~tn&mn,e[33]=Vr^~rn&pn,e[34]=tn^~mn&Tn,e[35]=rn^~pn&An,e[36]=mn^~Tn&Lr,e[37]=pn^~An&zr,e[38]=Tn^~Lr&Fr,e[39]=An^~zr&Vr,e[40]=Ur^~Kr&cn,e[41]=Pr^~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&Ur,e[47]=dn^~kn&Pr,e[48]=xn^~Ur&Kr,e[49]=kn^~Pr&Yr,e[0]^=Js[t*2],e[1]^=Js[t*2+1]}}function ei(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 ti(e,t){if(!e.length){const o=new Uint8Array(136);return o[0]=t,o[135]=128,[ei(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(ei)}function ri(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];fd(e)}return e}function ni(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 ni(ri(new Array(50).fill(0),ti(e,1)))}function hd(e){return ni(ri(new Array(50).fill(0),ti(e,6)))}function md(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 f=0;f<8;f++)if(d>>7-f&1)return o*8+f}return n}function pd(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 gd(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 yd(e,t,n){const s=Math.floor(t/8),o=t%8;return e[s]>>(n==="BE"?7-o:o)&1}function vd(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 si(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 wd(e,t,n=0){const s=e.length%t;return s===0?e:si(e,e.length+t-s,n)}function ii(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 _d(e,t,n=0){const s=e.length%t;return s===0?e:ii(e,e.length+t-s,n)}function bd(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 xd(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 dt(e,t){e=R(e,t);let[n,s]=[0n,1n],[o,d]=[t,e];for(;d!==0n;){const f=o/d;[n,s]=[s,n-f*s],[o,d]=[d,o-f*d]}if(o>1n)throw new Error("a is not invertible");return n<0n&&(n+=t),n}function kd(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 ai(e,t){return R(e,t)===0n?0n:t%4n===3n?kd(e,(t+1n)/4n,t):null}const z=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,D=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Lt=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,zt=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;function Or(e,t,n){if(t===0n)return[0n,0n];const s=R(3n*e*e*dt(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)*dt(n-e,o),o),f=R(d*d-e-n,o),g=R(d*(e-f)-t,o);return[f,g]}function Ed(e){if(e<=0n||e>=D)throw new Error("Invalid private key");return Oe(Lt,zt,e,z)}function Sd(e){const t=e[1]%2n===0n?2:3;return new Uint8Array([t,...Be(e[0],"BE")])}function Td(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=ai(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 Ad(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 Od(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 f=n.toString(2);for(const g of f)g==="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 Id(e,t,n){return oi(Le(ue(e),"BE"),t,n)}function oi(e,t,n){if(t<=0n||t>=D)throw new Error("Invalid private key");if(n||(n=R(Le(ue(Ze(ue(Be(t,"BE")),Be(e,"BE"))),"BE"),D)),n<=0n||n>=D)throw new Error("Invalid nonce");const s=R(e,D),o=Oe(Lt,zt,n,z),d=R(o[0],D);let f=R((s+R(d,D)*t)*dt(n,D),D);if(d===0n||f===0n)throw new Error("Invalid r or s value");let g=o[1]%2n===0n?27n:28n;return f>D/2n&&(f=D-f,g=g===27n?28n:27n),[d,f,g]}function Md(e,t,n,s){const o=ai(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,f=o%2n===d?o:z-o,g=R(Le(ue(e),"BE"),D),p=Oe(t,f,n,z),k=Oe(Lt,zt,g,z),$=Ft(p[0],p[1],k[0],R(-k[1],z),z);return Oe($[0],$[1],dt(t,D),z)}function $d(e,t,n,s){const o=R(Le(ue(e),"BE"),D),d=dt(s,D),f=R(o*d,D),g=R(n*d,D),p=Oe(Lt,zt,f,z),k=Oe(t[0],t[1],g,z),$=Ft(p[0],p[1],k[0],k[1],z);return n===R($[0],D)}class ci{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=ci;class ui{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=ui;class Vt{constructor(t,n=0n){this.span=n,this.writer=new ui(new Uint8Array(t))}build(){return Ze(Tr(this.span,"LE"),this.writer.buffer)}hash(){const t=Ks(Ar(this.writer.buffer,32),(n,s)=>ue(Ze(n,s)));return ue(Ze(Tr(this.span,"LE"),t))}}a.Chunk=Vt;class Ir{constructor(t,n=4096){this.counters=[1],this.capacity=n,this.chunks=[new Vt(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 ci(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 Vt(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 Vt(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 te{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 te(BigInt(s+o),n)}add(t){return this.assertSameScale(t),new te(this.value+t.value,this.scale)}subtract(t){return this.assertSameScale(t),new te(this.value-t.value,this.scale)}multiply(t){return new te(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 te(n,this.scale),new te(s,this.scale)]}exchange(t,n,s){if(t==="*"){const d=this.value*n.value/10n**BigInt(this.scale);return new te(d,s)}this.assertSameScale(n);const o=this.value*10n**BigInt(s)/n.value;return new te(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=te;function Rd(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 Wt(e,t,n,s){const o=e.findIndex(g=>g===`--${t}`||g.startsWith(`--${t}=`)),d=e[o];if(!d)return(n||{})[s||t||""]||null;if(d.includes("="))return d.split("=")[1];const f=e[o+1];return f&&!f.startsWith("-")?f:(n||{})[s||t||""]||null}function Cd(e,t,n,s){const o=Wt(e,t,n,s);if(!o)return null;try{return kr(o)}catch{throw new Error(`Invalid number argument ${t}: ${o}`)}}function Nd(e,t,n,s){const o=e.some(p=>p.endsWith("-"+t)),d=Wt(e,t,n,s);if(!d&&o)return!0;if(!d&&!o)return null;const f=["true","1","yes","y","on"],g=["false","0","no","n","off"];if(f.includes(d.toLowerCase()))return!0;if(g.includes(d.toLowerCase()))return!1;throw Error(`Invalid boolean argument ${t}: ${d}`)}function li(e,t,n,s){const o=Wt(e,t,n,s);if(!o)throw new Error(`Missing argument ${t}`);return o}function jd(e,t,n,s){const o=li(e,t,n,s);try{return kr(o)}catch{throw new Error(`Invalid argument ${t}: ${o}`)}}function di(e,t){const n=e[t];e.splice(t,1),e.unshift(n)}function Dd(e,t){const n=[...e];return di(n,t),n}function fi(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Ud(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 Pd(e){const t=Math.sqrt(e.x*e.x+e.y*e.y);return{x:e.x/t,y:e.y/t}}function hi(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 ft(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 Zd(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 Bd(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 pi(e,t,n){var s;return!((s=e[t-1])!=null&&s[n])}function gi(e,t,n){var s;return!((s=e[t+1])!=null&&s[n])}function yi(e,t,n){return!e[t][n-1]}function vi(e,t,n){return!e[t][n+1]}function Ld(e,t,n){var o,d,f,g,p,k,$,U;const s=[];return e[t][n]?Zd(e,t,n)||Bd(e,t,n)?[]:(!((o=e[t-1])!=null&&o[n-1])&&pi(e,t,n)&&yi(e,t,n)&&s.push({x:t,y:n}),!((d=e[t+1])!=null&&d[n-1])&&gi(e,t,n)&&yi(e,t,n)&&s.push({x:t+1,y:n}),!((f=e[t-1])!=null&&f[n+1])&&pi(e,t,n)&&vi(e,t,n)&&s.push({x:t,y:n+1}),!((g=e[t+1])!=null&&g[n+1])&&gi(e,t,n)&&vi(e,t,n)&&s.push({x:t+1,y:n+1}),s):((p=e[t-1])!=null&&p[n]&&e[t][n-1]&&s.push({x:t,y:n}),(k=e[t+1])!=null&&k[n]&&e[t][n-1]&&s.push({x:t+1,y:n}),($=e[t-1])!=null&&$[n]&&e[t][n+1]&&s.push({x:t,y:n+1}),(U=e[t+1])!=null&&U[n]&&e[t][n+1]&&s.push({x:t+1,y:n+1}),s)}function zd(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 f=0;f<e[0].length;f++){const g=Ld(e,d,f);for(const p of g)o.some(k=>k.x===p.x&&k.y===p.y)||o.push(p)}return o.map(d=>({x:d.x*t,y:d.y*t}))}function Fd(e,t){const n=ft(e,(p,k)=>e[p][k]===0&&e[p][k+1]!==0,"row-first").map(p=>({...p,dx:1,dy:0})),s=ft(e,(p,k)=>e[p][k]===0&&e[p][k-1]!==0,"row-first").map(p=>({...p,dx:1,dy:0})),o=ft(e,(p,k)=>{var $;return e[p][k]===0&&(($=e[p-1])==null?void 0:$[k])!==0},"column-first").map(p=>({...p,dx:0,dy:1})),d=ft(e,(p,k)=>{var $;return e[p][k]===0&&(($=e[p+1])==null?void 0:$[k])!==0},"column-first").map(p=>({...p,dx:0,dy:1}));n.forEach(p=>p.y++),d.forEach(p=>p.x++);const f=Sr([...o,...d],(p,k)=>p.x===k.x&&p.y-1===k.y),g=Sr([...s,...n],(p,k)=>p.y===k.y&&p.x-1===k.x);return[...f,...g].map(p=>({start:p[0],end:ot(p)})).map(p=>({start:Mr(p.start,t),end:Mr(fi(p.end,{x:p.start.dx,y:p.start.dy}),t)}))}function Vd(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}function Wd(e,t){return t.map(n=>Vd(e,n)).sort((n,s)=>n-s)}function wi(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,f=e.x-n.x;const g=(s.x-n.x)*d-(s.y-n.y)*f,p=(t.x-e.x)*d-(t.y-e.y)*f;return d=g/o,f=p/o,d>0&&d<1&&f>0&&f<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=hi(e,n,1e4);for(const d of t){const f=wi(e,o,d.start,d.end);f&&s.push(f)}return s.length?s.reduce((d,f)=>{const g=mi(e,f),p=mi(e,d);return g<p?f:d}):null}function Hd(e,t,n){const s=Wd(e,n),o=[];for(const d of s){const f=$r(e,t,d-.001),g=$r(e,t,d+.001);f&&o.push(f),g&&o.push(g)}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 qd{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=qd,a.Binary={hexToUint8Array:Xc,uint8ArrayToHex:Jc,base64ToUint8Array:Gc,uint8ArrayToBase64:Kc,base32ToUint8Array:Yc,uint8ArrayToBase32:Qc,log2Reduce:Ks,partition:Ar,concatBytes:Ze,numberToUint8:sd,uint8ToNumber:id,numberToUint16:ad,uint16ToNumber:od,numberToUint32:cd,uint32ToNumber:ud,numberToUint64:Tr,uint64ToNumber:ld,numberToUint256:Be,uint256ToNumber:Le,sliceBytes:dd,keccak256:ue,sha3_256:hd,proximity:md,commonPrefix:pd,setBit:gd,getBit:yd,indexOf:vd,equals:xd,padStart:si,padStartToMultiple:wd,padEnd:ii,padEndToMultiple:_d,xorCypher:bd},a.Elliptic={privateKeyToPublicKey:Ed,compressPublicKey:Sd,publicKeyFromCompressed:Td,publicKeyToAddress:Ad,signMessage:Id,signHash:oi,verifySignature:$d,recoverPublicKey:Md,checksumEncode:Od},a.Random={intBetween:at,floatBetween:Xn,chance:Jn,signed:Wa,makeSeededRng:sr,point:qa,procs:Ga},a.Arrays={countUnique:Pl,makeUnique:Ul,splitBySize:jl,splitByCount:Ws,index:Vs,indexCollection:Nl,onlyOrThrow:m,onlyOrNull:w,firstOrThrow:E,firstOrNull:v,shuffle:h,initialize:j,initialize2D:ce,rotate2D:oe,containsShape:it,glue:nc,pluck:nr,pick:ir,pickMany:Ka,pickManyUnique:Ya,pickWeighted:Ja,pickRandomIndices:je,pickGuaranteed:Qa,last:ot,pipe:es,makePipe:Xa,sortWeighted:eo,pushAll:jt,unshiftAll:tc,filterAndRemove:xu,merge:yl,empty:vl,pushToBucket:Xo,unshiftAndLimit:Jo,atRolling:ec,group:Sr,createOscillator:sl,organiseWithLimits:al,tickPlaybook:Rd,getArgument:Wt,getBooleanArgument:Nd,getNumberArgument:Cd,requireStringArgument:li,requireNumberArgument:jd,bringToFront:Dd,bringToFrontInPlace:di,findInstance:Ql,filterInstances:Xl,interleave:Jl,toggle:ed,createHierarchy:rd,multicall:Kl,maxBy:Yl},a.System={sleepMillis:l,forever:ao,scheduleMany:lc,waitFor:bu,expandError:Go,runAndSetInterval:oo},a.Numbers={make:kr,sum:fc,average:hc,median:mc,getDistanceFromMidpoint:pc,clamp:Er,range:hs,interpolate:dc,createSequence:nl,increment:hl,decrement:ml,format:fl,fromDecimals:dl,makeStorage:qu,asMegabytes:co,convertBytes:uo,hexToRgb:lo,rgbToHex:fo,haversineDistanceToMeters:ho,roundToNearest:$t,formatDistance:mo,triangularNumber:po,searchFloat:go},a.Promises={raceFulfilled:c,invert:i,runInParallelBatches:u},a.Dates={getTimestamp:$u,getTimeDelta:js,secondsToHumanTime:Ru,countCycles:Cu,isoDate:Su,throttle:Nu,timeSince:Du,dateTimeSlug:Tu,unixTimestamp:Eu,fromUtcString:Au,fromMillis:Ou,getProgress:Uu,humanizeTime:Zt,humanizeProgress:_u,createTimeDigits:ee,mapDayNumber:Ds,getDayInfoFromDate:br,getDayInfoFromDateTimeString:Zu,seconds:Bu,minutes:Lu,hours:zu,days:Fu,make:Wu,normalizeTime:Iu,absoluteDays:Te},a.Objects={safeParse:rl,deleteDeep:no,getDeep:ke,setDeep:Ee,incrementDeep:to,ensureDeep:ro,replaceDeep:so,getFirstDeep:io,deepMergeInPlace:Se,deepMerge2:Ko,deepMerge3:Yo,mapAllAsync:rc,cloneWithJson:ku,sortObject:Ps,sortArray:Zs,sortAny:Ae,deepEquals:Bs,deepEqualsEvery:tl,runOn:pl,ifPresent:gl,zip:fs,zipSum:Qo,removeEmptyArrays:wl,removeEmptyValues:_l,flatten:Rl,unflatten:Fs,match:Cl,sort:qs,map:kl,mapIterable:El,filterKeys:bl,filterValues:xl,rethrow:Sl,setSomeOnObject:Tl,setSomeDeep:Al,flip:Ol,getAllPermutations:Il,countTruthyValues:Ml,transformToArray:Zl,setMulti:Ll,incrementMulti:Bl,createBidirectionalMap:zl,createTemporalBidirectionalMap:Fl,pushToBidirectionalMap:Gs,unshiftToBidirectionalMap:Vl,addToTemporalBidirectionalMap:Wl,getFromTemporalBidirectionalMap:Hl,createStatefulToggle:il,diffKeys:ol,pickRandomKey:Ls,mapRandomKey:cl,fromObjectString:ul,toQueryString:Cs,parseQueryString:fu,hasKey:hu,selectMax:mu,reposition:pu,unwrapSingleKey:gu,parseKeyValues:yu},a.Types={isFunction:or,isObject:me,isStrictlyObject:De,isEmptyArray:ts,isEmptyObject:yo,isUndefined:ar,isString:W,isNumber:pe,isBoolean:rs,isDate:Ue,isBlank:Rt,isId:cr,isIntegerString:ns,isHexString:ss,isUrl:ls,isNullable:Vo,asString:cs,asHexString:Mo,asSafeString:$o,asIntegerString:Io,asNumber:Ct,asFunction:Ro,asInteger:dr,asBoolean:Co,asDate:No,asNullableString:jo,asEmptiableString:Do,asId:Uo,asTime:Po,asArray:Zo,asObject:Nt,asNullableObject:Bo,asStringMap:Lo,asNumericDictionary:zo,asUrl:Fo,asNullable:Wo,asOptional:Ho,enforceObjectShape:ds,enforceArrayShape:qo,isPng:Ys,isJpg:Qs,isWebp:Xs,isImage:nd},a.Strings={tokenizeByCount:Dl,tokenizeByLength:Hs,searchHex:To,searchSubstring:Ao,randomHex:Oo,randomLetter:xo,randomAlphanumeric:ko,randomRichAscii:Eo,randomUnicode:So,includesAny:gc,slugify:fr,normalForm:vc,enumify:Ec,escapeHtml:Tc,decodeHtmlEntities:Oc,after:hr,afterLast:ps,before:ms,beforeLast:mr,betweenWide:Ic,betweenNarrow:Mc,getPreLine:Gu,containsWord:wr,containsWords:cu,joinUrl:Us,getFuzzyMatchScore:Dt,sortByFuzzyScore:Sc,splitOnce:pr,splitAll:gs,randomize:Nc,expand:ys,shrinkTrim:ut,capitalize:Ut,decapitalize:vs,csvEscape:Bc,parseCsv:wu,surroundInOut:kc,getExtension:gr,getBasename:yr,normalizeEmail:$c,normalizeFilename:Rc,parseFilename:Cc,camelToTitle:wc,slugToTitle:_c,slugToCamel:bc,joinHumanly:xc,findWeightedPair:Es,extractBlock:Ss,extractAllBlocks:Fc,replaceBlocks:Vc,indexOfEarliest:Pe,lastIndexOfBefore:ks,parseHtmlAttributes:uu,readNextWord:Pt,resolveVariables:lu,resolveVariableWithDefaultSyntax:$s,resolveRemainingVariablesWithDefaults:Rs,isLetter:ws,isDigit:_s,isLetterOrDigit:lt,isValidObjectPathCharacter:Uc,insert:Pc,indexOfRegex:bs,lineMatches:xs,linesMatchInOrder:Zc,represent:ct,resolveMarkdownLinks:du,buildUrl:vu,isChinese:yc,replaceBetweenStrings:Qu,describeMarkdown:Xu,isBalanced:Ju,textToFormat:el,splitFormatting:Wc,splitHashtags:Hc,splitUrls:qc,route:eu,explodeReplace:vr,generateVariants:tu,replaceWord:ru,replacePascalCaseWords:nu,stripHtml:su,breakLine:Ms,measureTextWidth:iu,toLines:au,levenshteinDistance:ou},a.Assertions={asEqual:sc,asTrue:ic,asTruthy:ac,asFalse:oc,asFalsy:cc,asEither:uc},a.Cache={get:Ku,invalidate:Yu},a.Vector={addPoint:fi,subtractPoint:Ud,multiplyPoint:Mr,normalizePoint:Pd,pushPoint:hi,filterCoordinates:ft,findCorners:zd,findLines:Fd,raycast:$r,raycastCircle:Hd,getLineIntersectionPoint:wi}})($n);const C=Ei($n);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 Si=C.MerkleTree;C.FixedPointNumber,C.Lazy,C.AsyncLazy,C.AsyncQueue,C.Uint8ArrayReader,C.Uint8ArrayWriter;const Ti=new TextEncoder,Rn=1,Cn=4096,qt=4096,Ai=32;function Nn(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 Oi(a){const r=a.slice(0,A.Span.LENGTH),i=a.slice(A.Span.LENGTH),c=Ii(i),u=B.keccak256(B.concatBytes(r,c));return new A.Reference(u)}function Ii(a){if(a.length>qt)throw new A.BeeArgumentError(`payload size ${a.length} exceeds maximum chunk payload size ${qt}`,a);const r=new Uint8Array(qt);return r.set(a),B.log2Reduce(B.partition(r,Ai),(i,c)=>B.keccak256(B.concatBytes(i,c)))}function jn(a){if(a instanceof Uint8Array||(a=Ti.encode(a)),a.length<Rn||a.length>Cn)throw new RangeError(`payload size ${a.length} exceeds limits [${Rn}, ${Cn}]`);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:Oi(i)}}function Mi(a,r){return new A.Reference(B.keccak256(B.concatBytes(a.toUint8Array(),r.toUint8Array())))}function Dn(a,r,i){r=new A.Identifier(r),i=new A.PrivateKey(i);const c=Mi(r,i.publicKey().address()),u=i.sign(B.concatBytes(r.toUint8Array(),a.address.toUint8Array())),l=B.concatBytes(r.toUint8Array(),u.toUint8Array(),a.data),h=A.Span.fromSlice(a.data,0),m=A.Bytes.fromSlice(a.data,A.Span.LENGTH);return{data:l,identifier:r,signature:u,span:h,payload:m,address:c,owner:i.publicKey().address()}}class Y{constructor(){}static getInstance(){return Y.instance||(Y.instance=new Y),Y.instance}formatMessage(r,...i){return`[${new Date().toISOString()}] [${r.toUpperCase()}] - ${i.map(u=>typeof u=="object"?JSON.stringify(u):u).join(" ")}`}log(...r){console.log(this.formatMessage("log",...r))}info(...r){console.info(this.formatMessage("info",...r))}warn(...r){console.warn(this.formatMessage("warn",...r))}error(...r){console.error(this.formatMessage("error",...r))}debug(...r){console.debug(this.formatMessage("debug",...r))}}class ne{constructor(){this.logger=Y.getInstance()}static getInstance(){return ne.instance||(ne.instance=new ne),ne.instance}handleError(r,i){const c=r instanceof Error?r.message:"Unknown error occurred",u=r instanceof Error?r.stack:null;this.logger.error(`Error in ${i||"unknown context"}: ${c}`,{stack:u})}}const $i=Y.getInstance(),Ri=ne.getInstance();function Ci(a){return new Promise(r=>{setTimeout(r,a)})}function Gt(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?($i.info(`Retrying... Attempts left: ${r}. Error: ${l.message}`),setTimeout(()=>{Kt(a,r-1,i).then(c).catch(u)},i)):(Ri.handleError(l,"Utils.retryAwaitableAsync"),u(l))})})}class Ni{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 h of u)l[h]=h;return l},a.getValidEnumValues=u=>{const l=a.objectKeys(u).filter(m=>typeof u[u[m]]!="number"),h={};for(const m of l)h[m]=u[m];return a.objectValues(h)},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 h in u)Object.prototype.hasOwnProperty.call(u,h)&&l.push(h);return l},a.find=(u,l)=>{for(const h of u)if(l(h))return h},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(h=>typeof h=="string"?`'${h}'`:h).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 b=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 b.undefined;case"string":return b.string;case"number":return isNaN(a)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(a)?b.array:a===null?b.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?b.promise:typeof Map<"u"&&a instanceof Map?b.map:typeof Set<"u"&&a instanceof Set?b.set:typeof Date<"u"&&a instanceof Date?b.date:b.object;default:return b.unknown}},y=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"]),ji=a=>JSON.stringify(a,null,2).replace(/"([^"]+)":/g,"$1:");class V 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 h of l.issues)if(h.code==="invalid_union")h.unionErrors.map(u);else if(h.code==="invalid_return_type")u(h.returnTypeError);else if(h.code==="invalid_arguments")u(h.argumentsError);else if(h.path.length===0)c._errors.push(i(h));else{let m=c,w=0;for(;w<h.path.length;){const v=h.path[w];w===h.path.length-1?(m[v]=m[v]||{_errors:[]},m[v]._errors.push(i(h))):m[v]=m[v]||{_errors:[]},m=m[v],w++}}};return u(this),c}static assert(r){if(!(r instanceof V))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()}}V.create=a=>new V(a);const Ie=(a,r)=>{let i;switch(a.code){case y.invalid_type:a.received===b.undefined?i="Required":i=`Expected ${a.expected}, received ${a.received}`;break;case y.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(a.expected,M.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:i=`Unrecognized key(s) in object: ${M.joinValues(a.keys,", ")}`;break;case y.invalid_union:i="Invalid input";break;case y.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${M.joinValues(a.options)}`;break;case y.invalid_enum_value:i=`Invalid enum value. Expected ${M.joinValues(a.options)}, received '${a.received}'`;break;case y.invalid_arguments:i="Invalid function arguments";break;case y.invalid_return_type:i="Invalid function return type";break;case y.invalid_date:i="Invalid date";break;case y.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 y.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 y.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 y.custom:i="Invalid input";break;case y.invalid_intersection_types:i="Intersection results could not be merged";break;case y.not_multiple_of:i=`Number must be a multiple of ${a.multipleOf}`;break;case y.not_finite:i="Number must be finite";break;default:i=r.defaultError,M.assertNever(a)}return{message:i}};let Un=Ie;function Di(a){Un=a}function kt(){return Un}const Et=a=>{const{data:r,path:i,errorMaps:c,issueData:u}=a,l=[...i,...u.path||[]],h={...u,path:l};if(u.message!==void 0)return{...u,path:l,message:u.message};let m="";const w=c.filter(v=>!!v).slice().reverse();for(const v of w)m=v(h,{data:r,defaultError:m}).message;return{...u,path:l,message:m}},Ui=[];function _(a,r){const i=kt(),c=Et({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,h=await u.value;c.push({key:l,value:h})}return L.mergeObjectSync(r,c)}static mergeObjectSync(r,i){const c={};for(const u of i){const{key:l,value:h}=u;if(l.status==="aborted"||h.status==="aborted")return T;l.status==="dirty"&&r.dirty(),h.status==="dirty"&&r.dirty(),l.value!=="__proto__"&&(typeof h.value<"u"||u.alwaysSet)&&(c[l.value]=h.value)}return{status:r.value,value:c}}}const T=Object.freeze({status:"aborted"}),Me=a=>({status:"dirty",value:a}),F=a=>({status:"valid",value:a}),Qt=a=>a.status==="aborted",Xt=a=>a.status==="dirty",ve=a=>a.status==="valid",Fe=a=>typeof Promise<"u"&&a instanceof Promise;function St(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 Pn(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 Ve,We;class Q{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 Zn=(a,r)=>{if(ve(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 V(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:(h,m)=>{var w,v;const{message:E}=a;return h.code==="invalid_enum_value"?{message:E??m.defaultError}:typeof m.data>"u"?{message:(w=E??c)!==null&&w!==void 0?w:m.defaultError}:h.code!=="invalid_type"?{message:m.defaultError}:{message:(v=E??i)!==null&&v!==void 0?v:m.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(Fe(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 Zn(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 ve(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=>ve(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(Fe(u)?u:Promise.resolve(u));return Zn(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 h=r(u),m=()=>l.addIssue({code:y.custom,...c(u)});return typeof Promise<"u"&&h instanceof Promise?h.then(w=>w?!0:(m(),!1)):h?!0:(m(),!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 G({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 J.create(this,this._def)}nullable(){return he.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return q.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 G({...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 Pi=/^c[^\s-]{8,}$/i,Zi=/^[0-9a-z]+$/,Bi=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Li=/^[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,zi=/^[a-z0-9_-]{21}$/i,Fi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Vi=/^[-+]?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)?)??$/,Wi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Hi="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Jt;const qi=/^(?:(?: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])$/,Gi=/^(?:(?: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])$/,Ki=/^(([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]))$/,Yi=/^(([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])$/,Qi=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Xi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Bn="((\\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])))",Ji=new RegExp(`^${Bn}$`);function Ln(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 ea(a){return new RegExp(`^${Ln(a)}$`)}function zn(a){let r=`${Bn}T${Ln(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 ta(a,r){return!!((r==="v4"||!r)&&qi.test(a)||(r==="v6"||!r)&&Ki.test(a))}function ra(a,r){if(!Fi.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 na(a,r){return!!((r==="v4"||!r)&&Gi.test(a)||(r==="v6"||!r)&&Yi.test(a))}class H extends I{_parse(r){if(this._def.coerce&&(r.data=String(r.data)),this._getType(r)!==b.string){const l=this._getOrReturnCtx(r);return _(l,{code:y.invalid_type,expected:b.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),_(u,{code:y.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),_(u,{code:y.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),c.dirty());else if(l.kind==="length"){const h=r.data.length>l.value,m=r.data.length<l.value;(h||m)&&(u=this._getOrReturnCtx(r,u),h?_(u,{code:y.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):m&&_(u,{code:y.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),c.dirty())}else if(l.kind==="email")Wi.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"email",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="emoji")Jt||(Jt=new RegExp(Hi,"u")),Jt.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"emoji",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="uuid")Li.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"uuid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="nanoid")zi.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"nanoid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid")Pi.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"cuid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid2")Zi.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"cuid2",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="ulid")Bi.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"ulid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="url")try{new URL(r.data)}catch{u=this._getOrReturnCtx(r,u),_(u,{validation:"url",code:y.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),_(u,{validation:"regex",code:y.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),_(u,{code:y.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),_(u,{code:y.invalid_string,validation:{startsWith:l.value},message:l.message}),c.dirty()):l.kind==="endsWith"?r.data.endsWith(l.value)||(u=this._getOrReturnCtx(r,u),_(u,{code:y.invalid_string,validation:{endsWith:l.value},message:l.message}),c.dirty()):l.kind==="datetime"?zn(l).test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{code:y.invalid_string,validation:"datetime",message:l.message}),c.dirty()):l.kind==="date"?Ji.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{code:y.invalid_string,validation:"date",message:l.message}),c.dirty()):l.kind==="time"?ea(l).test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{code:y.invalid_string,validation:"time",message:l.message}),c.dirty()):l.kind==="duration"?Vi.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"duration",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="ip"?ta(r.data,l.version)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"ip",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="jwt"?ra(r.data,l.alg)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"jwt",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="cidr"?na(r.data,l.version)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"cidr",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="base64"?Qi.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"base64",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="base64url"?Xi.test(r.data)||(u=this._getOrReturnCtx(r,u),_(u,{validation:"base64url",code:y.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:y.invalid_string,...x.errToObj(c)})}_addCheck(r){return new H({...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 H({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new H({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new H({...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}}H.create=a=>{var r;return new H({checks:[],typeName:S.ZodString,coerce:(r=a==null?void 0:a.coerce)!==null&&r!==void 0?r:!1,...O(a)})};function sa(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(".","")),h=parseInt(r.toFixed(u).replace(".",""));return l%h/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)!==b.number){const l=this._getOrReturnCtx(r);return _(l,{code:y.invalid_type,expected:b.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),_(c,{code:y.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),_(c,{code:y.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),_(c,{code:y.too_big,maximum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),u.dirty()):l.kind==="multipleOf"?sa(r.data,l.value)!==0&&(c=this._getOrReturnCtx(r,c),_(c,{code:y.not_multiple_of,multipleOf:l.value,message:l.message}),u.dirty()):l.kind==="finite"?Number.isFinite(r.data)||(c=this._getOrReturnCtx(r,c),_(c,{code:y.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)!==b.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),_(c,{code:y.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),_(c,{code:y.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),_(c,{code:y.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 _(i,{code:y.invalid_type,expected:b.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)!==b.boolean){const c=this._getOrReturnCtx(r);return _(c,{code:y.invalid_type,expected:b.boolean,received:c.parsedType}),T}return F(r.data)}}He.create=a=>new He({typeName:S.ZodBoolean,coerce:(a==null?void 0:a.coerce)||!1,...O(a)});class we extends I{_parse(r){if(this._def.coerce&&(r.data=new Date(r.data)),this._getType(r)!==b.date){const l=this._getOrReturnCtx(r);return _(l,{code:y.invalid_type,expected:b.date,received:l.parsedType}),T}if(isNaN(r.data.getTime())){const l=this._getOrReturnCtx(r);return _(l,{code:y.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),_(u,{code:y.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),_(u,{code:y.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 we({...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}}we.create=a=>new we({checks:[],coerce:(a==null?void 0:a.coerce)||!1,typeName:S.ZodDate,...O(a)});class Tt extends I{_parse(r){if(this._getType(r)!==b.symbol){const c=this._getOrReturnCtx(r);return _(c,{code:y.invalid_type,expected:b.symbol,received:c.parsedType}),T}return F(r.data)}}Tt.create=a=>new Tt({typeName:S.ZodSymbol,...O(a)});class qe extends I{_parse(r){if(this._getType(r)!==b.undefined){const c=this._getOrReturnCtx(r);return _(c,{code:y.invalid_type,expected:b.undefined,received:c.parsedType}),T}return F(r.data)}}qe.create=a=>new qe({typeName:S.ZodUndefined,...O(a)});class Ge extends I{_parse(r){if(this._getType(r)!==b.null){const c=this._getOrReturnCtx(r);return _(c,{code:y.invalid_type,expected:b.null,received:c.parsedType}),T}return F(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 F(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 F(r.data)}}_e.create=a=>new _e({typeName:S.ZodUnknown,...O(a)});class ie extends I{_parse(r){const i=this._getOrReturnCtx(r);return _(i,{code:y.invalid_type,expected:b.never,received:i.parsedType}),T}}ie.create=a=>new ie({typeName:S.ZodNever,...O(a)});class At extends I{_parse(r){if(this._getType(r)!==b.undefined){const c=this._getOrReturnCtx(r);return _(c,{code:y.invalid_type,expected:b.void,received:c.parsedType}),T}return F(r.data)}}At.create=a=>new At({typeName:S.ZodVoid,...O(a)});class q extends I{_parse(r){const{ctx:i,status:c}=this._processInputParams(r),u=this._def;if(i.parsedType!==b.array)return _(i,{code:y.invalid_type,expected:b.array,received:i.parsedType}),T;if(u.exactLength!==null){const h=i.data.length>u.exactLength.value,m=i.data.length<u.exactLength.value;(h||m)&&(_(i,{code:h?y.too_big:y.too_small,minimum:m?u.exactLength.value:void 0,maximum:h?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&&(_(i,{code:y.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&&(_(i,{code:y.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((h,m)=>u.type._parseAsync(new Q(i,h,i.path,m)))).then(h=>L.mergeArray(c,h));const l=[...i.data].map((h,m)=>u.type._parseSync(new Q(i,h,i.path,m)));return L.mergeArray(c,l)}get element(){return this._def.type}min(r,i){return new q({...this._def,minLength:{value:r,message:x.toString(i)}})}max(r,i){return new q({...this._def,maxLength:{value:r,message:x.toString(i)}})}length(r,i){return new q({...this._def,exactLength:{value:r,message:x.toString(i)}})}nonempty(r){return this.min(1,r)}}q.create=(a,r)=>new q({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]=J.create(Re(c))}return new N({...a._def,shape:()=>r})}else return a instanceof q?new q({...a._def,type:Re(a.element)}):a instanceof J?J.create(Re(a.unwrap())):a instanceof he?he.create(Re(a.unwrap())):a instanceof X?X.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)!==b.object){const v=this._getOrReturnCtx(r);return _(v,{code:y.invalid_type,expected:b.object,received:v.parsedType}),T}const{status:c,ctx:u}=this._processInputParams(r),{shape:l,keys:h}=this._getCached(),m=[];if(!(this._def.catchall instanceof ie&&this._def.unknownKeys==="strip"))for(const v in u.data)h.includes(v)||m.push(v);const w=[];for(const v of h){const E=l[v],j=u.data[v];w.push({key:{status:"valid",value:v},value:E._parse(new Q(u,j,u.path,v)),alwaysSet:v in u.data})}if(this._def.catchall instanceof ie){const v=this._def.unknownKeys;if(v==="passthrough")for(const E of m)w.push({key:{status:"valid",value:E},value:{status:"valid",value:u.data[E]}});else if(v==="strict")m.length>0&&(_(u,{code:y.unrecognized_keys,keys:m}),c.dirty());else if(v!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const v=this._def.catchall;for(const E of m){const j=u.data[E];w.push({key:{status:"valid",value:E},value:v._parse(new Q(u,j,u.path,E)),alwaysSet:E in u.data})}}return u.common.async?Promise.resolve().then(async()=>{const v=[];for(const E of w){const j=await E.key,oe=await E.value;v.push({key:j,value:oe,alwaysSet:E.alwaysSet})}return v}).then(v=>L.mergeObjectSync(c,v)):L.mergeObjectSync(c,w)}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,h,m;const w=(h=(l=(u=this._def).errorMap)===null||l===void 0?void 0:l.call(u,i,c).message)!==null&&h!==void 0?h:c.defaultError;return i.code==="unrecognized_keys"?{message:(m=x.errToObj(r).message)!==null&&m!==void 0?m:w}:{message:w}}}:{}})}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 J;)l=l._def.innerType;i[c]=l}}),new N({...this._def,shape:()=>i})}keyof(){return Fn(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 m of l)if(m.result.status==="valid")return m.result;for(const m of l)if(m.result.status==="dirty")return i.common.issues.push(...m.ctx.common.issues),m.result;const h=l.map(m=>new V(m.ctx.common.issues));return _(i,{code:y.invalid_union,unionErrors:h}),T}if(i.common.async)return Promise.all(c.map(async l=>{const h={...i,common:{...i.common,issues:[]},parent:null};return{result:await l._parseAsync({data:i.data,path:i.path,parent:h}),ctx:h}})).then(u);{let l;const h=[];for(const w of c){const v={...i,common:{...i.common,issues:[]},parent:null},E=w._parseSync({data:i.data,path:i.path,parent:v});if(E.status==="valid")return E;E.status==="dirty"&&!l&&(l={result:E,ctx:v}),v.common.issues.length&&h.push(v.common.issues)}if(l)return i.common.issues.push(...l.ctx.common.issues),l.result;const m=h.map(w=>new V(w));return _(i,{code:y.invalid_union,unionErrors:m}),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 G?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 J?[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 Ot extends I{_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==b.object)return _(i,{code:y.invalid_type,expected:b.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}):(_(i,{code:y.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 h=ae(l.shape[r]);if(!h.length)throw new Error(`A discriminator value for key \`${r}\` could not be extracted from all schema options`);for(const m of h){if(u.has(m))throw new Error(`Discriminator property ${String(r)} has duplicate value ${String(m)}`);u.set(m,l)}}return new Ot({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===b.object&&c===b.object){const u=M.objectKeys(r),l=M.objectKeys(a).filter(m=>u.indexOf(m)!==-1),h={...a,...r};for(const m of l){const w=er(a[m],r[m]);if(!w.valid)return{valid:!1};h[m]=w.data}return{valid:!0,data:h}}else if(i===b.array&&c===b.array){if(a.length!==r.length)return{valid:!1};const u=[];for(let l=0;l<a.length;l++){const h=a[l],m=r[l],w=er(h,m);if(!w.valid)return{valid:!1};u.push(w.data)}return{valid:!0,data:u}}else return i===b.date&&c===b.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,h)=>{if(Qt(l)||Qt(h))return T;const m=er(l.value,h.value);return m.valid?((Xt(l)||Xt(h))&&i.dirty(),{status:i.value,value:m.data}):(_(c,{code:y.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,h])=>u(l,h)):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 X extends I{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==b.array)return _(c,{code:y.invalid_type,expected:b.array,received:c.parsedType}),T;if(c.data.length<this._def.items.length)return _(c,{code:y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T;!this._def.rest&&c.data.length>this._def.items.length&&(_(c,{code:y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty());const l=[...c.data].map((h,m)=>{const w=this._def.items[m]||this._def.rest;return w?w._parse(new Q(c,h,c.path,m)):null}).filter(h=>!!h);return c.common.async?Promise.all(l).then(h=>L.mergeArray(i,h)):L.mergeArray(i,l)}get items(){return this._def.items}rest(r){return new X({...this._def,rest:r})}}X.create=(a,r)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new X({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!==b.object)return _(c,{code:y.invalid_type,expected:b.object,received:c.parsedType}),T;const u=[],l=this._def.keyType,h=this._def.valueType;for(const m in c.data)u.push({key:l._parse(new Q(c,m,c.path,m)),value:h._parse(new Q(c,c.data[m],c.path,m)),alwaysSet:m 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:H.create(),valueType:r,typeName:S.ZodRecord,...O(i)})}}class It 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!==b.map)return _(c,{code:y.invalid_type,expected:b.map,received:c.parsedType}),T;const u=this._def.keyType,l=this._def.valueType,h=[...c.data.entries()].map(([m,w],v)=>({key:u._parse(new Q(c,m,c.path,[v,"key"])),value:l._parse(new Q(c,w,c.path,[v,"value"]))}));if(c.common.async){const m=new Map;return Promise.resolve().then(async()=>{for(const w of h){const v=await w.key,E=await w.value;if(v.status==="aborted"||E.status==="aborted")return T;(v.status==="dirty"||E.status==="dirty")&&i.dirty(),m.set(v.value,E.value)}return{status:i.value,value:m}})}else{const m=new Map;for(const w of h){const v=w.key,E=w.value;if(v.status==="aborted"||E.status==="aborted")return T;(v.status==="dirty"||E.status==="dirty")&&i.dirty(),m.set(v.value,E.value)}return{status:i.value,value:m}}}}It.create=(a,r,i)=>new It({valueType:r,keyType:a,typeName:S.ZodMap,...O(i)});class be extends I{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==b.set)return _(c,{code:y.invalid_type,expected:b.set,received:c.parsedType}),T;const u=this._def;u.minSize!==null&&c.data.size<u.minSize.value&&(_(c,{code:y.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&&(_(c,{code:y.too_big,maximum:u.maxSize.value,type:"set",inclusive:!0,exact:!1,message:u.maxSize.message}),i.dirty());const l=this._def.valueType;function h(w){const v=new Set;for(const E of w){if(E.status==="aborted")return T;E.status==="dirty"&&i.dirty(),v.add(E.value)}return{status:i.value,value:v}}const m=[...c.data.values()].map((w,v)=>l._parse(new Q(c,w,c.path,v)));return c.common.async?Promise.all(m).then(w=>h(w)):h(m)}min(r,i){return new be({...this._def,minSize:{value:r,message:x.toString(i)}})}max(r,i){return new be({...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)}}be.create=(a,r)=>new be({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!==b.function)return _(i,{code:y.invalid_type,expected:b.function,received:i.parsedType}),T;function c(m,w){return Et({data:m,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,kt(),Ie].filter(v=>!!v),issueData:{code:y.invalid_arguments,argumentsError:w}})}function u(m,w){return Et({data:m,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,kt(),Ie].filter(v=>!!v),issueData:{code:y.invalid_return_type,returnTypeError:w}})}const l={errorMap:i.common.contextualErrorMap},h=i.data;if(this._def.returns instanceof Ne){const m=this;return F(async function(...w){const v=new V([]),E=await m._def.args.parseAsync(w,l).catch(ce=>{throw v.addIssue(c(w,ce)),v}),j=await Reflect.apply(h,this,E);return await m._def.returns._def.type.parseAsync(j,l).catch(ce=>{throw v.addIssue(u(j,ce)),v})})}else{const m=this;return F(function(...w){const v=m._def.args.safeParse(w,l);if(!v.success)throw new V([c(w,v.error)]);const E=Reflect.apply(h,this,v.data),j=m._def.returns.safeParse(E,l);if(!j.success)throw new V([u(E,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...r){return new Ce({...this._def,args:X.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||X.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 _(i,{received:i.data,code:y.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 Fn(a,r){return new fe({values:a,typeName:S.ZodEnum,...O(r)})}class fe extends I{constructor(){super(...arguments),Ve.set(this,void 0)}_parse(r){if(typeof r.data!="string"){const i=this._getOrReturnCtx(r),c=this._def.values;return _(i,{expected:M.joinValues(c),received:i.parsedType,code:y.invalid_type}),T}if(St(this,Ve)||Pn(this,Ve,new Set(this._def.values)),!St(this,Ve).has(r.data)){const i=this._getOrReturnCtx(r),c=this._def.values;return _(i,{received:i.data,code:y.invalid_enum_value,options:c}),T}return F(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})}}Ve=new WeakMap,fe.create=Fn;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!==b.string&&c.parsedType!==b.number){const u=M.objectValues(i);return _(c,{expected:M.joinValues(u),received:c.parsedType,code:y.invalid_type}),T}if(St(this,We)||Pn(this,We,new Set(M.getValidEnumValues(this._def.values))),!St(this,We).has(r.data)){const u=M.objectValues(i);return _(c,{received:c.data,code:y.invalid_enum_value,options:u}),T}return F(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!==b.promise&&i.common.async===!1)return _(i,{code:y.invalid_type,expected:b.promise,received:i.parsedType}),T;const c=i.parsedType===b.promise?i.data:Promise.resolve(i.data);return F(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 G 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:h=>{_(c,h),h.fatal?i.abort():i.dirty()},get path(){return c.path}};if(l.addIssue=l.addIssue.bind(l),u.type==="preprocess"){const h=u.transform(c.data,l);if(c.common.async)return Promise.resolve(h).then(async m=>{if(i.value==="aborted")return T;const w=await this._def.schema._parseAsync({data:m,path:c.path,parent:c});return w.status==="aborted"?T:w.status==="dirty"||i.value==="dirty"?Me(w.value):w});{if(i.value==="aborted")return T;const m=this._def.schema._parseSync({data:h,path:c.path,parent:c});return m.status==="aborted"?T:m.status==="dirty"||i.value==="dirty"?Me(m.value):m}}if(u.type==="refinement"){const h=m=>{const w=u.refinement(m,l);if(c.common.async)return Promise.resolve(w);if(w instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return m};if(c.common.async===!1){const m=this._def.schema._parseSync({data:c.data,path:c.path,parent:c});return m.status==="aborted"?T:(m.status==="dirty"&&i.dirty(),h(m.value),{status:i.value,value:m.value})}else return this._def.schema._parseAsync({data:c.data,path:c.path,parent:c}).then(m=>m.status==="aborted"?T:(m.status==="dirty"&&i.dirty(),h(m.value).then(()=>({status:i.value,value:m.value}))))}if(u.type==="transform")if(c.common.async===!1){const h=this._def.schema._parseSync({data:c.data,path:c.path,parent:c});if(!ve(h))return h;const m=u.transform(h.value,l);if(m instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:m}}else return this._def.schema._parseAsync({data:c.data,path:c.path,parent:c}).then(h=>ve(h)?Promise.resolve(u.transform(h.value,l)).then(m=>({status:i.value,value:m})):h);M.assertNever(u)}}G.create=(a,r,i)=>new G({schema:a,typeName:S.ZodEffects,effect:r,...O(i)}),G.createWithPreprocess=(a,r,i)=>new G({schema:r,effect:{type:"preprocess",transform:a},typeName:S.ZodEffects,...O(i)});class J extends I{_parse(r){return this._getType(r)===b.undefined?F(void 0):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}J.create=(a,r)=>new J({innerType:a,typeName:S.ZodOptional,...O(r)});class he extends I{_parse(r){return this._getType(r)===b.null?F(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===b.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 Fe(u)?u.then(l=>({status:"valid",value:l.status==="valid"?l.value:this._def.catchValue({get error(){return new V(c.common.issues)},input:c.data})})):{status:"valid",value:u.status==="valid"?u.value:this._def.catchValue({get error(){return new V(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 Mt extends I{_parse(r){if(this._getType(r)!==b.nan){const c=this._getOrReturnCtx(r);return _(c,{code:y.invalid_type,expected:b.nan,received:c.parsedType}),T}return{status:"valid",value:r.data}}}Mt.create=a=>new Mt({typeName:S.ZodNaN,...O(a)});const ia=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=>(ve(u)&&(u.value=Object.freeze(u.value)),u);return Fe(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 Vn(a,r={},i){return a?$e.create().superRefine((c,u)=>{var l,h;if(!a(c)){const m=typeof r=="function"?r(c):typeof r=="string"?{message:r}:r,w=(h=(l=m.fatal)!==null&&l!==void 0?l:i)!==null&&h!==void 0?h:!0,v=typeof m=="string"?{message:m}:m;u.addIssue({code:"custom",...v,fatal:w})}}):$e.create()}const aa={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 oa=(a,r={message:`Input not instance of ${a.name}`})=>Vn(i=>i instanceof a,r),Wn=H.create,Hn=le.create,ca=Mt.create,ua=de.create,qn=He.create,la=we.create,da=Tt.create,fa=qe.create,ha=Ge.create,ma=$e.create,pa=_e.create,ga=ie.create,ya=At.create,va=q.create,wa=N.create,_a=N.strictCreate,ba=Ke.create,xa=Ot.create,ka=Ye.create,Ea=X.create,Sa=Qe.create,Ta=It.create,Aa=be.create,Oa=Ce.create,Ia=Xe.create,Ma=Je.create,$a=fe.create,Ra=et.create,Ca=Ne.create,Gn=G.create,Na=J.create,ja=he.create,Da=G.createWithPreprocess,Ua=nt.create;var Z=Object.freeze({__proto__:null,defaultErrorMap:Ie,setErrorMap:Di,getErrorMap:kt,makeIssue:Et,EMPTY_PATH:Ui,addIssueToContext:_,ParseStatus:L,INVALID:T,DIRTY:Me,OK:F,isAborted:Qt,isDirty:Xt,isValid:ve,isAsync:Fe,get util(){return M},get objectUtil(){return Yt},ZodParsedType:b,getParsedType:se,ZodType:I,datetimeRegex:zn,ZodString:H,ZodNumber:le,ZodBigInt:de,ZodBoolean:He,ZodDate:we,ZodSymbol:Tt,ZodUndefined:qe,ZodNull:Ge,ZodAny:$e,ZodUnknown:_e,ZodNever:ie,ZodVoid:At,ZodArray:q,ZodObject:N,ZodUnion:Ke,ZodDiscriminatedUnion:Ot,ZodIntersection:Ye,ZodTuple:X,ZodRecord:Qe,ZodMap:It,ZodSet:be,ZodFunction:Ce,ZodLazy:Xe,ZodLiteral:Je,ZodEnum:fe,ZodNativeEnum:et,ZodPromise:Ne,ZodEffects:G,ZodTransformer:G,ZodOptional:J,ZodNullable:he,ZodDefault:tt,ZodCatch:rt,ZodNaN:Mt,BRAND:ia,ZodBranded:tr,ZodPipeline:nt,ZodReadonly:st,custom:Vn,Schema:I,ZodSchema:I,late:aa,get ZodFirstPartyTypeKind(){return S},coerce:{string:a=>H.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=>we.create({...a,coerce:!0})},any:ma,array:va,bigint:ua,boolean:qn,date:la,discriminatedUnion:xa,effect:Gn,enum:$a,function:Oa,instanceof:oa,intersection:ka,lazy:Ia,literal:Ma,map:Ta,nan:ca,nativeEnum:Ra,never:ga,null:ha,nullable:ja,number:Hn,object:wa,oboolean:()=>qn().optional(),onumber:()=>Hn().optional(),optional:Na,ostring:()=>Wn().optional(),pipeline:Ua,preprocess:Da,promise:Ca,record:Sa,set:Aa,strictObject:_a,string:Wn,symbol:da,transformer:Gn,tuple:Ea,undefined:fa,union:ba,unknown:pa,void:ya,NEVER:T,ZodIssueCode:y,quotelessJson:ji,ZodError:V}),rr=(a=>(a.TEXT="text",a.THREAD="thread",a.REACTION="reaction",a))(rr||{});const xe=Y.getInstance(),Kn=Z.object({id:Z.string(),targetMessageId:Z.string().optional(),type:Z.nativeEnum(rr),message:Z.string(),username:Z.string(),address:Z.string(),timestamp:Z.number(),signature:Z.string(),index:Z.number(),chatTopic:Z.string(),userTopic:Z.string()}),Pa=Z.object({reference:Z.string(),timestamp:Z.number()}),Za=Z.object({message:Kn,messageStateRefs:Z.array(Pa).nullable()});function Yn(a){const r=Za.safeParse(a);return r.success?Qn(a.message)?!0:(xe.warn("Invalid main message signature"),!1):(xe.warn("GSOC message validation failed:",r.error.format()),!1)}function Ba(a){if(!Array.isArray(a))return xe.warn("Message state must be an array"),!1;for(const r of a)if(!La(r))return xe.warn("Invalid message in message state:",r.id),!1;return!0}function La(a){const r=Kn.safeParse(a);return r.success?Qn(a)?!0:(xe.warn("Invalid message signature"),!1):(xe.warn("Message data validation failed:",r.error.format()),!1)}function Qn(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 xe.warn("Error in validateUserSignature",r),!1}}const K={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 za{constructor(r,i){this.utils=r,this.emitter=i,this.logger=Y.getInstance(),this.errorHandler=ne.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(!Yn(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(!Ba(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(K.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 Ci(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 Fa{constructor(r,i){this.userDetails=r,this.swarmSettings=i,this.depth=26,this.errorHandler=ne.getInstance(),this.UPLOAD_GSOC_TIMEOUT=2e3}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:h,ownAddress:m}=this.userDetails,w=this.generateUserOwnedFeedId(l,m),v=A.Topic.fromString(w);await c.makeFeedWriter(v,new A.PrivateKey(h)).uploadPayload(u,JSON.stringify(i),{index:r})}async writeOwnFeedDataByIndexEnvelope(r,i){const{bee:c,stamp:u,chatTopic:l}=this.swarmSettings,{privateKey:h,ownAddress:m}=this.userDetails,w=new A.PrivateKey(h),v=A.Stamper.fromBlank(h,u,this.depth),E=this.generateUserOwnedFeedId(l,m),j=A.Topic.fromString(E),oe=Nn(j,r),ce=jn(i),it=Dn(ce,oe,w),je={hash:()=>it.address.toUint8Array()},nr=v.stamp(je),{upload:sr}=c.makeSOCWriter(w),at=A.Bytes.fromUtf8(i);return(await sr(nr,oe,at.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),h=A.Bytes.fromUtf8(JSON.stringify(r)),m=new Si(async v=>{await i.uploadChunk(l.stamp(v),v.build())});await m.append(h.toUint8Array());const w=await m.finalize();return B.uint8ArrayToHex(w.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),m=await r.makeFeedReader(l,c).downloadPayload(),w=Number(m.feedIndex.toBigInt()),v=w+1;return{latestIndex:w,nextIndex:v}}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),Gt(c)).downloadPayload();return{data:l.payload.toJSON(),index:l.feedIndex}}async fetchChatMessage(r){const{bee:i,chatTopic:c,chatAddress:u}=this.swarmSettings;return(await i.makeFeedReader(A.Topic.fromString(c),Gt(u)).downloadPayload({index:r})).payload.toJSON()}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}=this.swarmSettings,u=await fetch(`${c}/soc/${r}/${i}`,{headers:{"swarm-chunk-retrieval-timeout":"2000ms"}});if(!u.ok){const l=new Error(`Failed to fetch: ${r}/${i} [${u.status}]`);throw l.status=u.status,l}return u.text()}async sendMessageToGsocOwn(r){const{bee:i,stamp:c,gsocTopic:u,gsocResourceId:l}=this.swarmSettings,h=new A.PrivateKey(l),m=A.Identifier.fromString(u),w=A.Bytes.fromUtf8(r),{upload:v}=i.makeSOCWriter(h,{timeout:this.UPLOAD_GSOC_TIMEOUT});await v(c,m,w.toUint8Array())}async sendMessageToGsocEnvelope(r){const{bee:i,stamp:c,gsocTopic:u,gsocResourceId:l}=this.swarmSettings,{privateKey:h}=this.userDetails,m=A.Stamper.fromBlank(h,c,this.depth),w=new A.PrivateKey(l),v=A.Identifier.fromString(u),E=A.Bytes.fromUtf8(r),j=jn(E.toUint8Array()),oe=Dn(j,v,w),ce={hash:()=>oe.address.toUint8Array()},it=m.stamp(ce),{upload:je}=i.makeSOCWriter(w,{timeout:this.UPLOAD_GSOC_TIMEOUT});await je(it,v,E.toUint8Array())}}class Va{constructor(r){this.logger=Y.getInstance(),this.errorHandler=ne.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const i=new A.PrivateKey(Gt(r.user.privateKey));this.userDetails={privateKey:r.user.privateKey,ownAddress:i.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},this.emitter=new Ni,this.utils=new Fa(this.userDetails,this.swarmSettings),this.history=new za(this.utils,this.emitter)}start(){this.init(),this.startMessagesFetchProcess()}stop(){this.emitter.cleanAll(),this.stopMessagesFetchProcess(),this.history.cleanup()}getEmitter(){return this.emitter}orderMessages(r){return this.utils.orderMessages(r)}async sendMessage(r,i,c,u){const l=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,h={id:u||ki(),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:l,type:i,targetMessageId:c,message:r};try{this.emitter.emit(K.MESSAGE_REQUEST_INITIATED,h),await this.utils.writeOwnFeedDataByIndex(l,JSON.stringify(h)),this.userDetails.ownIndex=l,this.emitter.emit(K.MESSAGE_REQUEST_UPLOADED,h),await this.broadcastUserMessage(h)}catch(m){this.emitter.emit(K.MESSAGE_REQUEST_ERROR,h),this.errorHandler.handleError(m,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(K.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(K.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(r){this.sendMessage(r.message,r.type,r.targetMessageId,r.id)}async retryBroadcastUserMessage(r){await this.broadcastUserMessage(r)}async init(){try{this.emitter.emit(K.LOADING_INIT,!0);const[r,i]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(r.status==="rejected")throw r.reason;i.status==="fulfilled"&&(this.gsocIndex=i.value),this.emitter.emit(K.LOADING_INIT,!1)}catch(r){this.errorHandler.handleError(r,"Chat.initSelfState"),this.emitter.emit(K.CRITICAL_ERROR,r)}}async initOwnIndex(){const{latestIndex:c}=await Kt(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=c}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const r=A.Topic.fromString(this.swarmSettings.chatTopic),i=Nn(r,this.gsocIndex),c=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,i.toString()),u=JSON.parse(c);if(!Yn(u)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(K.MESSAGE_RECEIVED,u.message),this.gsocIndex=this.gsocIndex.next()}catch(r){if(this.utils.isNotFoundError(r))return;this.errorHandler.handleError(r,"Chat.fetchLatestMessage")}}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(),h=new A.PrivateKey(c);if(h.publicKey().address().toString()!==l)throw new Error("The provided address does not match the address derived from the private key");const w=Date.now();return h.sign(JSON.stringify({username:u,address:l,message:r,timestamp:w})).toHex()}async startMessagesFetchProcess(){if(this.fetchProcessRunning)return;this.fetchProcessRunning=!0,this.stopFetch=!1;const r=async()=>{if(this.stopFetch){this.fetchProcessRunning=!1;return}await this.fetchLatestMessage(),setTimeout(r,200)};r()}stopMessagesFetchProcess(){this.stopFetch=!0}}re.EVENTS=K,re.MessageType=rr,re.SwarmChat=Va,Object.defineProperty(re,Symbol.toStringTag,{value:"Module"})});