@solarpunkltd/swarm-chat-js 5.0.0 → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.esm.js +704 -632
- package/dist/index.js +10 -10
- package/dist/interfaces/message.d.ts +4 -0
- package/dist/interfaces/message.d.ts.map +1 -1
- package/dist/lib/core.d.ts +2 -2
- package/dist/lib/core.d.ts.map +1 -1
- package/dist/swarm-chat-umd.js +10 -10
- package/dist/utils/validation.d.ts +13 -0
- package/dist/utils/validation.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("@ethersphere/bee-js"),P=[];for(let a=0;a<256;++a)P.push((a+256).toString(16).slice(1));function $l(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 vn;const Rl=new Uint8Array(16);function Cl(){if(!vn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");vn=crypto.getRandomValues.bind(crypto)}return vn(Rl)}const Nl=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ys={randomUUID:Nl};function jl(a,r,i){if(Ys.randomUUID&&!r&&!a)return Ys.randomUUID();a=a||{};const c=a.random||(a.rng||Cl)();return c[6]=c[6]&15|64,c[8]=c[8]&63|128,$l(c)}function Dl(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var si={};(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=xs(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 re(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 ne(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 ze(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 Oe(e,t,n=Math.random){return h(Vn(0,e.length-1),n).slice(0,t)}function Wt(e,t){return e.map(n=>n[t])}function Ht(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 Fe(e,t,n=Math.random){return Math.floor(n()*(t-e+1))+e}function Mn(e,t,n=Math.random){return n()*(t-e)+e}function wi(){return Math.random()*2-1}function bi(e,t,n){return t>=e.x&&t<e.x+e.width&&n>=e.y&&n<e.y+e.height}function _i(e,t,n,s=Math.random){let o,d;do o=Fe(0,e-1,s),d=Fe(0,t-1,s);while(n&&bi(n,o,d));return[o,d]}function xi(e,t=Math.random){const n=Math.floor(e),s=e-n;return In(s,t)?n+1:n}function In(e,t=Math.random){return t()<e}function qt(e,t=Math.random){return e[Math.floor(e.length*t())]}function ki(e,t,n=Math.random){if(t>e.length)throw new Error(`Count (${t}) is greater than array length (${e.length})`);return Oe(e,t,n).map(s=>e[s])}function Ei(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=qt(e,s);o.some(f=>n(f,d))||o.push(d)}return o}function Si(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 Ve(e){if(!e.length)throw Error("Received empty array");return e[e.length-1]}function $n(e,t,n){return n(t.reduce((s,o)=>o(s),e))}function Ti(e,t){return n=>$n(n,e,t)}function Ai(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 Ve(e)}function Oi(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 ye(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 ve(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;ue(o[p])||(g?o[p]=[]:o[p]={}),o=o[p]}return n}function Mi(e,t,n=1){const s=ye(e,t)||0;return ve(e,t,s+n),s}function Ii(e,t,n){return ye(e,t)||ve(e,t,n)}function $i(e,t){const n=rr(t,"."),s=Hn(t,".");if(!n||!s)return;const o=ye(e,n);delete o[s]}function Ri(e,t,n){const s=ye(e,t);if(!s)throw new Error("Key '"+t+"' does not exist.");return ve(e,t,n),s}function Ci(e,t,n){for(const s of t){const o=ye(e,s);if(o)return o}if(n){const s=Object.values(e);if(s.length)return s[0]}return null}async function Ni(e,t,n){for(;;){try{await e()}catch(s){n&&n("Error in forever",s)}await l(t)}}function ji(e,t){e();const n=setInterval(()=>{e()},t);return()=>clearInterval(n)}function Di(e){return e/1024/1024}function Ui(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 Pi(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 Zi(e){return"#"+e.map(t=>t.toString(16).padStart(2,"0")).join("")}function Bi(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 xt(e,t){return Math.round(e/t)*t}function Li(e){return e>1e3?(e/1e3).toFixed(0)+" km":e>=500?xt(e,100)+" m":e>=100?xt(e,50)+" m":xt(e,10)+" m"}function zi(e){return e*(e+1)/2}function Fi(e){const t=e.match(/-?\d+(\.\d+)?/);if(!t)throw Error("No float found in "+e);return parseFloat(t[0])}function ue(e,t=!0){return!e||t&&!Gt(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 Me(e){return ue(e)&&!Array.isArray(e)}function Rn(e){return Array.isArray(e)&&e.length===0}function Vi(e){return Me(e)&&Object.keys(e).length===0}function Gt(e){return e===void 0}function Kt(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 le(e){return typeof e=="number"&&isFinite(e)}function Cn(e){return e===!0||e===!1}function Ie(e){return Object.prototype.toString.call(e)==="[object Date]"}function kt(e){return!W(e)||e.trim().length===0}function Jt(e){return le(e)&&Number.isInteger(e)&&e>=1}function Nn(e){return W(e)&&e.match(/^-?\d+$/)!==null}function jn(e){return W(e)&&e.match(/^(0x)?[0-9a-f]+$/i)!==null}const Wi="!@#$%^&*()_+-=[]{}|;:<>?,./",Hi="!@#$%^&*()_+-=[]{}|;:<>?,./".split(""),Yt="abcdefghijklmnopqrstuvwxyz",qi="ABCDEFGHIJKLMNOPQRSTUVWXYZ",Gi="1234567890",Qt=Yt+qi+Gi,Dn=Qt+Wi,Un=["—","\\","東","京","都","𝖆","𝖇","𝖈","👾","🙇","💁","🙅","ᚠ","ᛇ","ᚻ","ᛦ"],Pn="0123456789abcdef";function Ki(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=Yt[Math.floor(t()*Yt.length)];return n}function Ji(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=Qt[Math.floor(t()*Qt.length)];return n}function Yi(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=Dn[Math.floor(t()*Dn.length)];return n}function Qi(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=Un[Math.floor(t()*Un.length)];return n}function Xi(e,t){const n=new RegExp(`[0-9a-f]{${t}}`,"i"),s=e.match(n);return s?s[0]:null}function ea(e,t,n=Hi){const s=qn(e,n);for(const o of s)if(t(o))return o;return null}function ta(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=Pn[Math.floor(t()*Pn.length)];return n}function ra(e,t){if(!Nn(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 Zn(e,t){if(kt(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 na(e,t){if(!jn(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 sa(e,t){if(!Zn(e,t).split("").every(n=>n==="_"||qe(n)))throw new TypeError(`Expected safe string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Bn(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 ia(e,t){if(!Kt(e))throw new TypeError(`Expected function${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Et(e,t){if(le(e))return t&&Bn(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&&Bn(n,t),n}function Xt(e,t){return Et(e,t)|0}function aa(e,t){if(e==="true")return!0;if(e==="false")return!1;if(!Cn(e))throw new TypeError(`Expected boolean${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function oa(e,t){if(!Ie(e))throw new TypeError(`Expected date${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function ca(e){return kt(e)?null:e}function ua(e,t){if(!W(e))throw new TypeError(`Expected string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function la(e,t){if(Jt(e))return e;const n=parseInt(e,10);if(!Jt(n))throw new TypeError(`Expected id${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return n}function da(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(!le(s)||!le(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 fa(e,t){if(!Array.isArray(e))throw new TypeError(`Expected array${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function St(e,t){if(!Me(e))throw new TypeError(`Expected object${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function ha(e,t){return e===null?null:St(e,t)}function ma(e,t){const n=St(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 pa(e,t){const n=St(e),s=Object.keys(n),o=Object.values(n);if(!s.every(W)||!o.every(le))throw new TypeError(`Expected numeric dictionary${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return n}function Ln(e){return W(e)&&e.match(/^https?:\/\/.+/)!==null}function ga(e,t){if(!Ln(e))throw new TypeError(`Expected url${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function ya(e,t){return t==null?!0:e(t)}function va(e,t){return t==null?null:e(t)}function wa(e,t){return t==null?void 0:e(t)}function zn(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 ba(e,t){return e.every(n=>zn(n,t))}function We(e,t="json",n=0){if(ue(e,!1)){if(n>1)return"[object Object]";if(t==="json"){if(Array.isArray(e)){const o=e.map(d=>We(d,"json",n+1));return n===0?JSON.stringify(o):o}const s={};e.message&&(s.message=We(e.message,"json",n+1));for(const[o,d]of Object.entries(e))s[o]=We(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(We(e[o],"json",n+1))}`).join(" ")}}return Gt(e)&&(e="undefined"),n===0?JSON.stringify(e):e}function _a(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
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("@ethersphere/bee-js"),Z=[];for(let a=0;a<256;++a)Z.push((a+256).toString(16).slice(1));function $l(a,r=0){return(Z[a[r+0]]+Z[a[r+1]]+Z[a[r+2]]+Z[a[r+3]]+"-"+Z[a[r+4]]+Z[a[r+5]]+"-"+Z[a[r+6]]+Z[a[r+7]]+"-"+Z[a[r+8]]+Z[a[r+9]]+"-"+Z[a[r+10]]+Z[a[r+11]]+Z[a[r+12]]+Z[a[r+13]]+Z[a[r+14]]+Z[a[r+15]]).toLowerCase()}let vn;const Rl=new Uint8Array(16);function Cl(){if(!vn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");vn=crypto.getRandomValues.bind(crypto)}return vn(Rl)}const Nl=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Qs={randomUUID:Nl};function jl(a,r,i){if(Qs.randomUUID&&!r&&!a)return Qs.randomUUID();a=a||{};const c=a.random||(a.rng||Cl)();return c[6]=c[6]&15|64,c[8]=c[8]&63|128,$l(c)}function Dl(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var ii={};(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=ks(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 p(e){if(e.length===1)return e[0];throw Error(`Expected exactly one element, actual: ${e.length}`)}function g(e){return e.length===1?e[0]:null}function y(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 re(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 ne(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 ze(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 Oe(e,t,n=Math.random){return h(Wn(0,e.length-1),n).slice(0,t)}function Wt(e,t){return e.map(n=>n[t])}function Ht(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 Fe(e,t,n=Math.random){return Math.floor(n()*(t-e+1))+e}function In(e,t,n=Math.random){return n()*(t-e)+e}function wi(){return Math.random()*2-1}function bi(e,t,n){return t>=e.x&&t<e.x+e.width&&n>=e.y&&n<e.y+e.height}function _i(e,t,n,s=Math.random){let o,d;do o=Fe(0,e-1,s),d=Fe(0,t-1,s);while(n&&bi(n,o,d));return[o,d]}function xi(e,t=Math.random){const n=Math.floor(e),s=e-n;return $n(s,t)?n+1:n}function $n(e,t=Math.random){return t()<e}function qt(e,t=Math.random){return e[Math.floor(e.length*t())]}function ki(e,t,n=Math.random){if(t>e.length)throw new Error(`Count (${t}) is greater than array length (${e.length})`);return Oe(e,t,n).map(s=>e[s])}function Ei(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=qt(e,s);o.some(f=>n(f,d))||o.push(d)}return o}function Si(e,t,n,s,o,d=Math.random){const f=e.filter(m=>m!==t&&m!==n),v=[];for(t!==null&&v.push(t);f.length&&v.length<s;){const m=a.Random.intBetween(0,f.length-1,d);o(f[m],v)&&v.push(f[m]),f.splice(m,1)}return h(v,d),{values:v,indexOfGuaranteed:t!==null?v.indexOf(t):-1}}function Ve(e){if(!e.length)throw Error("Received empty array");return e[e.length-1]}function Rn(e,t,n){return n(t.reduce((s,o)=>o(s),e))}function Ai(e,t){return n=>Rn(n,e,t)}function Ti(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 Ve(e)}function Oi(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 ve(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 we(e,t,n){const s=t.split(/\.|\[/);let o=e;for(let d=0;d<s.length;d++){const f=s[d],v=d<s.length-1&&s[d+1].includes("]"),m=f.includes("]")?f.replace(/\[|\]/g,""):f;if(d===s.length-1)return o[m]=n,n;ue(o[m])||(v?o[m]=[]:o[m]={}),o=o[m]}return n}function Mi(e,t,n=1){const s=ve(e,t)||0;return we(e,t,s+n),s}function Ii(e,t,n){return ve(e,t)||we(e,t,n)}function $i(e,t){const n=rr(t,"."),s=qn(t,".");if(!n||!s)return;const o=ve(e,n);delete o[s]}function Ri(e,t,n){const s=ve(e,t);if(!s)throw new Error("Key '"+t+"' does not exist.");return we(e,t,n),s}function Ci(e,t,n){for(const s of t){const o=ve(e,s);if(o)return o}if(n){const s=Object.values(e);if(s.length)return s[0]}return null}async function Ni(e,t,n){for(;;){try{await e()}catch(s){n&&n("Error in forever",s)}await l(t)}}function ji(e,t){e();const n=setInterval(()=>{e()},t);return()=>clearInterval(n)}function Di(e){return e/1024/1024}function Pi(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 Ui(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 Zi(e){return"#"+e.map(t=>t.toString(16).padStart(2,"0")).join("")}function Bi(e,t,n,s){const o=e*Math.PI/180,d=n*Math.PI/180,f=(n-e)*Math.PI/180,v=(s-t)*Math.PI/180,m=Math.sin(f/2)*Math.sin(f/2)+Math.cos(o)*Math.cos(d)*Math.sin(v/2)*Math.sin(v/2);return 6371e3*(2*Math.atan2(Math.sqrt(m),Math.sqrt(1-m)))}function xt(e,t){return Math.round(e/t)*t}function Li(e){return e>1e3?(e/1e3).toFixed(0)+" km":e>=500?xt(e,100)+" m":e>=100?xt(e,50)+" m":xt(e,10)+" m"}function zi(e){return e*(e+1)/2}function Fi(e){const t=e.match(/-?\d+(\.\d+)?/);if(!t)throw Error("No float found in "+e);return parseFloat(t[0])}function ue(e,t=!0){return!e||t&&!Gt(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 Me(e){return ue(e)&&!Array.isArray(e)}function Cn(e){return Array.isArray(e)&&e.length===0}function Vi(e){return Me(e)&&Object.keys(e).length===0}function Gt(e){return e===void 0}function Kt(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 le(e){return typeof e=="number"&&isFinite(e)}function Nn(e){return e===!0||e===!1}function Ie(e){return Object.prototype.toString.call(e)==="[object Date]"}function kt(e){return!W(e)||e.trim().length===0}function Jt(e){return le(e)&&Number.isInteger(e)&&e>=1}function jn(e){return W(e)&&e.match(/^-?\d+$/)!==null}function Dn(e){return W(e)&&e.match(/^(0x)?[0-9a-f]+$/i)!==null}const Wi="!@#$%^&*()_+-=[]{}|;:<>?,./",Hi="!@#$%^&*()_+-=[]{}|;:<>?,./".split(""),Yt="abcdefghijklmnopqrstuvwxyz",qi="ABCDEFGHIJKLMNOPQRSTUVWXYZ",Gi="1234567890",Qt=Yt+qi+Gi,Pn=Qt+Wi,Un=["—","\\","東","京","都","𝖆","𝖇","𝖈","👾","🙇","💁","🙅","ᚠ","ᛇ","ᚻ","ᛦ"],Zn="0123456789abcdef";function Ki(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=Yt[Math.floor(t()*Yt.length)];return n}function Ji(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=Qt[Math.floor(t()*Qt.length)];return n}function Yi(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=Pn[Math.floor(t()*Pn.length)];return n}function Qi(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=Un[Math.floor(t()*Un.length)];return n}function Xi(e,t){const n=new RegExp(`[0-9a-f]{${t}}`,"i"),s=e.match(n);return s?s[0]:null}function ea(e,t,n=Hi){const s=Gn(e,n);for(const o of s)if(t(o))return o;return null}function ta(e,t=Math.random){let n="";for(let s=0;s<e;s++)n+=Zn[Math.floor(t()*Zn.length)];return n}function ra(e,t){if(!jn(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 Bn(e,t){if(kt(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 na(e,t){if(!Dn(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 sa(e,t){if(!Bn(e,t).split("").every(n=>n==="_"||qe(n)))throw new TypeError(`Expected safe string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Ln(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 ia(e,t){if(!Kt(e))throw new TypeError(`Expected function${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function Et(e,t){if(le(e))return t&&Ln(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&&Ln(n,t),n}function Xt(e,t){return Et(e,t)|0}function aa(e,t){if(e==="true")return!0;if(e==="false")return!1;if(!Nn(e))throw new TypeError(`Expected boolean${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function oa(e,t){if(!Ie(e))throw new TypeError(`Expected date${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function ca(e){return kt(e)?null:e}function ua(e,t){if(!W(e))throw new TypeError(`Expected string${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function la(e,t){if(Jt(e))return e;const n=parseInt(e,10);if(!Jt(n))throw new TypeError(`Expected id${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return n}function da(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(!le(s)||!le(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 fa(e,t){if(!Array.isArray(e))throw new TypeError(`Expected array${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function St(e,t){if(!Me(e))throw new TypeError(`Expected object${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function ha(e,t){return e===null?null:St(e,t)}function pa(e,t){const n=St(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 ma(e,t){const n=St(e),s=Object.keys(n),o=Object.values(n);if(!s.every(W)||!o.every(le))throw new TypeError(`Expected numeric dictionary${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return n}function zn(e){return W(e)&&e.match(/^https?:\/\/.+/)!==null}function ga(e,t){if(!zn(e))throw new TypeError(`Expected url${t!=null&&t.name?` for ${t.name}`:""}, got: `+e);return e}function ya(e,t){return t==null?!0:e(t)}function va(e,t){return t==null?null:e(t)}function wa(e,t){return t==null?void 0:e(t)}function Fn(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 ba(e,t){return e.every(n=>Fn(n,t))}function We(e,t="json",n=0){if(ue(e,!1)){if(n>1)return"[object Object]";if(t==="json"){if(Array.isArray(e)){const o=e.map(d=>We(d,"json",n+1));return n===0?JSON.stringify(o):o}const s={};e.message&&(s.message=We(e.message,"json",n+1));for(const[o,d]of Object.entries(e))s[o]=We(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(We(e[o],"json",n+1))}`).join(" ")}}return Gt(e)&&(e="undefined"),n===0?JSON.stringify(e):e}function _a(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 be(e,t){if(Me(e)&&Me(t))for(const n in t)Me(t[n])?(e[n]||(e[n]={}),be(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 xa(e,t){const n={};return be(n,e),be(n,t),n}function ka(e,t,n){const s={};return be(s,e),be(s,t),be(s,n),s}function Vn(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 Ea(e){return Vn(e,(t,n)=>t+n)}function Sa(e,t,n){e[t]||(e[t]=[]),e[t].push(n)}function Aa(e,t,n){for(e.unshift(t);e.length>n;)e.pop()}function Ta(e,t){let n=t%e.length;return n<0&&(n+=e.length),e[n]}function At(e,t){Array.prototype.push.apply(e,t)}function Oa(e,t){Array.prototype.unshift.apply(e,t)}async function Ma(e,t){const n=[];for(const s of e)n.push(await t(s));return n}function Ia(e,t){const n=[];for(let s=0;s<e.length;s++)n.push(e[s]),s<e.length-1&&(Kt(t)?n.push(t()):n.push(t));return n}function $a(e,t){if(e!==t)throw Error(`Expected [${e}] to equal [${t}]`);return[e,t]}function Ra(e){if(e!==!0)throw Error(`Expected [true], got: [${e}]`);return e}function Ca(e){if(!e)throw Error(`Expected truthy value, got: [${e}]`);return e}function Na(e){if(e!==!1)throw Error(`Expected [false], got: [${e}]`);return e}function ja(e){if(e)throw Error(`Expected falsy value, got: [${e}]`);return e}function Da(e,t){if(!t.includes(e))throw Error(`Expected any of [${t.join(", ")}], got: [${e}]`);return e}function Pa(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 Ua(e,t,n){return e+(t-e)*n}function Za(e){return e.reduce((t,n)=>t+n,0)}function Ba(e){return e.reduce((t,n)=>t+n,0)/e.length}function La(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 za(e,t){return e-(t-1)/2}function Wn(e,t){const n=[];for(let s=e;s<=t;s++)n.push(s);return n}function Fa(e,t){return t.some(n=>e.includes(n))}function Va(e){return/^[\u4E00-\u9FA5]+$/.test(e)}function er(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 Wa(e){return er(e).replaceAll("-","")}function Ha(e){return Ot(e.replace(/([A-Z])/g," $1"))}function qa(e){return e.split("-").map(Ot).join(" ")}function Ga(e){return Jn(e.split("-").map(Ot).join(""))}function Ka(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 Ja(e,t){return t+e.split("").join(t)+t}function Ya(e){return er(e).replace(/-/g,"_").toUpperCase()}function Tt(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 Qa(e,t){return e.filter(n=>Tt(n,t)).sort((n,s)=>Tt(s,t)-Tt(n,t))}function Xa(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const eo={"&":"&",""":'"',"'":"'",">":">","<":"<"};function to(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(eo))t=t.replaceAll(n,s);return t}function Hn(e,t){const n=e.indexOf(t);return n===-1?null:e.slice(0,n)}function tr(e,t){const n=e.indexOf(t);return n===-1?null:e.slice(n+t.length)}function rr(e,t){const n=e.lastIndexOf(t);return n===-1?null:e.slice(0,n)}function qn(e,t){const n=e.lastIndexOf(t);return n===-1?null:e.slice(n+t.length)}function ro(e,t,n){const s=rr(e,n);return s?tr(s,t):null}function no(e,t,n){const s=tr(e,t);return s?Hn(s,n):null}function nr(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 Gn(e,t){let n=[e];for(const s of t)n=n.flatMap(o=>o.split(s));return n.filter(s=>s)}function sr(e){const t=Ve(e.split(/\\|\//g)),n=t.lastIndexOf(".",t.length-1);return n<=0?"":t.slice(n+1)}function ir(e){const t=Ve(e.split(/\\|\//g)),n=t.lastIndexOf(".",t.length-1);return n<=0?t:t.slice(0,n)}function so(e){let[t,n]=e.split("@");t=He(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=He(n.toLowerCase()).replaceAll(" ",""),`${s}@${n}`}function io(e){const t=ir(e),n=sr(e);return n?`${t}.${n}`:t}function ao(e){const t=ir(e),n=sr(e);return{basename:t,extension:n,filename:n?`${t}.${n}`:t}}function oo(e,t=Math.random){return e.replace(/\{(.+?)\}/g,(n,s)=>qt(s.split("|"),t))}function Kn(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 v of s){const m=Kn(o+v+d);f=f.concat(m)}return f}function He(e){return e.split(`
|
|
3
3
|
`).map(t=>t.trim().replace(/\s+/g," ")).filter(t=>t.length>0).join(`
|
|
4
|
-
`)}function Ot(e){return e.charAt(0).toUpperCase()+e.slice(1)}function
|
|
5
|
-
\r.,?!:;"'\`(){}[]~@#$%^&*-+=|<>/\\`.split("");function uo(e){return co.includes(e)}function lo(e){return qe(e)||e==="."||e==="["||e==="]"||e==="_"}function fo(e,t,n,s,o){return e.slice(0,t)+s+e.slice(t,t+n)+o+e.slice(t+n)}function
|
|
6
|
-
`],t.start||0):e.indexOf(t.opening,t.start||0);if(n===-1)return null;const s=
|
|
7
|
-
`],t.start||0):e.indexOf(t.opening,t.start||0);for(;;){if(s===-1)return n;const o=
|
|
8
|
-
`],s+o.length):e.indexOf(t.opening,s+o.length)}}function vo(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 wo(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 bo(e){const t=[];let n=0;for(;n<e.length;){const s=go(e,n);if(s===-1){t.push({string:e.slice(n),symbol:null});break}const o=
|
|
9
|
-
`],s);if(o===-1){s>n&&t.push({string:e.slice(n,s),symbol:null}),t.push({string:e.slice(s),symbol:"http"});break}s>n&&t.push({string:e.slice(n,s),symbol:null}),t.push({string:e.slice(s,o),symbol:"http"}),n=o}return t}const ns="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ss="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function xo(e){return is(e,ns)}function ko(e){return as(e,ns)}function Eo(e){return is(e,ss)}function So(e){return as(e,ss)}function is(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 x=t.indexOf(p);if(x===-1)throw new Error(`Invalid character: ${p}`);d=d<<Math.log2(s)|x,o+=Math.log2(s),o>=8&&(o-=8,f.push(d>>o&255))}return new Uint8Array(f)}function as(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 To(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 Ao(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function Oo(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 ar(e,t,n){const s=[];for(const o of n)o!==t&&s.push(e.replace(t,o));return s}function Mo(e,t,n,s=Math.random){const o=a.Arrays.shuffle(t.map(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(x=>x!==f.avoid),p=g.find(x=>e.includes(x));if(p&&(Tt(d,ar(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&&(Tt(d,ar(e,g,f.variants)),d.length>=n))break}return d.slice(0,n)}function Io(e,t,n,s=!1){const o=new RegExp(s?`(?<=\\s|^)${t}(?=\\s|$)`:`\\b${t}\\b`,"g");return e.replace(o,n)}function $o(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 Ro(e){return e.replace(/<[^>]*>/g,"")}function os(e){const t=e.lastIndexOf(" ");if(t===-1)return{line:e,rest:""};const n=e.slice(0,t),s=e.slice(t+1);return{line:n,rest:s}}function Co(e,t={}){return[...e].reduce((n,s)=>n+(t[s]||1),0)}function No(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:x,rest:$}=os(o);s.push(x),o=$,d=$.split("").map(U=>n[U]||1).reduce((U,je)=>U+je,0)}}return o&&s.push(o),s}function jo(e,t){const n=[];for(let s=0;s<=e.length;s++)n[s]=[s];for(let s=0;s<=t.length;s++)n[0][s]=s;for(let s=1;s<=e.length;s++)for(let o=1;o<=t.length;o++){const d=e[s-1]===t[o-1]?0:1;n[s][o]=Math.min(n[s-1][o]+1,n[s][o-1]+1,n[s-1][o-1]+d)}return n[e.length][t.length]}function or(e,t){return new RegExp(`\\b${t}\\b`).test(e)}function Do(e,t,n){return n==="any"?t.some(s=>or(e,s)):t.every(s=>or(e,s))}function Uo(e){const t={},n=e.match(/([a-z\-]+)="([^"]+)"/g);if(n)for(const s of n){const[o,d]=nr(s,"=");t[o]=d.slice(1,d.length-1)}return t}function Mt(e,t,n=[]){let s="";for(;t<e.length&&(qe(e[t])||n.includes(e[t]));)s+=e[t++];return s}function Po(e,t,n="$",s=":"){for(const o in t)e=cs(e,o,t[o],n,s);return e=us(e),e}function cs(e,t,n,s="$",o=":"){if(n==="")return e;let d=e.indexOf(`${s}${t}`);for(;d!==-1;){if(e[d+t.length+1]===o)if(e[d+t.length+2]===o)e=e.replace(`${s}${t}${o}${o}`,n);else{const f=Mt(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 us(e,t="$",n=":"){let s=e.indexOf(t);for(;s!==-1;){const o=Mt(e,s+1);if(e[s+o.length+1]===n)if(e[s+o.length+2]===n)e=e.replace(`${t}${o}${n}${n}`,"");else{const d=Mt(e,s+o.length+2);e=e.replace(`${t}${o}${n}${d}`,d)}s=e.indexOf(t,s+1)}return e}function Zo(e,t){let n=e.indexOf("](");for(;n!==-1;){const s=es(e,"[",n),o=e.indexOf(")",n);if(s!==-1&&o!==-1){const[d,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 ls(e,t=!0){const n=Object.entries(e).filter(([s,o])=>o!=null).map(([s,o])=>`${s}=${encodeURIComponent(o)}`).join("&");return n?(t?"?":"")+n:""}function Bo(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 Lo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function zo(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 Fo(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)=>Et(f[t])-Et(g[t])),e.forEach((f,g)=>f[t]=g+1)}function Vo(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 Wo(e,t=":"){return Object.fromEntries(e.map(n=>nr(n,t)).map(n=>n[0]&&n[1]?[He(n[0]),He(n[1])]:null).filter(n=>n))}function Ho(e,t,n){return ms(e,t)+ls(n||{})}function qo(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 Go(e){return`[${Math.floor(e.progress*100)}%] ${It(e.deltaMs)} out of ${It(e.totalTimeMs)} (${It(e.remainingTimeMs)} left) [${Math.round(e.baseTimeMs)} ms each]`}async function Ko(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 Jo(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 Yo(e){return JSON.parse(JSON.stringify(e))}function Qo(e){return Math.ceil((e||Date.now())/1e3)}function Xo(e){return(e||new Date).toISOString().slice(0,10)}function ec(e){return(e||new Date).toISOString().slice(0,19).replace(/T|:/g,"-")}function tc(e){const t=new Date(e);return new Date(t.getTime()-t.getTimezoneOffset()*6e4)}function rc(e){return new Date(e)}function J(e){return String(Math.floor(e)).padStart(2,"0")}function nc(e){let[t,n]=e.split(":");le(parseInt(t,10))||(t="0"),le(parseInt(n,10))||(n="0");let s=fr(Xt(t),0,23),o=fr(Xt(n),0,59);return`${J(s)}:${J(o)}`}function It(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?`${J(t)}:${J(n)}:${J(s)}`:`${J(n)}:${J(s)}`}function be(e){return Math.floor((Ie(e)?e.getTime():e)/864e5)}const sc={today:(e,t)=>J(e)+":"+J(t),yesterday:()=>"Yesterday",monday:()=>"Mon",tuesday:()=>"Tue",wednesday:()=>"Wed",thursday:()=>"Thu",friday:()=>"Fri",saturday:()=>"Sat",sunday:()=>"Sun",weeks:e=>`${e}w`};function ic(e,t){const n=new Date((t==null?void 0:t.now)||Date.now()),s=(t==null?void 0:t.labels)||sc,o=Ie(e)?e:new Date(e);if(be(n)===be(o))return s.today(o.getUTCHours(),o.getUTCMinutes(),o.getUTCHours()>12);if(be(n)-be(o)===1)return s.yesterday();const d=ur(o);return be(n)-be(o)<7?s[d.day]():s.weeks(Math.round((n.getTime()-o.getTime())/6048e5))}const ds={now:()=>"A few seconds",seconds:e=>`${e} seconds`,minutes:e=>`${e} minutes`,hours:e=>`${e} hours`,days:e=>`${e} days`,weeks:e=>`${e} weeks`};function fs(e,t){const n=(t==null?void 0:t.now)??Date.now(),s=(t==null?void 0:t.labels)||ds,o=a.Types.isDate(e)?e.getTime():e;let d=(n-o)/1e3;return d<10?s.now():d<120?s.seconds(Math.floor(d)):(d/=60,d<120?s.minutes(Math.floor(d)):(d/=60,d<48?s.hours(Math.floor(d)):(d/=24,d<14?s.days(Math.floor(d)):(d/=7,s.weeks(Math.floor(d))))))}function ac(e,t=ds){return fs(0,{now:e*1e3,labels:t})}function oc(e,t,n){const s=((n==null?void 0:n.now)??Date.now())-e,o=Math.floor(s/t),d=t/((n==null?void 0:n.precision)??1)-Math.ceil(s%t/((n==null?void 0:n.precision)??1));return{cycles:o,remaining:d}}const cr={};function cc(e,t){return!cr[e]||Date.now()>cr[e]?(cr[e]=Date.now()+t,!0):!1}const uc={s:1e3,m:6e4,h:36e5,d:864e5};function lc(e,t,n){return t=Ie(t)?t.getTime():t,n=n?Ie(n)?n.getTime():n:Date.now(),(n-t)/uc[e]}function dc(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 fc={0:"sunday",1:"monday",2:"tuesday",3:"wednesday",4:"thursday",5:"friday",6:"saturday"};function hs(e){return{zeroBasedIndex:e,day:fc[e]}}function ur(e){return hs(e.getDay())}function hc(e){return ur(new Date(e))}function mc(e){return e*1e3}function pc(e){return e*6e4}function gc(e){return e*36e5}function yc(e){return e*864e5}const vc={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 wc(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=vc[n];if(!s)throw Error(`Unknown unit: "${n}"`);return t*s}const bc={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 _c(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=bc[n];if(!s)throw Error(`Unknown unit: "${n}"`);return t*s}function xc(e){return e.replace(/ +/g," ").replace(/^ /gm,"")}const lr={};async function kc(e,t,n){const s=Date.now(),o=lr[e];if(o&&o.validUntil>s)return o.value;const d=await n(),f=s+t;return lr[e]={value:d,validUntil:f},d}function Ec(e){delete lr[e]}function ms(...e){return e.filter(t=>t).join("/").replace(new RegExp("(?<!:)\\/+","g"),"/")}function Sc(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 Tc(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 Ac(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 Oc(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]=_e(e[s]);return n}function gs(e){const t=[];return e.sort((n,s)=>JSON.stringify(_e(n)).localeCompare(JSON.stringify(_e(s)))).forEach(n=>t.push(_e(n))),t}function _e(e){return Array.isArray(e)?gs(e):ue(e)?ps(e):e}function ys(e,t){return JSON.stringify(_e(e))===JSON.stringify(_e(t))}function Mc(...e){for(let t=1;t<e.length;t++)if(!ys(e[t-1],e[t]))return!1;return!0}function Ic(e){try{return JSON.parse(e)}catch{return null}}function $c(){let e=0;return{next:()=>e++}}function Rc(e){let t=0;return{next:()=>e[t++%e.length]}}function Cc(e){let t;return n=>{const s=n===e&&t!==e;return t=n,s}}function Nc(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 jc(e,t){const n=Object.keys(e),s=Object.keys(t);return{uniqueToA:n.filter(o=>!s.includes(o)),uniqueToB:s.filter(o=>!n.includes(o))}}function vs(e){const t=Object.keys(e);return t[Math.floor(Math.random()*t.length)]}function Dc(e,t){const n=vs(e);return e[n]=t(e[n]),n}function Uc(e){return e=e.replace(/\r\n/g,`
|
|
10
|
-
`),e=e.replace(/(\w+)\((.+)\)/g,(t,n,s)=>`${n}(${s.replaceAll(",",",")})`),e=e.replace(/(,)(\s+})/g,"$2"),e=e.replace(/\.\.\..+?,/g,""),e=e.replace(/({\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/(,\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/:(.+)\?(.+):/g,(t,n,s)=>`: (${n.trim()} && ${s.trim()}) ||`),e=e.replace(/([a-zA-Z0-9]+)( ?: ?{)/g,'"$1"$2'),e=e.replace(/([a-zA-Z0-9]+) ?: ?(.+?)(,|\n|})/g,(t,n,s,o)=>`"${n}":"${s.trim()}"${o}`),e=e.replace(/("'|'")/g,'"'),e=e.replaceAll(",",","),JSON.parse(e)}const de=[1e3,1e6,1e9,1e12,1e15,1e18,1e21,1e24,1e27,1e30,1e9,1e16,1e18,1e18,1e18,1e33],Pc=["thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion","gwei","bzz","btc","eth","dai","decillion"],ws=["K","M","B","T","Qa","Qi","Sx","Sp","O","N","gwei","bzz","eth","btc","dai","D"];function Zc(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 Bc(e,t){const n=(t==null?void 0:t.longForm)??!1,s=t!=null&&t.unit?` ${t.unit}`:"",o=n?Pc:ws,d=(t==null?void 0:t.precision)??1;if(e<de[0])return`${e}${s}`;for(let f=0;f<de.length-1;f++)if(e<de[f+1])return`${(e/de[f]).toFixed(d)}${n?" ":""}${o[f]}${s}`;return`${(e/de[de.length-1]).toFixed(d)}${n?" ":""}${o[de.length-1]}${s}`}function dr(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeNumber got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim(),s=ws.findIndex(o=>o.toLowerCase()===n.toLowerCase());return s===-1?t:t*de[s]}function fr(e,t,n){return e<t?t:e>n?n:e}function Lc(e,t,n){const s=e+t;return s>n?n:s}function zc(e,t,n){const s=e-t;return s<n?n:s}function Fc(e,t){return t(e),e}function Vc(e,t){e&&t(e)}function Wc(e,t){const n=Object.keys(t);for(const s of n)Array.isArray(t[s])&&Array.isArray(e[s])&&Tt(e[s],t[s])}function Hc(e){return e.splice(0,e.length),e}function qc(e){for(const t of Object.keys(e))(Rn(e[t])||Array.isArray(e[t])&&e[t].every(n=>n==null))&&delete e[t];return e}function Gc(e){for(const t of Object.entries(e))(t[1]===null||t[1]===void 0||W(t[1])&&kt(t[1]))&&delete e[t[0]];return e}function Kc(e,t){const n={};for(const[s,o]of Object.entries(e))t(s)&&(n[s]=o);return n}function Jc(e,t){const n={};for(const[s,o]of Object.entries(e))t(o)&&(n[s]=o);return n}function Yc(e,t){const n={};for(const s of Object.entries(e))n[s[0]]=t(s[1]);return n}function Qc(e,t){const n=[];let s=0;for(const o of e)n.push(t(o,s++));return n}async function Xc(e,t){try{return await e()}catch{throw t}}function eu(e,t,n){n!=null&&(e[t]=n)}function tu(e,t,n,s){const o=ye(n,s);o!=null&&ve(e,t,o)}function ru(e){const t={};for(const[n,s]of Object.entries(e))t[s]=n;return t}function nu(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 x=0;x<t.length;x++){const $=e[t[x]],U=Math.floor(g/d[x])%$.length;p[t[x]]=$[U]}f.push(p)}return f}function su(e){return Object.values(e).filter(t=>t).length}function iu(e,t,n){return e+(n?"["+t+"]":(e.length?".":"")+t)}function $t(e,t,n,s,o){if(!ue(t))return t;for(const[d,f]of Object.entries(t)){const g=iu(n,d,s);Array.isArray(f)?o?$t(e,f,g,!0,o):e[g]=f.map(p=>$t(Array.isArray(p)?[]:{},p,"",!1,o)):ue(f)?$t(e,f,g,!1,o):e[g]=f}return e}function au(e,t=!1,n){return $t({},e,n||"",!1,t)}function bs(e){if(!ue(e))return e;const t=Array.isArray(e)?[]:{};for(const[n,s]of Object.entries(e))Array.isArray(s)?ve(t,n,s.map(o=>bs(o))):ve(t,n,s);return t}function ou(e,t,n){return t[e]?t[e]:n}function _s(e,t){const n={};for(const s of e){const o=t(s);n[o]=s}return n}function cu(e,t){const n={};for(const s of e){const o=t(s);n[o]||(n[o]=[]),n[o].push(s)}return n}function uu(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function xs(e,t){const n=Math.ceil(e.length/t),s=[];for(let o=0;o<e.length;o+=n)s.push(e.slice(o,o+n));return s}function ks(e,t){const n=[],s=Math.ceil(e.length/t);for(let o=0;o<s;o++)n.push(e.slice(o*t,o*t+t));return n}function lu(e,t){const n=Math.ceil(e.length/t);return ks(e,n)}function du(e,t){return Object.values(_s(e,t))}function fu(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?Es(f,o?(p,x)=>p[1]-x[1]:(p,x)=>x[1]-p[1]):f;return n?Object.keys(g):g}function Es(e,t){return Object.fromEntries(Object.entries(e).sort(t))}function hu(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 mu(e,t,n=1){for(const s of e)s[t]+=n}function pu(e,t,n){for(const s of e)s[t]=n}function hr(e,t){const n=[];let s=[];return e.forEach((o,d)=>{(d===0||!t(o,e[d-1]))&&(s=[],n.push(s)),s.push(o)}),n}function gu(){return{map:new Map,keys:[]}}function yu(){return{map:new Map,keys:[]}}function Ss(e,t,n,s=100){if(e.map.has(t)){const o=e.keys.indexOf(t);e.keys.splice(o,1)}if(e.map.set(t,n),e.keys.push(t),e.keys.length>s){const o=e.keys.shift();o&&e.map.delete(o)}}function vu(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 wu(e,t,n,s,o=100){Ss(e,t,{validUntil:Date.now()+s,data:n},o)}function bu(e,t){const n=e.map.get(t);return n&&n.validUntil>Date.now()?n.data:null}class fe{constructor(t){this.value=t}static of(t){return new fe(t)}static empty(){return new fe(null)}map(t){return new fe(this.value!==null&&this.value!==void 0?t(this.value):null)}mapAsync(t){return this.value!==null&&this.value!==void 0?t(this.value).then(n=>fe.of(n)):Promise.resolve(fe.empty())}ifPresent(t){return this.value!==null&&this.value!==void 0&&t(this.value),this}ifPresentAsync(t){return this.value!==null&&this.value!==void 0?t(this.value).then(()=>this):Promise.resolve(this)}ifAbsent(t){return(this.value===null||this.value===void 0)&&t(),this}ifAbsentAsync(t){return this.value===null||this.value===void 0?t().then(()=>this):Promise.resolve(this)}getOrFallback(t){return this.value??t()}getOrFallbackAsync(t){return this.value!==null&&this.value!==void 0?Promise.resolve(this.value):t()}getOrThrow(){if(this.value===null||this.value===void 0)throw Error("Optional.value is empty");return this.value}}a.Optional=fe;class _u{constructor(t){this.supplier=t,this.value=null}get(){return this.value||(this.value=this.supplier()),this.value}}a.Lazy=_u;class xu{constructor(t){this.supplier=t,this.value=null}async get(){return this.value||(this.value=await this.supplier()),this.value}}a.AsyncLazy=xu;function ku(e){return()=>e.forEach(t=>t())}function Eu(e,t){return e.reduce((n,s)=>t(n)>t(s)?n:s)}function Su(e,t){const n=e.find(s=>s instanceof t);return fe.of(n)}function Tu(e,t){return e.filter(n=>n instanceof t)}function Au(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 Ou(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}class Mu{constructor(t){this.value=t,this.children=[]}}function Iu(e,t,n,s,o=!1){const d=new Map,f=[];e.forEach(p=>{const x=new Mu(p);d.set(p[t],x)}),e.forEach(p=>{const x=d.get(p[t]);if(!x)return;const $=p[n];if($){const U=d.get($);U&&U.children.push(x)}else f.push(x)});const g=p=>{p.children.sort((x,$)=>{const U=x.value[s],je=$.value[s];return o?je-U:U-je}),p.children.forEach(g)};return f.forEach(g),f}function Ts(e,t){if(Math.log2(e.length)%1!==0)throw new Error("Array length must be a power of 2");let n=[...e];for(;n.length>1;){const s=[];for(let o=0;o<n.length;o+=2){const d=n[o+1];s.push(t(n[o],d))}n=s}return n[0]}function Re(...e){const t=e.reduce((o,d)=>o+d.length,0),n=new Uint8Array(t);let s=0;return e.forEach(o=>{n.set(o,s),s+=o.length}),n}function As(e){return e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}function Os(e){return e[0]===255&&e[1]===216}function Ms(e){return e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function $u(e){return As(e)||Os(e)||Ms(e)}function Ru(e){return new Uint8Array([e])}function Cu(e){return e[0]}function Nu(e,t){const n=new ArrayBuffer(2);return new DataView(n).setUint16(0,e,t==="LE"),new Uint8Array(n)}function ju(e,t){return new DataView(e.buffer).getUint16(e.byteOffset,t==="LE")}function Du(e,t){const n=new ArrayBuffer(4);return new DataView(n).setUint32(0,e,t==="LE"),new Uint8Array(n)}function Uu(e,t){return new DataView(e.buffer).getUint32(e.byteOffset,t==="LE")}function mr(e,t){const n=new ArrayBuffer(8);return new DataView(n).setBigUint64(0,BigInt(e),t==="LE"),new Uint8Array(n)}function Pu(e,t){return new DataView(e.buffer).getBigUint64(e.byteOffset,t==="LE")}function Ce(e,t){const n=new Uint8Array(32);let s=e;if(t==="LE"){for(let o=0;o<32;o++)n[o]=Number(s&0xffn),s>>=8n;return n}for(let o=31;o>=0;o--)n[o]=Number(s&0xffn),s>>=8n;return n}function Ne(e,t){let n=0n;if(t==="LE"){for(let s=31;s>=0;s--)n=n<<8n|BigInt(e[s]);return n}for(let s=0;s<32;s++)n=n<<8n|BigInt(e[s]);return n}function Zu(e,t){const n=[];let s=0;for(const o of t)n.push(e.subarray(s,s+o)),s+=o;return n}function pr(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.subarray(s,s+t));return n}const Is=[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 Bu(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],x=e[7]^e[17]^e[27]^e[37]^e[47],$=e[8]^e[18]^e[28]^e[38]^e[48],U=e[9]^e[19]^e[29]^e[39]^e[49],je=o<<1|d>>>31,xl=d<<1|o>>>31,Je=$^je,Ye=U^xl,kl=f<<1|g>>>31,El=g<<1|f>>>31,Qe=n^kl,Xe=s^El,Sl=p<<1|x>>>31,Tl=x<<1|p>>>31,et=o^Sl,tt=d^Tl,Al=$<<1|U>>>31,Ol=U<<1|$>>>31,rt=f^Al,nt=g^Ol,Ml=n<<1|s>>>31,Il=s<<1|n>>>31,st=p^Ml,it=x^Il;e[0]^=Je,e[1]^=Ye,e[2]^=Qe,e[3]^=Xe,e[4]^=et,e[5]^=tt,e[6]^=rt,e[7]^=nt,e[8]^=st,e[9]^=it,e[10]^=Je,e[11]^=Ye,e[12]^=Qe,e[13]^=Xe,e[14]^=et,e[15]^=tt,e[16]^=rt,e[17]^=nt,e[18]^=st,e[19]^=it,e[20]^=Je,e[21]^=Ye,e[22]^=Qe,e[23]^=Xe,e[24]^=et,e[25]^=tt,e[26]^=rt,e[27]^=nt,e[28]^=st,e[29]^=it,e[30]^=Je,e[31]^=Ye,e[32]^=Qe,e[33]^=Xe,e[34]^=et,e[35]^=tt,e[36]^=rt,e[37]^=nt,e[38]^=st,e[39]^=it,e[40]^=Je,e[41]^=Ye,e[42]^=Qe,e[43]^=Xe,e[44]^=et,e[45]^=tt,e[46]^=rt,e[47]^=nt,e[48]^=st,e[49]^=it;const _r=e[0],xr=e[1],kr=e[2]<<1|e[3]>>>31,Er=e[3]<<1|e[2]>>>31,Sr=e[5]<<30|e[4]>>>2,Tr=e[4]<<30|e[5]>>>2,Ar=e[6]<<28|e[7]>>>4,Or=e[7]<<28|e[6]>>>4,Mr=e[8]<<27|e[9]>>>5,Ir=e[9]<<27|e[8]>>>5,$r=e[11]<<4|e[10]>>>28,Rr=e[10]<<4|e[11]>>>28,Cr=e[13]<<12|e[12]>>>20,Nr=e[12]<<12|e[13]>>>20,jr=e[14]<<6|e[15]>>>26,Dr=e[15]<<6|e[14]>>>26,Ur=e[17]<<23|e[16]>>>9,Pr=e[16]<<23|e[17]>>>9,Zr=e[18]<<20|e[19]>>>12,Br=e[19]<<20|e[18]>>>12,Lr=e[20]<<3|e[21]>>>29,zr=e[21]<<3|e[20]>>>29,Fr=e[22]<<10|e[23]>>>22,Vr=e[23]<<10|e[22]>>>22,Wr=e[25]<<11|e[24]>>>21,Hr=e[24]<<11|e[25]>>>21,qr=e[26]<<25|e[27]>>>7,Gr=e[27]<<25|e[26]>>>7,Kr=e[29]<<7|e[28]>>>25,Jr=e[28]<<7|e[29]>>>25,Yr=e[31]<<9|e[30]>>>23,Qr=e[30]<<9|e[31]>>>23,Xr=e[33]<<13|e[32]>>>19,en=e[32]<<13|e[33]>>>19,tn=e[34]<<15|e[35]>>>17,rn=e[35]<<15|e[34]>>>17,nn=e[36]<<21|e[37]>>>11,sn=e[37]<<21|e[36]>>>11,an=e[38]<<8|e[39]>>>24,on=e[39]<<8|e[38]>>>24,cn=e[40]<<18|e[41]>>>14,un=e[41]<<18|e[40]>>>14,ln=e[42]<<2|e[43]>>>30,dn=e[43]<<2|e[42]>>>30,fn=e[45]<<29|e[44]>>>3,hn=e[44]<<29|e[45]>>>3,mn=e[47]<<24|e[46]>>>8,pn=e[46]<<24|e[47]>>>8,gn=e[48]<<14|e[49]>>>18,yn=e[49]<<14|e[48]>>>18;e[0]=_r^~Cr&Wr,e[1]=xr^~Nr&Hr,e[2]=Cr^~Wr&nn,e[3]=Nr^~Hr&sn,e[4]=Wr^~nn&gn,e[5]=Hr^~sn&yn,e[6]=nn^~gn&_r,e[7]=sn^~yn&xr,e[8]=gn^~_r&Cr,e[9]=yn^~xr&Nr,e[10]=Ar^~Zr&Lr,e[11]=Or^~Br&zr,e[12]=Zr^~Lr&Xr,e[13]=Br^~zr&en,e[14]=Lr^~Xr&fn,e[15]=zr^~en&hn,e[16]=Xr^~fn&Ar,e[17]=en^~hn&Or,e[18]=fn^~Ar&Zr,e[19]=hn^~Or&Br,e[20]=kr^~jr&qr,e[21]=Er^~Dr&Gr,e[22]=jr^~qr&an,e[23]=Dr^~Gr&on,e[24]=qr^~an&cn,e[25]=Gr^~on&un,e[26]=an^~cn&kr,e[27]=on^~un&Er,e[28]=cn^~kr&jr,e[29]=un^~Er&Dr,e[30]=Mr^~$r&Fr,e[31]=Ir^~Rr&Vr,e[32]=$r^~Fr&tn,e[33]=Rr^~Vr&rn,e[34]=Fr^~tn&mn,e[35]=Vr^~rn&pn,e[36]=tn^~mn&Mr,e[37]=rn^~pn&Ir,e[38]=mn^~Mr&$r,e[39]=pn^~Ir&Rr,e[40]=Sr^~Ur&Kr,e[41]=Tr^~Pr&Jr,e[42]=Ur^~Kr&Yr,e[43]=Pr^~Jr&Qr,e[44]=Kr^~Yr&ln,e[45]=Jr^~Qr&dn,e[46]=Yr^~ln&Sr,e[47]=Qr^~dn&Tr,e[48]=ln^~Sr&Ur,e[49]=dn^~Tr&Pr,e[0]^=Is[t*2],e[1]^=Is[t*2+1]}}function $s(e){const t=[];for(let n=0;n<e.length;n+=4)t.push(e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24);return t}function Rs(e,t){if(!e.length){const o=new Uint8Array(136);return o[0]=t,o[135]=128,[$s(o)]}const n=pr(e,136),s=n[n.length-1];if(s.length<136){const o=new Uint8Array(136);o.set(s),o[s.length]=t,o[135]|=128,n[n.length-1]=o}if(s.length===136){const o=new Uint8Array(136);o[0]=t,o[135]=128,n.push(o)}return n.map($s)}function Cs(e,t){for(const n of t){for(let s=0;s<34;s+=2)e[s]^=n[s+1],e[s+1]^=n[s];Bu(e)}return e}function Ns(e){return new Uint8Array([e[1],e[1]>>-24,e[1]>>-16,e[1]>>-8,e[0],e[0]>>8,e[0]>>16,e[0]>>24,e[3],e[3]>>-24,e[3]>>-16,e[3]>>-8,e[2],e[2]>>8,e[2]>>16,e[2]>>24,e[5],e[5]>>-24,e[5]>>-16,e[5]>>-8,e[4],e[4]>>8,e[4]>>16,e[4]>>24,e[7],e[7]>>-24,e[7]>>-16,e[7]>>-8,e[6],e[6]>>8,e[6]>>16,e[6]>>24])}function se(e){return Ns(Cs(new Array(50).fill(0),Rs(e,1)))}function Lu(e){return Ns(Cs(new Array(50).fill(0),Rs(e,6)))}function zu(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 Fu(e,t){const n=Math.min(e.length,t.length);for(let s=0;s<n;s++)if(e[s]!==t[s])return e.subarray(0,s);return e.subarray(0,n)}function Vu(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 Wu(e,t,n){const s=Math.floor(t/8),o=t%8;return e[s]>>(n==="BE"?7-o:o)&1}function Hu(e,t,n=0){for(let s=n;s<e.length;s++)for(let o=0;o<t.length&&e[s+o]===t[o];o++)if(o===t.length-1)return s;return-1}function js(e,t,n=0){if(e.length>=t)return e;const s=new Uint8Array(t);return s.fill(n),s.set(e,t-e.length),s}function qu(e,t,n=0){const s=e.length%t;return s===0?e:js(e,e.length+t-s,n)}function Ds(e,t,n=0){if(e.length>=t)return e;const s=new Uint8Array(t);return s.fill(n),s.set(e,0),s}function Gu(e,t,n=0){const s=e.length%t;return s===0?e:Ds(e,e.length+t-s,n)}function Ku(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 Ju(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 Ge(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 Yu(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 Us(e,t){return R(e,t)===0n?0n:t%4n===3n?Yu(e,(t+1n)/4n,t):null}const B=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,D=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Rt=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Ct=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;function gr(e,t,n){if(t===0n)return[0n,0n];const s=R(3n*e*e*Ge(2n*t,n),n),o=R(s*s-2n*e,n),d=R(s*(e-o)-t,n);return[o,d]}function Nt(e,t,n,s,o){if(e===0n&&t===0n)return[n,s];if(n===0n&&s===0n)return[e,t];if(e===n&&t===R(-s,o))return[0n,0n];if(e===n&&t===s)return gr(e,t,o);const d=R((s-t)*Ge(n-e,o),o),f=R(d*d-e-n,o),g=R(d*(e-f)-t,o);return[f,g]}function Qu(e){if(e<=0n||e>=D)throw new Error("Invalid private key");return xe(Rt,Ct,e,B)}function Xu(e){const t=e[1]%2n===0n?2:3;return new Uint8Array([t,...Ce(e[0],"BE")])}function el(e){if(e.length!==33||e[0]!==2&&e[0]!==3)throw new Error("Invalid compressed public key");const t=Ne(e.slice(1),"BE"),n=Us(R(t**3n+7n,B),B);if(!n)throw Error("Invalid x: does not correspond to a valid curve point");const s=R(-n,B),o=n%2n===0n;return[t,e[0]===2?o?n:s:o?s:n]}function tl(e){const t=new Uint8Array(20),n=se(Re(Ce(e[0],"BE"),Ce(e[1],"BE")));return t.set(n.subarray(12)),t}function rl(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 xe(e,t,n,s){let o=[0n,0n],d=[e,t];const f=n.toString(2);for(const g of f)g==="0"?(d=Nt(o[0],o[1],d[0],d[1],s),o=gr(o[0],o[1],s)):(o=Nt(o[0],o[1],d[0],d[1],s),d=gr(d[0],d[1],s));return o}function nl(e,t,n){return Ps(Ne(se(e),"BE"),t,n)}function Ps(e,t,n){if(t<=0n||t>=D)throw new Error("Invalid private key");if(n||(n=R(Ne(se(Re(se(Ce(t,"BE")),Ce(e,"BE"))),"BE"),D)),n<=0n||n>=D)throw new Error("Invalid nonce");const s=R(e,D),o=xe(Rt,Ct,n,B),d=R(o[0],D);let f=R((s+R(d,D)*t)*Ge(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 sl(e,t,n,s){const o=Us(R(t**3n+7n,B),B);if(!o)throw new Error("Invalid r: does not correspond to a valid curve point");const d=s===27n?0n:1n,f=o%2n===d?o:B-o,g=R(Ne(se(e),"BE"),D),p=xe(t,f,n,B),x=xe(Rt,Ct,g,B),$=Nt(p[0],p[1],x[0],R(-x[1],B),B);return xe($[0],$[1],Ge(t,D),B)}function il(e,t,n,s){const o=R(Ne(se(e),"BE"),D),d=Ge(s,D),f=R(o*d,D),g=R(n*d,D),p=xe(Rt,Ct,f,B),x=xe(t[0],t[1],g,B),$=Nt(p[0],p[1],x[0],x[1],B);return n===R($[0],D)}class Zs{constructor(t){this.cursor=0,this.buffer=t}read(t){const n=this.buffer.subarray(this.cursor,this.cursor+t);return this.cursor+=t,n}max(){return this.buffer.length-this.cursor}}a.Uint8ArrayReader=Zs;class Bs{constructor(t){this.buffer=t,this.cursor=0}write(t){const n=Math.min(this.max(),t.max());return this.buffer.set(t.read(n),this.cursor),this.cursor+=n,n}max(){return this.buffer.length-this.cursor}}a.Uint8ArrayWriter=Bs;class jt{constructor(t,n=0n){this.span=n,this.writer=new Bs(new Uint8Array(t))}build(){return Re(mr(this.span,"LE"),this.writer.buffer)}hash(){const t=Ts(pr(this.writer.buffer,32),(n,s)=>se(Re(n,s)));return se(Re(mr(this.span,"LE"),t))}}a.Chunk=jt;class yr{constructor(t,n=4096){this.counters=[1],this.capacity=n,this.chunks=[new jt(n)],this.onChunk=t}static async root(t,n=4096){const s=new r(r.NOOP,n);return await s.append(t),s.finalize()}async append(t,n=0,s=0n){const o=new Zs(t);for(;o.max()>0;){this.chunks[n].writer.max()===0&&await this.elevate(n);const d=this.chunks[n].writer.write(o);s?this.chunks[n].span+=s:this.chunks[0].span+=BigInt(d)}}async elevate(t){this.counters[t]=++this.counters[t]%(this.capacity/32),this.chunks[t+1]||(this.chunks.push(new jt(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 jt(this.capacity)}async finalize(t=0){return this.chunks[t+1]?this.counters[t]===1?(await this.elevate(t+1),this.chunks[t+1]=this.chunks[t],this.finalize(t+1)):(await this.elevate(t),this.finalize(t+1)):(await this.onChunk(this.chunks[t]),this.chunks[t])}}a.MerkleTree=yr,r=yr,yr.NOOP=async e=>{};class Y{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 Y(BigInt(s+o),n)}add(t){return this.assertSameScale(t),new Y(this.value+t.value,this.scale)}subtract(t){return this.assertSameScale(t),new Y(this.value-t.value,this.scale)}multiply(t){return new Y(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 Y(n,this.scale),new Y(s,this.scale)]}exchange(t,n,s){if(t==="*"){const d=this.value*n.value/10n**BigInt(this.scale);return new Y(d,s)}this.assertSameScale(n);const o=this.value*10n**BigInt(s)/n.value;return new Y(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=Y;function al(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 Dt(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 ol(e,t,n,s){const o=Dt(e,t,n,s);if(!o)return null;try{return dr(o)}catch{throw new Error(`Invalid number argument ${t}: ${o}`)}}function cl(e,t,n,s){const o=e.some(p=>p.endsWith("-"+t)),d=Dt(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 Ls(e,t,n,s){const o=Dt(e,t,n,s);if(!o)throw new Error(`Missing argument ${t}`);return o}function ul(e,t,n,s){const o=Ls(e,t,n,s);try{return dr(o)}catch{throw new Error(`Invalid argument ${t}: ${o}`)}}function zs(e,t){const n=e[t];e.splice(t,1),e.unshift(n)}function ll(e,t){const n=[...e];return zs(n,t),n}function Fs(e,t){return{x:e.x+t.x,y:e.y+t.y}}function dl(e,t){return{x:e.x-t.x,y:e.y-t.y}}function vr(e,t){return{x:e.x*t,y:e.y*t}}function fl(e){const t=Math.sqrt(e.x*e.x+e.y*e.y);return{x:e.x/t,y:e.y/t}}function Vs(e,t,n){return{x:e.x+Math.cos(t)*n,y:e.y+Math.sin(t)*n}}function Ws(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Ke(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 hl(e,t,n){var s,o;return((s=e[t+1])==null?void 0:s[n])&&((o=e[t-1])==null?void 0:o[n])&&!e[t][n-1]&&!e[t][n+1]}function ml(e,t,n){var s,o;return e[t][n+1]&&e[t][n-1]&&!((s=e[t-1])!=null&&s[n])&&!((o=e[t+1])!=null&&o[n])}function Hs(e,t,n){var s;return!((s=e[t-1])!=null&&s[n])}function qs(e,t,n){var s;return!((s=e[t+1])!=null&&s[n])}function Gs(e,t,n){return!e[t][n-1]}function Ks(e,t,n){return!e[t][n+1]}function pl(e,t,n){var o,d,f,g,p,x,$,U;const s=[];return e[t][n]?hl(e,t,n)||ml(e,t,n)?[]:(!((o=e[t-1])!=null&&o[n-1])&&Hs(e,t,n)&&Gs(e,t,n)&&s.push({x:t,y:n}),!((d=e[t+1])!=null&&d[n-1])&&qs(e,t,n)&&Gs(e,t,n)&&s.push({x:t+1,y:n}),!((f=e[t-1])!=null&&f[n+1])&&Hs(e,t,n)&&Ks(e,t,n)&&s.push({x:t,y:n+1}),!((g=e[t+1])!=null&&g[n+1])&&qs(e,t,n)&&Ks(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}),(x=e[t+1])!=null&&x[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 gl(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=pl(e,d,f);for(const p of g)o.some(x=>x.x===p.x&&x.y===p.y)||o.push(p)}return o.map(d=>({x:d.x*t,y:d.y*t}))}function yl(e,t){const n=Ke(e,(p,x)=>e[p][x]===0&&e[p][x+1]!==0,"row-first").map(p=>({...p,dx:1,dy:0})),s=Ke(e,(p,x)=>e[p][x]===0&&e[p][x-1]!==0,"row-first").map(p=>({...p,dx:1,dy:0})),o=Ke(e,(p,x)=>{var $;return e[p][x]===0&&(($=e[p-1])==null?void 0:$[x])!==0},"column-first").map(p=>({...p,dx:0,dy:1})),d=Ke(e,(p,x)=>{var $;return e[p][x]===0&&(($=e[p+1])==null?void 0:$[x])!==0},"column-first").map(p=>({...p,dx:0,dy:1}));n.forEach(p=>p.y++),d.forEach(p=>p.x++);const f=hr([...o,...d],(p,x)=>p.x===x.x&&p.y-1===x.y),g=hr([...s,...n],(p,x)=>p.y===x.y&&p.x-1===x.x);return[...f,...g].map(p=>({start:p[0],end:Ve(p)})).map(p=>({start:vr(p.start,t),end:vr(Fs(p.end,{x:p.start.dx,y:p.start.dy}),t)}))}function vl(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}function wl(e,t){return t.map(n=>vl(e,n)).sort((n,s)=>n-s)}function Js(e,t,n,s){const o=(s.y-n.y)*(t.x-e.x)-(s.x-n.x)*(t.y-e.y);if(o===0)return null;let d=e.y-n.y,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 wr(e,t,n){const s=[],o=Vs(e,n,1e4);for(const d of t){const f=Js(e,o,d.start,d.end);f&&s.push(f)}return s.length?s.reduce((d,f)=>{const g=Ws(e,f),p=Ws(e,d);return g<p?f:d}):null}function bl(e,t,n){const s=wl(e,n),o=[];for(const d of s){const f=wr(e,t,d-.001),g=wr(e,t,d+.001);f&&o.push(f),g&&o.push(g)}return o}class br{constructor(){this.subscribers=[]}subscribe(t){return this.subscribers.push(t),()=>{this.subscribers=this.subscribers.filter(n=>n!==t)}}publish(t){this.subscribers.forEach(n=>n(t))}clear(){this.subscribers=[]}getSubscriberCount(){return this.subscribers.length}}a.PubSubChannel=br;class _l{constructor(t,n){this.queue=[],this.running=0,this.onProcessed=new br,this.onDrained=new br,this.concurrency=t,this.capacity=n}process(){if(this.running>=this.concurrency)return;const t=this.queue.shift();t&&(this.running++,t().finally(()=>{this.running--,this.process(),this.onProcessed.publish(),this.running===0&&this.onDrained.publish()}))}enqueue(t){if(this.queue.length<this.capacity)return this.queue.push(t),this.process(),Promise.resolve();if(this.onProcessed.getSubscriberCount())throw Error("Queue capacity is full");return new Promise(n=>{this.onProcessed.subscribe(()=>{this.queue.length<this.capacity&&(this.queue.push(t),this.process(),this.onProcessed.clear(),n())})})}drain(){if(this.running===0)return Promise.resolve();if(this.onDrained.getSubscriberCount())throw Error("Already draining");return new Promise(t=>{this.onDrained.subscribe(()=>{this.onDrained.clear(),t()})})}}a.AsyncQueue=_l,a.Binary={hexToUint8Array:To,uint8ArrayToHex:Ao,base64ToUint8Array:xo,uint8ArrayToBase64:ko,base32ToUint8Array:Eo,uint8ArrayToBase32:So,log2Reduce:Ts,partition:pr,concatBytes:Re,numberToUint8:Ru,uint8ToNumber:Cu,numberToUint16:Nu,uint16ToNumber:ju,numberToUint32:Du,uint32ToNumber:Uu,numberToUint64:mr,uint64ToNumber:Pu,numberToUint256:Ce,uint256ToNumber:Ne,sliceBytes:Zu,keccak256:se,sha3_256:Lu,proximity:zu,commonPrefix:Fu,setBit:Vu,getBit:Wu,indexOf:Hu,equals:Ju,padStart:js,padStartToMultiple:qu,padEnd:Ds,padEndToMultiple:Gu,xorCypher:Ku},a.Elliptic={privateKeyToPublicKey:Qu,compressPublicKey:Xu,publicKeyFromCompressed:el,publicKeyToAddress:tl,signMessage:nl,signHash:Ps,verifySignature:il,recoverPublicKey:sl,checksumEncode:rl},a.Random={intBetween:Fe,floatBetween:Mn,chance:In,signed:wi,makeSeededRng:Ht,point:_i,procs:xi},a.Arrays={countUnique:fu,makeUnique:du,splitBySize:uu,splitByCount:xs,index:_s,indexCollection:cu,onlyOrThrow:m,onlyOrNull:w,firstOrThrow:E,firstOrNull:v,shuffle:h,initialize:j,initialize2D:ne,rotate2D:re,containsShape:ze,glue:Ia,pluck:Wt,pick:qt,pickMany:ki,pickManyUnique:Ei,pickWeighted:Ai,pickRandomIndices:Oe,pickGuaranteed:Si,last:Ve,pipe:$n,makePipe:Ti,sortWeighted:Oi,pushAll:Tt,unshiftAll:Oa,filterAndRemove:Jo,merge:Wc,empty:Hc,pushToBucket:Sa,unshiftAndLimit:Ta,atRolling:Aa,group:hr,createOscillator:Rc,organiseWithLimits:Nc,tickPlaybook:al,getArgument:Dt,getBooleanArgument:cl,getNumberArgument:ol,requireStringArgument:Ls,requireNumberArgument:ul,bringToFront:ll,bringToFrontInPlace:zs,findInstance:Su,filterInstances:Tu,interleave:Au,toggle:Ou,createHierarchy:Iu,multicall:ku,maxBy:Eu},a.System={sleepMillis:l,forever:Ni,scheduleMany:Ua,waitFor:Ko,expandError:_a,runAndSetInterval:ji},a.Numbers={make:dr,sum:Za,average:Ba,median:La,getDistanceFromMidpoint:za,clamp:fr,range:Vn,interpolate:Pa,createSequence:$c,increment:Lc,decrement:zc,format:Bc,fromDecimals:Zc,makeStorage:_c,asMegabytes:Di,convertBytes:Ui,hexToRgb:Pi,rgbToHex:Zi,haversineDistanceToMeters:Bi,roundToNearest:xt,formatDistance:Li,triangularNumber:zi,searchFloat:Fi},a.Promises={raceFulfilled:c,invert:i,runInParallelBatches:u},a.Dates={getTimestamp:ic,getTimeDelta:fs,secondsToHumanTime:ac,countCycles:oc,isoDate:Xo,throttle:cc,timeSince:lc,dateTimeSlug:ec,unixTimestamp:Qo,fromUtcString:tc,fromMillis:rc,getProgress:dc,humanizeTime:It,humanizeProgress:Go,createTimeDigits:J,mapDayNumber:hs,getDayInfoFromDate:ur,getDayInfoFromDateTimeString:hc,seconds:mc,minutes:pc,hours:gc,days:yc,make:wc,normalizeTime:nc,absoluteDays:be},a.Objects={safeParse:Ic,deleteDeep:$i,getDeep:ye,setDeep:ve,incrementDeep:Mi,ensureDeep:Ii,replaceDeep:Ri,getFirstDeep:Ci,deepMergeInPlace:we,deepMerge2:xa,deepMerge3:ka,mapAllAsync:Ma,cloneWithJson:Yo,sortObject:ps,sortArray:gs,sortAny:_e,deepEquals:ys,deepEqualsEvery:Mc,runOn:Fc,ifPresent:Vc,zip:Fn,zipSum:Ea,removeEmptyArrays:qc,removeEmptyValues:Gc,flatten:au,unflatten:bs,match:ou,sort:Es,map:Yc,mapIterable:Qc,filterKeys:Kc,filterValues:Jc,rethrow:Xc,setSomeOnObject:eu,setSomeDeep:tu,flip:ru,getAllPermutations:nu,countTruthyValues:su,transformToArray:hu,setMulti:pu,incrementMulti:mu,createBidirectionalMap:gu,createTemporalBidirectionalMap:yu,pushToBidirectionalMap:Ss,unshiftToBidirectionalMap:vu,addToTemporalBidirectionalMap:wu,getFromTemporalBidirectionalMap:bu,createStatefulToggle:Cc,diffKeys:jc,pickRandomKey:vs,mapRandomKey:Dc,fromObjectString:Uc,toQueryString:ls,parseQueryString:Bo,hasKey:Lo,selectMax:zo,reposition:Fo,unwrapSingleKey:Vo,parseKeyValues:Wo},a.Types={isFunction:Kt,isObject:ue,isStrictlyObject:Me,isEmptyArray:Rn,isEmptyObject:Vi,isUndefined:Gt,isString:W,isNumber:le,isBoolean:Cn,isDate:Ie,isBlank:kt,isId:Jt,isIntegerString:Nn,isHexString:jn,isUrl:Ln,isNullable:ya,asString:Zn,asHexString:na,asSafeString:sa,asIntegerString:ra,asNumber:Et,asFunction:ia,asInteger:Xt,asBoolean:aa,asDate:oa,asNullableString:ca,asEmptiableString:ua,asId:la,asTime:da,asArray:fa,asObject:St,asNullableObject:ha,asStringMap:ma,asNumericDictionary:pa,asUrl:ga,asNullable:va,asOptional:wa,enforceObjectShape:zn,enforceArrayShape:ba,isPng:As,isJpg:Os,isWebp:Ms,isImage:$u},a.Strings={tokenizeByCount:lu,tokenizeByLength:ks,searchHex:Xi,searchSubstring:ea,randomHex:ta,randomLetter:Ki,randomAlphanumeric:Ji,randomRichAscii:Yi,randomUnicode:Qi,includesAny:Fa,slugify:er,normalForm:Wa,enumify:Ya,escapeHtml:Xa,decodeHtmlEntities:to,after:tr,afterLast:Hn,before:Wn,beforeLast:rr,betweenWide:ro,betweenNarrow:no,getPreLine:xc,containsWord:or,containsWords:Do,joinUrl:ms,getFuzzyMatchScore:At,sortByFuzzyScore:Qa,splitOnce:nr,splitAll:qn,randomize:oo,expand:Gn,shrinkTrim:He,capitalize:Ot,decapitalize:Kn,csvEscape:mo,parseCsv:qo,surroundInOut:Ja,getExtension:sr,getBasename:ir,normalizeEmail:so,normalizeFilename:io,parseFilename:ao,camelToTitle:Ha,slugToTitle:qa,slugToCamel:Ga,joinHumanly:Ka,findWeightedPair:ts,extractBlock:rs,extractAllBlocks:yo,replaceBlocks:vo,indexOfEarliest:$e,lastIndexOfBefore:es,parseHtmlAttributes:Uo,readNextWord:Mt,resolveVariables:Po,resolveVariableWithDefaultSyntax:cs,resolveRemainingVariablesWithDefaults:us,isLetter:Jn,isDigit:Yn,isLetterOrDigit:qe,isValidObjectPathCharacter:lo,insert:fo,indexOfRegex:Qn,lineMatches:Xn,linesMatchInOrder:ho,represent:We,resolveMarkdownLinks:Zo,buildUrl:Ho,isChinese:Va,replaceBetweenStrings:Sc,describeMarkdown:Tc,isBalanced:Ac,textToFormat:Oc,splitFormatting:wo,splitHashtags:bo,splitUrls:_o,route:Oo,explodeReplace:ar,generateVariants:Mo,replaceWord:Io,replacePascalCaseWords:$o,stripHtml:Ro,breakLine:os,measureTextWidth:Co,toLines:No,levenshteinDistance:jo},a.Assertions={asEqual:$a,asTrue:Ra,asTruthy:Ca,asFalse:Na,asFalsy:ja,asEither:Da},a.Cache={get:kc,invalidate:Ec},a.Vector={addPoint:Fs,subtractPoint:dl,multiplyPoint:vr,normalizePoint:fl,pushPoint:Vs,filterCoordinates:Ke,findCorners:gl,findLines:yl,raycast:wr,raycastCircle:bl,getLineIntersectionPoint:Js}})(si);const C=Dl(si);C.Arrays;C.Assertions;const L=C.Binary;C.Cache;C.Dates;C.Elliptic;C.Numbers;C.Objects;C.Pagination;C.Promises;C.Random;C.Strings;C.System;C.Types;C.Optional;C.Vector;C.PubSubChannel;C.Chunk;const Ul=C.MerkleTree;C.FixedPointNumber;C.Lazy;C.AsyncLazy;C.AsyncQueue;C.Uint8ArrayReader;C.Uint8ArrayWriter;const Pl=new TextEncoder,Qs=1,Xs=4096,wn=4096,Zl=32;function ii(a,r){return r=typeof r=="number"?O.FeedIndex.fromBigInt(BigInt(r)):r,new O.Identifier(L.keccak256(L.concatBytes(a.toUint8Array(),r.toUint8Array())))}function Bl(a){const r=a.slice(0,O.Span.LENGTH),i=a.slice(O.Span.LENGTH),c=Ll(i),u=L.keccak256(L.concatBytes(r,c));return new O.Reference(u)}function Ll(a){if(a.length>wn)throw new O.BeeArgumentError(`payload size ${a.length} exceeds maximum chunk payload size ${wn}`,a);const r=new Uint8Array(wn);return r.set(a),L.log2Reduce(L.partition(r,Zl),(i,c)=>L.keccak256(L.concatBytes(i,c)))}function ei(a){if(a instanceof Uint8Array||(a=Pl.encode(a)),a.length<Qs||a.length>Xs)throw new RangeError(`payload size ${a.length} exceeds limits [${Qs}, ${Xs}]`);const r=O.Span.fromBigInt(BigInt(a.length)),i=L.concatBytes(r.toUint8Array(),a);return{data:i,span:r,payload:O.Bytes.fromSlice(i,O.Span.LENGTH),address:Bl(i)}}function zl(a,r){return new O.Reference(L.keccak256(L.concatBytes(a.toUint8Array(),r.toUint8Array())))}function ti(a,r,i){r=new O.Identifier(r),i=new O.PrivateKey(i);const c=zl(r,i.publicKey().address()),u=i.sign(L.concatBytes(r.toUint8Array(),a.address.toUint8Array())),l=L.concatBytes(r.toUint8Array(),u.toUint8Array(),a.data),h=O.Span.fromSlice(a.data,0),m=O.Bytes.fromSlice(a.data,O.Span.LENGTH);return{data:l,identifier:r,signature:u,span:h,payload:m,address:c,owner:i.publicKey().address()}}class Q{constructor(){}static getInstance(){return Q.instance||(Q.instance=new Q),Q.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 oe{constructor(){this.logger=Q.getInstance()}static getInstance(){return oe.instance||(oe.instance=new oe),oe.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 Fl=Q.getInstance(),Vl=oe.getInstance();function Wl(a){return new Promise(r=>{setTimeout(r,a)})}function _n(a){return(a.startsWith("0x")?a.slice(2):a).toLowerCase()}async function xn(a,r=3,i=250){return new Promise((c,u)=>{a().then(c).catch(l=>{r>0?(Fl.info(`Retrying... Attempts left: ${r}. Error: ${l.message}`),setTimeout(()=>{xn(a,r-1,i).then(c).catch(u)},i)):(Vl.handleError(l,"Utils.retryAwaitableAsync"),u(l))})})}class Hl{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 I;(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})(I||(I={}));var kn;(function(a){a.mergeShapes=(r,i)=>({...r,...i})})(kn||(kn={}));const _=I.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ae=a=>{switch(typeof a){case"undefined":return _.undefined;case"string":return _.string;case"number":return isNaN(a)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(a)?_.array:a===null?_.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?_.promise:typeof Map<"u"&&a instanceof Map?_.map:typeof Set<"u"&&a instanceof Set?_.set:typeof Date<"u"&&a instanceof Date?_.date:_.object;default:return _.unknown}},y=I.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"]),ql=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,I.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 Ze=(a,r)=>{let i;switch(a.code){case y.invalid_type:a.received===_.undefined?i="Required":i=`Expected ${a.expected}, received ${a.received}`;break;case y.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(a.expected,I.jsonStringifyReplacer)}`;break;case y.unrecognized_keys:i=`Unrecognized key(s) in object: ${I.joinValues(a.keys,", ")}`;break;case y.invalid_union:i="Invalid input";break;case y.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${I.joinValues(a.options)}`;break;case y.invalid_enum_value:i=`Invalid enum value. Expected ${I.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}"`:I.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,I.assertNever(a)}return{message:i}};let ai=Ze;function Gl(a){ai=a}function Ut(){return ai}const Pt=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}},Kl=[];function b(a,r){const i=Ut(),c=Pt({issueData:r,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,i,i===Ze?void 0:Ze].filter(u=>!!u)});a.common.issues.push(c)}class z{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(r,i){const c=[];for(const u of i){if(u.status==="aborted")return T;u.status==="dirty"&&r.dirty(),c.push(u.value)}return{status:r.value,value:c}}static async mergeObjectAsync(r,i){const c=[];for(const u of i){const l=await u.key,h=await u.value;c.push({key:l,value:h})}return z.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"}),Ue=a=>({status:"dirty",value:a}),F=a=>({status:"valid",value:a}),En=a=>a.status==="aborted",Sn=a=>a.status==="dirty",Ee=a=>a.status==="valid",ct=a=>typeof Promise<"u"&&a instanceof Promise;function Zt(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 oi(a,r,i,c,u){if(typeof r=="function"?a!==r||!u:!r.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r.set(a,i),i}var k;(function(a){a.errToObj=r=>typeof r=="string"?{message:r}:r||{},a.toString=r=>typeof r=="string"?r:r==null?void 0:r.message})(k||(k={}));var at,ot;class ee{constructor(r,i,c,u){this._cachedPath=[],this.parent=r,this.data=i,this._path=c,this._key=u}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ri=(a,r)=>{if(Ee(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 A(a){if(!a)return{};const{errorMap:r,invalid_type_error:i,required_error:c,description:u}=a;if(r&&(i||c))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return r?{errorMap:r,description:u}:{errorMap:(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 M{get description(){return this._def.description}_getType(r){return ae(r.data)}_getOrReturnCtx(r,i){return i||{common:r.parent.common,data:r.data,parsedType:ae(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}_processInputParams(r){return{status:new z,ctx:{common:r.parent.common,data:r.data,parsedType:ae(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}}_parseSync(r){const i=this._parse(r);if(ct(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:ae(r)},l=this._parseSync({data:r,path:u.path,parent:u});return ri(u,l)}"~validate"(r){var i,c;const u={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:ae(r)};if(!this["~standard"].async)try{const l=this._parseSync({data:r,path:[],parent:u});return Ee(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=>Ee(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:ae(r)},u=this._parse({data:r,path:c.path,parent:c}),l=await(ct(u)?u:Promise.resolve(u));return ri(c,l)}refine(r,i){const c=u=>typeof i=="string"||typeof i>"u"?{message:i}:typeof i=="function"?i(u):i;return this._refinement((u,l)=>{const 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 K({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 X.create(this,this._def)}nullable(){return ge.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return G.create(this)}promise(){return Le.create(this,this._def)}or(r){return ft.create([this,r],this._def)}and(r){return ht.create(this,r,this._def)}transform(r){return new K({...A(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:r}})}default(r){const i=typeof r=="function"?r:()=>r;return new vt({...A(this._def),innerType:this,defaultValue:i,typeName:S.ZodDefault})}brand(){return new An({typeName:S.ZodBranded,type:this,...A(this._def)})}catch(r){const i=typeof r=="function"?r:()=>r;return new wt({...A(this._def),innerType:this,catchValue:i,typeName:S.ZodCatch})}describe(r){const i=this.constructor;return new i({...this._def,description:r})}pipe(r){return _t.create(this,r)}readonly(){return bt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Jl=/^c[^\s-]{8,}$/i,Yl=/^[0-9a-z]+$/,Ql=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Xl=/^[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,ed=/^[a-z0-9_-]{21}$/i,td=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rd=/^[-+]?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)?)??$/,nd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let bn;const id=/^(?:(?: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])$/,ad=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,od=/^(([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]))$/,cd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ud=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ld=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ci="((\\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])))",dd=new RegExp(`^${ci}$`);function ui(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 fd(a){return new RegExp(`^${ui(a)}$`)}function li(a){let r=`${ci}T${ui(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 hd(a,r){return!!((r==="v4"||!r)&&id.test(a)||(r==="v6"||!r)&&od.test(a))}function md(a,r){if(!td.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 pd(a,r){return!!((r==="v4"||!r)&&ad.test(a)||(r==="v6"||!r)&&cd.test(a))}class q extends M{_parse(r){if(this._def.coerce&&(r.data=String(r.data)),this._getType(r)!==_.string){const l=this._getOrReturnCtx(r);return b(l,{code:y.invalid_type,expected:_.string,received:l.parsedType}),T}const c=new z;let u;for(const l of this._def.checks)if(l.kind==="min")r.data.length<l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code: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),b(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?b(u,{code:y.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):m&&b(u,{code:y.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),c.dirty())}else if(l.kind==="email")nd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"email",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="emoji")bn||(bn=new RegExp(sd,"u")),bn.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"emoji",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="uuid")Xl.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"uuid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="nanoid")ed.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"nanoid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid")Jl.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cuid",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid2")Yl.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cuid2",code:y.invalid_string,message:l.message}),c.dirty());else if(l.kind==="ulid")Ql.test(r.data)||(u=this._getOrReturnCtx(r,u),b(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),b(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),b(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),b(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),b(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),b(u,{code:y.invalid_string,validation:{endsWith:l.value},message:l.message}),c.dirty()):l.kind==="datetime"?li(l).test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:y.invalid_string,validation:"datetime",message:l.message}),c.dirty()):l.kind==="date"?dd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:y.invalid_string,validation:"date",message:l.message}),c.dirty()):l.kind==="time"?fd(l).test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:y.invalid_string,validation:"time",message:l.message}),c.dirty()):l.kind==="duration"?rd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"duration",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="ip"?hd(r.data,l.version)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"ip",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="jwt"?md(r.data,l.alg)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"jwt",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="cidr"?pd(r.data,l.version)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cidr",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="base64"?ud.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"base64",code:y.invalid_string,message:l.message}),c.dirty()):l.kind==="base64url"?ld.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"base64url",code:y.invalid_string,message:l.message}),c.dirty()):I.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,...k.errToObj(c)})}_addCheck(r){return new q({...this._def,checks:[...this._def.checks,r]})}email(r){return this._addCheck({kind:"email",...k.errToObj(r)})}url(r){return this._addCheck({kind:"url",...k.errToObj(r)})}emoji(r){return this._addCheck({kind:"emoji",...k.errToObj(r)})}uuid(r){return this._addCheck({kind:"uuid",...k.errToObj(r)})}nanoid(r){return this._addCheck({kind:"nanoid",...k.errToObj(r)})}cuid(r){return this._addCheck({kind:"cuid",...k.errToObj(r)})}cuid2(r){return this._addCheck({kind:"cuid2",...k.errToObj(r)})}ulid(r){return this._addCheck({kind:"ulid",...k.errToObj(r)})}base64(r){return this._addCheck({kind:"base64",...k.errToObj(r)})}base64url(r){return this._addCheck({kind:"base64url",...k.errToObj(r)})}jwt(r){return this._addCheck({kind:"jwt",...k.errToObj(r)})}ip(r){return this._addCheck({kind:"ip",...k.errToObj(r)})}cidr(r){return this._addCheck({kind:"cidr",...k.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,...k.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,...k.errToObj(r==null?void 0:r.message)})}duration(r){return this._addCheck({kind:"duration",...k.errToObj(r)})}regex(r,i){return this._addCheck({kind:"regex",regex:r,...k.errToObj(i)})}includes(r,i){return this._addCheck({kind:"includes",value:r,position:i==null?void 0:i.position,...k.errToObj(i==null?void 0:i.message)})}startsWith(r,i){return this._addCheck({kind:"startsWith",value:r,...k.errToObj(i)})}endsWith(r,i){return this._addCheck({kind:"endsWith",value:r,...k.errToObj(i)})}min(r,i){return this._addCheck({kind:"min",value:r,...k.errToObj(i)})}max(r,i){return this._addCheck({kind:"max",value:r,...k.errToObj(i)})}length(r,i){return this._addCheck({kind:"length",value:r,...k.errToObj(i)})}nonempty(r){return this.min(1,k.errToObj(r))}trim(){return new q({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new q({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new q({...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}}q.create=a=>{var r;return new q({checks:[],typeName:S.ZodString,coerce:(r=a==null?void 0:a.coerce)!==null&&r!==void 0?r:!1,...A(a)})};function gd(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 he extends M{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(r){if(this._def.coerce&&(r.data=Number(r.data)),this._getType(r)!==_.number){const l=this._getOrReturnCtx(r);return b(l,{code:y.invalid_type,expected:_.number,received:l.parsedType}),T}let c;const u=new z;for(const l of this._def.checks)l.kind==="int"?I.isInteger(r.data)||(c=this._getOrReturnCtx(r,c),b(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),b(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),b(c,{code:y.too_big,maximum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),u.dirty()):l.kind==="multipleOf"?gd(r.data,l.value)!==0&&(c=this._getOrReturnCtx(r,c),b(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),b(c,{code:y.not_finite,message:l.message}),u.dirty()):I.assertNever(l);return{status:u.value,value:r.data}}gte(r,i){return this.setLimit("min",r,!0,k.toString(i))}gt(r,i){return this.setLimit("min",r,!1,k.toString(i))}lte(r,i){return this.setLimit("max",r,!0,k.toString(i))}lt(r,i){return this.setLimit("max",r,!1,k.toString(i))}setLimit(r,i,c,u){return new he({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:c,message:k.toString(u)}]})}_addCheck(r){return new he({...this._def,checks:[...this._def.checks,r]})}int(r){return this._addCheck({kind:"int",message:k.toString(r)})}positive(r){return this._addCheck({kind:"min",value:0,inclusive:!1,message:k.toString(r)})}negative(r){return this._addCheck({kind:"max",value:0,inclusive:!1,message:k.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:0,inclusive:!0,message:k.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:0,inclusive:!0,message:k.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:k.toString(i)})}finite(r){return this._addCheck({kind:"finite",message:k.toString(r)})}safe(r){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:k.toString(r)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:k.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"&&I.isInteger(r.value))}get isFinite(){let r=null,i=null;for(const c of this._def.checks){if(c.kind==="finite"||c.kind==="int"||c.kind==="multipleOf")return!0;c.kind==="min"?(i===null||c.value>i)&&(i=c.value):c.kind==="max"&&(r===null||c.value<r)&&(r=c.value)}return Number.isFinite(i)&&Number.isFinite(r)}}he.create=a=>new he({checks:[],typeName:S.ZodNumber,coerce:(a==null?void 0:a.coerce)||!1,...A(a)});class me extends M{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(r){if(this._def.coerce)try{r.data=BigInt(r.data)}catch{return this._getInvalidInput(r)}if(this._getType(r)!==_.bigint)return this._getInvalidInput(r);let c;const u=new z;for(const l of this._def.checks)l.kind==="min"?(l.inclusive?r.data<l.value:r.data<=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code: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),b(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),b(c,{code:y.not_multiple_of,multipleOf:l.value,message:l.message}),u.dirty()):I.assertNever(l);return{status:u.value,value:r.data}}_getInvalidInput(r){const i=this._getOrReturnCtx(r);return b(i,{code:y.invalid_type,expected:_.bigint,received:i.parsedType}),T}gte(r,i){return this.setLimit("min",r,!0,k.toString(i))}gt(r,i){return this.setLimit("min",r,!1,k.toString(i))}lte(r,i){return this.setLimit("max",r,!0,k.toString(i))}lt(r,i){return this.setLimit("max",r,!1,k.toString(i))}setLimit(r,i,c,u){return new me({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:c,message:k.toString(u)}]})}_addCheck(r){return new me({...this._def,checks:[...this._def.checks,r]})}positive(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:k.toString(r)})}negative(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:k.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:k.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:k.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:k.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}}me.create=a=>{var r;return new me({checks:[],typeName:S.ZodBigInt,coerce:(r=a==null?void 0:a.coerce)!==null&&r!==void 0?r:!1,...A(a)})};class ut extends M{_parse(r){if(this._def.coerce&&(r.data=!!r.data),this._getType(r)!==_.boolean){const c=this._getOrReturnCtx(r);return b(c,{code:y.invalid_type,expected:_.boolean,received:c.parsedType}),T}return F(r.data)}}ut.create=a=>new ut({typeName:S.ZodBoolean,coerce:(a==null?void 0:a.coerce)||!1,...A(a)});class Se extends M{_parse(r){if(this._def.coerce&&(r.data=new Date(r.data)),this._getType(r)!==_.date){const l=this._getOrReturnCtx(r);return b(l,{code:y.invalid_type,expected:_.date,received:l.parsedType}),T}if(isNaN(r.data.getTime())){const l=this._getOrReturnCtx(r);return b(l,{code:y.invalid_date}),T}const c=new z;let u;for(const l of this._def.checks)l.kind==="min"?r.data.getTime()<l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code: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),b(u,{code:y.too_big,message:l.message,inclusive:!0,exact:!1,maximum:l.value,type:"date"}),c.dirty()):I.assertNever(l);return{status:c.value,value:new Date(r.data.getTime())}}_addCheck(r){return new Se({...this._def,checks:[...this._def.checks,r]})}min(r,i){return this._addCheck({kind:"min",value:r.getTime(),message:k.toString(i)})}max(r,i){return this._addCheck({kind:"max",value:r.getTime(),message:k.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}}Se.create=a=>new Se({checks:[],coerce:(a==null?void 0:a.coerce)||!1,typeName:S.ZodDate,...A(a)});class Bt extends M{_parse(r){if(this._getType(r)!==_.symbol){const c=this._getOrReturnCtx(r);return b(c,{code:y.invalid_type,expected:_.symbol,received:c.parsedType}),T}return F(r.data)}}Bt.create=a=>new Bt({typeName:S.ZodSymbol,...A(a)});class lt extends M{_parse(r){if(this._getType(r)!==_.undefined){const c=this._getOrReturnCtx(r);return b(c,{code:y.invalid_type,expected:_.undefined,received:c.parsedType}),T}return F(r.data)}}lt.create=a=>new lt({typeName:S.ZodUndefined,...A(a)});class dt extends M{_parse(r){if(this._getType(r)!==_.null){const c=this._getOrReturnCtx(r);return b(c,{code:y.invalid_type,expected:_.null,received:c.parsedType}),T}return F(r.data)}}dt.create=a=>new dt({typeName:S.ZodNull,...A(a)});class Be extends M{constructor(){super(...arguments),this._any=!0}_parse(r){return F(r.data)}}Be.create=a=>new Be({typeName:S.ZodAny,...A(a)});class ke extends M{constructor(){super(...arguments),this._unknown=!0}_parse(r){return F(r.data)}}ke.create=a=>new ke({typeName:S.ZodUnknown,...A(a)});class ce extends M{_parse(r){const i=this._getOrReturnCtx(r);return b(i,{code:y.invalid_type,expected:_.never,received:i.parsedType}),T}}ce.create=a=>new ce({typeName:S.ZodNever,...A(a)});class Lt extends M{_parse(r){if(this._getType(r)!==_.undefined){const c=this._getOrReturnCtx(r);return b(c,{code:y.invalid_type,expected:_.void,received:c.parsedType}),T}return F(r.data)}}Lt.create=a=>new Lt({typeName:S.ZodVoid,...A(a)});class G extends M{_parse(r){const{ctx:i,status:c}=this._processInputParams(r),u=this._def;if(i.parsedType!==_.array)return b(i,{code:y.invalid_type,expected:_.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)&&(b(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&&(b(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&&(b(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 ee(i,h,i.path,m)))).then(h=>z.mergeArray(c,h));const l=[...i.data].map((h,m)=>u.type._parseSync(new ee(i,h,i.path,m)));return z.mergeArray(c,l)}get element(){return this._def.type}min(r,i){return new G({...this._def,minLength:{value:r,message:k.toString(i)}})}max(r,i){return new G({...this._def,maxLength:{value:r,message:k.toString(i)}})}length(r,i){return new G({...this._def,exactLength:{value:r,message:k.toString(i)}})}nonempty(r){return this.min(1,r)}}G.create=(a,r)=>new G({type:a,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...A(r)});function De(a){if(a instanceof N){const r={};for(const i in a.shape){const c=a.shape[i];r[i]=X.create(De(c))}return new N({...a._def,shape:()=>r})}else return a instanceof G?new G({...a._def,type:De(a.element)}):a instanceof X?X.create(De(a.unwrap())):a instanceof ge?ge.create(De(a.unwrap())):a instanceof te?te.create(a.items.map(r=>De(r))):a}class N extends M{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=I.objectKeys(r);return this._cached={shape:r,keys:i}}_parse(r){if(this._getType(r)!==_.object){const v=this._getOrReturnCtx(r);return b(v,{code:y.invalid_type,expected:_.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 ce&&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 ee(u,j,u.path,v)),alwaysSet:v in u.data})}if(this._def.catchall instanceof ce){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&&(b(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 ee(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,re=await E.value;v.push({key:j,value:re,alwaysSet:E.alwaysSet})}return v}).then(v=>z.mergeObjectSync(c,v)):z.mergeObjectSync(c,w)}get shape(){return this._def.shape()}strict(r){return k.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=k.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 I.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 I.objectKeys(this.shape).forEach(c=>{r[c]||(i[c]=this.shape[c])}),new N({...this._def,shape:()=>i})}deepPartial(){return De(this)}partial(r){const i={};return I.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 I.objectKeys(this.shape).forEach(c=>{if(r&&!r[c])i[c]=this.shape[c];else{let l=this.shape[c];for(;l instanceof X;)l=l._def.innerType;i[c]=l}}),new N({...this._def,shape:()=>i})}keyof(){return di(I.objectKeys(this.shape))}}N.create=(a,r)=>new N({shape:()=>a,unknownKeys:"strip",catchall:ce.create(),typeName:S.ZodObject,...A(r)});N.strictCreate=(a,r)=>new N({shape:()=>a,unknownKeys:"strict",catchall:ce.create(),typeName:S.ZodObject,...A(r)});N.lazycreate=(a,r)=>new N({shape:a,unknownKeys:"strip",catchall:ce.create(),typeName:S.ZodObject,...A(r)});class ft extends M{_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 b(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 b(i,{code:y.invalid_union,unionErrors:m}),T}}get options(){return this._def.options}}ft.create=(a,r)=>new ft({options:a,typeName:S.ZodUnion,...A(r)});const ie=a=>a instanceof pt?ie(a.schema):a instanceof K?ie(a.innerType()):a instanceof gt?[a.value]:a instanceof pe?a.options:a instanceof yt?I.objectValues(a.enum):a instanceof vt?ie(a._def.innerType):a instanceof lt?[void 0]:a instanceof dt?[null]:a instanceof X?[void 0,...ie(a.unwrap())]:a instanceof ge?[null,...ie(a.unwrap())]:a instanceof An||a instanceof bt?ie(a.unwrap()):a instanceof wt?ie(a._def.innerType):[];class Vt extends M{_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.object)return b(i,{code:y.invalid_type,expected:_.object,received:i.parsedType}),T;const c=this.discriminator,u=i.data[c],l=this.optionsMap.get(u);return l?i.common.async?l._parseAsync({data:i.data,path:i.path,parent:i}):l._parseSync({data:i.data,path:i.path,parent:i}):(b(i,{code: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=ie(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 Vt({typeName:S.ZodDiscriminatedUnion,discriminator:r,options:i,optionsMap:u,...A(c)})}}function Tn(a,r){const i=ae(a),c=ae(r);if(a===r)return{valid:!0,data:a};if(i===_.object&&c===_.object){const u=I.objectKeys(r),l=I.objectKeys(a).filter(m=>u.indexOf(m)!==-1),h={...a,...r};for(const m of l){const w=Tn(a[m],r[m]);if(!w.valid)return{valid:!1};h[m]=w.data}return{valid:!0,data:h}}else if(i===_.array&&c===_.array){if(a.length!==r.length)return{valid:!1};const u=[];for(let l=0;l<a.length;l++){const h=a[l],m=r[l],w=Tn(h,m);if(!w.valid)return{valid:!1};u.push(w.data)}return{valid:!0,data:u}}else return i===_.date&&c===_.date&&+a==+r?{valid:!0,data:a}:{valid:!1}}class ht extends M{_parse(r){const{status:i,ctx:c}=this._processInputParams(r),u=(l,h)=>{if(En(l)||En(h))return T;const m=Tn(l.value,h.value);return m.valid?((Sn(l)||Sn(h))&&i.dirty(),{status:i.value,value:m.data}):(b(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}))}}ht.create=(a,r,i)=>new ht({left:a,right:r,typeName:S.ZodIntersection,...A(i)});class te extends M{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.array)return b(c,{code:y.invalid_type,expected:_.array,received:c.parsedType}),T;if(c.data.length<this._def.items.length)return b(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&&(b(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 ee(c,h,c.path,m)):null}).filter(h=>!!h);return c.common.async?Promise.all(l).then(h=>z.mergeArray(i,h)):z.mergeArray(i,l)}get items(){return this._def.items}rest(r){return new te({...this._def,rest:r})}}te.create=(a,r)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new te({items:a,typeName:S.ZodTuple,rest:null,...A(r)})};class mt extends M{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.object)return b(c,{code:y.invalid_type,expected:_.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 ee(c,m,c.path,m)),value:h._parse(new ee(c,c.data[m],c.path,m)),alwaysSet:m in c.data});return c.common.async?z.mergeObjectAsync(i,u):z.mergeObjectSync(i,u)}get element(){return this._def.valueType}static create(r,i,c){return i instanceof M?new mt({keyType:r,valueType:i,typeName:S.ZodRecord,...A(c)}):new mt({keyType:q.create(),valueType:r,typeName:S.ZodRecord,...A(i)})}}class zt extends M{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.map)return b(c,{code:y.invalid_type,expected:_.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 ee(c,m,c.path,[v,"key"])),value:l._parse(new ee(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}}}}zt.create=(a,r,i)=>new zt({valueType:r,keyType:a,typeName:S.ZodMap,...A(i)});class Te extends M{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.set)return b(c,{code:y.invalid_type,expected:_.set,received:c.parsedType}),T;const u=this._def;u.minSize!==null&&c.data.size<u.minSize.value&&(b(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&&(b(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 ee(c,w,c.path,v)));return c.common.async?Promise.all(m).then(w=>h(w)):h(m)}min(r,i){return new Te({...this._def,minSize:{value:r,message:k.toString(i)}})}max(r,i){return new Te({...this._def,maxSize:{value:r,message:k.toString(i)}})}size(r,i){return this.min(r,i).max(r,i)}nonempty(r){return this.min(1,r)}}Te.create=(a,r)=>new Te({valueType:a,minSize:null,maxSize:null,typeName:S.ZodSet,...A(r)});class Pe extends M{constructor(){super(...arguments),this.validate=this.implement}_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.function)return b(i,{code:y.invalid_type,expected:_.function,received:i.parsedType}),T;function c(m,w){return Pt({data:m,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Ut(),Ze].filter(v=>!!v),issueData:{code:y.invalid_arguments,argumentsError:w}})}function u(m,w){return Pt({data:m,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Ut(),Ze].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 Le){const m=this;return F(async function(...w){const v=new V([]),E=await m._def.args.parseAsync(w,l).catch(ne=>{throw v.addIssue(c(w,ne)),v}),j=await Reflect.apply(h,this,E);return await m._def.returns._def.type.parseAsync(j,l).catch(ne=>{throw v.addIssue(u(j,ne)),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 Pe({...this._def,args:te.create(r).rest(ke.create())})}returns(r){return new Pe({...this._def,returns:r})}implement(r){return this.parse(r)}strictImplement(r){return this.parse(r)}static create(r,i,c){return new Pe({args:r||te.create([]).rest(ke.create()),returns:i||ke.create(),typeName:S.ZodFunction,...A(c)})}}class pt extends M{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})}}pt.create=(a,r)=>new pt({getter:a,typeName:S.ZodLazy,...A(r)});class gt extends M{_parse(r){if(r.data!==this._def.value){const i=this._getOrReturnCtx(r);return b(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}}gt.create=(a,r)=>new gt({value:a,typeName:S.ZodLiteral,...A(r)});function di(a,r){return new pe({values:a,typeName:S.ZodEnum,...A(r)})}class pe extends M{constructor(){super(...arguments),at.set(this,void 0)}_parse(r){if(typeof r.data!="string"){const i=this._getOrReturnCtx(r),c=this._def.values;return b(i,{expected:I.joinValues(c),received:i.parsedType,code:y.invalid_type}),T}if(Zt(this,at)||oi(this,at,new Set(this._def.values)),!Zt(this,at).has(r.data)){const i=this._getOrReturnCtx(r),c=this._def.values;return b(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 pe.create(r,{...this._def,...i})}exclude(r,i=this._def){return pe.create(this.options.filter(c=>!r.includes(c)),{...this._def,...i})}}at=new WeakMap;pe.create=di;class yt extends M{constructor(){super(...arguments),ot.set(this,void 0)}_parse(r){const i=I.getValidEnumValues(this._def.values),c=this._getOrReturnCtx(r);if(c.parsedType!==_.string&&c.parsedType!==_.number){const u=I.objectValues(i);return b(c,{expected:I.joinValues(u),received:c.parsedType,code:y.invalid_type}),T}if(Zt(this,ot)||oi(this,ot,new Set(I.getValidEnumValues(this._def.values))),!Zt(this,ot).has(r.data)){const u=I.objectValues(i);return b(c,{received:c.data,code:y.invalid_enum_value,options:u}),T}return F(r.data)}get enum(){return this._def.values}}ot=new WeakMap;yt.create=(a,r)=>new yt({values:a,typeName:S.ZodNativeEnum,...A(r)});class Le extends M{unwrap(){return this._def.type}_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.promise&&i.common.async===!1)return b(i,{code:y.invalid_type,expected:_.promise,received:i.parsedType}),T;const c=i.parsedType===_.promise?i.data:Promise.resolve(i.data);return F(c.then(u=>this._def.type.parseAsync(u,{path:i.path,errorMap:i.common.contextualErrorMap})))}}Le.create=(a,r)=>new Le({type:a,typeName:S.ZodPromise,...A(r)});class K extends M{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=>{b(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"?Ue(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"?Ue(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(!Ee(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=>Ee(h)?Promise.resolve(u.transform(h.value,l)).then(m=>({status:i.value,value:m})):h);I.assertNever(u)}}K.create=(a,r,i)=>new K({schema:a,typeName:S.ZodEffects,effect:r,...A(i)});K.createWithPreprocess=(a,r,i)=>new K({schema:r,effect:{type:"preprocess",transform:a},typeName:S.ZodEffects,...A(i)});class X extends M{_parse(r){return this._getType(r)===_.undefined?F(void 0):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}X.create=(a,r)=>new X({innerType:a,typeName:S.ZodOptional,...A(r)});class ge extends M{_parse(r){return this._getType(r)===_.null?F(null):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}ge.create=(a,r)=>new ge({innerType:a,typeName:S.ZodNullable,...A(r)});class vt extends M{_parse(r){const{ctx:i}=this._processInputParams(r);let c=i.data;return i.parsedType===_.undefined&&(c=this._def.defaultValue()),this._def.innerType._parse({data:c,path:i.path,parent:i})}removeDefault(){return this._def.innerType}}vt.create=(a,r)=>new vt({innerType:a,typeName:S.ZodDefault,defaultValue:typeof r.default=="function"?r.default:()=>r.default,...A(r)});class wt extends M{_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 ct(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}}wt.create=(a,r)=>new wt({innerType:a,typeName:S.ZodCatch,catchValue:typeof r.catch=="function"?r.catch:()=>r.catch,...A(r)});class Ft extends M{_parse(r){if(this._getType(r)!==_.nan){const c=this._getOrReturnCtx(r);return b(c,{code:y.invalid_type,expected:_.nan,received:c.parsedType}),T}return{status:"valid",value:r.data}}}Ft.create=a=>new Ft({typeName:S.ZodNaN,...A(a)});const yd=Symbol("zod_brand");class An extends M{_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 _t extends M{_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(),Ue(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 _t({in:r,out:i,typeName:S.ZodPipeline})}}class bt extends M{_parse(r){const i=this._def.innerType._parse(r),c=u=>(Ee(u)&&(u.value=Object.freeze(u.value)),u);return ct(i)?i.then(u=>c(u)):c(i)}unwrap(){return this._def.innerType}}bt.create=(a,r)=>new bt({innerType:a,typeName:S.ZodReadonly,...A(r)});function fi(a,r={},i){return a?Be.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})}}):Be.create()}const vd={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 wd=(a,r={message:`Input not instance of ${a.name}`})=>fi(i=>i instanceof a,r),hi=q.create,mi=he.create,bd=Ft.create,_d=me.create,pi=ut.create,xd=Se.create,kd=Bt.create,Ed=lt.create,Sd=dt.create,Td=Be.create,Ad=ke.create,Od=ce.create,Md=Lt.create,Id=G.create,$d=N.create,Rd=N.strictCreate,Cd=ft.create,Nd=Vt.create,jd=ht.create,Dd=te.create,Ud=mt.create,Pd=zt.create,Zd=Te.create,Bd=Pe.create,Ld=pt.create,zd=gt.create,Fd=pe.create,Vd=yt.create,Wd=Le.create,ni=K.create,Hd=X.create,qd=ge.create,Gd=K.createWithPreprocess,Kd=_t.create,Jd=()=>hi().optional(),Yd=()=>mi().optional(),Qd=()=>pi().optional(),Xd={string:a=>q.create({...a,coerce:!0}),number:a=>he.create({...a,coerce:!0}),boolean:a=>ut.create({...a,coerce:!0}),bigint:a=>me.create({...a,coerce:!0}),date:a=>Se.create({...a,coerce:!0})},ef=T;var Z=Object.freeze({__proto__:null,defaultErrorMap:Ze,setErrorMap:Gl,getErrorMap:Ut,makeIssue:Pt,EMPTY_PATH:Kl,addIssueToContext:b,ParseStatus:z,INVALID:T,DIRTY:Ue,OK:F,isAborted:En,isDirty:Sn,isValid:Ee,isAsync:ct,get util(){return I},get objectUtil(){return kn},ZodParsedType:_,getParsedType:ae,ZodType:M,datetimeRegex:li,ZodString:q,ZodNumber:he,ZodBigInt:me,ZodBoolean:ut,ZodDate:Se,ZodSymbol:Bt,ZodUndefined:lt,ZodNull:dt,ZodAny:Be,ZodUnknown:ke,ZodNever:ce,ZodVoid:Lt,ZodArray:G,ZodObject:N,ZodUnion:ft,ZodDiscriminatedUnion:Vt,ZodIntersection:ht,ZodTuple:te,ZodRecord:mt,ZodMap:zt,ZodSet:Te,ZodFunction:Pe,ZodLazy:pt,ZodLiteral:gt,ZodEnum:pe,ZodNativeEnum:yt,ZodPromise:Le,ZodEffects:K,ZodTransformer:K,ZodOptional:X,ZodNullable:ge,ZodDefault:vt,ZodCatch:wt,ZodNaN:Ft,BRAND:yd,ZodBranded:An,ZodPipeline:_t,ZodReadonly:bt,custom:fi,Schema:M,ZodSchema:M,late:vd,get ZodFirstPartyTypeKind(){return S},coerce:Xd,any:Td,array:Id,bigint:_d,boolean:pi,date:xd,discriminatedUnion:Nd,effect:ni,enum:Fd,function:Bd,instanceof:wd,intersection:jd,lazy:Ld,literal:zd,map:Pd,nan:bd,nativeEnum:Vd,never:Od,null:Sd,nullable:qd,number:mi,object:$d,oboolean:Qd,onumber:Yd,optional:Hd,ostring:Jd,pipeline:Kd,preprocess:Gd,promise:Wd,record:Ud,set:Zd,strictObject:Rd,string:hi,symbol:kd,transformer:ni,tuple:Dd,undefined:Ed,union:Cd,unknown:Ad,void:Md,NEVER:ef,ZodIssueCode:y,quotelessJson:ql,ZodError:V}),On=(a=>(a.TEXT="text",a.THREAD="thread",a.REACTION="reaction",a))(On||{});const Ae=Q.getInstance(),gi=Z.object({id:Z.string(),targetMessageId:Z.string().optional(),type:Z.nativeEnum(On),message:Z.string(),username:Z.string(),address:Z.string(),timestamp:Z.number(),signature:Z.string(),index:Z.number(),chatTopic:Z.string(),userTopic:Z.string()}),tf=Z.object({reference:Z.string(),timestamp:Z.number()}),rf=Z.object({message:gi,messageStateRefs:Z.array(tf).nullable()});function yi(a){const r=rf.safeParse(a);return r.success?vi(a.message)?!0:(Ae.warn("Invalid main message signature"),!1):(Ae.warn("GSOC message validation failed:",r.error.format()),!1)}function nf(a){if(!Array.isArray(a))return Ae.warn("Message state must be an array"),!1;for(const r of a)if(!sf(r))return Ae.warn("Invalid message in message state:",r.id),!1;return!0}function sf(a){const r=gi.safeParse(a);return r.success?vi(a)?!0:(Ae.warn("Invalid message signature"),!1):(Ae.warn("Message data validation failed:",r.error.format()),!1)}function vi(a){try{const r={username:a.username,address:a.address,timestamp:a.timestamp,message:a.message},i=new TextEncoder,c=L.concatBytes(i.encode(`Ethereum Signed Message:
|
|
11
|
-
32`),L.keccak256(i.encode(JSON.stringify(r))));if(new O.Signature(a.signature).isValid(c,a.address))throw new Error("Signature verification failed!");return!0}catch(r){return Ae.warn("Error in validateUserSignature",r),!1}}const H={LOADING_INIT:"loadingInit",LOADING_PREVIOUS_MESSAGES:"loadingPreviousMessages",MESSAGE_RECEIVED:"messageReceived",MESSAGE_REQUEST_INITIATED:"messageRequestInitiated",MESSAGE_REQUEST_UPLOADED:"messageRequestUploaded",MESSAGE_REQUEST_ERROR:"messageRequestError",CRITICAL_ERROR:"criticalError"};class af{constructor(r,i){this.utils=r,this.emitter=i,this.logger=Q.getInstance(),this.errorHandler=oe.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"),O.FeedIndex.fromBigInt(0n)}}async initMessageState(r){try{if(!yi(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(!nf(i))throw new Error(`Invalid message state for ref: ${r}`);this.processedRefs.add(r),this.refRetryCount.delete(r);for(const u of i)this.emitter.emit(H.MESSAGE_RECEIVED,u)}async handleRefError(r,i){const c=this.refRetryCount.get(r)||0,u=c+1;if(this.logger.warn(`Error processing ref ${r} (attempt ${u}/${this.MAX_RETRIES}):`,i),u>=this.MAX_RETRIES)this.bannedRefs.add(r),this.refRetryCount.delete(r),this.logger.error(`Ref ${r} has been banned after ${this.MAX_RETRIES} failed attempts`),this.errorHandler.handleError(i,"SwarmHistory.processMessageRef");else{this.refRetryCount.set(r,u);const l=this.RETRY_DELAY*Math.pow(2,c);this.logger.debug(`Retrying ref ${r} after ${l}ms delay`),await Wl(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 of{constructor(r,i){this.userDetails=r,this.swarmSettings=i,this.depth=26,this.errorHandler=oe.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=O.Topic.fromString(w);await c.makeFeedWriter(v,new O.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 O.PrivateKey(h),v=O.Stamper.fromBlank(h,u,this.depth),E=this.generateUserOwnedFeedId(l,m),j=O.Topic.fromString(E),re=ii(j,r),ne=ei(i),ze=ti(ne,re,w),Oe={hash:()=>ze.address.toUint8Array()},Wt=v.stamp(Oe),{upload:Ht}=c.makeSOCWriter(w),Fe=O.Bytes.fromUtf8(i);return(await Ht(Wt,re,Fe.toUint8Array())).reference.toHex()}orderMessages(r){return r.sort((i,c)=>i.timestamp-c.timestamp)}async downloadObjectFromBee(r){try{const{bee:i}=this.swarmSettings,c=await i.downloadData(r);return c?c.toJSON():null}catch(i){return this.errorHandler.handleError(i,"Utils.downloadObjectFromBee"),null}}async uploadObjectToBee(r){const{enveloped:i,stamp:c}=this.swarmSettings;if(i){if(c)return this.uploadObjectToBeeEnvelope(r);throw new Error("Enveloped mode is enabled, but stamp is not provided")}else return this.uploadObjectToBeeOwn(r)}async uploadObjectToBeeOwn(r){try{const{bee:i,stamp:c}=this.swarmSettings;return(await i.uploadData(c,JSON.stringify(r),{redundancyLevel:4})).reference.toString()}catch(i){return this.errorHandler.handleError(i,"Utils.uploadObjectToBee"),null}}async uploadObjectToBeeEnvelope(r){try{const{bee:i,stamp:c}=this.swarmSettings,{privateKey:u}=this.userDetails,l=O.Stamper.fromBlank(u,c,this.depth),h=O.Bytes.fromUtf8(JSON.stringify(r)),m=new Ul(async v=>{await i.uploadChunk(l.stamp(v),v.build())});await m.append(h.toUint8Array());const w=await m.finalize();return L.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=O.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(O.Topic.fromString(i),_n(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(O.Topic.fromString(c),_n(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 O.PrivateKey(l),m=O.Identifier.fromString(u),w=O.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=O.Stamper.fromBlank(h,c,this.depth),w=new O.PrivateKey(l),v=O.Identifier.fromString(u),E=O.Bytes.fromUtf8(r),j=ei(E.toUint8Array()),re=ti(j,v,w),ne={hash:()=>re.address.toUint8Array()},ze=m.stamp(ne),{upload:Oe}=i.makeSOCWriter(w,{timeout:this.UPLOAD_GSOC_TIMEOUT});await Oe(ze,v,E.toUint8Array())}}class cf{constructor(r){this.logger=Q.getInstance(),this.errorHandler=oe.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const i=new O.PrivateKey(_n(r.user.privateKey));this.userDetails={privateKey:r.user.privateKey,ownAddress:i.publicKey().address().toString(),nickname:r.user.nickname,ownIndex:-1},this.swarmSettings={bee:new O.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 Hl,this.utils=new of(this.userDetails,this.swarmSettings),this.history=new af(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||jl(),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(H.MESSAGE_REQUEST_INITIATED,h),await this.utils.writeOwnFeedDataByIndex(l,JSON.stringify(h)),this.userDetails.ownIndex=l,this.emitter.emit(H.MESSAGE_REQUEST_UPLOADED,h),await this.broadcastUserMessage(h)}catch(m){this.emitter.emit(H.MESSAGE_REQUEST_ERROR,h),this.errorHandler.handleError(m,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(H.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(H.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(r){this.sendMessage(r.message,r.type,r.targetMessageId,r.id)}async retryBroadcastUserMessage(r){await this.broadcastUserMessage(r)}async init(){try{this.emitter.emit(H.LOADING_INIT,!0);const[r,i]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(r.status==="rejected")throw r.reason;i.status==="fulfilled"&&(this.gsocIndex=i.value),this.emitter.emit(H.LOADING_INIT,!1)}catch(r){this.errorHandler.handleError(r,"Chat.initSelfState"),this.emitter.emit(H.CRITICAL_ERROR,r)}}async initOwnIndex(){const{latestIndex:c}=await xn(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=c}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const r=O.Topic.fromString(this.swarmSettings.chatTopic),i=ii(r,this.gsocIndex),c=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,i.toString()),u=JSON.parse(c);if(!yi(u)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(H.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 xn(()=>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 O.EthAddress(i).toString(),h=new O.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}}exports.EVENTS=H;exports.MessageType=On;exports.SwarmChat=cf;
|
|
4
|
+
`)}function Ot(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Jn(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Yn(e){if(!e)return!1;const t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function Qn(e){if(!e)return!1;const t=e.charCodeAt(0);return t>=48&&t<=57}function qe(e){return Yn(e)||Qn(e)}const co=`
|
|
5
|
+
\r.,?!:;"'\`(){}[]~@#$%^&*-+=|<>/\\`.split("");function uo(e){return co.includes(e)}function lo(e){return qe(e)||e==="."||e==="["||e==="]"||e==="_"}function fo(e,t,n,s,o){return e.slice(0,t)+s+e.slice(t,t+n)+o+e.slice(t+n)}function Xn(e,t,n=0){const s=t.exec(e.slice(n));return s?{index:s.index,match:s[0]}:null}function es(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=Xn(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 ho(e,t,n=!0){let s=0;for(const o of t){let d=!1;for(;!d&&s<e.length;)es(e[s],o,n)&&(d=!0),s++;if(!d)return!1}return!0}function po(e){return e.match(/"|,/)?`"${e.replace(/"/g,'""')}"`:e}function $e(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 mo(e,t=0){for(let n=t;n<e.length;n++)if(uo(e[n]))return n;return-1}function go(e,t=0){for(let n=t;n<e.length;n++)if(e[n]==="#"&&qe(e[n+1]))return n;return-1}function ts(e,t,n=0){return e.slice(0,n).lastIndexOf(t)}function rs(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 ns(e,t){const n=t.wordBoundary?$e(e,[`${t.opening} `,`${t.opening}
|
|
6
|
+
`],t.start||0):e.indexOf(t.opening,t.start||0);if(n===-1)return null;const s=rs(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 yo(e,t){const n=[];let s=t.wordBoundary?$e(e,[`${t.opening} `,`${t.opening}
|
|
7
|
+
`],t.start||0):e.indexOf(t.opening,t.start||0);for(;;){if(s===-1)return n;const o=ns(e,{...t,start:s});if(!o)return n;n.push(o),s=t.wordBoundary?$e(e,[`${t.opening} `,`${t.opening}
|
|
8
|
+
`],s+o.length):e.indexOf(t.opening,s+o.length)}}function vo(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 wo(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 bo(e){const t=[];let n=0;for(;n<e.length;){const s=go(e,n);if(s===-1){t.push({string:e.slice(n),symbol:null});break}const o=mo(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 _o(e){const t=[];let n=0;for(;n<e.length;){const s=$e(e,["http://","https://"],n);if(s===-1){t.push({string:e.slice(n),symbol:null});break}const o=$e(e,[" ",`
|
|
9
|
+
`],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 ss="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",is="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function xo(e){return as(e,ss)}function ko(e){return os(e,ss)}function Eo(e){return as(e,is)}function So(e){return os(e,is)}function as(e,t){const n="=",s=t.length;let o=0,d=0;const f=[];for(let v=0;v<e.length;v++){const m=e[v];if(m===n)break;const x=t.indexOf(m);if(x===-1)throw new Error(`Invalid character: ${m}`);d=d<<Math.log2(s)|x,o+=Math.log2(s),o>=8&&(o-=8,f.push(d>>o&255))}return new Uint8Array(f)}function os(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 Ao(e){e.startsWith("0x")&&(e=e.slice(2));const t=e.length/2,n=new Uint8Array(t);for(let s=0;s<t;s++){const o=parseInt(e.slice(s*2,s*2+2),16);n[s]=o}return n}function To(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function Oo(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 ar(e,t,n){const s=[];for(const o of n)o!==t&&s.push(e.replace(t,o));return s}function Mo(e,t,n,s=Math.random){const o=a.Arrays.shuffle(t.map(f=>({variants:a.Arrays.shuffle(f.variants.map(v=>v),s),avoid:f.avoid})),s),d=[];for(const f of o){const v=f.variants.filter(x=>x!==f.avoid),m=v.find(x=>e.includes(x));if(m&&(At(d,ar(e,m,v)),d.length>=n))break}if(d.length<n)for(const f of o){const v=f.variants.find(m=>e.includes(m));if(v&&(At(d,ar(e,v,f.variants)),d.length>=n))break}return d.slice(0,n)}function Io(e,t,n,s=!1){const o=new RegExp(s?`(?<=\\s|^)${t}(?=\\s|$)`:`\\b${t}\\b`,"g");return e.replace(o,n)}function $o(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 Ro(e){return e.replace(/<[^>]*>/g,"")}function cs(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 Co(e,t={}){return[...e].reduce((n,s)=>n+(t[s]||1),0)}function No(e,t,n={}){const s=[];let o="",d=0;for(let f=0;f<e.length;f++){const v=e[f],m=n[v]||1;if(o+=v,d+=m,d>t){const{line:x,rest:$}=cs(o);s.push(x),o=$,d=$.split("").map(U=>n[U]||1).reduce((U,je)=>U+je,0)}}return o&&s.push(o),s}function jo(e,t){const n=[];for(let s=0;s<=e.length;s++)n[s]=[s];for(let s=0;s<=t.length;s++)n[0][s]=s;for(let s=1;s<=e.length;s++)for(let o=1;o<=t.length;o++){const d=e[s-1]===t[o-1]?0:1;n[s][o]=Math.min(n[s-1][o]+1,n[s][o-1]+1,n[s-1][o-1]+d)}return n[e.length][t.length]}function or(e,t){return new RegExp(`\\b${t}\\b`).test(e)}function Do(e,t,n){return n==="any"?t.some(s=>or(e,s)):t.every(s=>or(e,s))}function Po(e){const t={},n=e.match(/([a-z\-]+)="([^"]+)"/g);if(n)for(const s of n){const[o,d]=nr(s,"=");t[o]=d.slice(1,d.length-1)}return t}function Mt(e,t,n=[]){let s="";for(;t<e.length&&(qe(e[t])||n.includes(e[t]));)s+=e[t++];return s}function Uo(e,t,n="$",s=":"){for(const o in t)e=us(e,o,t[o],n,s);return e=ls(e),e}function us(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=Mt(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 ls(e,t="$",n=":"){let s=e.indexOf(t);for(;s!==-1;){const o=Mt(e,s+1);if(e[s+o.length+1]===n)if(e[s+o.length+2]===n)e=e.replace(`${t}${o}${n}${n}`,"");else{const d=Mt(e,s+o.length+2);e=e.replace(`${t}${o}${n}${d}`,d)}s=e.indexOf(t,s+1)}return e}function Zo(e,t){let n=e.indexOf("](");for(;n!==-1;){const s=ts(e,"[",n),o=e.indexOf(")",n);if(s!==-1&&o!==-1){const[d,f]=e.slice(s+1,o).split("]("),v=t(d,f);e=e.slice(0,s)+v+e.slice(o+1)}n=e.indexOf("](",n+1)}return e}function ds(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 Bo(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 Lo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function zo(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 Fo(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,v)=>Et(f[t])-Et(v[t])),e.forEach((f,v)=>f[t]=v+1)}function Vo(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 Wo(e,t=":"){return Object.fromEntries(e.map(n=>nr(n,t)).map(n=>n[0]&&n[1]?[He(n[0]),He(n[1])]:null).filter(n=>n))}function Ho(e,t,n){return ms(e,t)+ds(n||{})}function qo(e,t=",",n='"'){const s=[];let o="",d=!1;const f=e.split("");for(const v of f)v===t&&!d?(s.push(o),o=""):v===n&&(!o&&!d||d)?d=!d:o+=v;return s.push(o),s}function Go(e){return`[${Math.floor(e.progress*100)}%] ${It(e.deltaMs)} out of ${It(e.totalTimeMs)} (${It(e.remainingTimeMs)} left) [${Math.round(e.baseTimeMs)} ms each]`}async function Ko(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 Jo(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 Yo(e){return JSON.parse(JSON.stringify(e))}function Qo(e){return Math.ceil((e||Date.now())/1e3)}function Xo(e){return(e||new Date).toISOString().slice(0,10)}function ec(e){return(e||new Date).toISOString().slice(0,19).replace(/T|:/g,"-")}function tc(e){const t=new Date(e);return new Date(t.getTime()-t.getTimezoneOffset()*6e4)}function rc(e){return new Date(e)}function J(e){return String(Math.floor(e)).padStart(2,"0")}function nc(e){let[t,n]=e.split(":");le(parseInt(t,10))||(t="0"),le(parseInt(n,10))||(n="0");let s=fr(Xt(t),0,23),o=fr(Xt(n),0,59);return`${J(s)}:${J(o)}`}function It(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?`${J(t)}:${J(n)}:${J(s)}`:`${J(n)}:${J(s)}`}function _e(e){return Math.floor((Ie(e)?e.getTime():e)/864e5)}const sc={today:(e,t)=>J(e)+":"+J(t),yesterday:()=>"Yesterday",monday:()=>"Mon",tuesday:()=>"Tue",wednesday:()=>"Wed",thursday:()=>"Thu",friday:()=>"Fri",saturday:()=>"Sat",sunday:()=>"Sun",weeks:e=>`${e}w`};function ic(e,t){const n=new Date((t==null?void 0:t.now)||Date.now()),s=(t==null?void 0:t.labels)||sc,o=Ie(e)?e:new Date(e);if(_e(n)===_e(o))return s.today(o.getUTCHours(),o.getUTCMinutes(),o.getUTCHours()>12);if(_e(n)-_e(o)===1)return s.yesterday();const d=ur(o);return _e(n)-_e(o)<7?s[d.day]():s.weeks(Math.round((n.getTime()-o.getTime())/6048e5))}const fs={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 hs(e,t){const n=(t==null?void 0:t.now)??Date.now(),s=(t==null?void 0:t.labels)||fs,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 ac(e,t=fs){return hs(0,{now:e*1e3,labels:t})}function oc(e,t,n){const s=((n==null?void 0:n.now)??Date.now())-e,o=Math.floor(s/t),d=t/((n==null?void 0:n.precision)??1)-Math.ceil(s%t/((n==null?void 0:n.precision)??1));return{cycles:o,remaining:d}}const cr={};function cc(e,t){return!cr[e]||Date.now()>cr[e]?(cr[e]=Date.now()+t,!0):!1}const uc={s:1e3,m:6e4,h:36e5,d:864e5};function lc(e,t,n){return t=Ie(t)?t.getTime():t,n=n?Ie(n)?n.getTime():n:Date.now(),(n-t)/uc[e]}function dc(e,t,n,s){s||(s=Date.now());const o=t/n,d=s-e,f=d/t,v=f*n,m=v-d;return{deltaMs:d,progress:o,baseTimeMs:f,totalTimeMs:v,remainingTimeMs:m}}const fc={0:"sunday",1:"monday",2:"tuesday",3:"wednesday",4:"thursday",5:"friday",6:"saturday"};function ps(e){return{zeroBasedIndex:e,day:fc[e]}}function ur(e){return ps(e.getDay())}function hc(e){return ur(new Date(e))}function pc(e){return e*1e3}function mc(e){return e*6e4}function gc(e){return e*36e5}function yc(e){return e*864e5}const vc={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 wc(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=vc[n];if(!s)throw Error(`Unknown unit: "${n}"`);return t*s}const bc={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 _c(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),s=bc[n];if(!s)throw Error(`Unknown unit: "${n}"`);return t*s}function xc(e){return e.replace(/ +/g," ").replace(/^ /gm,"")}const lr={};async function kc(e,t,n){const s=Date.now(),o=lr[e];if(o&&o.validUntil>s)return o.value;const d=await n(),f=s+t;return lr[e]={value:d,validUntil:f},d}function Ec(e){delete lr[e]}function ms(...e){return e.filter(t=>t).join("/").replace(new RegExp("(?<!:)\\/+","g"),"/")}function Sc(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 Ac(e){let t="p";e.startsWith("#")?(t="h1",e=e.slice(1).trim()):e.startsWith("-")&&(t="li",e=e.slice(1).trim());const n=e[0]===e[0].toUpperCase(),s=/[.?!]$/.test(e),o=/:$/.test(e);return{type:t,isCapitalized:n,hasPunctuation:s,endsWithColon:o}}function Tc(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 Oc(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 gs(e){const t=Object.keys(e).sort((s,o)=>s.localeCompare(o)),n={};for(const s of t)n[s]=xe(e[s]);return n}function ys(e){const t=[];return e.sort((n,s)=>JSON.stringify(xe(n)).localeCompare(JSON.stringify(xe(s)))).forEach(n=>t.push(xe(n))),t}function xe(e){return Array.isArray(e)?ys(e):ue(e)?gs(e):e}function vs(e,t){return JSON.stringify(xe(e))===JSON.stringify(xe(t))}function Mc(...e){for(let t=1;t<e.length;t++)if(!vs(e[t-1],e[t]))return!1;return!0}function Ic(e){try{return JSON.parse(e)}catch{return null}}function $c(){let e=0;return{next:()=>e++}}function Rc(e){let t=0;return{next:()=>e[t++%e.length]}}function Cc(e){let t;return n=>{const s=n===e&&t!==e;return t=n,s}}function Nc(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 v=f[n],m=t[v]?v:s;d[m].length>=t[m]?d[s].push(f):d[m].push(f)}return d}function jc(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 ws(e){const t=Object.keys(e);return t[Math.floor(Math.random()*t.length)]}function Dc(e,t){const n=ws(e);return e[n]=t(e[n]),n}function Pc(e){return e=e.replace(/\r\n/g,`
|
|
10
|
+
`),e=e.replace(/(\w+)\((.+)\)/g,(t,n,s)=>`${n}(${s.replaceAll(",",",")})`),e=e.replace(/(,)(\s+})/g,"$2"),e=e.replace(/\.\.\..+?,/g,""),e=e.replace(/({\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/(,\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',"),e=e.replace(/:(.+)\?(.+):/g,(t,n,s)=>`: (${n.trim()} && ${s.trim()}) ||`),e=e.replace(/([a-zA-Z0-9]+)( ?: ?{)/g,'"$1"$2'),e=e.replace(/([a-zA-Z0-9]+) ?: ?(.+?)(,|\n|})/g,(t,n,s,o)=>`"${n}":"${s.trim()}"${o}`),e=e.replace(/("'|'")/g,'"'),e=e.replaceAll(",",","),JSON.parse(e)}const de=[1e3,1e6,1e9,1e12,1e15,1e18,1e21,1e24,1e27,1e30,1e9,1e16,1e18,1e18,1e18,1e33],Uc=["thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion","gwei","bzz","btc","eth","dai","decillion"],bs=["K","M","B","T","Qa","Qi","Sx","Sp","O","N","gwei","bzz","eth","btc","dai","D"];function Zc(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 Bc(e,t){const n=(t==null?void 0:t.longForm)??!1,s=t!=null&&t.unit?` ${t.unit}`:"",o=n?Uc:bs,d=(t==null?void 0:t.precision)??1;if(e<de[0])return`${e}${s}`;for(let f=0;f<de.length-1;f++)if(e<de[f+1])return`${(e/de[f]).toFixed(d)}${n?" ":""}${o[f]}${s}`;return`${(e/de[de.length-1]).toFixed(d)}${n?" ":""}${o[de.length-1]}${s}`}function dr(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeNumber got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim(),s=bs.findIndex(o=>o.toLowerCase()===n.toLowerCase());return s===-1?t:t*de[s]}function fr(e,t,n){return e<t?t:e>n?n:e}function Lc(e,t,n){const s=e+t;return s>n?n:s}function zc(e,t,n){const s=e-t;return s<n?n:s}function Fc(e,t){return t(e),e}function Vc(e,t){e&&t(e)}function Wc(e,t){const n=Object.keys(t);for(const s of n)Array.isArray(t[s])&&Array.isArray(e[s])&&At(e[s],t[s])}function Hc(e){return e.splice(0,e.length),e}function qc(e){for(const t of Object.keys(e))(Cn(e[t])||Array.isArray(e[t])&&e[t].every(n=>n==null))&&delete e[t];return e}function Gc(e){for(const t of Object.entries(e))(t[1]===null||t[1]===void 0||W(t[1])&&kt(t[1]))&&delete e[t[0]];return e}function Kc(e,t){const n={};for(const[s,o]of Object.entries(e))t(s)&&(n[s]=o);return n}function Jc(e,t){const n={};for(const[s,o]of Object.entries(e))t(o)&&(n[s]=o);return n}function Yc(e,t){const n={};for(const s of Object.entries(e))n[s[0]]=t(s[1]);return n}function Qc(e,t){const n=[];let s=0;for(const o of e)n.push(t(o,s++));return n}async function Xc(e,t){try{return await e()}catch{throw t}}function eu(e,t,n){n!=null&&(e[t]=n)}function tu(e,t,n,s){const o=ve(n,s);o!=null&&we(e,t,o)}function ru(e){const t={};for(const[n,s]of Object.entries(e))t[s]=n;return t}function nu(e){const t=Object.keys(e),n=t.map(v=>e[v].length),s=n.reduce((v,m)=>v*=m);let o=1;const d=[1];for(let v=0;v<n.length-1;v++)o*=n[v],d.push(o);const f=[];for(let v=0;v<s;v++){const m={};for(let x=0;x<t.length;x++){const $=e[t[x]],U=Math.floor(v/d[x])%$.length;m[t[x]]=$[U]}f.push(m)}return f}function su(e){return Object.values(e).filter(t=>t).length}function iu(e,t,n){return e+(n?"["+t+"]":(e.length?".":"")+t)}function $t(e,t,n,s,o){if(!ue(t))return t;for(const[d,f]of Object.entries(t)){const v=iu(n,d,s);Array.isArray(f)?o?$t(e,f,v,!0,o):e[v]=f.map(m=>$t(Array.isArray(m)?[]:{},m,"",!1,o)):ue(f)?$t(e,f,v,!1,o):e[v]=f}return e}function au(e,t=!1,n){return $t({},e,n||"",!1,t)}function _s(e){if(!ue(e))return e;const t=Array.isArray(e)?[]:{};for(const[n,s]of Object.entries(e))Array.isArray(s)?we(t,n,s.map(o=>_s(o))):we(t,n,s);return t}function ou(e,t,n){return t[e]?t[e]:n}function xs(e,t){const n={};for(const s of e){const o=t(s);n[o]=s}return n}function cu(e,t){const n={};for(const s of e){const o=t(s);n[o]||(n[o]=[]),n[o].push(s)}return n}function uu(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function ks(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 Es(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 lu(e,t){const n=Math.ceil(e.length/t);return Es(e,n)}function du(e,t){return Object.values(xs(e,t))}function fu(e,t,n,s,o){const d=t?e.map(t):e,f={};for(const m of d)f[m]=(f[m]||0)+1;const v=s?Ss(f,o?(m,x)=>m[1]-x[1]:(m,x)=>x[1]-m[1]):f;return n?Object.keys(v):v}function Ss(e,t){return Object.fromEntries(Object.entries(e).sort(t))}function hu(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 pu(e,t,n=1){for(const s of e)s[t]+=n}function mu(e,t,n){for(const s of e)s[t]=n}function hr(e,t){const n=[];let s=[];return e.forEach((o,d)=>{(d===0||!t(o,e[d-1]))&&(s=[],n.push(s)),s.push(o)}),n}function gu(){return{map:new Map,keys:[]}}function yu(){return{map:new Map,keys:[]}}function As(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 vu(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 wu(e,t,n,s,o=100){As(e,t,{validUntil:Date.now()+s,data:n},o)}function bu(e,t){const n=e.map.get(t);return n&&n.validUntil>Date.now()?n.data:null}class fe{constructor(t){this.value=t}static of(t){return new fe(t)}static empty(){return new fe(null)}map(t){return new fe(this.value!==null&&this.value!==void 0?t(this.value):null)}mapAsync(t){return this.value!==null&&this.value!==void 0?t(this.value).then(n=>fe.of(n)):Promise.resolve(fe.empty())}ifPresent(t){return this.value!==null&&this.value!==void 0&&t(this.value),this}ifPresentAsync(t){return this.value!==null&&this.value!==void 0?t(this.value).then(()=>this):Promise.resolve(this)}ifAbsent(t){return(this.value===null||this.value===void 0)&&t(),this}ifAbsentAsync(t){return this.value===null||this.value===void 0?t().then(()=>this):Promise.resolve(this)}getOrFallback(t){return this.value??t()}getOrFallbackAsync(t){return this.value!==null&&this.value!==void 0?Promise.resolve(this.value):t()}getOrThrow(){if(this.value===null||this.value===void 0)throw Error("Optional.value is empty");return this.value}}a.Optional=fe;class _u{constructor(t){this.supplier=t,this.value=null}get(){return this.value||(this.value=this.supplier()),this.value}}a.Lazy=_u;class xu{constructor(t){this.supplier=t,this.value=null}async get(){return this.value||(this.value=await this.supplier()),this.value}}a.AsyncLazy=xu;function ku(e){return()=>e.forEach(t=>t())}function Eu(e,t){return e.reduce((n,s)=>t(n)>t(s)?n:s)}function Su(e,t){const n=e.find(s=>s instanceof t);return fe.of(n)}function Au(e,t){return e.filter(n=>n instanceof t)}function Tu(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 Ou(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}class Mu{constructor(t){this.value=t,this.children=[]}}function Iu(e,t,n,s,o=!1){const d=new Map,f=[];e.forEach(m=>{const x=new Mu(m);d.set(m[t],x)}),e.forEach(m=>{const x=d.get(m[t]);if(!x)return;const $=m[n];if($){const U=d.get($);U&&U.children.push(x)}else f.push(x)});const v=m=>{m.children.sort((x,$)=>{const U=x.value[s],je=$.value[s];return o?je-U:U-je}),m.children.forEach(v)};return f.forEach(v),f}function Ts(e,t){if(Math.log2(e.length)%1!==0)throw new Error("Array length must be a power of 2");let n=[...e];for(;n.length>1;){const s=[];for(let o=0;o<n.length;o+=2){const d=n[o+1];s.push(t(n[o],d))}n=s}return n[0]}function Re(...e){const t=e.reduce((o,d)=>o+d.length,0),n=new Uint8Array(t);let s=0;return e.forEach(o=>{n.set(o,s),s+=o.length}),n}function Os(e){return e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}function Ms(e){return e[0]===255&&e[1]===216}function Is(e){return e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function $u(e){return Os(e)||Ms(e)||Is(e)}function Ru(e){return new Uint8Array([e])}function Cu(e){return e[0]}function Nu(e,t){const n=new ArrayBuffer(2);return new DataView(n).setUint16(0,e,t==="LE"),new Uint8Array(n)}function ju(e,t){return new DataView(e.buffer).getUint16(e.byteOffset,t==="LE")}function Du(e,t){const n=new ArrayBuffer(4);return new DataView(n).setUint32(0,e,t==="LE"),new Uint8Array(n)}function Pu(e,t){return new DataView(e.buffer).getUint32(e.byteOffset,t==="LE")}function pr(e,t){const n=new ArrayBuffer(8);return new DataView(n).setBigUint64(0,BigInt(e),t==="LE"),new Uint8Array(n)}function Uu(e,t){return new DataView(e.buffer).getBigUint64(e.byteOffset,t==="LE")}function Ce(e,t){const n=new Uint8Array(32);let s=e;if(t==="LE"){for(let o=0;o<32;o++)n[o]=Number(s&0xffn),s>>=8n;return n}for(let o=31;o>=0;o--)n[o]=Number(s&0xffn),s>>=8n;return n}function Ne(e,t){let n=0n;if(t==="LE"){for(let s=31;s>=0;s--)n=n<<8n|BigInt(e[s]);return n}for(let s=0;s<32;s++)n=n<<8n|BigInt(e[s]);return n}function Zu(e,t){const n=[];let s=0;for(const o of t)n.push(e.subarray(s,s+o)),s+=o;return n}function mr(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.subarray(s,s+t));return n}const $s=[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 Bu(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],v=e[5]^e[15]^e[25]^e[35]^e[45],m=e[6]^e[16]^e[26]^e[36]^e[46],x=e[7]^e[17]^e[27]^e[37]^e[47],$=e[8]^e[18]^e[28]^e[38]^e[48],U=e[9]^e[19]^e[29]^e[39]^e[49],je=o<<1|d>>>31,xl=d<<1|o>>>31,Je=$^je,Ye=U^xl,kl=f<<1|v>>>31,El=v<<1|f>>>31,Qe=n^kl,Xe=s^El,Sl=m<<1|x>>>31,Al=x<<1|m>>>31,et=o^Sl,tt=d^Al,Tl=$<<1|U>>>31,Ol=U<<1|$>>>31,rt=f^Tl,nt=v^Ol,Ml=n<<1|s>>>31,Il=s<<1|n>>>31,st=m^Ml,it=x^Il;e[0]^=Je,e[1]^=Ye,e[2]^=Qe,e[3]^=Xe,e[4]^=et,e[5]^=tt,e[6]^=rt,e[7]^=nt,e[8]^=st,e[9]^=it,e[10]^=Je,e[11]^=Ye,e[12]^=Qe,e[13]^=Xe,e[14]^=et,e[15]^=tt,e[16]^=rt,e[17]^=nt,e[18]^=st,e[19]^=it,e[20]^=Je,e[21]^=Ye,e[22]^=Qe,e[23]^=Xe,e[24]^=et,e[25]^=tt,e[26]^=rt,e[27]^=nt,e[28]^=st,e[29]^=it,e[30]^=Je,e[31]^=Ye,e[32]^=Qe,e[33]^=Xe,e[34]^=et,e[35]^=tt,e[36]^=rt,e[37]^=nt,e[38]^=st,e[39]^=it,e[40]^=Je,e[41]^=Ye,e[42]^=Qe,e[43]^=Xe,e[44]^=et,e[45]^=tt,e[46]^=rt,e[47]^=nt,e[48]^=st,e[49]^=it;const _r=e[0],xr=e[1],kr=e[2]<<1|e[3]>>>31,Er=e[3]<<1|e[2]>>>31,Sr=e[5]<<30|e[4]>>>2,Ar=e[4]<<30|e[5]>>>2,Tr=e[6]<<28|e[7]>>>4,Or=e[7]<<28|e[6]>>>4,Mr=e[8]<<27|e[9]>>>5,Ir=e[9]<<27|e[8]>>>5,$r=e[11]<<4|e[10]>>>28,Rr=e[10]<<4|e[11]>>>28,Cr=e[13]<<12|e[12]>>>20,Nr=e[12]<<12|e[13]>>>20,jr=e[14]<<6|e[15]>>>26,Dr=e[15]<<6|e[14]>>>26,Pr=e[17]<<23|e[16]>>>9,Ur=e[16]<<23|e[17]>>>9,Zr=e[18]<<20|e[19]>>>12,Br=e[19]<<20|e[18]>>>12,Lr=e[20]<<3|e[21]>>>29,zr=e[21]<<3|e[20]>>>29,Fr=e[22]<<10|e[23]>>>22,Vr=e[23]<<10|e[22]>>>22,Wr=e[25]<<11|e[24]>>>21,Hr=e[24]<<11|e[25]>>>21,qr=e[26]<<25|e[27]>>>7,Gr=e[27]<<25|e[26]>>>7,Kr=e[29]<<7|e[28]>>>25,Jr=e[28]<<7|e[29]>>>25,Yr=e[31]<<9|e[30]>>>23,Qr=e[30]<<9|e[31]>>>23,Xr=e[33]<<13|e[32]>>>19,en=e[32]<<13|e[33]>>>19,tn=e[34]<<15|e[35]>>>17,rn=e[35]<<15|e[34]>>>17,nn=e[36]<<21|e[37]>>>11,sn=e[37]<<21|e[36]>>>11,an=e[38]<<8|e[39]>>>24,on=e[39]<<8|e[38]>>>24,cn=e[40]<<18|e[41]>>>14,un=e[41]<<18|e[40]>>>14,ln=e[42]<<2|e[43]>>>30,dn=e[43]<<2|e[42]>>>30,fn=e[45]<<29|e[44]>>>3,hn=e[44]<<29|e[45]>>>3,pn=e[47]<<24|e[46]>>>8,mn=e[46]<<24|e[47]>>>8,gn=e[48]<<14|e[49]>>>18,yn=e[49]<<14|e[48]>>>18;e[0]=_r^~Cr&Wr,e[1]=xr^~Nr&Hr,e[2]=Cr^~Wr&nn,e[3]=Nr^~Hr&sn,e[4]=Wr^~nn&gn,e[5]=Hr^~sn&yn,e[6]=nn^~gn&_r,e[7]=sn^~yn&xr,e[8]=gn^~_r&Cr,e[9]=yn^~xr&Nr,e[10]=Tr^~Zr&Lr,e[11]=Or^~Br&zr,e[12]=Zr^~Lr&Xr,e[13]=Br^~zr&en,e[14]=Lr^~Xr&fn,e[15]=zr^~en&hn,e[16]=Xr^~fn&Tr,e[17]=en^~hn&Or,e[18]=fn^~Tr&Zr,e[19]=hn^~Or&Br,e[20]=kr^~jr&qr,e[21]=Er^~Dr&Gr,e[22]=jr^~qr&an,e[23]=Dr^~Gr&on,e[24]=qr^~an&cn,e[25]=Gr^~on&un,e[26]=an^~cn&kr,e[27]=on^~un&Er,e[28]=cn^~kr&jr,e[29]=un^~Er&Dr,e[30]=Mr^~$r&Fr,e[31]=Ir^~Rr&Vr,e[32]=$r^~Fr&tn,e[33]=Rr^~Vr&rn,e[34]=Fr^~tn&pn,e[35]=Vr^~rn&mn,e[36]=tn^~pn&Mr,e[37]=rn^~mn&Ir,e[38]=pn^~Mr&$r,e[39]=mn^~Ir&Rr,e[40]=Sr^~Pr&Kr,e[41]=Ar^~Ur&Jr,e[42]=Pr^~Kr&Yr,e[43]=Ur^~Jr&Qr,e[44]=Kr^~Yr&ln,e[45]=Jr^~Qr&dn,e[46]=Yr^~ln&Sr,e[47]=Qr^~dn&Ar,e[48]=ln^~Sr&Pr,e[49]=dn^~Ar&Ur,e[0]^=$s[t*2],e[1]^=$s[t*2+1]}}function Rs(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 Cs(e,t){if(!e.length){const o=new Uint8Array(136);return o[0]=t,o[135]=128,[Rs(o)]}const n=mr(e,136),s=n[n.length-1];if(s.length<136){const o=new Uint8Array(136);o.set(s),o[s.length]=t,o[135]|=128,n[n.length-1]=o}if(s.length===136){const o=new Uint8Array(136);o[0]=t,o[135]=128,n.push(o)}return n.map(Rs)}function Ns(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];Bu(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 se(e){return js(Ns(new Array(50).fill(0),Cs(e,1)))}function Lu(e){return js(Ns(new Array(50).fill(0),Cs(e,6)))}function zu(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 Fu(e,t){const n=Math.min(e.length,t.length);for(let s=0;s<n;s++)if(e[s]!==t[s])return e.subarray(0,s);return e.subarray(0,n)}function Vu(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 Wu(e,t,n){const s=Math.floor(t/8),o=t%8;return e[s]>>(n==="BE"?7-o:o)&1}function Hu(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 Ds(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 qu(e,t,n=0){const s=e.length%t;return s===0?e:Ds(e,e.length+t-s,n)}function Ps(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 Gu(e,t,n=0){const s=e.length%t;return s===0?e:Ps(e,e.length+t-s,n)}function Ku(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 Ju(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 Ge(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 Yu(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 Us(e,t){return R(e,t)===0n?0n:t%4n===3n?Yu(e,(t+1n)/4n,t):null}const B=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,P=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Rt=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Ct=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;function gr(e,t,n){if(t===0n)return[0n,0n];const s=R(3n*e*e*Ge(2n*t,n),n),o=R(s*s-2n*e,n),d=R(s*(e-o)-t,n);return[o,d]}function Nt(e,t,n,s,o){if(e===0n&&t===0n)return[n,s];if(n===0n&&s===0n)return[e,t];if(e===n&&t===R(-s,o))return[0n,0n];if(e===n&&t===s)return gr(e,t,o);const d=R((s-t)*Ge(n-e,o),o),f=R(d*d-e-n,o),v=R(d*(e-f)-t,o);return[f,v]}function Qu(e){if(e<=0n||e>=P)throw new Error("Invalid private key");return ke(Rt,Ct,e,B)}function Xu(e){const t=e[1]%2n===0n?2:3;return new Uint8Array([t,...Ce(e[0],"BE")])}function el(e){if(e.length!==33||e[0]!==2&&e[0]!==3)throw new Error("Invalid compressed public key");const t=Ne(e.slice(1),"BE"),n=Us(R(t**3n+7n,B),B);if(!n)throw Error("Invalid x: does not correspond to a valid curve point");const s=R(-n,B),o=n%2n===0n;return[t,e[0]===2?o?n:s:o?s:n]}function tl(e){const t=new Uint8Array(20),n=se(Re(Ce(e[0],"BE"),Ce(e[1],"BE")));return t.set(n.subarray(12)),t}function rl(e){const t=a.Binary.uint8ArrayToHex(e),n=a.Binary.uint8ArrayToHex(a.Binary.keccak256(new Uint8Array([...t].map(o=>o.charCodeAt(0)))));let s="0x";for(let o=0;o<t.length;o++)parseInt(n[o],16)>7?s+=t[o].toUpperCase():s+=t[o];return s}function ke(e,t,n,s){let o=[0n,0n],d=[e,t];const f=n.toString(2);for(const v of f)v==="0"?(d=Nt(o[0],o[1],d[0],d[1],s),o=gr(o[0],o[1],s)):(o=Nt(o[0],o[1],d[0],d[1],s),d=gr(d[0],d[1],s));return o}function nl(e,t,n){return Zs(Ne(se(e),"BE"),t,n)}function Zs(e,t,n){if(t<=0n||t>=P)throw new Error("Invalid private key");if(n||(n=R(Ne(se(Re(se(Ce(t,"BE")),Ce(e,"BE"))),"BE"),P)),n<=0n||n>=P)throw new Error("Invalid nonce");const s=R(e,P),o=ke(Rt,Ct,n,B),d=R(o[0],P);let f=R((s+R(d,P)*t)*Ge(n,P),P);if(d===0n||f===0n)throw new Error("Invalid r or s value");let v=o[1]%2n===0n?27n:28n;return f>P/2n&&(f=P-f,v=v===27n?28n:27n),[d,f,v]}function sl(e,t,n,s){const o=Us(R(t**3n+7n,B),B);if(!o)throw new Error("Invalid r: does not correspond to a valid curve point");const d=s===27n?0n:1n,f=o%2n===d?o:B-o,v=R(Ne(se(e),"BE"),P),m=ke(t,f,n,B),x=ke(Rt,Ct,v,B),$=Nt(m[0],m[1],x[0],R(-x[1],B),B);return ke($[0],$[1],Ge(t,P),B)}function il(e,t,n,s){const o=R(Ne(se(e),"BE"),P),d=Ge(s,P),f=R(o*d,P),v=R(n*d,P),m=ke(Rt,Ct,f,B),x=ke(t[0],t[1],v,B),$=Nt(m[0],m[1],x[0],x[1],B);return n===R($[0],P)}class Bs{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=Bs;class Ls{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=Ls;class jt{constructor(t,n=0n){this.span=n,this.writer=new Ls(new Uint8Array(t))}build(){return Re(pr(this.span,"LE"),this.writer.buffer)}hash(){const t=Ts(mr(this.writer.buffer,32),(n,s)=>se(Re(n,s)));return se(Re(pr(this.span,"LE"),t))}}a.Chunk=jt;class yr{constructor(t,n=4096){this.counters=[1],this.capacity=n,this.chunks=[new jt(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 Bs(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 jt(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 jt(this.capacity)}async finalize(t=0){return this.chunks[t+1]?this.counters[t]===1?(await this.elevate(t+1),this.chunks[t+1]=this.chunks[t],this.finalize(t+1)):(await this.elevate(t),this.finalize(t+1)):(await this.onChunk(this.chunks[t]),this.chunks[t])}}a.MerkleTree=yr,r=yr,yr.NOOP=async e=>{};class Y{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 Y(BigInt(s+o),n)}add(t){return this.assertSameScale(t),new Y(this.value+t.value,this.scale)}subtract(t){return this.assertSameScale(t),new Y(this.value-t.value,this.scale)}multiply(t){return new Y(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 Y(n,this.scale),new Y(s,this.scale)]}exchange(t,n,s){if(t==="*"){const d=this.value*n.value/10n**BigInt(this.scale);return new Y(d,s)}this.assertSameScale(n);const o=this.value*10n**BigInt(s)/n.value;return new Y(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=Y;function al(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 Dt(e,t,n,s){const o=e.findIndex(v=>v===`--${t}`||v.startsWith(`--${t}=`)),d=e[o];if(!d)return(n||{})[s||t||""]||null;if(d.includes("="))return d.split("=")[1];const f=e[o+1];return f&&!f.startsWith("-")?f:(n||{})[s||t||""]||null}function ol(e,t,n,s){const o=Dt(e,t,n,s);if(!o)return null;try{return dr(o)}catch{throw new Error(`Invalid number argument ${t}: ${o}`)}}function cl(e,t,n,s){const o=e.some(m=>m.endsWith("-"+t)),d=Dt(e,t,n,s);if(!d&&o)return!0;if(!d&&!o)return null;const f=["true","1","yes","y","on"],v=["false","0","no","n","off"];if(f.includes(d.toLowerCase()))return!0;if(v.includes(d.toLowerCase()))return!1;throw Error(`Invalid boolean argument ${t}: ${d}`)}function zs(e,t,n,s){const o=Dt(e,t,n,s);if(!o)throw new Error(`Missing argument ${t}`);return o}function ul(e,t,n,s){const o=zs(e,t,n,s);try{return dr(o)}catch{throw new Error(`Invalid argument ${t}: ${o}`)}}function Fs(e,t){const n=e[t];e.splice(t,1),e.unshift(n)}function ll(e,t){const n=[...e];return Fs(n,t),n}function Vs(e,t){return{x:e.x+t.x,y:e.y+t.y}}function dl(e,t){return{x:e.x-t.x,y:e.y-t.y}}function vr(e,t){return{x:e.x*t,y:e.y*t}}function fl(e){const t=Math.sqrt(e.x*e.x+e.y*e.y);return{x:e.x/t,y:e.y/t}}function Ws(e,t,n){return{x:e.x+Math.cos(t)*n,y:e.y+Math.sin(t)*n}}function Hs(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Ke(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 hl(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 pl(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 qs(e,t,n){var s;return!((s=e[t-1])!=null&&s[n])}function Gs(e,t,n){var s;return!((s=e[t+1])!=null&&s[n])}function Ks(e,t,n){return!e[t][n-1]}function Js(e,t,n){return!e[t][n+1]}function ml(e,t,n){var o,d,f,v,m,x,$,U;const s=[];return e[t][n]?hl(e,t,n)||pl(e,t,n)?[]:(!((o=e[t-1])!=null&&o[n-1])&&qs(e,t,n)&&Ks(e,t,n)&&s.push({x:t,y:n}),!((d=e[t+1])!=null&&d[n-1])&&Gs(e,t,n)&&Ks(e,t,n)&&s.push({x:t+1,y:n}),!((f=e[t-1])!=null&&f[n+1])&&qs(e,t,n)&&Js(e,t,n)&&s.push({x:t,y:n+1}),!((v=e[t+1])!=null&&v[n+1])&&Gs(e,t,n)&&Js(e,t,n)&&s.push({x:t+1,y:n+1}),s):((m=e[t-1])!=null&&m[n]&&e[t][n-1]&&s.push({x:t,y:n}),(x=e[t+1])!=null&&x[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 gl(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 v=ml(e,d,f);for(const m of v)o.some(x=>x.x===m.x&&x.y===m.y)||o.push(m)}return o.map(d=>({x:d.x*t,y:d.y*t}))}function yl(e,t){const n=Ke(e,(m,x)=>e[m][x]===0&&e[m][x+1]!==0,"row-first").map(m=>({...m,dx:1,dy:0})),s=Ke(e,(m,x)=>e[m][x]===0&&e[m][x-1]!==0,"row-first").map(m=>({...m,dx:1,dy:0})),o=Ke(e,(m,x)=>{var $;return e[m][x]===0&&(($=e[m-1])==null?void 0:$[x])!==0},"column-first").map(m=>({...m,dx:0,dy:1})),d=Ke(e,(m,x)=>{var $;return e[m][x]===0&&(($=e[m+1])==null?void 0:$[x])!==0},"column-first").map(m=>({...m,dx:0,dy:1}));n.forEach(m=>m.y++),d.forEach(m=>m.x++);const f=hr([...o,...d],(m,x)=>m.x===x.x&&m.y-1===x.y),v=hr([...s,...n],(m,x)=>m.y===x.y&&m.x-1===x.x);return[...f,...v].map(m=>({start:m[0],end:Ve(m)})).map(m=>({start:vr(m.start,t),end:vr(Vs(m.end,{x:m.start.dx,y:m.start.dy}),t)}))}function vl(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}function wl(e,t){return t.map(n=>vl(e,n)).sort((n,s)=>n-s)}function Ys(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 v=(s.x-n.x)*d-(s.y-n.y)*f,m=(t.x-e.x)*d-(t.y-e.y)*f;return d=v/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 wr(e,t,n){const s=[],o=Ws(e,n,1e4);for(const d of t){const f=Ys(e,o,d.start,d.end);f&&s.push(f)}return s.length?s.reduce((d,f)=>{const v=Hs(e,f),m=Hs(e,d);return v<m?f:d}):null}function bl(e,t,n){const s=wl(e,n),o=[];for(const d of s){const f=wr(e,t,d-.001),v=wr(e,t,d+.001);f&&o.push(f),v&&o.push(v)}return o}class br{constructor(){this.subscribers=[]}subscribe(t){return this.subscribers.push(t),()=>{this.subscribers=this.subscribers.filter(n=>n!==t)}}publish(t){this.subscribers.forEach(n=>n(t))}clear(){this.subscribers=[]}getSubscriberCount(){return this.subscribers.length}}a.PubSubChannel=br;class _l{constructor(t,n){this.queue=[],this.running=0,this.onProcessed=new br,this.onDrained=new br,this.concurrency=t,this.capacity=n}process(){if(this.running>=this.concurrency)return;const t=this.queue.shift();t&&(this.running++,t().finally(()=>{this.running--,this.process(),this.onProcessed.publish(),this.running===0&&this.onDrained.publish()}))}enqueue(t){if(this.queue.length<this.capacity)return this.queue.push(t),this.process(),Promise.resolve();if(this.onProcessed.getSubscriberCount())throw Error("Queue capacity is full");return new Promise(n=>{this.onProcessed.subscribe(()=>{this.queue.length<this.capacity&&(this.queue.push(t),this.process(),this.onProcessed.clear(),n())})})}drain(){if(this.running===0)return Promise.resolve();if(this.onDrained.getSubscriberCount())throw Error("Already draining");return new Promise(t=>{this.onDrained.subscribe(()=>{this.onDrained.clear(),t()})})}}a.AsyncQueue=_l,a.Binary={hexToUint8Array:Ao,uint8ArrayToHex:To,base64ToUint8Array:xo,uint8ArrayToBase64:ko,base32ToUint8Array:Eo,uint8ArrayToBase32:So,log2Reduce:Ts,partition:mr,concatBytes:Re,numberToUint8:Ru,uint8ToNumber:Cu,numberToUint16:Nu,uint16ToNumber:ju,numberToUint32:Du,uint32ToNumber:Pu,numberToUint64:pr,uint64ToNumber:Uu,numberToUint256:Ce,uint256ToNumber:Ne,sliceBytes:Zu,keccak256:se,sha3_256:Lu,proximity:zu,commonPrefix:Fu,setBit:Vu,getBit:Wu,indexOf:Hu,equals:Ju,padStart:Ds,padStartToMultiple:qu,padEnd:Ps,padEndToMultiple:Gu,xorCypher:Ku},a.Elliptic={privateKeyToPublicKey:Qu,compressPublicKey:Xu,publicKeyFromCompressed:el,publicKeyToAddress:tl,signMessage:nl,signHash:Zs,verifySignature:il,recoverPublicKey:sl,checksumEncode:rl},a.Random={intBetween:Fe,floatBetween:In,chance:$n,signed:wi,makeSeededRng:Ht,point:_i,procs:xi},a.Arrays={countUnique:fu,makeUnique:du,splitBySize:uu,splitByCount:ks,index:xs,indexCollection:cu,onlyOrThrow:p,onlyOrNull:g,firstOrThrow:E,firstOrNull:y,shuffle:h,initialize:j,initialize2D:ne,rotate2D:re,containsShape:ze,glue:Ia,pluck:Wt,pick:qt,pickMany:ki,pickManyUnique:Ei,pickWeighted:Ti,pickRandomIndices:Oe,pickGuaranteed:Si,last:Ve,pipe:Rn,makePipe:Ai,sortWeighted:Oi,pushAll:At,unshiftAll:Oa,filterAndRemove:Jo,merge:Wc,empty:Hc,pushToBucket:Sa,unshiftAndLimit:Aa,atRolling:Ta,group:hr,createOscillator:Rc,organiseWithLimits:Nc,tickPlaybook:al,getArgument:Dt,getBooleanArgument:cl,getNumberArgument:ol,requireStringArgument:zs,requireNumberArgument:ul,bringToFront:ll,bringToFrontInPlace:Fs,findInstance:Su,filterInstances:Au,interleave:Tu,toggle:Ou,createHierarchy:Iu,multicall:ku,maxBy:Eu},a.System={sleepMillis:l,forever:Ni,scheduleMany:Pa,waitFor:Ko,expandError:_a,runAndSetInterval:ji},a.Numbers={make:dr,sum:Za,average:Ba,median:La,getDistanceFromMidpoint:za,clamp:fr,range:Wn,interpolate:Ua,createSequence:$c,increment:Lc,decrement:zc,format:Bc,fromDecimals:Zc,makeStorage:_c,asMegabytes:Di,convertBytes:Pi,hexToRgb:Ui,rgbToHex:Zi,haversineDistanceToMeters:Bi,roundToNearest:xt,formatDistance:Li,triangularNumber:zi,searchFloat:Fi},a.Promises={raceFulfilled:c,invert:i,runInParallelBatches:u},a.Dates={getTimestamp:ic,getTimeDelta:hs,secondsToHumanTime:ac,countCycles:oc,isoDate:Xo,throttle:cc,timeSince:lc,dateTimeSlug:ec,unixTimestamp:Qo,fromUtcString:tc,fromMillis:rc,getProgress:dc,humanizeTime:It,humanizeProgress:Go,createTimeDigits:J,mapDayNumber:ps,getDayInfoFromDate:ur,getDayInfoFromDateTimeString:hc,seconds:pc,minutes:mc,hours:gc,days:yc,make:wc,normalizeTime:nc,absoluteDays:_e},a.Objects={safeParse:Ic,deleteDeep:$i,getDeep:ve,setDeep:we,incrementDeep:Mi,ensureDeep:Ii,replaceDeep:Ri,getFirstDeep:Ci,deepMergeInPlace:be,deepMerge2:xa,deepMerge3:ka,mapAllAsync:Ma,cloneWithJson:Yo,sortObject:gs,sortArray:ys,sortAny:xe,deepEquals:vs,deepEqualsEvery:Mc,runOn:Fc,ifPresent:Vc,zip:Vn,zipSum:Ea,removeEmptyArrays:qc,removeEmptyValues:Gc,flatten:au,unflatten:_s,match:ou,sort:Ss,map:Yc,mapIterable:Qc,filterKeys:Kc,filterValues:Jc,rethrow:Xc,setSomeOnObject:eu,setSomeDeep:tu,flip:ru,getAllPermutations:nu,countTruthyValues:su,transformToArray:hu,setMulti:mu,incrementMulti:pu,createBidirectionalMap:gu,createTemporalBidirectionalMap:yu,pushToBidirectionalMap:As,unshiftToBidirectionalMap:vu,addToTemporalBidirectionalMap:wu,getFromTemporalBidirectionalMap:bu,createStatefulToggle:Cc,diffKeys:jc,pickRandomKey:ws,mapRandomKey:Dc,fromObjectString:Pc,toQueryString:ds,parseQueryString:Bo,hasKey:Lo,selectMax:zo,reposition:Fo,unwrapSingleKey:Vo,parseKeyValues:Wo},a.Types={isFunction:Kt,isObject:ue,isStrictlyObject:Me,isEmptyArray:Cn,isEmptyObject:Vi,isUndefined:Gt,isString:W,isNumber:le,isBoolean:Nn,isDate:Ie,isBlank:kt,isId:Jt,isIntegerString:jn,isHexString:Dn,isUrl:zn,isNullable:ya,asString:Bn,asHexString:na,asSafeString:sa,asIntegerString:ra,asNumber:Et,asFunction:ia,asInteger:Xt,asBoolean:aa,asDate:oa,asNullableString:ca,asEmptiableString:ua,asId:la,asTime:da,asArray:fa,asObject:St,asNullableObject:ha,asStringMap:pa,asNumericDictionary:ma,asUrl:ga,asNullable:va,asOptional:wa,enforceObjectShape:Fn,enforceArrayShape:ba,isPng:Os,isJpg:Ms,isWebp:Is,isImage:$u},a.Strings={tokenizeByCount:lu,tokenizeByLength:Es,searchHex:Xi,searchSubstring:ea,randomHex:ta,randomLetter:Ki,randomAlphanumeric:Ji,randomRichAscii:Yi,randomUnicode:Qi,includesAny:Fa,slugify:er,normalForm:Wa,enumify:Ya,escapeHtml:Xa,decodeHtmlEntities:to,after:tr,afterLast:qn,before:Hn,beforeLast:rr,betweenWide:ro,betweenNarrow:no,getPreLine:xc,containsWord:or,containsWords:Do,joinUrl:ms,getFuzzyMatchScore:Tt,sortByFuzzyScore:Qa,splitOnce:nr,splitAll:Gn,randomize:oo,expand:Kn,shrinkTrim:He,capitalize:Ot,decapitalize:Jn,csvEscape:po,parseCsv:qo,surroundInOut:Ja,getExtension:sr,getBasename:ir,normalizeEmail:so,normalizeFilename:io,parseFilename:ao,camelToTitle:Ha,slugToTitle:qa,slugToCamel:Ga,joinHumanly:Ka,findWeightedPair:rs,extractBlock:ns,extractAllBlocks:yo,replaceBlocks:vo,indexOfEarliest:$e,lastIndexOfBefore:ts,parseHtmlAttributes:Po,readNextWord:Mt,resolveVariables:Uo,resolveVariableWithDefaultSyntax:us,resolveRemainingVariablesWithDefaults:ls,isLetter:Yn,isDigit:Qn,isLetterOrDigit:qe,isValidObjectPathCharacter:lo,insert:fo,indexOfRegex:Xn,lineMatches:es,linesMatchInOrder:ho,represent:We,resolveMarkdownLinks:Zo,buildUrl:Ho,isChinese:Va,replaceBetweenStrings:Sc,describeMarkdown:Ac,isBalanced:Tc,textToFormat:Oc,splitFormatting:wo,splitHashtags:bo,splitUrls:_o,route:Oo,explodeReplace:ar,generateVariants:Mo,replaceWord:Io,replacePascalCaseWords:$o,stripHtml:Ro,breakLine:cs,measureTextWidth:Co,toLines:No,levenshteinDistance:jo},a.Assertions={asEqual:$a,asTrue:Ra,asTruthy:Ca,asFalse:Na,asFalsy:ja,asEither:Da},a.Cache={get:kc,invalidate:Ec},a.Vector={addPoint:Vs,subtractPoint:dl,multiplyPoint:vr,normalizePoint:fl,pushPoint:Ws,filterCoordinates:Ke,findCorners:gl,findLines:yl,raycast:wr,raycastCircle:bl,getLineIntersectionPoint:Ys}})(ii);const C=Dl(ii);C.Arrays;C.Assertions;const L=C.Binary;C.Cache;C.Dates;C.Elliptic;C.Numbers;C.Objects;C.Pagination;C.Promises;C.Random;C.Strings;C.System;C.Types;C.Optional;C.Vector;C.PubSubChannel;C.Chunk;const Pl=C.MerkleTree;C.FixedPointNumber;C.Lazy;C.AsyncLazy;C.AsyncQueue;C.Uint8ArrayReader;C.Uint8ArrayWriter;const Ul=new TextEncoder,Xs=1,ei=4096,wn=4096,Zl=32;function ai(a,r){return r=typeof r=="number"?O.FeedIndex.fromBigInt(BigInt(r)):r,new O.Identifier(L.keccak256(L.concatBytes(a.toUint8Array(),r.toUint8Array())))}function Bl(a){const r=a.slice(0,O.Span.LENGTH),i=a.slice(O.Span.LENGTH),c=Ll(i),u=L.keccak256(L.concatBytes(r,c));return new O.Reference(u)}function Ll(a){if(a.length>wn)throw new O.BeeArgumentError(`payload size ${a.length} exceeds maximum chunk payload size ${wn}`,a);const r=new Uint8Array(wn);return r.set(a),L.log2Reduce(L.partition(r,Zl),(i,c)=>L.keccak256(L.concatBytes(i,c)))}function ti(a){if(a instanceof Uint8Array||(a=Ul.encode(a)),a.length<Xs||a.length>ei)throw new RangeError(`payload size ${a.length} exceeds limits [${Xs}, ${ei}]`);const r=O.Span.fromBigInt(BigInt(a.length)),i=L.concatBytes(r.toUint8Array(),a);return{data:i,span:r,payload:O.Bytes.fromSlice(i,O.Span.LENGTH),address:Bl(i)}}function zl(a,r){return new O.Reference(L.keccak256(L.concatBytes(a.toUint8Array(),r.toUint8Array())))}function ri(a,r,i){r=new O.Identifier(r),i=new O.PrivateKey(i);const c=zl(r,i.publicKey().address()),u=i.sign(L.concatBytes(r.toUint8Array(),a.address.toUint8Array())),l=L.concatBytes(r.toUint8Array(),u.toUint8Array(),a.data),h=O.Span.fromSlice(a.data,0),p=O.Bytes.fromSlice(a.data,O.Span.LENGTH);return{data:l,identifier:r,signature:u,span:h,payload:p,address:c,owner:i.publicKey().address()}}class Q{constructor(){}static getInstance(){return Q.instance||(Q.instance=new Q),Q.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 oe{constructor(){this.logger=Q.getInstance()}static getInstance(){return oe.instance||(oe.instance=new oe),oe.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 Fl=Q.getInstance(),Vl=oe.getInstance();function Wl(a){return new Promise(r=>{setTimeout(r,a)})}function _n(a){return(a.startsWith("0x")?a.slice(2):a).toLowerCase()}async function xn(a,r=3,i=250){return new Promise((c,u)=>{a().then(c).catch(l=>{r>0?(Fl.info(`Retrying... Attempts left: ${r}. Error: ${l.message}`),setTimeout(()=>{xn(a,r-1,i).then(c).catch(u)},i)):(Vl.handleError(l,"Utils.retryAwaitableAsync"),u(l))})})}class Hl{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 I;(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(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})(I||(I={}));var kn;(function(a){a.mergeShapes=(r,i)=>({...r,...i})})(kn||(kn={}));const _=I.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ae=a=>{switch(typeof a){case"undefined":return _.undefined;case"string":return _.string;case"number":return isNaN(a)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":return Array.isArray(a)?_.array:a===null?_.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?_.promise:typeof Map<"u"&&a instanceof Map?_.map:typeof Set<"u"&&a instanceof Set?_.set:typeof Date<"u"&&a instanceof Date?_.date:_.object;default:return _.unknown}},w=I.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"]),ql=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 p=c,g=0;for(;g<h.path.length;){const y=h.path[g];g===h.path.length-1?(p[y]=p[y]||{_errors:[]},p[y]._errors.push(i(h))):p[y]=p[y]||{_errors:[]},p=p[y],g++}}};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,I.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 Ze=(a,r)=>{let i;switch(a.code){case w.invalid_type:a.received===_.undefined?i="Required":i=`Expected ${a.expected}, received ${a.received}`;break;case w.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(a.expected,I.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:i=`Unrecognized key(s) in object: ${I.joinValues(a.keys,", ")}`;break;case w.invalid_union:i="Invalid input";break;case w.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${I.joinValues(a.options)}`;break;case w.invalid_enum_value:i=`Invalid enum value. Expected ${I.joinValues(a.options)}, received '${a.received}'`;break;case w.invalid_arguments:i="Invalid function arguments";break;case w.invalid_return_type:i="Invalid function return type";break;case w.invalid_date:i="Invalid date";break;case w.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(i=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(i=`${i} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?i=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?i=`Invalid input: must end with "${a.validation.endsWith}"`:I.assertNever(a.validation):a.validation!=="regex"?i=`Invalid ${a.validation}`:i="Invalid";break;case w.too_small:a.type==="array"?i=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?i=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?i=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?i=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:i="Invalid input";break;case w.too_big:a.type==="array"?i=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?i=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?i=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?i=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?i=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:i="Invalid input";break;case w.custom:i="Invalid input";break;case w.invalid_intersection_types:i="Intersection results could not be merged";break;case w.not_multiple_of:i=`Number must be a multiple of ${a.multipleOf}`;break;case w.not_finite:i="Number must be finite";break;default:i=r.defaultError,I.assertNever(a)}return{message:i}};let oi=Ze;function Gl(a){oi=a}function Pt(){return oi}const Ut=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 p="";const g=c.filter(y=>!!y).slice().reverse();for(const y of g)p=y(h,{data:r,defaultError:p}).message;return{...u,path:l,message:p}},Kl=[];function b(a,r){const i=Pt(),c=Ut({issueData:r,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,i,i===Ze?void 0:Ze].filter(u=>!!u)});a.common.issues.push(c)}class z{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(r,i){const c=[];for(const u of i){if(u.status==="aborted")return A;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 z.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 A;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 A=Object.freeze({status:"aborted"}),Pe=a=>({status:"dirty",value:a}),F=a=>({status:"valid",value:a}),En=a=>a.status==="aborted",Sn=a=>a.status==="dirty",Se=a=>a.status==="valid",ct=a=>typeof Promise<"u"&&a instanceof Promise;function Zt(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 ci(a,r,i,c,u){if(typeof r=="function"?a!==r||!u:!r.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r.set(a,i),i}var k;(function(a){a.errToObj=r=>typeof r=="string"?{message:r}:r||{},a.toString=r=>typeof r=="string"?r:r==null?void 0:r.message})(k||(k={}));var at,ot;class ee{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 ni=(a,r)=>{if(Se(r))return{success:!0,data:r.value};if(!a.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const i=new V(a.common.issues);return this._error=i,this._error}}};function T(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,p)=>{var g,y;const{message:E}=a;return h.code==="invalid_enum_value"?{message:E??p.defaultError}:typeof p.data>"u"?{message:(g=E??c)!==null&&g!==void 0?g:p.defaultError}:h.code!=="invalid_type"?{message:p.defaultError}:{message:(y=E??i)!==null&&y!==void 0?y:p.defaultError}},description:u}}class M{get description(){return this._def.description}_getType(r){return ae(r.data)}_getOrReturnCtx(r,i){return i||{common:r.parent.common,data:r.data,parsedType:ae(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}_processInputParams(r){return{status:new z,ctx:{common:r.parent.common,data:r.data,parsedType:ae(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}}_parseSync(r){const i=this._parse(r);if(ct(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:ae(r)},l=this._parseSync({data:r,path:u.path,parent:u});return ni(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:ae(r)};if(!this["~standard"].async)try{const l=this._parseSync({data:r,path:[],parent:u});return Se(l)?{value:l.value}:{issues:u.common.issues}}catch(l){!((c=(i=l==null?void 0:l.message)===null||i===void 0?void 0:i.toLowerCase())===null||c===void 0)&&c.includes("encountered")&&(this["~standard"].async=!0),u.common={issues:[],async:!0}}return this._parseAsync({data:r,path:[],parent:u}).then(l=>Se(l)?{value:l.value}:{issues:u.common.issues})}async parseAsync(r,i){const c=await this.safeParseAsync(r,i);if(c.success)return c.data;throw c.error}async safeParseAsync(r,i){const c={common:{issues:[],contextualErrorMap:i==null?void 0:i.errorMap,async:!0},path:(i==null?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:ae(r)},u=this._parse({data:r,path:c.path,parent:c}),l=await(ct(u)?u:Promise.resolve(u));return ni(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),p=()=>l.addIssue({code:w.custom,...c(u)});return typeof Promise<"u"&&h instanceof Promise?h.then(g=>g?!0:(p(),!1)):h?!0:(p(),!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 K({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 X.create(this,this._def)}nullable(){return ge.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return G.create(this)}promise(){return Le.create(this,this._def)}or(r){return ft.create([this,r],this._def)}and(r){return ht.create(this,r,this._def)}transform(r){return new K({...T(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:r}})}default(r){const i=typeof r=="function"?r:()=>r;return new vt({...T(this._def),innerType:this,defaultValue:i,typeName:S.ZodDefault})}brand(){return new Tn({typeName:S.ZodBranded,type:this,...T(this._def)})}catch(r){const i=typeof r=="function"?r:()=>r;return new wt({...T(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 _t.create(this,r)}readonly(){return bt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Jl=/^c[^\s-]{8,}$/i,Yl=/^[0-9a-z]+$/,Ql=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Xl=/^[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,ed=/^[a-z0-9_-]{21}$/i,td=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rd=/^[-+]?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)?)??$/,nd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let bn;const id=/^(?:(?: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])$/,ad=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,od=/^(([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]))$/,cd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ud=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ld=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ui="((\\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])))",dd=new RegExp(`^${ui}$`);function li(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 fd(a){return new RegExp(`^${li(a)}$`)}function di(a){let r=`${ui}T${li(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 hd(a,r){return!!((r==="v4"||!r)&&id.test(a)||(r==="v6"||!r)&&od.test(a))}function pd(a,r){if(!td.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 md(a,r){return!!((r==="v4"||!r)&&ad.test(a)||(r==="v6"||!r)&&cd.test(a))}class q extends M{_parse(r){if(this._def.coerce&&(r.data=String(r.data)),this._getType(r)!==_.string){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_type,expected:_.string,received:l.parsedType}),A}const c=new z;let u;for(const l of this._def.checks)if(l.kind==="min")r.data.length<l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),c.dirty());else if(l.kind==="max")r.data.length>l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),c.dirty());else if(l.kind==="length"){const h=r.data.length>l.value,p=r.data.length<l.value;(h||p)&&(u=this._getOrReturnCtx(r,u),h?b(u,{code:w.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):p&&b(u,{code:w.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),c.dirty())}else if(l.kind==="email")nd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"email",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="emoji")bn||(bn=new RegExp(sd,"u")),bn.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"emoji",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="uuid")Xl.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"uuid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="nanoid")ed.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"nanoid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid")Jl.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cuid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="cuid2")Yl.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cuid2",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="ulid")Ql.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"ulid",code:w.invalid_string,message:l.message}),c.dirty());else if(l.kind==="url")try{new URL(r.data)}catch{u=this._getOrReturnCtx(r,u),b(u,{validation:"url",code:w.invalid_string,message:l.message}),c.dirty()}else l.kind==="regex"?(l.regex.lastIndex=0,l.regex.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"regex",code:w.invalid_string,message:l.message}),c.dirty())):l.kind==="trim"?r.data=r.data.trim():l.kind==="includes"?r.data.includes(l.value,l.position)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),c.dirty()):l.kind==="toLowerCase"?r.data=r.data.toLowerCase():l.kind==="toUpperCase"?r.data=r.data.toUpperCase():l.kind==="startsWith"?r.data.startsWith(l.value)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:{startsWith:l.value},message:l.message}),c.dirty()):l.kind==="endsWith"?r.data.endsWith(l.value)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:{endsWith:l.value},message:l.message}),c.dirty()):l.kind==="datetime"?di(l).test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:"datetime",message:l.message}),c.dirty()):l.kind==="date"?dd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:"date",message:l.message}),c.dirty()):l.kind==="time"?fd(l).test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{code:w.invalid_string,validation:"time",message:l.message}),c.dirty()):l.kind==="duration"?rd.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"duration",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="ip"?hd(r.data,l.version)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"ip",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="jwt"?pd(r.data,l.alg)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"jwt",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="cidr"?md(r.data,l.version)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"cidr",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="base64"?ud.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"base64",code:w.invalid_string,message:l.message}),c.dirty()):l.kind==="base64url"?ld.test(r.data)||(u=this._getOrReturnCtx(r,u),b(u,{validation:"base64url",code:w.invalid_string,message:l.message}),c.dirty()):I.assertNever(l);return{status:c.value,value:r.data}}_regex(r,i,c){return this.refinement(u=>r.test(u),{validation:i,code:w.invalid_string,...k.errToObj(c)})}_addCheck(r){return new q({...this._def,checks:[...this._def.checks,r]})}email(r){return this._addCheck({kind:"email",...k.errToObj(r)})}url(r){return this._addCheck({kind:"url",...k.errToObj(r)})}emoji(r){return this._addCheck({kind:"emoji",...k.errToObj(r)})}uuid(r){return this._addCheck({kind:"uuid",...k.errToObj(r)})}nanoid(r){return this._addCheck({kind:"nanoid",...k.errToObj(r)})}cuid(r){return this._addCheck({kind:"cuid",...k.errToObj(r)})}cuid2(r){return this._addCheck({kind:"cuid2",...k.errToObj(r)})}ulid(r){return this._addCheck({kind:"ulid",...k.errToObj(r)})}base64(r){return this._addCheck({kind:"base64",...k.errToObj(r)})}base64url(r){return this._addCheck({kind:"base64url",...k.errToObj(r)})}jwt(r){return this._addCheck({kind:"jwt",...k.errToObj(r)})}ip(r){return this._addCheck({kind:"ip",...k.errToObj(r)})}cidr(r){return this._addCheck({kind:"cidr",...k.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,...k.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,...k.errToObj(r==null?void 0:r.message)})}duration(r){return this._addCheck({kind:"duration",...k.errToObj(r)})}regex(r,i){return this._addCheck({kind:"regex",regex:r,...k.errToObj(i)})}includes(r,i){return this._addCheck({kind:"includes",value:r,position:i==null?void 0:i.position,...k.errToObj(i==null?void 0:i.message)})}startsWith(r,i){return this._addCheck({kind:"startsWith",value:r,...k.errToObj(i)})}endsWith(r,i){return this._addCheck({kind:"endsWith",value:r,...k.errToObj(i)})}min(r,i){return this._addCheck({kind:"min",value:r,...k.errToObj(i)})}max(r,i){return this._addCheck({kind:"max",value:r,...k.errToObj(i)})}length(r,i){return this._addCheck({kind:"length",value:r,...k.errToObj(i)})}nonempty(r){return this.min(1,k.errToObj(r))}trim(){return new q({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new q({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new q({...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}}q.create=a=>{var r;return new q({checks:[],typeName:S.ZodString,coerce:(r=a==null?void 0:a.coerce)!==null&&r!==void 0?r:!1,...T(a)})};function gd(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 he extends M{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(r){if(this._def.coerce&&(r.data=Number(r.data)),this._getType(r)!==_.number){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_type,expected:_.number,received:l.parsedType}),A}let c;const u=new z;for(const l of this._def.checks)l.kind==="int"?I.isInteger(r.data)||(c=this._getOrReturnCtx(r,c),b(c,{code:w.invalid_type,expected:"integer",received:"float",message:l.message}),u.dirty()):l.kind==="min"?(l.inclusive?r.data<l.value:r.data<=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_small,minimum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),u.dirty()):l.kind==="max"?(l.inclusive?r.data>l.value:r.data>=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_big,maximum:l.value,type:"number",inclusive:l.inclusive,exact:!1,message:l.message}),u.dirty()):l.kind==="multipleOf"?gd(r.data,l.value)!==0&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.not_multiple_of,multipleOf:l.value,message:l.message}),u.dirty()):l.kind==="finite"?Number.isFinite(r.data)||(c=this._getOrReturnCtx(r,c),b(c,{code:w.not_finite,message:l.message}),u.dirty()):I.assertNever(l);return{status:u.value,value:r.data}}gte(r,i){return this.setLimit("min",r,!0,k.toString(i))}gt(r,i){return this.setLimit("min",r,!1,k.toString(i))}lte(r,i){return this.setLimit("max",r,!0,k.toString(i))}lt(r,i){return this.setLimit("max",r,!1,k.toString(i))}setLimit(r,i,c,u){return new he({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:c,message:k.toString(u)}]})}_addCheck(r){return new he({...this._def,checks:[...this._def.checks,r]})}int(r){return this._addCheck({kind:"int",message:k.toString(r)})}positive(r){return this._addCheck({kind:"min",value:0,inclusive:!1,message:k.toString(r)})}negative(r){return this._addCheck({kind:"max",value:0,inclusive:!1,message:k.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:0,inclusive:!0,message:k.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:0,inclusive:!0,message:k.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:k.toString(i)})}finite(r){return this._addCheck({kind:"finite",message:k.toString(r)})}safe(r){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:k.toString(r)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:k.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"&&I.isInteger(r.value))}get isFinite(){let r=null,i=null;for(const c of this._def.checks){if(c.kind==="finite"||c.kind==="int"||c.kind==="multipleOf")return!0;c.kind==="min"?(i===null||c.value>i)&&(i=c.value):c.kind==="max"&&(r===null||c.value<r)&&(r=c.value)}return Number.isFinite(i)&&Number.isFinite(r)}}he.create=a=>new he({checks:[],typeName:S.ZodNumber,coerce:(a==null?void 0:a.coerce)||!1,...T(a)});class pe extends M{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(r){if(this._def.coerce)try{r.data=BigInt(r.data)}catch{return this._getInvalidInput(r)}if(this._getType(r)!==_.bigint)return this._getInvalidInput(r);let c;const u=new z;for(const l of this._def.checks)l.kind==="min"?(l.inclusive?r.data<l.value:r.data<=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_small,type:"bigint",minimum:l.value,inclusive:l.inclusive,message:l.message}),u.dirty()):l.kind==="max"?(l.inclusive?r.data>l.value:r.data>=l.value)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.too_big,type:"bigint",maximum:l.value,inclusive:l.inclusive,message:l.message}),u.dirty()):l.kind==="multipleOf"?r.data%l.value!==BigInt(0)&&(c=this._getOrReturnCtx(r,c),b(c,{code:w.not_multiple_of,multipleOf:l.value,message:l.message}),u.dirty()):I.assertNever(l);return{status:u.value,value:r.data}}_getInvalidInput(r){const i=this._getOrReturnCtx(r);return b(i,{code:w.invalid_type,expected:_.bigint,received:i.parsedType}),A}gte(r,i){return this.setLimit("min",r,!0,k.toString(i))}gt(r,i){return this.setLimit("min",r,!1,k.toString(i))}lte(r,i){return this.setLimit("max",r,!0,k.toString(i))}lt(r,i){return this.setLimit("max",r,!1,k.toString(i))}setLimit(r,i,c,u){return new pe({...this._def,checks:[...this._def.checks,{kind:r,value:i,inclusive:c,message:k.toString(u)}]})}_addCheck(r){return new pe({...this._def,checks:[...this._def.checks,r]})}positive(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:k.toString(r)})}negative(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:k.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:k.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:k.toString(r)})}multipleOf(r,i){return this._addCheck({kind:"multipleOf",value:r,message:k.toString(i)})}get minValue(){let r=null;for(const i of this._def.checks)i.kind==="min"&&(r===null||i.value>r)&&(r=i.value);return r}get maxValue(){let r=null;for(const i of this._def.checks)i.kind==="max"&&(r===null||i.value<r)&&(r=i.value);return r}}pe.create=a=>{var r;return new pe({checks:[],typeName:S.ZodBigInt,coerce:(r=a==null?void 0:a.coerce)!==null&&r!==void 0?r:!1,...T(a)})};class ut extends M{_parse(r){if(this._def.coerce&&(r.data=!!r.data),this._getType(r)!==_.boolean){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.boolean,received:c.parsedType}),A}return F(r.data)}}ut.create=a=>new ut({typeName:S.ZodBoolean,coerce:(a==null?void 0:a.coerce)||!1,...T(a)});class Ae extends M{_parse(r){if(this._def.coerce&&(r.data=new Date(r.data)),this._getType(r)!==_.date){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_type,expected:_.date,received:l.parsedType}),A}if(isNaN(r.data.getTime())){const l=this._getOrReturnCtx(r);return b(l,{code:w.invalid_date}),A}const c=new z;let u;for(const l of this._def.checks)l.kind==="min"?r.data.getTime()<l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_small,message:l.message,inclusive:!0,exact:!1,minimum:l.value,type:"date"}),c.dirty()):l.kind==="max"?r.data.getTime()>l.value&&(u=this._getOrReturnCtx(r,u),b(u,{code:w.too_big,message:l.message,inclusive:!0,exact:!1,maximum:l.value,type:"date"}),c.dirty()):I.assertNever(l);return{status:c.value,value:new Date(r.data.getTime())}}_addCheck(r){return new Ae({...this._def,checks:[...this._def.checks,r]})}min(r,i){return this._addCheck({kind:"min",value:r.getTime(),message:k.toString(i)})}max(r,i){return this._addCheck({kind:"max",value:r.getTime(),message:k.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}}Ae.create=a=>new Ae({checks:[],coerce:(a==null?void 0:a.coerce)||!1,typeName:S.ZodDate,...T(a)});class Bt extends M{_parse(r){if(this._getType(r)!==_.symbol){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.symbol,received:c.parsedType}),A}return F(r.data)}}Bt.create=a=>new Bt({typeName:S.ZodSymbol,...T(a)});class lt extends M{_parse(r){if(this._getType(r)!==_.undefined){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.undefined,received:c.parsedType}),A}return F(r.data)}}lt.create=a=>new lt({typeName:S.ZodUndefined,...T(a)});class dt extends M{_parse(r){if(this._getType(r)!==_.null){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.null,received:c.parsedType}),A}return F(r.data)}}dt.create=a=>new dt({typeName:S.ZodNull,...T(a)});class Be extends M{constructor(){super(...arguments),this._any=!0}_parse(r){return F(r.data)}}Be.create=a=>new Be({typeName:S.ZodAny,...T(a)});class Ee extends M{constructor(){super(...arguments),this._unknown=!0}_parse(r){return F(r.data)}}Ee.create=a=>new Ee({typeName:S.ZodUnknown,...T(a)});class ce extends M{_parse(r){const i=this._getOrReturnCtx(r);return b(i,{code:w.invalid_type,expected:_.never,received:i.parsedType}),A}}ce.create=a=>new ce({typeName:S.ZodNever,...T(a)});class Lt extends M{_parse(r){if(this._getType(r)!==_.undefined){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.void,received:c.parsedType}),A}return F(r.data)}}Lt.create=a=>new Lt({typeName:S.ZodVoid,...T(a)});class G extends M{_parse(r){const{ctx:i,status:c}=this._processInputParams(r),u=this._def;if(i.parsedType!==_.array)return b(i,{code:w.invalid_type,expected:_.array,received:i.parsedType}),A;if(u.exactLength!==null){const h=i.data.length>u.exactLength.value,p=i.data.length<u.exactLength.value;(h||p)&&(b(i,{code:h?w.too_big:w.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&&(b(i,{code:w.too_small,minimum:u.minLength.value,type:"array",inclusive:!0,exact:!1,message:u.minLength.message}),c.dirty()),u.maxLength!==null&&i.data.length>u.maxLength.value&&(b(i,{code:w.too_big,maximum:u.maxLength.value,type:"array",inclusive:!0,exact:!1,message:u.maxLength.message}),c.dirty()),i.common.async)return Promise.all([...i.data].map((h,p)=>u.type._parseAsync(new ee(i,h,i.path,p)))).then(h=>z.mergeArray(c,h));const l=[...i.data].map((h,p)=>u.type._parseSync(new ee(i,h,i.path,p)));return z.mergeArray(c,l)}get element(){return this._def.type}min(r,i){return new G({...this._def,minLength:{value:r,message:k.toString(i)}})}max(r,i){return new G({...this._def,maxLength:{value:r,message:k.toString(i)}})}length(r,i){return new G({...this._def,exactLength:{value:r,message:k.toString(i)}})}nonempty(r){return this.min(1,r)}}G.create=(a,r)=>new G({type:a,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...T(r)});function De(a){if(a instanceof N){const r={};for(const i in a.shape){const c=a.shape[i];r[i]=X.create(De(c))}return new N({...a._def,shape:()=>r})}else return a instanceof G?new G({...a._def,type:De(a.element)}):a instanceof X?X.create(De(a.unwrap())):a instanceof ge?ge.create(De(a.unwrap())):a instanceof te?te.create(a.items.map(r=>De(r))):a}class N extends M{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=I.objectKeys(r);return this._cached={shape:r,keys:i}}_parse(r){if(this._getType(r)!==_.object){const y=this._getOrReturnCtx(r);return b(y,{code:w.invalid_type,expected:_.object,received:y.parsedType}),A}const{status:c,ctx:u}=this._processInputParams(r),{shape:l,keys:h}=this._getCached(),p=[];if(!(this._def.catchall instanceof ce&&this._def.unknownKeys==="strip"))for(const y in u.data)h.includes(y)||p.push(y);const g=[];for(const y of h){const E=l[y],j=u.data[y];g.push({key:{status:"valid",value:y},value:E._parse(new ee(u,j,u.path,y)),alwaysSet:y in u.data})}if(this._def.catchall instanceof ce){const y=this._def.unknownKeys;if(y==="passthrough")for(const E of p)g.push({key:{status:"valid",value:E},value:{status:"valid",value:u.data[E]}});else if(y==="strict")p.length>0&&(b(u,{code:w.unrecognized_keys,keys:p}),c.dirty());else if(y!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const y=this._def.catchall;for(const E of p){const j=u.data[E];g.push({key:{status:"valid",value:E},value:y._parse(new ee(u,j,u.path,E)),alwaysSet:E in u.data})}}return u.common.async?Promise.resolve().then(async()=>{const y=[];for(const E of g){const j=await E.key,re=await E.value;y.push({key:j,value:re,alwaysSet:E.alwaysSet})}return y}).then(y=>z.mergeObjectSync(c,y)):z.mergeObjectSync(c,g)}get shape(){return this._def.shape()}strict(r){return k.errToObj,new N({...this._def,unknownKeys:"strict",...r!==void 0?{errorMap:(i,c)=>{var u,l,h,p;const g=(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=k.errToObj(r).message)!==null&&p!==void 0?p:g}:{message:g}}}:{}})}strip(){return new N({...this._def,unknownKeys:"strip"})}passthrough(){return new N({...this._def,unknownKeys:"passthrough"})}extend(r){return new N({...this._def,shape:()=>({...this._def.shape(),...r})})}merge(r){return new N({unknownKeys:r._def.unknownKeys,catchall:r._def.catchall,shape:()=>({...this._def.shape(),...r._def.shape()}),typeName:S.ZodObject})}setKey(r,i){return this.augment({[r]:i})}catchall(r){return new N({...this._def,catchall:r})}pick(r){const i={};return I.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 I.objectKeys(this.shape).forEach(c=>{r[c]||(i[c]=this.shape[c])}),new N({...this._def,shape:()=>i})}deepPartial(){return De(this)}partial(r){const i={};return I.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 I.objectKeys(this.shape).forEach(c=>{if(r&&!r[c])i[c]=this.shape[c];else{let l=this.shape[c];for(;l instanceof X;)l=l._def.innerType;i[c]=l}}),new N({...this._def,shape:()=>i})}keyof(){return fi(I.objectKeys(this.shape))}}N.create=(a,r)=>new N({shape:()=>a,unknownKeys:"strip",catchall:ce.create(),typeName:S.ZodObject,...T(r)});N.strictCreate=(a,r)=>new N({shape:()=>a,unknownKeys:"strict",catchall:ce.create(),typeName:S.ZodObject,...T(r)});N.lazycreate=(a,r)=>new N({shape:a,unknownKeys:"strip",catchall:ce.create(),typeName:S.ZodObject,...T(r)});class ft extends M{_parse(r){const{ctx:i}=this._processInputParams(r),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 V(p.ctx.common.issues));return b(i,{code:w.invalid_union,unionErrors:h}),A}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 g of c){const y={...i,common:{...i.common,issues:[]},parent:null},E=g._parseSync({data:i.data,path:i.path,parent:y});if(E.status==="valid")return E;E.status==="dirty"&&!l&&(l={result:E,ctx:y}),y.common.issues.length&&h.push(y.common.issues)}if(l)return i.common.issues.push(...l.ctx.common.issues),l.result;const p=h.map(g=>new V(g));return b(i,{code:w.invalid_union,unionErrors:p}),A}}get options(){return this._def.options}}ft.create=(a,r)=>new ft({options:a,typeName:S.ZodUnion,...T(r)});const ie=a=>a instanceof mt?ie(a.schema):a instanceof K?ie(a.innerType()):a instanceof gt?[a.value]:a instanceof me?a.options:a instanceof yt?I.objectValues(a.enum):a instanceof vt?ie(a._def.innerType):a instanceof lt?[void 0]:a instanceof dt?[null]:a instanceof X?[void 0,...ie(a.unwrap())]:a instanceof ge?[null,...ie(a.unwrap())]:a instanceof Tn||a instanceof bt?ie(a.unwrap()):a instanceof wt?ie(a._def.innerType):[];class Vt extends M{_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.object)return b(i,{code:w.invalid_type,expected:_.object,received:i.parsedType}),A;const c=this.discriminator,u=i.data[c],l=this.optionsMap.get(u);return l?i.common.async?l._parseAsync({data:i.data,path:i.path,parent:i}):l._parseSync({data:i.data,path:i.path,parent:i}):(b(i,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[c]}),A)}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=ie(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 p of h){if(u.has(p))throw new Error(`Discriminator property ${String(r)} has duplicate value ${String(p)}`);u.set(p,l)}}return new Vt({typeName:S.ZodDiscriminatedUnion,discriminator:r,options:i,optionsMap:u,...T(c)})}}function An(a,r){const i=ae(a),c=ae(r);if(a===r)return{valid:!0,data:a};if(i===_.object&&c===_.object){const u=I.objectKeys(r),l=I.objectKeys(a).filter(p=>u.indexOf(p)!==-1),h={...a,...r};for(const p of l){const g=An(a[p],r[p]);if(!g.valid)return{valid:!1};h[p]=g.data}return{valid:!0,data:h}}else if(i===_.array&&c===_.array){if(a.length!==r.length)return{valid:!1};const u=[];for(let l=0;l<a.length;l++){const h=a[l],p=r[l],g=An(h,p);if(!g.valid)return{valid:!1};u.push(g.data)}return{valid:!0,data:u}}else return i===_.date&&c===_.date&&+a==+r?{valid:!0,data:a}:{valid:!1}}class ht extends M{_parse(r){const{status:i,ctx:c}=this._processInputParams(r),u=(l,h)=>{if(En(l)||En(h))return A;const p=An(l.value,h.value);return p.valid?((Sn(l)||Sn(h))&&i.dirty(),{status:i.value,value:p.data}):(b(c,{code:w.invalid_intersection_types}),A)};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}))}}ht.create=(a,r,i)=>new ht({left:a,right:r,typeName:S.ZodIntersection,...T(i)});class te extends M{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.array)return b(c,{code:w.invalid_type,expected:_.array,received:c.parsedType}),A;if(c.data.length<this._def.items.length)return b(c,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),A;!this._def.rest&&c.data.length>this._def.items.length&&(b(c,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty());const l=[...c.data].map((h,p)=>{const g=this._def.items[p]||this._def.rest;return g?g._parse(new ee(c,h,c.path,p)):null}).filter(h=>!!h);return c.common.async?Promise.all(l).then(h=>z.mergeArray(i,h)):z.mergeArray(i,l)}get items(){return this._def.items}rest(r){return new te({...this._def,rest:r})}}te.create=(a,r)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new te({items:a,typeName:S.ZodTuple,rest:null,...T(r)})};class pt extends M{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.object)return b(c,{code:w.invalid_type,expected:_.object,received:c.parsedType}),A;const u=[],l=this._def.keyType,h=this._def.valueType;for(const p in c.data)u.push({key:l._parse(new ee(c,p,c.path,p)),value:h._parse(new ee(c,c.data[p],c.path,p)),alwaysSet:p in c.data});return c.common.async?z.mergeObjectAsync(i,u):z.mergeObjectSync(i,u)}get element(){return this._def.valueType}static create(r,i,c){return i instanceof M?new pt({keyType:r,valueType:i,typeName:S.ZodRecord,...T(c)}):new pt({keyType:q.create(),valueType:r,typeName:S.ZodRecord,...T(i)})}}class zt extends M{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.map)return b(c,{code:w.invalid_type,expected:_.map,received:c.parsedType}),A;const u=this._def.keyType,l=this._def.valueType,h=[...c.data.entries()].map(([p,g],y)=>({key:u._parse(new ee(c,p,c.path,[y,"key"])),value:l._parse(new ee(c,g,c.path,[y,"value"]))}));if(c.common.async){const p=new Map;return Promise.resolve().then(async()=>{for(const g of h){const y=await g.key,E=await g.value;if(y.status==="aborted"||E.status==="aborted")return A;(y.status==="dirty"||E.status==="dirty")&&i.dirty(),p.set(y.value,E.value)}return{status:i.value,value:p}})}else{const p=new Map;for(const g of h){const y=g.key,E=g.value;if(y.status==="aborted"||E.status==="aborted")return A;(y.status==="dirty"||E.status==="dirty")&&i.dirty(),p.set(y.value,E.value)}return{status:i.value,value:p}}}}zt.create=(a,r,i)=>new zt({valueType:r,keyType:a,typeName:S.ZodMap,...T(i)});class Te extends M{_parse(r){const{status:i,ctx:c}=this._processInputParams(r);if(c.parsedType!==_.set)return b(c,{code:w.invalid_type,expected:_.set,received:c.parsedType}),A;const u=this._def;u.minSize!==null&&c.data.size<u.minSize.value&&(b(c,{code:w.too_small,minimum:u.minSize.value,type:"set",inclusive:!0,exact:!1,message:u.minSize.message}),i.dirty()),u.maxSize!==null&&c.data.size>u.maxSize.value&&(b(c,{code:w.too_big,maximum:u.maxSize.value,type:"set",inclusive:!0,exact:!1,message:u.maxSize.message}),i.dirty());const l=this._def.valueType;function h(g){const y=new Set;for(const E of g){if(E.status==="aborted")return A;E.status==="dirty"&&i.dirty(),y.add(E.value)}return{status:i.value,value:y}}const p=[...c.data.values()].map((g,y)=>l._parse(new ee(c,g,c.path,y)));return c.common.async?Promise.all(p).then(g=>h(g)):h(p)}min(r,i){return new Te({...this._def,minSize:{value:r,message:k.toString(i)}})}max(r,i){return new Te({...this._def,maxSize:{value:r,message:k.toString(i)}})}size(r,i){return this.min(r,i).max(r,i)}nonempty(r){return this.min(1,r)}}Te.create=(a,r)=>new Te({valueType:a,minSize:null,maxSize:null,typeName:S.ZodSet,...T(r)});class Ue extends M{constructor(){super(...arguments),this.validate=this.implement}_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.function)return b(i,{code:w.invalid_type,expected:_.function,received:i.parsedType}),A;function c(p,g){return Ut({data:p,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Pt(),Ze].filter(y=>!!y),issueData:{code:w.invalid_arguments,argumentsError:g}})}function u(p,g){return Ut({data:p,path:i.path,errorMaps:[i.common.contextualErrorMap,i.schemaErrorMap,Pt(),Ze].filter(y=>!!y),issueData:{code:w.invalid_return_type,returnTypeError:g}})}const l={errorMap:i.common.contextualErrorMap},h=i.data;if(this._def.returns instanceof Le){const p=this;return F(async function(...g){const y=new V([]),E=await p._def.args.parseAsync(g,l).catch(ne=>{throw y.addIssue(c(g,ne)),y}),j=await Reflect.apply(h,this,E);return await p._def.returns._def.type.parseAsync(j,l).catch(ne=>{throw y.addIssue(u(j,ne)),y})})}else{const p=this;return F(function(...g){const y=p._def.args.safeParse(g,l);if(!y.success)throw new V([c(g,y.error)]);const E=Reflect.apply(h,this,y.data),j=p._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 Ue({...this._def,args:te.create(r).rest(Ee.create())})}returns(r){return new Ue({...this._def,returns:r})}implement(r){return this.parse(r)}strictImplement(r){return this.parse(r)}static create(r,i,c){return new Ue({args:r||te.create([]).rest(Ee.create()),returns:i||Ee.create(),typeName:S.ZodFunction,...T(c)})}}class mt extends M{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})}}mt.create=(a,r)=>new mt({getter:a,typeName:S.ZodLazy,...T(r)});class gt extends M{_parse(r){if(r.data!==this._def.value){const i=this._getOrReturnCtx(r);return b(i,{received:i.data,code:w.invalid_literal,expected:this._def.value}),A}return{status:"valid",value:r.data}}get value(){return this._def.value}}gt.create=(a,r)=>new gt({value:a,typeName:S.ZodLiteral,...T(r)});function fi(a,r){return new me({values:a,typeName:S.ZodEnum,...T(r)})}class me extends M{constructor(){super(...arguments),at.set(this,void 0)}_parse(r){if(typeof r.data!="string"){const i=this._getOrReturnCtx(r),c=this._def.values;return b(i,{expected:I.joinValues(c),received:i.parsedType,code:w.invalid_type}),A}if(Zt(this,at)||ci(this,at,new Set(this._def.values)),!Zt(this,at).has(r.data)){const i=this._getOrReturnCtx(r),c=this._def.values;return b(i,{received:i.data,code:w.invalid_enum_value,options:c}),A}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 me.create(r,{...this._def,...i})}exclude(r,i=this._def){return me.create(this.options.filter(c=>!r.includes(c)),{...this._def,...i})}}at=new WeakMap;me.create=fi;class yt extends M{constructor(){super(...arguments),ot.set(this,void 0)}_parse(r){const i=I.getValidEnumValues(this._def.values),c=this._getOrReturnCtx(r);if(c.parsedType!==_.string&&c.parsedType!==_.number){const u=I.objectValues(i);return b(c,{expected:I.joinValues(u),received:c.parsedType,code:w.invalid_type}),A}if(Zt(this,ot)||ci(this,ot,new Set(I.getValidEnumValues(this._def.values))),!Zt(this,ot).has(r.data)){const u=I.objectValues(i);return b(c,{received:c.data,code:w.invalid_enum_value,options:u}),A}return F(r.data)}get enum(){return this._def.values}}ot=new WeakMap;yt.create=(a,r)=>new yt({values:a,typeName:S.ZodNativeEnum,...T(r)});class Le extends M{unwrap(){return this._def.type}_parse(r){const{ctx:i}=this._processInputParams(r);if(i.parsedType!==_.promise&&i.common.async===!1)return b(i,{code:w.invalid_type,expected:_.promise,received:i.parsedType}),A;const c=i.parsedType===_.promise?i.data:Promise.resolve(i.data);return F(c.then(u=>this._def.type.parseAsync(u,{path:i.path,errorMap:i.common.contextualErrorMap})))}}Le.create=(a,r)=>new Le({type:a,typeName:S.ZodPromise,...T(r)});class K extends M{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=>{b(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 A;const g=await this._def.schema._parseAsync({data:p,path:c.path,parent:c});return g.status==="aborted"?A:g.status==="dirty"||i.value==="dirty"?Pe(g.value):g});{if(i.value==="aborted")return A;const p=this._def.schema._parseSync({data:h,path:c.path,parent:c});return p.status==="aborted"?A:p.status==="dirty"||i.value==="dirty"?Pe(p.value):p}}if(u.type==="refinement"){const h=p=>{const g=u.refinement(p,l);if(c.common.async)return Promise.resolve(g);if(g instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return p};if(c.common.async===!1){const p=this._def.schema._parseSync({data:c.data,path:c.path,parent:c});return p.status==="aborted"?A:(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"?A:(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(!Se(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=>Se(h)?Promise.resolve(u.transform(h.value,l)).then(p=>({status:i.value,value:p})):h);I.assertNever(u)}}K.create=(a,r,i)=>new K({schema:a,typeName:S.ZodEffects,effect:r,...T(i)});K.createWithPreprocess=(a,r,i)=>new K({schema:r,effect:{type:"preprocess",transform:a},typeName:S.ZodEffects,...T(i)});class X extends M{_parse(r){return this._getType(r)===_.undefined?F(void 0):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}X.create=(a,r)=>new X({innerType:a,typeName:S.ZodOptional,...T(r)});class ge extends M{_parse(r){return this._getType(r)===_.null?F(null):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}}ge.create=(a,r)=>new ge({innerType:a,typeName:S.ZodNullable,...T(r)});class vt extends M{_parse(r){const{ctx:i}=this._processInputParams(r);let c=i.data;return i.parsedType===_.undefined&&(c=this._def.defaultValue()),this._def.innerType._parse({data:c,path:i.path,parent:i})}removeDefault(){return this._def.innerType}}vt.create=(a,r)=>new vt({innerType:a,typeName:S.ZodDefault,defaultValue:typeof r.default=="function"?r.default:()=>r.default,...T(r)});class wt extends M{_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 ct(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}}wt.create=(a,r)=>new wt({innerType:a,typeName:S.ZodCatch,catchValue:typeof r.catch=="function"?r.catch:()=>r.catch,...T(r)});class Ft extends M{_parse(r){if(this._getType(r)!==_.nan){const c=this._getOrReturnCtx(r);return b(c,{code:w.invalid_type,expected:_.nan,received:c.parsedType}),A}return{status:"valid",value:r.data}}}Ft.create=a=>new Ft({typeName:S.ZodNaN,...T(a)});const yd=Symbol("zod_brand");class Tn extends M{_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 _t extends M{_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"?A:l.status==="dirty"?(i.dirty(),Pe(l.value)):this._def.out._parseAsync({data:l.value,path:c.path,parent:c})})();{const u=this._def.in._parseSync({data:c.data,path:c.path,parent:c});return u.status==="aborted"?A: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 _t({in:r,out:i,typeName:S.ZodPipeline})}}class bt extends M{_parse(r){const i=this._def.innerType._parse(r),c=u=>(Se(u)&&(u.value=Object.freeze(u.value)),u);return ct(i)?i.then(u=>c(u)):c(i)}unwrap(){return this._def.innerType}}bt.create=(a,r)=>new bt({innerType:a,typeName:S.ZodReadonly,...T(r)});function hi(a,r={},i){return a?Be.create().superRefine((c,u)=>{var l,h;if(!a(c)){const p=typeof r=="function"?r(c):typeof r=="string"?{message:r}:r,g=(h=(l=p.fatal)!==null&&l!==void 0?l:i)!==null&&h!==void 0?h:!0,y=typeof p=="string"?{message:p}:p;u.addIssue({code:"custom",...y,fatal:g})}}):Be.create()}const vd={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 wd=(a,r={message:`Input not instance of ${a.name}`})=>hi(i=>i instanceof a,r),pi=q.create,mi=he.create,bd=Ft.create,_d=pe.create,gi=ut.create,xd=Ae.create,kd=Bt.create,Ed=lt.create,Sd=dt.create,Ad=Be.create,Td=Ee.create,Od=ce.create,Md=Lt.create,Id=G.create,$d=N.create,Rd=N.strictCreate,Cd=ft.create,Nd=Vt.create,jd=ht.create,Dd=te.create,Pd=pt.create,Ud=zt.create,Zd=Te.create,Bd=Ue.create,Ld=mt.create,zd=gt.create,Fd=me.create,Vd=yt.create,Wd=Le.create,si=K.create,Hd=X.create,qd=ge.create,Gd=K.createWithPreprocess,Kd=_t.create,Jd=()=>pi().optional(),Yd=()=>mi().optional(),Qd=()=>gi().optional(),Xd={string:a=>q.create({...a,coerce:!0}),number:a=>he.create({...a,coerce:!0}),boolean:a=>ut.create({...a,coerce:!0}),bigint:a=>pe.create({...a,coerce:!0}),date:a=>Ae.create({...a,coerce:!0})},ef=A;var D=Object.freeze({__proto__:null,defaultErrorMap:Ze,setErrorMap:Gl,getErrorMap:Pt,makeIssue:Ut,EMPTY_PATH:Kl,addIssueToContext:b,ParseStatus:z,INVALID:A,DIRTY:Pe,OK:F,isAborted:En,isDirty:Sn,isValid:Se,isAsync:ct,get util(){return I},get objectUtil(){return kn},ZodParsedType:_,getParsedType:ae,ZodType:M,datetimeRegex:di,ZodString:q,ZodNumber:he,ZodBigInt:pe,ZodBoolean:ut,ZodDate:Ae,ZodSymbol:Bt,ZodUndefined:lt,ZodNull:dt,ZodAny:Be,ZodUnknown:Ee,ZodNever:ce,ZodVoid:Lt,ZodArray:G,ZodObject:N,ZodUnion:ft,ZodDiscriminatedUnion:Vt,ZodIntersection:ht,ZodTuple:te,ZodRecord:pt,ZodMap:zt,ZodSet:Te,ZodFunction:Ue,ZodLazy:mt,ZodLiteral:gt,ZodEnum:me,ZodNativeEnum:yt,ZodPromise:Le,ZodEffects:K,ZodTransformer:K,ZodOptional:X,ZodNullable:ge,ZodDefault:vt,ZodCatch:wt,ZodNaN:Ft,BRAND:yd,ZodBranded:Tn,ZodPipeline:_t,ZodReadonly:bt,custom:hi,Schema:M,ZodSchema:M,late:vd,get ZodFirstPartyTypeKind(){return S},coerce:Xd,any:Ad,array:Id,bigint:_d,boolean:gi,date:xd,discriminatedUnion:Nd,effect:si,enum:Fd,function:Bd,instanceof:wd,intersection:jd,lazy:Ld,literal:zd,map:Ud,nan:bd,nativeEnum:Vd,never:Od,null:Sd,nullable:qd,number:mi,object:$d,oboolean:Qd,onumber:Yd,optional:Hd,ostring:Jd,pipeline:Kd,preprocess:Gd,promise:Wd,record:Pd,set:Zd,strictObject:Rd,string:pi,symbol:kd,transformer:si,tuple:Dd,undefined:Ed,union:Cd,unknown:Td,void:Md,NEVER:ef,ZodIssueCode:w,quotelessJson:ql,ZodError:V}),On=(a=>(a.TEXT="text",a.THREAD="thread",a.REACTION="reaction",a))(On||{});const ye=Q.getInstance(),tf=["id","targetMessageId","type","message","username","address","timestamp","signature","index","chatTopic","userTopic","additionalProps"],Mn=D.object({id:D.string(),targetMessageId:D.string().optional(),type:D.nativeEnum(On),message:D.string(),username:D.string(),address:D.string(),timestamp:D.number(),signature:D.string(),index:D.number(),chatTopic:D.string(),userTopic:D.string(),additionalProps:D.record(D.any()).optional()}).refine(a=>!a.additionalProps||Object.keys(a.additionalProps).length===0?!0:of(a.additionalProps).isValid,{message:"Invalid additional properties in message"}),rf=D.object({reference:D.string(),timestamp:D.number()}),nf=D.object({message:Mn,messageStateRefs:D.array(rf).nullable()});function yi(a){const r=nf.safeParse(a);return r.success?vi(a.message)?!0:(ye.warn("Invalid main message signature"),!1):(ye.warn("GSOC message validation failed:",r.error.format()),!1)}function sf(a){if(!Array.isArray(a))return ye.warn("Message state must be an array"),!1;for(const r of a)if(!af(r))return ye.warn("Invalid message in message state:",r.id),!1;return!0}function af(a){const r=Mn.safeParse(a);return r.success?vi(a)?!0:(ye.warn("Invalid message signature"),!1):(ye.warn("Message data validation failed:",r.error.format()),!1)}function vi(a){try{const r={username:a.username,address:a.address,timestamp:a.timestamp,message:a.message},i=new TextEncoder,c=L.concatBytes(i.encode(`Ethereum Signed Message:
|
|
11
|
+
32`),L.keccak256(i.encode(JSON.stringify(r))));if(new O.Signature(a.signature).isValid(c,a.address))throw new Error("Signature verification failed!");return!0}catch(r){return ye.warn("Error in validateUserSignature",r),!1}}function of(a){const r=[];if(a==null)return{isValid:!0,errors:[]};if(typeof a!="object"||Array.isArray(a))return r.push("Additional properties must be a plain object"),{isValid:!1,errors:r};for(const g of Object.keys(a))tf.includes(g)&&r.push(`Property '${g}' is reserved and cannot be overridden`);const i=JSON.stringify(a),c=new TextEncoder().encode(i).length,u=1*1024;c>u&&r.push(`Additional properties too large: ${c} bytes (max: ${u} bytes)`);const l=5;function h(g,y=0){if(y>l)return!1;if(typeof g=="object"&&g!==null&&!Array.isArray(g)){for(const E of Object.values(g))if(!h(E,y+1))return!1}return!0}h(a)||r.push(`Additional properties nested too deeply (max depth: ${l})`);for(const[g,y]of Object.entries(a))if(g.length>100&&r.push(`Property key '${g}' too long (max: 100 characters)`),typeof y=="string"&&y.length>1e3&&r.push(`Property '${g}' value too long (max: 1000 characters)`),typeof y=="string"){const E=[/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,/javascript:/gi,/data:text\/html/gi,/vbscript:/gi,/on\w+\s*=/gi];for(const j of E)if(j.test(y)){r.push(`Property '${g}' contains potentially dangerous content`);break}}const p=20;return Object.keys(a).length>p&&r.push(`Too many additional properties: ${Object.keys(a).length} (max: ${p})`),{isValid:r.length===0,errors:r}}function cf(a){const r=Mn.safeParse(a);if(!r.success){const i=r.error.issues.map(c=>c.path.length>0?`${c.path.join(".")}: ${c.message}`:c.message);return ye.warn("Message validation failed:",r.error.format()),{isValid:!1,errors:i}}return{isValid:!0,errors:[]}}const H={LOADING_INIT:"loadingInit",LOADING_PREVIOUS_MESSAGES:"loadingPreviousMessages",MESSAGE_RECEIVED:"messageReceived",MESSAGE_REQUEST_INITIATED:"messageRequestInitiated",MESSAGE_REQUEST_UPLOADED:"messageRequestUploaded",MESSAGE_REQUEST_ERROR:"messageRequestError",CRITICAL_ERROR:"criticalError"};class uf{constructor(r,i){this.utils=r,this.emitter=i,this.logger=Q.getInstance(),this.errorHandler=oe.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"),O.FeedIndex.fromBigInt(0n)}}async initMessageState(r){try{if(!yi(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(!sf(i))throw new Error(`Invalid message state for ref: ${r}`);this.processedRefs.add(r),this.refRetryCount.delete(r);for(const u of i)this.emitter.emit(H.MESSAGE_RECEIVED,u)}async handleRefError(r,i){const c=this.refRetryCount.get(r)||0,u=c+1;if(this.logger.warn(`Error processing ref ${r} (attempt ${u}/${this.MAX_RETRIES}):`,i),u>=this.MAX_RETRIES)this.bannedRefs.add(r),this.refRetryCount.delete(r),this.logger.error(`Ref ${r} has been banned after ${this.MAX_RETRIES} failed attempts`),this.errorHandler.handleError(i,"SwarmHistory.processMessageRef");else{this.refRetryCount.set(r,u);const l=this.RETRY_DELAY*Math.pow(2,c);this.logger.debug(`Retrying ref ${r} after ${l}ms delay`),await Wl(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 lf{constructor(r,i){this.userDetails=r,this.swarmSettings=i,this.depth=26,this.errorHandler=oe.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:p}=this.userDetails,g=this.generateUserOwnedFeedId(l,p),y=O.Topic.fromString(g);await c.makeFeedWriter(y,new O.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:p}=this.userDetails,g=new O.PrivateKey(h),y=O.Stamper.fromBlank(h,u,this.depth),E=this.generateUserOwnedFeedId(l,p),j=O.Topic.fromString(E),re=ai(j,r),ne=ti(i),ze=ri(ne,re,g),Oe={hash:()=>ze.address.toUint8Array()},Wt=y.stamp(Oe),{upload:Ht}=c.makeSOCWriter(g),Fe=O.Bytes.fromUtf8(i);return(await Ht(Wt,re,Fe.toUint8Array())).reference.toHex()}orderMessages(r){return r.sort((i,c)=>i.timestamp-c.timestamp)}async downloadObjectFromBee(r){try{const{bee:i}=this.swarmSettings,c=await i.downloadData(r);return c?c.toJSON():null}catch(i){return this.errorHandler.handleError(i,"Utils.downloadObjectFromBee"),null}}async uploadObjectToBee(r){const{enveloped:i,stamp:c}=this.swarmSettings;if(i){if(c)return this.uploadObjectToBeeEnvelope(r);throw new Error("Enveloped mode is enabled, but stamp is not provided")}else return this.uploadObjectToBeeOwn(r)}async uploadObjectToBeeOwn(r){try{const{bee:i,stamp:c}=this.swarmSettings;return(await i.uploadData(c,JSON.stringify(r),{redundancyLevel:4})).reference.toString()}catch(i){return this.errorHandler.handleError(i,"Utils.uploadObjectToBee"),null}}async uploadObjectToBeeEnvelope(r){try{const{bee:i,stamp:c}=this.swarmSettings,{privateKey:u}=this.userDetails,l=O.Stamper.fromBlank(u,c,this.depth),h=O.Bytes.fromUtf8(JSON.stringify(r)),p=new Pl(async y=>{await i.uploadChunk(l.stamp(y),y.build())});await p.append(h.toUint8Array());const g=await p.finalize();return L.uint8ArrayToHex(g.hash())}catch(i){return this.errorHandler.handleError(i,"Utils.uploadObjectToBee"),null}}async getOwnLatestFeedIndex(){try{const{bee:r,chatTopic:i}=this.swarmSettings,{ownAddress:c}=this.userDetails,u=this.generateUserOwnedFeedId(i,c),l=O.Topic.fromString(u),p=await r.makeFeedReader(l,c).downloadPayload(),g=Number(p.feedIndex.toBigInt()),y=g+1;return{latestIndex:g,nextIndex:y}}catch(r){if(this.isNotFoundError(r))return{latestIndex:-1,nextIndex:0};throw r}}async fetchLatestChatMessage(){const{bee:r,chatTopic:i,chatAddress:c}=this.swarmSettings,l=await r.makeFeedReader(O.Topic.fromString(i),_n(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(O.Topic.fromString(c),_n(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 O.PrivateKey(l),p=O.Identifier.fromString(u),g=O.Bytes.fromUtf8(r),{upload:y}=i.makeSOCWriter(h,{timeout:this.UPLOAD_GSOC_TIMEOUT});await y(c,p,g.toUint8Array())}async sendMessageToGsocEnvelope(r){const{bee:i,stamp:c,gsocTopic:u,gsocResourceId:l}=this.swarmSettings,{privateKey:h}=this.userDetails,p=O.Stamper.fromBlank(h,c,this.depth),g=new O.PrivateKey(l),y=O.Identifier.fromString(u),E=O.Bytes.fromUtf8(r),j=ti(E.toUint8Array()),re=ri(j,y,g),ne={hash:()=>re.address.toUint8Array()},ze=p.stamp(ne),{upload:Oe}=i.makeSOCWriter(g,{timeout:this.UPLOAD_GSOC_TIMEOUT});await Oe(ze,y,E.toUint8Array())}}class df{constructor(r){this.logger=Q.getInstance(),this.errorHandler=oe.getInstance(),this.gsocIndex=null,this.fetchProcessRunning=!1,this.stopFetch=!1;const i=new O.PrivateKey(_n(r.user.privateKey));this.userDetails={privateKey:r.user.privateKey,ownAddress:i.publicKey().address().toString(),nickname:r.user.nickname,ownIndex:-1},this.swarmSettings={bee:new O.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 Hl,this.utils=new lf(this.userDetails,this.swarmSettings),this.history=new uf(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,l){const h=this.userDetails.ownIndex===-1?0:this.userDetails.ownIndex+1,p={id:u||jl(),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:h,type:i,targetMessageId:c,message:r,additionalProps:l},g=cf(p);if(!g.isValid){const y=`Invalid message: ${g.errors.join(", ")}`;throw this.logger.error(y),new Error(y)}try{this.emitter.emit(H.MESSAGE_REQUEST_INITIATED,p),await this.utils.writeOwnFeedDataByIndex(h,JSON.stringify(p)),this.userDetails.ownIndex=h,this.emitter.emit(H.MESSAGE_REQUEST_UPLOADED,p),await this.broadcastUserMessage(p)}catch(y){this.emitter.emit(H.MESSAGE_REQUEST_ERROR,p),this.errorHandler.handleError(y,"Chat.sendMessage")}}async fetchPreviousMessages(){try{return this.emitter.emit(H.LOADING_PREVIOUS_MESSAGES,!0),await this.history.fetchPreviousMessageState()}finally{this.emitter.emit(H.LOADING_PREVIOUS_MESSAGES,!1)}}hasPreviousMessages(){return this.history.hasPreviousMessages()}async retrySendMessage(r){this.sendMessage(r.message,r.type,r.targetMessageId,r.id,r.additionalProps)}async retryBroadcastUserMessage(r){await this.broadcastUserMessage(r)}async init(){try{this.emitter.emit(H.LOADING_INIT,!0);const[r,i]=await Promise.allSettled([this.initOwnIndex(),this.history.init()]);if(r.status==="rejected")throw r.reason;i.status==="fulfilled"&&(this.gsocIndex=i.value),this.emitter.emit(H.LOADING_INIT,!1)}catch(r){this.errorHandler.handleError(r,"Chat.initSelfState"),this.emitter.emit(H.CRITICAL_ERROR,r)}}async initOwnIndex(){const{latestIndex:c}=await xn(()=>this.utils.getOwnLatestFeedIndex(),10,1e3);this.userDetails.ownIndex=c}async fetchLatestMessage(){try{if(!this.gsocIndex)return;const r=O.Topic.fromString(this.swarmSettings.chatTopic),i=ai(r,this.gsocIndex),c=await this.utils.rawSocDownload(this.swarmSettings.chatAddress,i.toString()),u=JSON.parse(c);if(!yi(u)){this.logger.warn("Invalid GSOC message during fetching");return}this.emitter.emit(H.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 xn(()=>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 O.EthAddress(i).toString(),h=new O.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 g=Date.now();return h.sign(JSON.stringify({username:u,address:l,message:r,timestamp:g})).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}}exports.EVENTS=H;exports.MessageType=On;exports.SwarmChat=df;
|