mirror of
https://github.com/logos-messaging/lab.waku.org.git
synced 2026-05-05 18:39:30 +00:00
3 lines
642 KiB
JavaScript
3 lines
642 KiB
JavaScript
/*! For license information please see index.js.LICENSE.txt */
|
|
(()=>{var __webpack_modules__={194:e=>{e.exports=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function s(s,i){r[s]=i,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(s(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:s(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function i(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function o(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=new Array(i);s<i;s++)o[s]=n[s].fn;return o},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,s,i,o){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,s),!0;case 5:return u.fn.call(u.context,t,n,s,i),!0;case 6:return u.fn.call(u.context,t,n,s,i,o),!0}for(l=1,c=new Array(h-1);l<h;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var d,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),h){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,s);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,r){return i(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return i(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,s){var i=r?r+e:e;if(!this._events[i])return this;if(!t)return o(this,i),this;var a=this._events[i];if(a.fn)a.fn!==t||s&&!a.once||n&&a.context!==n||o(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=1===l.length?l[0]:l:o(this,i)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a},361:(e,t,r)=>{"use strict";var n=t,s=r(3262),i=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function o(e,t){var r=0,n={};for(t|=0;r<e.length;)n[i[r+t]]=e[r++];return n}n.basic=o([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),n.defaults=o([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",s.emptyArray,null]),n.long=o([0,0,0,1,1],7),n.mapKey=o([0,0,0,5,5,0,0,0,1,1,0,2],2),n.packed=o([1,5,0,0,0,5,5,0,0,0,1,1,0])},420:(e,t,r)=>{"use strict";e.exports=function(e){var t=s.codegen(["m"],e.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),r={};e.oneofsArray.length&&t("var p={}");for(var n=0;n<e.fieldsArray.length;++n){var c=e._fieldsArray[n].resolve(),l="m"+s.safeProp(c.name);if(c.optional&&t("if(%s!=null&&m.hasOwnProperty(%j)){",l,c.name),c.map)t("if(!util.isObject(%s))",l)("return%j",i(c,"object"))("var k=Object.keys(%s)",l)("for(var i=0;i<k.length;++i){"),a(t,c,"k[i]"),o(t,c,n,l+"[k[i]]")("}");else if(c.repeated)t("if(!Array.isArray(%s))",l)("return%j",i(c,"array"))("for(var i=0;i<%s.length;++i){",l),o(t,c,n,l+"[i]")("}");else{if(c.partOf){var u=s.safeProp(c.partOf.name);1===r[c.partOf.name]&&t("if(p%s===1)",u)("return%j",c.partOf.name+": multiple values"),r[c.partOf.name]=1,t("p%s=1",u)}o(t,c,n,l)}c.optional&&t("}")}return t("return null")};var n=r(5643),s=r(3262);function i(e,t){return e.name+": "+t+(e.repeated&&"array"!==t?"[]":e.map&&"object"!==t?"{k:"+e.keyType+"}":"")+" expected"}function o(e,t,r,s){if(t.resolvedType)if(t.resolvedType instanceof n){e("switch(%s){",s)("default:")("return%j",i(t,"enum value"));for(var o=Object.keys(t.resolvedType.values),a=0;a<o.length;++a)e("case %i:",t.resolvedType.values[o[a]]);e("break")("}")}else e("{")("var e=types[%i].verify(%s);",r,s)("if(e)")("return%j+e",t.name+".")("}");else switch(t.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.isInteger(%s))",s)("return%j",i(t,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",s,s,s,s)("return%j",i(t,"integer|Long"));break;case"float":case"double":e('if(typeof %s!=="number")',s)("return%j",i(t,"number"));break;case"bool":e('if(typeof %s!=="boolean")',s)("return%j",i(t,"boolean"));break;case"string":e("if(!util.isString(%s))",s)("return%j",i(t,"string"));break;case"bytes":e('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',s,s,s)("return%j",i(t,"buffer"))}return e}function a(e,t,r){switch(t.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":e("if(!util.key32Re.test(%s))",r)("return%j",i(t,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":e("if(!util.key64Re.test(%s))",r)("return%j",i(t,"integer|Long key"));break;case"bool":e("if(!util.key2Re.test(%s))",r)("return%j",i(t,"boolean key"))}return e}},495:()=>{},527:e=>{"use strict";e.exports=h;var t=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,n=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,s=/^ *[*/]+ */,i=/^\s*\*?\/*/,o=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(e){return e.replace(c,function(e,t){switch(t){case"\\":case"":return t;default:return l[t]||""}})}function h(e,c){e=e.toString();var l=0,h=e.length,d=1,p=0,f={},g=[],m=null;function y(e){return Error("illegal "+e+" (line "+d+")")}function b(t){return e.charAt(t)}function w(t,r,n){var a,l={type:e.charAt(t++),lineEmpty:!1,leading:n},u=t-(c?2:3);do{if(--u<0||"\n"===(a=e.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var h=e.substring(t,r).split(o),g=0;g<h.length;++g)h[g]=h[g].replace(c?i:s,"").trim();l.text=h.join("\n").trim(),f[d]=l,p=d}function v(t){var r=E(t),n=e.substring(t,r);return/^\s*\/\//.test(n)}function E(e){for(var t=e;t<h&&"\n"!==b(t);)t++;return t}function S(){if(g.length>0)return g.shift();if(m)return function(){var t="'"===m?n:r;t.lastIndex=l-1;var s=t.exec(e);if(!s)throw y("string");return l=t.lastIndex,A(m),m=null,u(s[1])}();var s,i,o,p,f,S=0===l;do{if(l===h)return null;for(s=!1;a.test(o=b(l));)if("\n"===o&&(S=!0,++d),++l===h)return null;if("/"===b(l)){if(++l===h)throw y("comment");if("/"===b(l))if(c){if(p=l,f=!1,v(l-1)){f=!0;do{if((l=E(l))===h)break;if(l++,!S)break}while(v(l))}else l=Math.min(h,E(l)+1);f&&(w(p,l,S),S=!0),d++,s=!0}else{for(f="/"===b(p=l+1);"\n"!==b(++l);)if(l===h)return null;++l,f&&(w(p,l-1,S),S=!0),++d,s=!0}else{if("*"!==(o=b(l)))return"/";p=l+1,f=c||"*"===b(p);do{if("\n"===o&&++d,++l===h)throw y("comment");i=o,o=b(l)}while("*"!==i||"/"!==o);++l,f&&(w(p,l-2,S),S=!0),s=!0}}}while(s);var I=l;if(t.lastIndex=0,!t.test(b(I++)))for(;I<h&&!t.test(b(I));)++I;var k=e.substring(l,l=I);return'"'!==k&&"'"!==k||(m=k),k}function A(e){g.push(e)}function I(){if(!g.length){var e=S();if(null===e)return null;A(e)}return g[0]}return Object.defineProperty({next:S,peek:I,push:A,skip:function(e,t){var r=I();if(r===e)return S(),!0;if(!t)throw y("token '"+r+"', '"+e+"' expected");return!1},cmnt:function(e){var t,r=null;return void 0===e?(t=f[d-1],delete f[d-1],t&&(c||"*"===t.type||t.lineEmpty)&&(r=t.leading?t.text:null)):(p<e&&I(),t=f[e],delete f[e],!t||t.lineEmpty||!c&&"/"!==t.type||(r=t.leading?null:t.text)),r}},"line",{get:function(){return d}})}h.unescape=u},544:(e,t,r)=>{"use strict";const n=r(9939);t.PP=n.EventIterator,n.EventIterator},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,s,i,o=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),i=s-(r||s);n.diff=i,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,s)=>{if("%%"===r)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];r=i.call(n,t),e.splice(o,1),o--}return r}),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function s(e,t){let r=0,n=0,s=-1,i=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(s=n,i=r,n++):(r++,n++);else{if(-1===s)return!1;n=s+1,i++,r=i}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(s(e,r))return!1;for(const r of t.names)if(s(e,r))return!0;return!1},t.humanize=r(6585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},744:(e,t,r)=>{"use strict";var n=t,s=r(5643),i=r(3262);function o(e,t,r,n){var i=!1;if(t.resolvedType)if(t.resolvedType instanceof s){e("switch(d%s){",n);for(var o=t.resolvedType.values,a=Object.keys(o),c=0;c<a.length;++c)o[a[c]]!==t.typeDefault||i||(e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}',n,n,n),t.repeated||e("break"),i=!0),e("case%j:",a[c])("case %i:",o[a[c]])("m%s=%j",n,o[a[c]])("break");e("}")}else e('if(typeof d%s!=="object")',n)("throw TypeError(%j)",t.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",n,r,n);else{var l=!1;switch(t.type){case"double":case"float":e("m%s=Number(d%s)",n,n);break;case"uint32":case"fixed32":e("m%s=d%s>>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":l=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",n,n,l)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,l?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function a(e,t,r,n){if(t.resolvedType)t.resolvedType instanceof s?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,r,n,n,r,n,n):e("d%s=types[%i].toObject(m%s,o)",n,r,n);else{var i=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":i=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,i?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}n.fromObject=function(e){var t=e.fieldsArray,r=i.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var n=0;n<t.length;++n){var a=t[n].resolve(),c=i.safeProp(a.name);a.map?(r("if(d%s){",c)('if(typeof d%s!=="object")',c)("throw TypeError(%j)",a.fullName+": object expected")("m%s={}",c)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",c),o(r,a,n,c+"[ks[i]]")("}")("}")):a.repeated?(r("if(d%s){",c)("if(!Array.isArray(d%s))",c)("throw TypeError(%j)",a.fullName+": array expected")("m%s=[]",c)("for(var i=0;i<d%s.length;++i){",c),o(r,a,n,c+"[i]")("}")("}")):(a.resolvedType instanceof s||r("if(d%s!=null){",c),o(r,a,n,c),a.resolvedType instanceof s||r("}"))}return r("return m")},n.toObject=function(e){var t=e.fieldsArray.slice().sort(i.compareFieldsById);if(!t.length)return i.codegen()("return {}");for(var r=i.codegen(["m","o"],e.name+"$toObject")("if(!o)")("o={}")("var d={}"),n=[],o=[],c=[],l=0;l<t.length;++l)t[l].partOf||(t[l].resolve().repeated?n:t[l].map?o:c).push(t[l]);if(n.length){for(r("if(o.arrays||o.defaults){"),l=0;l<n.length;++l)r("d%s=[]",i.safeProp(n[l].name));r("}")}if(o.length){for(r("if(o.objects||o.defaults){"),l=0;l<o.length;++l)r("d%s={}",i.safeProp(o[l].name));r("}")}if(c.length){for(r("if(o.defaults){"),l=0;l<c.length;++l){var u=c[l],h=i.safeProp(u.name);if(u.resolvedType instanceof s)r("d%s=o.enums===String?%j:%j",h,u.resolvedType.valuesById[u.typeDefault],u.typeDefault);else if(u.long)r("if(util.Long){")("var n=new util.Long(%i,%i,%j)",u.typeDefault.low,u.typeDefault.high,u.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",h)("}else")("d%s=o.longs===String?%j:%i",h,u.typeDefault.toString(),u.typeDefault.toNumber());else if(u.bytes){var d="["+Array.prototype.slice.call(u.typeDefault).join(",")+"]";r("if(o.bytes===String)d%s=%j",h,String.fromCharCode.apply(String,u.typeDefault))("else{")("d%s=%s",h,d)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)",h,h)("}")}else r("d%s=%j",h,u.typeDefault)}r("}")}var p=!1;for(l=0;l<t.length;++l){u=t[l];var f=e._fieldsArray.indexOf(u);h=i.safeProp(u.name),u.map?(p||(p=!0,r("var ks2")),r("if(m%s&&(ks2=Object.keys(m%s)).length){",h,h)("d%s={}",h)("for(var j=0;j<ks2.length;++j){"),a(r,u,f,h+"[ks2[j]]")("}")):u.repeated?(r("if(m%s&&m%s.length){",h,h)("d%s=[]",h)("for(var j=0;j<m%s.length;++j){",h),a(r,u,f,h+"[j]")("}")):(r("if(m%s!=null&&m.hasOwnProperty(%j)){",h,u.name),a(r,u,f,h),u.partOf&&r("if(o.oneofs)")("d%s=%j",i.safeProp(u.partOf.name),u.name)),r("}")}return r("return d")}},818:(e,t,r)=>{"use strict";e.exports=i;var n=r(3449);(i.prototype=Object.create(n.prototype)).constructor=i;var s=r(3610);function i(){n.call(this)}function o(e,t,r){e.length<40?s.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}i._configure=function(){i.alloc=s._Buffer_allocUnsafe,i.writeBytesBuffer=s.Buffer&&s.Buffer.prototype instanceof Uint8Array&&"set"===s.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n<e.length;)t[r++]=e[n++]}},i.prototype.bytes=function(e){s.isString(e)&&(e=s._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(i.writeBytesBuffer,t,e),this},i.prototype.string=function(e){var t=s.Buffer.byteLength(e);return this.uint32(t),t&&this._push(o,t,e),this},i._configure()},1080:(e,t,r)=>{"use strict";e.exports=function(e){for(var t,r=i.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(i.compareFieldsById),c=0;c<a.length;++c){var l=a[c].resolve(),u=e._fieldsArray.indexOf(l),h=l.resolvedType instanceof n?"int32":l.type,d=s.basic[h];t="m"+i.safeProp(l.name),l.map?(r("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){",t,l.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",t)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(l.id<<3|2)>>>0,8|s.mapKey[l.keyType],l.keyType),void 0===d?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|d,h,t),r("}")("}")):l.repeated?(r("if(%s!=null&&%s.length){",t,t),l.packed&&void 0!==s.packed[h]?r("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",h,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),void 0===d?o(r,l,u,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(l.id<<3|d)>>>0,h,t)),r("}")):(l.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,l.name),void 0===d?o(r,l,u,t):r("w.uint32(%i).%s(%s)",(l.id<<3|d)>>>0,h,t))}return r("return w")};var n=r(5643),s=r(361),i=r(3262);function o(e,t,r,n){return t.delimited?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},1176:(e,t,r)=>{var n;!function(){"use strict";var s="input is invalid type",i="object"==typeof window,o=i?window:{};o.JS_SHA3_NO_WINDOW&&(i=!1);var a=!i&&"object"==typeof self;!o.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?o=global:a&&(o=self);for(var c=!o.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!o.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],p=[0,8,16,24],f=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],m=[128,256],y=["hex","buffer","arrayBuffer","array","digest"],b={128:168,256:136},w=o.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,v=!u||!o.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer},E=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(s);if(u&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!w(e)&&!v(e))throw new Error(s);return[e,!1]},S=function(e){return 0===E(e)[0].length},A=function(e){for(var t=[],r=0;r<e.length;++r)t[r]=e[r];return t},I=function(e,t,r){return function(n){return new U(e,t,e).update(n)[r]()}},k=function(e,t,r){return function(n,s){return new U(e,t,s).update(n)[r]()}},x=function(e,t,r){return function(t,n,s,i){return R["cshake"+e].update(t,n,s,i)[r]()}},C=function(e,t,r){return function(t,n,s,i){return R["kmac"+e].update(t,n,s,i)[r]()}},_=function(e,t,r,n){for(var s=0;s<y.length;++s){var i=y[s];e[i]=t(r,n,i)}return e},T=function(e,t){var r=I(e,t,"hex");return r.create=function(){return new U(e,t,e)},r.update=function(e){return r.create().update(e)},_(r,I,e,t)},P=[{name:"keccak",padding:[1,256,65536,16777216],bits:g,createMethod:T},{name:"sha3",padding:[6,1536,393216,100663296],bits:g,createMethod:T},{name:"shake",padding:[31,7936,2031616,520093696],bits:m,createMethod:function(e,t){var r=k(e,t,"hex");return r.create=function(r){return new U(e,t,r)},r.update=function(e,t){return r.create(t).update(e)},_(r,k,e,t)}},{name:"cshake",padding:d,bits:m,createMethod:function(e,t){var r=b[e],n=x(e,0,"hex");return n.create=function(n,s,i){return S(s)&&S(i)?R["shake"+e].create(n):new U(e,t,n).bytepad([s,i],r)},n.update=function(e,t,r,s){return n.create(t,r,s).update(e)},_(n,x,e,t)}},{name:"kmac",padding:d,bits:m,createMethod:function(e,t){var r=b[e],n=C(e,0,"hex");return n.create=function(n,s,i){return new $(e,t,s).bytepad(["KMAC",i],r).bytepad([n],r)},n.update=function(e,t,r,s){return n.create(e,r,s).update(t)},_(n,C,e,t)}}],R={},O=[],L=0;L<P.length;++L)for(var D=P[L],N=D.bits,M=0;M<N.length;++M){var F=D.name+"_"+N[M];if(O.push(F),R[F]=D.createMethod(N[M],D.padding),"sha3"!==D.name){var B=D.name+N[M];O.push(B),R[B]=R[F]}}function U(e,t,r){this.blocks=[],this.s=[],this.padding=t,this.outputBits=r,this.reset=!0,this.finalized=!1,this.block=0,this.start=0,this.blockCount=1600-(e<<1)>>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function $(e,t,r){U.call(this,e,t,r)}U.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=E(e);e=t[0];for(var r,n,s=t[1],i=this.blocks,o=this.byteCount,a=e.length,c=this.blockCount,l=0,u=this.s;l<a;){if(this.reset)for(this.reset=!1,i[0]=this.block,r=1;r<c+1;++r)i[r]=0;if(s)for(r=this.start;l<a&&r<o;++l)(n=e.charCodeAt(l))<128?i[r>>2]|=n<<p[3&r++]:n<2048?(i[r>>2]|=(192|n>>6)<<p[3&r++],i[r>>2]|=(128|63&n)<<p[3&r++]):n<55296||n>=57344?(i[r>>2]|=(224|n>>12)<<p[3&r++],i[r>>2]|=(128|n>>6&63)<<p[3&r++],i[r>>2]|=(128|63&n)<<p[3&r++]):(n=65536+((1023&n)<<10|1023&e.charCodeAt(++l)),i[r>>2]|=(240|n>>18)<<p[3&r++],i[r>>2]|=(128|n>>12&63)<<p[3&r++],i[r>>2]|=(128|n>>6&63)<<p[3&r++],i[r>>2]|=(128|63&n)<<p[3&r++]);else for(r=this.start;l<a&&r<o;++l)i[r>>2]|=e[l]<<p[3&r++];if(this.lastByteIndex=r,r>=o){for(this.start=r-o,this.block=i[c],r=0;r<c;++r)u[r]^=i[r];q(u),this.reset=!0}else this.start=r}return this},U.prototype.encode=function(e,t){var r=255&e,n=1,s=[r];for(r=255&(e>>=8);r>0;)s.unshift(r),r=255&(e>>=8),++n;return t?s.push(n):s.unshift(n),this.update(s),s.length},U.prototype.encodeString=function(e){var t=E(e);e=t[0];var r=t[1],n=0,s=e.length;if(r)for(var i=0;i<e.length;++i){var o=e.charCodeAt(i);o<128?n+=1:o<2048?n+=2:o<55296||o>=57344?n+=3:(o=65536+((1023&o)<<10|1023&e.charCodeAt(++i)),n+=4)}else n=s;return n+=this.encode(8*n),this.update(e),n},U.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n<e.length;++n)r+=this.encodeString(e[n]);var s=(t-r%t)%t,i=[];return i.length=s,this.update(i),this},U.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex,r=this.blockCount,n=this.s;if(e[t>>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t<r+1;++t)e[t]=0;for(e[r-1]|=2147483648,t=0;t<r;++t)n[t]^=e[t];q(n)}},U.prototype.toString=U.prototype.hex=function(){this.finalize();for(var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,a="";o<n;){for(i=0;i<t&&o<n;++i,++o)e=r[i],a+=h[e>>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];o%t===0&&(r=A(r),q(r),i=0)}return s&&(e=r[i],a+=h[e>>4&15]+h[15&e],s>1&&(a+=h[e>>12&15]+h[e>>8&15]),s>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},U.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,i=0,o=0,a=this.outputBits>>3;e=s?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);o<n;){for(i=0;i<t&&o<n;++i,++o)c[o]=r[i];o%t===0&&(r=A(r),q(r))}return s&&(c[o]=r[i],e=e.slice(0,a)),e},U.prototype.buffer=U.prototype.arrayBuffer,U.prototype.digest=U.prototype.array=function(){this.finalize();for(var e,t,r=this.blockCount,n=this.s,s=this.outputBlocks,i=this.extraBytes,o=0,a=0,c=[];a<s;){for(o=0;o<r&&a<s;++o,++a)e=a<<2,t=n[o],c[e]=255&t,c[e+1]=t>>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r===0&&(n=A(n),q(n))}return i&&(e=a<<2,t=n[o],c[e]=255&t,i>1&&(c[e+1]=t>>8&255),i>2&&(c[e+2]=t>>16&255)),c},$.prototype=new U,$.prototype.finalize=function(){return this.encode(this.outputBits,!0),U.prototype.finalize.call(this)};var q=function(e){var t,r,n,s,i,o,a,c,l,u,h,d,p,g,m,y,b,w,v,E,S,A,I,k,x,C,_,T,P,R,O,L,D,N,M,F,B,U,$,q,j,z,K,V,H,G,W,X,J,Y,Z,Q,ee,te,re,ne,se,ie,oe,ae,ce,le,ue;for(n=0;n<48;n+=2)s=e[0]^e[10]^e[20]^e[30]^e[40],i=e[1]^e[11]^e[21]^e[31]^e[41],o=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(o<<1|a>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|o>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=s^(c<<1|l>>>31),r=i^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=o^(u<<1|h>>>31),r=a^(h<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=l^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(s<<1|i>>>31),r=h^(i<<1|s>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],m=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,T=e[20]<<3|e[21]>>>29,P=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,z=e[40]<<18|e[41]>>>14,K=e[41]<<18|e[40]>>>14,N=e[2]<<1|e[3]>>>31,M=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,X=e[22]<<10|e[23]>>>22,J=e[23]<<10|e[22]>>>22,R=e[33]<<13|e[32]>>>19,O=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,F=e[14]<<6|e[15]>>>26,B=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,Y=e[34]<<15|e[35]>>>17,Z=e[35]<<15|e[34]>>>17,L=e[45]<<29|e[44]>>>3,D=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,x=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,se=e[16]<<23|e[17]>>>9,U=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,V=e[8]<<27|e[9]>>>5,H=e[9]<<27|e[8]>>>5,C=e[18]<<20|e[19]>>>12,_=e[19]<<20|e[18]>>>12,ie=e[29]<<7|e[28]>>>25,oe=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,j=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,I=e[49]<<14|e[48]>>>18,e[0]=g^~y&w,e[1]=m^~b&v,e[10]=k^~C&T,e[11]=x^~_&P,e[20]=N^~F&U,e[21]=M^~B&$,e[30]=V^~G&X,e[31]=H^~W&J,e[40]=te^~ne&ie,e[41]=re^~se&oe,e[2]=y^~w&E,e[3]=b^~v&S,e[12]=C^~T&R,e[13]=_^~P&O,e[22]=F^~U&q,e[23]=B^~$&j,e[32]=G^~X&Y,e[33]=W^~J&Z,e[42]=ne^~ie&ae,e[43]=se^~oe&ce,e[4]=w^~E&A,e[5]=v^~S&I,e[14]=T^~R&L,e[15]=P^~O&D,e[24]=U^~q&z,e[25]=$^~j&K,e[34]=X^~Y&Q,e[35]=J^~Z&ee,e[44]=ie^~ae&le,e[45]=oe^~ce&ue,e[6]=E^~A&g,e[7]=S^~I&m,e[16]=R^~L&k,e[17]=O^~D&x,e[26]=q^~z&N,e[27]=j^~K&M,e[36]=Y^~Q&V,e[37]=Z^~ee&H,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=A^~g&y,e[9]=I^~m&b,e[18]=L^~k&C,e[19]=D^~x&_,e[28]=z^~N&F,e[29]=K^~M&B,e[38]=Q^~V&G,e[39]=ee^~H&W,e[48]=le^~te&ne,e[49]=ue^~re&se,e[0]^=f[n],e[1]^=f[n+1]};if(c)e.exports=R;else{for(L=0;L<O.length;++L)o[O[L]]=R[O[L]];l&&(void 0===(n=function(){return R}.call(t,r,t,e))||(e.exports=n))}}()},1344:(e,t,r)=>{"use strict";e.exports=l;var n=r(7209);((l.prototype=Object.create(n.prototype)).constructor=l).className="Field";var s,i=r(5643),o=r(361),a=r(3262),c=/^required|optional|repeated$/;function l(e,t,r,s,i,l,u){if(a.isObject(s)?(u=i,l=s,s=i=void 0):a.isObject(i)&&(u=l,l=i,i=void 0),n.call(this,e,l),!a.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!a.isString(r))throw TypeError("type must be a string");if(void 0!==s&&!c.test(s=s.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==i&&!a.isString(i))throw TypeError("extend must be a string");"proto3_optional"===s&&(s="optional"),this.rule=s&&"optional"!==s?s:void 0,this.type=r,this.id=t,this.extend=i||void 0,this.repeated="repeated"===s,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==o.long[r],this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this.comment=u}l.fromJSON=function(e,t){var r=new l(e,t.id,t.type,t.rule,t.extend,t.options,t.comment);return t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},Object.defineProperty(l.prototype,"required",{get:function(){return"LEGACY_REQUIRED"===this._features.field_presence}}),Object.defineProperty(l.prototype,"optional",{get:function(){return!this.required}}),Object.defineProperty(l.prototype,"delimited",{get:function(){return this.resolvedType instanceof s&&"DELIMITED"===this._features.message_encoding}}),Object.defineProperty(l.prototype,"packed",{get:function(){return"PACKED"===this._features.repeated_field_encoding}}),Object.defineProperty(l.prototype,"hasPresence",{get:function(){return!this.repeated&&!this.map&&(this.partOf||this.declaringField||this.extensionField||"IMPLICIT"!==this._features.field_presence)}}),l.prototype.setOption=function(e,t,r){return n.prototype.setOption.call(this,e,t,r)},l.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return a.toObject(["edition",this._editionToJSON(),"rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=o.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof s?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof i&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof i||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=a.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var e;a.base64.test(this.typeDefault)?a.base64.decode(this.typeDefault,e=a.newBuffer(a.base64.length(this.typeDefault)),0):a.utf8.write(this.typeDefault,e=a.newBuffer(a.utf8.length(this.typeDefault)),0),this.typeDefault=e}return this.map?this.defaultValue=a.emptyObject:this.repeated?this.defaultValue=a.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof s&&(this.parent.ctor.prototype[this.name]=this.defaultValue),n.prototype.resolve.call(this)},l.prototype._inferLegacyProtoFeatures=function(e){if("proto2"!==e&&"proto3"!==e)return{};var t={};if("required"===this.rule&&(t.field_presence="LEGACY_REQUIRED"),this.parent&&void 0===o.defaults[this.type]){var r=this.parent.get(this.type.split(".").pop());r&&r instanceof s&&r.group&&(t.message_encoding="DELIMITED")}return!0===this.getOption("packed")?t.repeated_field_encoding="PACKED":!1===this.getOption("packed")&&(t.repeated_field_encoding="EXPANDED"),t},l.prototype._resolveFeatures=function(e){return n.prototype._resolveFeatures.call(this,this._edition||e)},l.d=function(e,t,r,n){return"function"==typeof t?t=a.decorateType(t).name:t&&"object"==typeof t&&(t=a.decorateEnum(t).name),function(s,i){a.decorateType(s.constructor).add(new l(i,e,t,r,{default:n}))}},l._configure=function(e){s=e}},1447:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n<e.length;++n)(r=e.charCodeAt(n))<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t},r.read=function(e,t,r){if(r-t<1)return"";for(var n,s=null,i=[],o=0;t<r;)(n=e[t++])<128?i[o++]=n:n>191&&n<224?i[o++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[o++]=55296+(n>>10),i[o++]=56320+(1023&n)):i[o++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s?(o&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))},r.write=function(e,t,r){for(var n,s,i=r,o=0;o<e.length;++o)(n=e.charCodeAt(o))<128?t[r++]=n:n<2048?(t[r++]=n>>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(s=e.charCodeAt(o+1)))?(n=65536+((1023&n)<<10)+(1023&s),++o,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-i}},1457:(e,t,r)=>{"use strict";e.exports=o;var n=r(7209);((o.prototype=Object.create(n.prototype)).constructor=o).className="OneOf";var s=r(1344),i=r(3262);function o(e,t,r,s){if(Array.isArray(t)||(r=t,t=void 0),n.call(this,e,r),void 0!==t&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=s}function a(e){if(e.parent)for(var t=0;t<e.fieldsArray.length;++t)e.fieldsArray[t].parent||e.parent.add(e.fieldsArray[t])}o.fromJSON=function(e,t){return new o(e,t.oneof,t.options,t.comment)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.toObject(["options",this.options,"oneof",this.oneof,"comment",t?this.comment:void 0])},o.prototype.add=function(e){if(!(e instanceof s))throw TypeError("field must be a Field");return e.parent&&e.parent!==this.parent&&e.parent.remove(e),this.oneof.push(e.name),this.fieldsArray.push(e),e.partOf=this,a(this),this},o.prototype.remove=function(e){if(!(e instanceof s))throw TypeError("field must be a Field");var t=this.fieldsArray.indexOf(e);if(t<0)throw Error(e+" is not a member of "+this);return this.fieldsArray.splice(t,1),(t=this.oneof.indexOf(e.name))>-1&&this.oneof.splice(t,1),e.partOf=null,this},o.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t<this.oneof.length;++t){var r=e.get(this.oneof[t]);r&&!r.partOf&&(r.partOf=this,this.fieldsArray.push(r))}a(this)},o.prototype.onRemove=function(e){for(var t,r=0;r<this.fieldsArray.length;++r)(t=this.fieldsArray[r]).parent&&t.parent.remove(t);n.prototype.onRemove.call(this,e)},Object.defineProperty(o.prototype,"isProto3Optional",{get:function(){if(null==this.fieldsArray||1!==this.fieldsArray.length)return!1;var e=this.fieldsArray[0];return null!=e.options&&!0===e.options.proto3_optional}}),o.d=function(){for(var e=new Array(arguments.length),t=0;t<arguments.length;)e[t]=arguments[t++];return function(t,r){i.decorateType(t.constructor).add(new o(r,e)),Object.defineProperty(t,r,{get:i.oneOfGetter(e),set:i.oneOfSetter(e)})}}},2239:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e,t){this.lo=e>>>0,this.hi=t>>>0}var i=s.zero=new s(0,0);i.toNumber=function(){return 0},i.zzEncode=i.zzDecode=function(){return this},i.length=function(){return 1};var o=s.zeroHash="\0\0\0\0\0\0\0\0";s.fromNumber=function(e){if(0===e)return i;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new s(r,n)},s.from=function(e){if("number"==typeof e)return s.fromNumber(e);if(n.isString(e)){if(!n.Long)return s.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new s(e.low>>>0,e.high>>>0):i},s.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},s.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;s.fromHash=function(e){return e===o?i:new s((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},s.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},s.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},s.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},s.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},2549:(e,t,r)=>{"use strict";e.exports=r(9100)},2551:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e){if(e)for(var t=Object.keys(e),r=0;r<t.length;++r)this[t[r]]=e[t[r]]}s.create=function(e){return this.$type.create(e)},s.encode=function(e,t){return this.$type.encode(e,t)},s.encodeDelimited=function(e,t){return this.$type.encodeDelimited(e,t)},s.decode=function(e){return this.$type.decode(e)},s.decodeDelimited=function(e){return this.$type.decodeDelimited(e)},s.verify=function(e){return this.$type.verify(e)},s.fromObject=function(e){return this.$type.fromObject(e)},s.toObject=function(e,t){return this.$type.toObject(e,t)},s.prototype.toJSON=function(){return this.$type.toObject(this,n.toJSONOptions)}},3158:(e,t,r)=>{"use strict";e.exports=i;var n=r(6237);(i.prototype=Object.create(n.prototype)).constructor=i;var s=r(3610);function i(e){n.call(this,e)}i._configure=function(){s.Buffer&&(i.prototype._slice=s.Buffer.prototype.slice)},i.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},i._configure()},3262:(e,t,r)=>{"use strict";var n,s,i=e.exports=r(3610),o=r(4529);i.codegen=r(8561),i.fetch=r(5212),i.path=r(9207),i.fs=i.inquire("fs"),i.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),n=0;n<t.length;)r[n]=e[t[n++]];return r}return[]},i.toObject=function(e){for(var t={},r=0;r<e.length;){var n=e[r++],s=e[r++];void 0!==s&&(t[n]=s)}return t};var a=/\\/g,c=/"/g;i.isReserved=function(e){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(e)},i.safeProp=function(e){return!/^[$\w_]+$/.test(e)||i.isReserved(e)?'["'+e.replace(a,"\\\\").replace(c,'\\"')+'"]':"."+e},i.ucFirst=function(e){return e.charAt(0).toUpperCase()+e.substring(1)};var l=/_([a-z])/g;i.camelCase=function(e){return e.substring(0,1)+e.substring(1).replace(l,function(e,t){return t.toUpperCase()})},i.compareFieldsById=function(e,t){return e.id-t.id},i.decorateType=function(e,t){if(e.$type)return t&&e.$type.name!==t&&(i.decorateRoot.remove(e.$type),e.$type.name=t,i.decorateRoot.add(e.$type)),e.$type;n||(n=r(7882));var s=new n(t||e.name);return i.decorateRoot.add(s),s.ctor=e,Object.defineProperty(e,"$type",{value:s,enumerable:!1}),Object.defineProperty(e.prototype,"$type",{value:s,enumerable:!1}),s};var u=0;i.decorateEnum=function(e){if(e.$type)return e.$type;s||(s=r(5643));var t=new s("Enum"+u++,e);return i.decorateRoot.add(t),Object.defineProperty(e,"$type",{value:t,enumerable:!1}),t},i.setProperty=function(e,t,r,n){if("object"!=typeof e)throw TypeError("dst must be an object");if(!t)throw TypeError("path must be specified");return function e(t,r,s){var i=r.shift();if("__proto__"===i||"prototype"===i)return t;if(r.length>0)t[i]=e(t[i]||{},r,s);else{var o=t[i];if(o&&n)return t;o&&(s=[].concat(o).concat(s)),t[i]=s}return t}(e,t=t.split("."),r)},Object.defineProperty(i,"decorateRoot",{get:function(){return o.decorated||(o.decorated=new(r(5330)))}})},3449:(e,t,r)=>{"use strict";e.exports=h;var n,s=r(3610),i=s.LongBits,o=s.base64,a=s.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function l(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var d=function(){return s.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function p(e,t,r){t[r]=255&e}function f(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function m(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new s.Array(e)},s.Array!==Array&&(h.alloc=s.pool(h.alloc,s.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},f.prototype=Object.create(c.prototype),f.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new f((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,i.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=i.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=i.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(p,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(m,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=i.from(e);return this._push(m,4,t.lo)._push(m,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(s.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(s.float.writeDoubleLE,8,e)};var y=s.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n<e.length;++n)t[r+n]=e[n]};h.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(p,1,0);if(s.isString(e)){var r=h.alloc(t=o.length(e));o.decode(e,r,0),e=r}return this.uint32(t)._push(y,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(p,1,0)},h.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new c(l,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(l,0,0),this.len=0),this},h.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},3610:function(e,t,r){"use strict";var n=t;function s(e,t,r){for(var n=Object.keys(t),s=0;s<n.length;++s)void 0!==e[n[s]]&&r||(e[n[s]]=t[n[s]]);return e}function i(e){function t(e,r){if(!(this instanceof t))return new t(e,r);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),r&&s(this,r)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}n.asPromise=r(8045),n.base64=r(8839),n.EventEmitter=r(4358),n.float=r(9410),n.inquire=r(4153),n.utf8=r(1447),n.pool=r(9390),n.LongBits=r(2239),n.isNode=Boolean("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),n.global=n.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,n.emptyArray=Object.freeze?Object.freeze([]):[],n.emptyObject=Object.freeze?Object.freeze({}):{},n.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},n.isString=function(e){return"string"==typeof e||e instanceof String},n.isObject=function(e){return e&&"object"==typeof e},n.isset=n.isSet=function(e,t){var r=e[t];return!(null==r||!e.hasOwnProperty(t))&&("object"!=typeof r||(Array.isArray(r)?r.length:Object.keys(r).length)>0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"==typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=s,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=i,n.ProtocolError=i("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=1;return function(){for(var e=Object.keys(this),r=e.length-1;r>-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},n.oneOfSetter=function(e){return function(t){for(var r=0;r<e.length;++r)e[r]!==t&&delete this[e[r]]}},n.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},n._configure=function(){var e=n.Buffer;e?(n._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,r){return new e(t,r)},n._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):n._Buffer_from=n._Buffer_allocUnsafe=null}},3961:e=>{function t(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}e.exports=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var s=this._errors[n],i=s.message,o=(e[i]||0)+1;e[i]=o,o>=r&&(t=s,r=o)}return t}},4153:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},4358:e=>{"use strict";function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n<r.length;)r[n].fn===t?r.splice(n,1):++n;return this},t.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var r=[],n=1;n<arguments.length;)r.push(arguments[n++]);for(n=0;n<t.length;)t[n].fn.apply(t[n++].ctx,r)}return this}},4394:(e,t,r)=>{"use strict";var n=t;function s(){n.util._configure(),n.Writer._configure(n.BufferWriter),n.Reader._configure(n.BufferReader)}n.build="minimal",n.Writer=r(3449),n.BufferWriter=r(818),n.Reader=r(6237),n.BufferReader=r(3158),n.util=r(3610),n.rpc=r(5047),n.roots=r(4529),n.configure=s,s()},4529:e=>{"use strict";e.exports={}},4863:(e,t,r)=>{"use strict";e.exports=I,I.filename=null,I.defaults={keepCase:!1};var n=r(527),s=r(5330),i=r(7882),o=r(1344),a=r(8252),c=r(1457),l=r(5643),u=r(9687),h=r(8811),d=r(7209),p=r(361),f=r(3262),g=/^[1-9][0-9]*$/,m=/^-?[1-9][0-9]*$/,y=/^0[x][0-9a-fA-F]+$/,b=/^-?0[x][0-9a-fA-F]+$/,w=/^0[0-7]+$/,v=/^-?0[0-7]+$/,E=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,S=/^[a-zA-Z_][a-zA-Z_0-9]*$/,A=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;function I(e,t,r){t instanceof s||(r=t,t=new s),r||(r=I.defaults);var k,x,C,_,T=r.preferTrailingComment||!1,P=n(e,r.alternateCommentMode||!1),R=P.next,O=P.push,L=P.peek,D=P.skip,N=P.cmnt,M=!0,F="proto2",B=t,U=[],$={},q=r.keepCase?function(e){return e}:f.camelCase;function j(e,t,r){var n=I.filename;return r||(I.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+P.line+")")}function z(){var e,t=[];do{if('"'!==(e=R())&&"'"!==e)throw j(e);t.push(R()),D(e),e=L()}while('"'===e||"'"===e);return t.join("")}function K(e){var t=R();switch(t){case"'":case'"':return O(t),z();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e){var t=1;switch("-"===e.charAt(0)&&(t=-1,e=e.substring(1)),e){case"inf":case"INF":case"Inf":return t*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(g.test(e))return t*parseInt(e,10);if(y.test(e))return t*parseInt(e,16);if(w.test(e))return t*parseInt(e,8);if(E.test(e))return t*parseFloat(e);throw j(e,"number",!0)}(t)}catch(r){if(e&&A.test(t))return t;throw j(t,"value")}}function V(e,t){var r,n;do{if(!t||'"'!==(r=L())&&"'"!==r)try{e.push([n=H(R()),D("to",!0)?H(R()):n])}catch(n){if(!(t&&A.test(r)&&F>=2023))throw n;e.push(r)}else{var s=z();if(e.push(s),F>=2023)throw j(s,"id")}}while(D(",",!0));var i={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};Z(i,function(e){if("option"!==e)throw j(e);re(i,e),D(";")},function(){ie(i)})}function H(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw j(e,"id");if(m.test(e))return parseInt(e,10);if(b.test(e))return parseInt(e,16);if(v.test(e))return parseInt(e,8);throw j(e,"id")}function G(){if(void 0!==k)throw j("package");if(k=R(),!A.test(k))throw j(k,"name");B=B.define(k),D(";")}function W(){var e,t=L();switch(t){case"weak":e=C||(C=[]),R();break;case"public":R();default:e=x||(x=[])}t=z(),D(";"),e.push(t)}function X(){if(D("="),(F=z())<2023)throw j(F,"syntax");D(";")}function J(){if(D("="),F=z(),!["2023"].includes(F))throw j(F,"edition");D(";")}function Y(e,t){switch(t){case"option":return re(e,t),D(";"),!0;case"message":return Q(e,t),!0;case"enum":return te(e,t),!0;case"service":return function(e,t){if(!S.test(t=R()))throw j(t,"service name");var r=new u(t);Z(r,function(e){if(!Y(r,e)){if("rpc"!==e)throw j(e);!function(e,t){var r=N(),n=t;if(!S.test(t=R()))throw j(t,"name");var s,i,o,a,c=t;if(D("("),D("stream",!0)&&(i=!0),!A.test(t=R()))throw j(t);if(s=t,D(")"),D("returns"),D("("),D("stream",!0)&&(a=!0),!A.test(t=R()))throw j(t);o=t,D(")");var l=new h(c,n,s,o,i,a);l.comment=r,Z(l,function(e){if("option"!==e)throw j(e);re(l,e),D(";")}),e.add(l)}(r,e)}}),e.add(r),e===B&&U.push(r)}(e,t),!0;case"extend":return function(e,t){if(!A.test(t=R()))throw j(t,"reference");var r=t;Z(null,function(t){switch(t){case"required":case"repeated":ee(e,t,r);break;case"optional":ee(e,"proto3"===F?"proto3_optional":"optional",r);break;default:if("proto2"===F||!A.test(t))throw j(t);O(t),ee(e,"optional",r)}})}(e,t),!0}return!1}function Z(e,t,r){var n=P.line;if(e&&("string"!=typeof e.comment&&(e.comment=N()),e.filename=I.filename),D("{",!0)){for(var s;"}"!==(s=R());)t(s);D(";",!0)}else r&&r(),D(";"),e&&("string"!=typeof e.comment||T)&&(e.comment=N(n)||e.comment)}function Q(e,t){if(!S.test(t=R()))throw j(t,"type name");var r=new i(t);Z(r,function(e){if(!Y(r,e))switch(e){case"map":!function(e){D("<");var t=R();if(void 0===p.mapKey[t])throw j(t,"type");D(",");var r=R();if(!A.test(r))throw j(r,"type");D(">");var n=R();if(!S.test(n))throw j(n,"name");D("=");var s=new a(q(n),H(R()),t,r);Z(s,function(e){if("option"!==e)throw j(e);re(s,e),D(";")},function(){ie(s)}),e.add(s)}(r);break;case"required":if("proto2"!==F)throw j(e);case"repeated":ee(r,e);break;case"optional":if("proto3"===F)ee(r,"proto3_optional");else{if("proto2"!==F)throw j(e);ee(r,"optional")}break;case"oneof":!function(e,t){if(!S.test(t=R()))throw j(t,"name");var r=new c(q(t));Z(r,function(e){"option"===e?(re(r,e),D(";")):(O(e),ee(r,"optional"))}),e.add(r)}(r,e);break;case"extensions":V(r.extensions||(r.extensions=[]));break;case"reserved":V(r.reserved||(r.reserved=[]),!0);break;default:if("proto2"===F||!A.test(e))throw j(e);O(e),ee(r,"optional")}}),e.add(r),e===B&&U.push(r)}function ee(e,t,r){var n=R();if("group"!==n){for(;n.endsWith(".")||L().startsWith(".");)n+=R();if(!A.test(n))throw j(n,"type");var s=R();if(!S.test(s))throw j(s,"name");s=q(s),D("=");var a=new o(s,H(R()),n,t,r);if(Z(a,function(e){if("option"!==e)throw j(e);re(a,e),D(";")},function(){ie(a)}),"proto3_optional"===t){var l=new c("_"+s);a.setOption("proto3_optional",!0),l.add(a),e.add(l)}else e.add(a);e===B&&U.push(a)}else!function(e,t){if(F>=2023)throw j("group");var r=R();if(!S.test(r))throw j(r,"name");var n=f.lcFirst(r);r===n&&(r=f.ucFirst(r)),D("=");var s=H(R()),a=new i(r);a.group=!0;var c=new o(n,s,r,t);c.filename=I.filename,Z(a,function(e){switch(e){case"option":re(a,e),D(";");break;case"required":case"repeated":ee(a,e);break;case"optional":ee(a,"proto3"===F?"proto3_optional":"optional");break;case"message":Q(a,e);break;case"enum":te(a,e);break;case"reserved":V(a.reserved||(a.reserved=[]),!0);break;default:throw j(e)}}),e.add(a).add(c)}(e,t)}function te(e,t){if(!S.test(t=R()))throw j(t,"name");var r=new l(t);Z(r,function(e){switch(e){case"option":re(r,e),D(";");break;case"reserved":V(r.reserved||(r.reserved=[]),!0),void 0===r.reserved&&(r.reserved=[]);break;default:!function(e,t){if(!S.test(t))throw j(t,"name");D("=");var r=H(R(),!0),n={options:void 0,getOption:function(e){return this.options[e]},setOption:function(e,t){d.prototype.setOption.call(n,e,t)},setParsedOption:function(){}};Z(n,function(e){if("option"!==e)throw j(e);re(n,e),D(";")},function(){ie(n)}),e.add(t,r,n.comment,n.parsedOptions||n.options)}(r,e)}}),e.add(r),e===B&&U.push(r)}function re(e,t){var r,n,s=!0;for("option"===t&&(t=R());"="!==t;){if("("===t){var i=R();D(")"),t="("+i+")"}if(s){if(s=!1,t.includes(".")&&!t.includes("(")){var o=t.split(".");r=o[0]+".",t=o[1];continue}r=t}else n=n?n+=t:t;t=R()}var a=ne(e,n?r.concat(n):r);n=n&&"."===n[0]?n.slice(1):n,function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,r=r&&"."===r[r.length-1]?r.slice(0,-1):r,a,n)}function ne(e,t){if(D("{",!0)){for(var r={};!D("}",!0);){if(!S.test(_=R()))throw j(_,"name");if(null===_)throw j(_,"end of input");var n,s=_;if(D(":",!0),"{"===L())n=ne(e,t+"."+_);else if("["===L()){var i;if(n=[],D("[",!0)){do{i=K(!0),n.push(i)}while(D(",",!0));D("]"),void 0!==i&&se(e,t+"."+_,i)}}else n=K(!0),se(e,t+"."+_,n);var o=r[s];o&&(n=[].concat(o).concat(n)),r[s]=n,D(",",!0),D(";",!0)}return r}var a=K(!0);return se(e,t,a),a}function se(e,t,r){B===e&&/^features\./.test(t)?$[t]=r:e.setOption&&e.setOption(t,r)}function ie(e){if(D("[",!0)){do{re(e,"option")}while(D(",",!0));D("]")}return e}for(;null!==(_=R());)switch(_){case"package":if(!M)throw j(_);G();break;case"import":if(!M)throw j(_);W();break;case"syntax":if(!M)throw j(_);X();break;case"edition":if(!M)throw j(_);J();break;case"option":re(B,_),D(";",!0);break;default:if(Y(B,_)){M=!1;continue}throw j(_)}return U.forEach(e=>{e._edition=F,Object.keys($).forEach(t=>{void 0===e.getOption(t)&&e.setOption(t,$[t],!0)})}),I.filename=null,{package:k,imports:x,weakImports:C,root:t}}},5047:(e,t,r)=>{"use strict";t.Service=r(7595)},5095:e=>{"use strict";e.exports=n;var t,r=/\/|\./;function n(e,t){r.test(e)||(e="google/protobuf/"+e+".proto",t={nested:{google:{nested:{protobuf:{nested:t}}}}}),n[e]=t}n("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),n("duration",{Duration:t={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),n("timestamp",{Timestamp:t}),n("empty",{Empty:{fields:{}}}),n("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),n("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),n("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),n.get=function(e){return n[e]||null}},5212:(e,t,r)=>{"use strict";e.exports=i;var n=r(8045),s=r(4153)("fs");function i(e,t,r){return"function"==typeof t?(r=t,t={}):t||(t={}),r?!t.xhr&&s&&s.readFile?s.readFile(e,function(n,s){return n&&"undefined"!=typeof XMLHttpRequest?i.xhr(e,t,r):n?r(n):r(null,t.binary?s:s.toString("utf8"))}):i.xhr(e,t,r):n(i,this,e,t)}i.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4===n.readyState){if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){var e=n.response;if(!e){e=[];for(var s=0;s<n.responseText.length;++s)e.push(255&n.responseText.charCodeAt(s))}return r(null,"undefined"!=typeof Uint8Array?new Uint8Array(e):e)}return r(null,n.responseText)}},t.binary&&("overrideMimeType"in n&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.responseType="arraybuffer"),n.open("GET",e),n.send()}},5325:(e,t,r)=>{"use strict";var n=e.exports=r(4394);n.build="light",n.load=function(e,t,r){return"function"==typeof t?(r=t,t=new n.Root):t||(t=new n.Root),t.load(e,r)},n.loadSync=function(e,t){return t||(t=new n.Root),t.loadSync(e)},n.encoder=r(1080),n.decoder=r(7728),n.verifier=r(420),n.converter=r(744),n.ReflectionObject=r(7209),n.Namespace=r(8923),n.Root=r(5330),n.Enum=r(5643),n.Type=r(7882),n.Field=r(1344),n.OneOf=r(1457),n.MapField=r(8252),n.Service=r(9687),n.Method=r(8811),n.Message=r(2551),n.wrappers=r(6434),n.types=r(361),n.util=r(3262),n.ReflectionObject._configure(n.Root),n.Namespace._configure(n.Type,n.Service,n.Enum),n.Root._configure(n.Type),n.Field._configure(n.Type)},5330:(e,t,r)=>{"use strict";e.exports=h;var n=r(8923);((h.prototype=Object.create(n.prototype)).constructor=h).className="Root";var s,i,o,a=r(1344),c=r(5643),l=r(1457),u=r(3262);function h(e){n.call(this,"",e),this.deferred=[],this.files=[],this._edition="proto2",this._fullyQualifiedObjects={}}function d(){}h.fromJSON=function(e,t){return t||(t=new h),e.options&&t.setOptions(e.options),t.addJSON(e.nested).resolveAll()},h.prototype.resolvePath=u.path.resolve,h.prototype.fetch=u.fetch,h.prototype.load=function e(t,r,n){"function"==typeof r&&(n=r,r=void 0);var s=this;if(!n)return u.asPromise(e,s,t,r);var a=n===d;function c(e,t){if(n){if(a)throw e;t&&t.resolveAll();var r=n;n=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in o)return r}return null}function h(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){i.filename=e;var n,o=i(t,s,r),h=0;if(o.imports)for(;h<o.imports.length;++h)(n=l(o.imports[h])||s.resolvePath(e,o.imports[h]))&&p(n);if(o.weakImports)for(h=0;h<o.weakImports.length;++h)(n=l(o.weakImports[h])||s.resolvePath(e,o.weakImports[h]))&&p(n,!0)}else s.setOptions(t.options).addJSON(t.nested)}catch(e){c(e)}a||f||c(null,s)}function p(e,t){if(e=l(e)||e,!(s.files.indexOf(e)>-1))if(s.files.push(e),e in o)a?h(e,o[e]):(++f,setTimeout(function(){--f,h(e,o[e])}));else if(a){var r;try{r=u.fs.readFileSync(e).toString("utf8")}catch(e){return void(t||c(e))}h(e,r)}else++f,s.fetch(e,function(r,i){--f,n&&(r?t?f||c(null,s):c(r):h(e,i))})}var f=0;u.isString(t)&&(t=[t]);for(var g,m=0;m<t.length;++m)(g=s.resolvePath("",t[m]))&&p(g);return a?(s.resolveAll(),s):(f||c(null,s),s)},h.prototype.loadSync=function(e,t){if(!u.isNode)throw Error("not supported");return this.load(e,t,d)},h.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(e){return"'extend "+e.extend+"' in "+e.parent.fullName}).join(", "));return n.prototype.resolveAll.call(this)};var p=/^[A-Z]/;function f(e,t){var r=t.parent.lookup(t.extend);if(r){var n=new a(t.fullName,t.id,t.type,t.rule,void 0,t.options);return r.get(n.name)||(n.declaringField=t,t.extensionField=n,r.add(n)),!0}return!1}h.prototype._handleAdd=function(e){if(e instanceof a)void 0===e.extend||e.extensionField||f(0,e)||this.deferred.push(e);else if(e instanceof c)p.test(e.name)&&(e.parent[e.name]=e.values);else if(!(e instanceof l)){if(e instanceof s)for(var t=0;t<this.deferred.length;)f(0,this.deferred[t])?this.deferred.splice(t,1):++t;for(var r=0;r<e.nestedArray.length;++r)this._handleAdd(e._nestedArray[r]);p.test(e.name)&&(e.parent[e.name]=e)}(e instanceof s||e instanceof c||e instanceof a)&&(this._fullyQualifiedObjects[e.fullName]=e)},h.prototype._handleRemove=function(e){if(e instanceof a){if(void 0!==e.extend)if(e.extensionField)e.extensionField.parent.remove(e.extensionField),e.extensionField=null;else{var t=this.deferred.indexOf(e);t>-1&&this.deferred.splice(t,1)}}else if(e instanceof c)p.test(e.name)&&delete e.parent[e.name];else if(e instanceof n){for(var r=0;r<e.nestedArray.length;++r)this._handleRemove(e._nestedArray[r]);p.test(e.name)&&delete e.parent[e.name]}delete this._fullyQualifiedObjects[e.fullName]},h._configure=function(e,t,r){s=e,i=t,o=r}},5507:function(e,t){(function(){var e,r,n,s,i,o,a,c;c=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,s,i,o,a;for(t=[],s=i=0;i<=3&&0!==e.length;s=++i){if(s>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}o=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(o)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},s=(n=function(e){return e.charCodeAt(0)})("0"),o=n("a"),i=n("A"),r=function(e){var t,r,a,c,l;for(c=0,t=10,r="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,r="7")),l=a;a<e.length;){if("0"<=e[a]&&e[a]<=r)c=c*t+(n(e[a])-s)>>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-o)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-i)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===l)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,s;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(s=e.split("/",2),e=s[0],t=s[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(c(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},5617:(e,t,r)=>{e.exports=r(8303)},5643:(e,t,r)=>{"use strict";e.exports=o;var n=r(7209);((o.prototype=Object.create(n.prototype)).constructor=o).className="Enum";var s=r(8923),i=r(3262);function o(e,t,r,s,i,o){if(n.call(this,e,r),t&&"object"!=typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=s,this.comments=i||{},this.valuesOptions=o,this._valuesFeatures={},this.reserved=void 0,t)for(var a=Object.keys(t),c=0;c<a.length;++c)"number"==typeof t[a[c]]&&(this.valuesById[this.values[a[c]]=t[a[c]]]=a[c])}o.prototype._resolveFeatures=function(e){return e=this._edition||e,n.prototype._resolveFeatures.call(this,e),Object.keys(this.values).forEach(e=>{var t=Object.assign({},this._features);this._valuesFeatures[e]=Object.assign(t,this.valuesOptions&&this.valuesOptions[e]&&this.valuesOptions[e].features)}),this},o.fromJSON=function(e,t){var r=new o(e,t.values,t.options,t.comment,t.comments);return r.reserved=t.reserved,t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.toObject(["edition",this._editionToJSON(),"options",this.options,"valuesOptions",this.valuesOptions,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"comment",t?this.comment:void 0,"comments",t?this.comments:void 0])},o.prototype.add=function(e,t,r,n){if(!i.isString(e))throw TypeError("name must be a string");if(!i.isInteger(t))throw TypeError("id must be an integer");if(void 0!==this.values[e])throw Error("duplicate name '"+e+"' in "+this);if(this.isReservedId(t))throw Error("id "+t+" is reserved in "+this);if(this.isReservedName(e))throw Error("name '"+e+"' is reserved in "+this);if(void 0!==this.valuesById[t]){if(!this.options||!this.options.allow_alias)throw Error("duplicate id "+t+" in "+this);this.values[e]=t}else this.valuesById[this.values[e]=t]=e;return n&&(void 0===this.valuesOptions&&(this.valuesOptions={}),this.valuesOptions[e]=n||null),this.comments[e]=r||null,this},o.prototype.remove=function(e){if(!i.isString(e))throw TypeError("name must be a string");var t=this.values[e];if(null==t)throw Error("name '"+e+"' does not exist in "+this);return delete this.valuesById[t],delete this.values[e],delete this.comments[e],this.valuesOptions&&delete this.valuesOptions[e],this},o.prototype.isReservedId=function(e){return s.isReservedId(this.reserved,e)},o.prototype.isReservedName=function(e){return s.isReservedName(this.reserved,e)}},5818:(e,t,r)=>{var n;!function(){"use strict";var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node&&(t=global);var s=!t.HI_BASE32_NO_COMMON_JS&&e.exports,i=r.amdO,o="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},c=[0,0,0,0,0,0,0,0],l=function(e,t){t.length>10&&(t="..."+t.substr(-10));var r=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},u=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,r,n,s,i,o,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p<f;)t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],o=a[e.charAt(p++)],c=a[e.charAt(p++)],l=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|i>>>1),u[h++]=255&(i<<7|o<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4)):5===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|i>>>1)):7===g&&(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],o=a[e.charAt(p++)],c=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|i>>>1),u[h++]=255&(i<<7|o<<2|c>>>3)),u},h=function(e,t){if(!t)return function(e){for(var t,r,n="",s=e.length,i=0,o=0;i<s;)if((t=e[i++])<=127)n+=String.fromCharCode(t);else{t>191&&t<=223?(r=31&t,o=1):t<=239?(r=15&t,o=2):t<=247?(r=7&t,o=3):l(i,n);for(var a=0;a<o;++a)((t=e[i++])<128||t>191)&&l(i,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&l(i,n),r>1114111&&l(i,n),r<=65535?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode(55296+(r>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n}(u(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var r,n,s,i,o,c,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,m=f>>3<<3;g<m;)r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],d=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))+String.fromCharCode(255&(o<<7|c<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var y=f-m;return 2===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))):5===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))):7===y&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],o=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|i>>>4))+String.fromCharCode(255&(i<<4|o>>>1))+String.fromCharCode(255&(o<<7|c<<2|h>>>3))),p},d={encode:function(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?function(e){for(var t,r,n,s,i,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e[l++],r=e[l++],n=e[l++],s=e[l++],i=e[l++],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i];var h=c-u;return 1===h?(t=e[l],a+=o[t>>>3]+o[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],n=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],n=e[l++],s=e[l],a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"="),a}(e):t?function(e){for(var t,r,n,s,i,a="",c=e.length,l=0,u=5*parseInt(c/5);l<u;)t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),s=e.charCodeAt(l++),i=e.charCodeAt(l++),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=o[t>>>3]+o[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),s=e.charCodeAt(l),a+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"="),a}(e):function(e){var t,r,n,s,i,a,l,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(c[0]=c[5],c[1]=c[6],c[2]=c[7],l=p;d<f&&l<5;++d)(a=e.charCodeAt(d))<128?c[l++]=a:a<2048?(c[l++]=192|a>>6,c[l++]=128|63&a):a<55296||a>=57344?(c[l++]=224|a>>12,c[l++]=128|a>>6&63,c[l++]=128|63&a):(a=65536+((1023&a)<<10|1023&e.charCodeAt(++d)),c[l++]=240|a>>18,c[l++]=128|a>>12&63,c[l++]=128|a>>6&63,c[l++]=128|63&a);p=l-5,d===f&&++d,d>f&&l<6&&(u=!0),t=c[0],l>4?(r=c[1],n=c[2],s=c[3],i=c[4],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[31&(s<<3|i>>>5)]+o[31&i]):1===l?h+=o[t>>>3]+o[t<<2&31]+"======":2===l?(r=c[1],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[r<<4&31]+"===="):3===l?(r=c[1],n=c[2],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[n<<1&31]+"==="):(r=c[1],n=c[2],s=c[3],h+=o[t>>>3]+o[31&(t<<2|r>>>6)]+o[r>>>1&31]+o[31&(r<<4|n>>>4)]+o[31&(n<<1|s>>>7)]+o[s>>>2&31]+o[s<<3&31]+"=")}while(!u);return h}(e)},decode:h};h.asBytes=u,s?e.exports=d:(t.base32=d,i&&(void 0===(n=function(){return d}.call(d,r,d,e))||(e.exports=n)))}()},6237:(e,t,r)=>{"use strict";e.exports=c;var n,s=r(3610),i=s.LongBits,o=s.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l,u="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},h=function(){return s.Buffer?function(e){return(c.create=function(e){return s.Buffer.isBuffer(e)?new n(e):u(e)})(e)}:u};function d(){var e=new i(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function p(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new i(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}c.create=h(),c.prototype._slice=s.Array.prototype.subarray||s.Array.prototype.slice,c.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return l}),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return p(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|p(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=s.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=s.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,r);if(t===r){var n=s.Buffer;return n?n.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return o.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){n=e,c.create=h(),n._configure();var t=s.Long?"toLong":"toNumber";s.merge(c.prototype,{int64:function(){return d.call(this)[t](!1)},uint64:function(){return d.call(this)[t](!0)},sint64:function(){return d.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},6434:(e,t,r)=>{"use strict";var n=t,s=r(2551);n[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,t){var r="",n="";if(t&&t.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),r=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var i=this.lookup(n);i&&(e=i.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof s){var o=e.$type.toObject(e,t);return""===r&&(r="type.googleapis.com/"),n=r+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),o["@type"]=n,o}return this.toObject(e,t)}}},6585:e=>{var t=1e3,r=60*t,n=60*r,s=24*n,i=7*s;function o(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}e.exports=function(e,a){a=a||{};var c,l,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(o){var a=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*s;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===u&&isFinite(e))return a.long?(c=e,(l=Math.abs(c))>=s?o(c,l,s,"day"):l>=n?o(c,l,n,"hour"):l>=r?o(c,l,r,"minute"):l>=t?o(c,l,t,"second"):c+" ms"):function(e){var i=Math.abs(e);return i>=s?Math.round(e/s)+"d":i>=n?Math.round(e/n)+"h":i>=r?Math.round(e/r)+"m":i>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},7209:(e,t,r)=>{"use strict";e.exports=l,l.className="ReflectionObject";const n=r(1457);var s,i=r(3262),o={enum_type:"OPEN",field_presence:"EXPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"},a={enum_type:"CLOSED",field_presence:"EXPLICIT",json_format:"LEGACY_BEST_EFFORT",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"EXPANDED",utf8_validation:"NONE"},c={enum_type:"OPEN",field_presence:"IMPLICIT",json_format:"ALLOW",message_encoding:"LENGTH_PREFIXED",repeated_field_encoding:"PACKED",utf8_validation:"VERIFY"};function l(e,t){if(!i.isString(e))throw TypeError("name must be a string");if(t&&!i.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this._edition=null,this._defaultEdition="proto2",this._features={},this._featuresResolved=!1,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(l.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),l.prototype.toJSON=function(){throw Error()},l.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var t=e.root;t instanceof s&&t._handleAdd(this)},l.prototype.onRemove=function(e){var t=e.root;t instanceof s&&t._handleRemove(this),this.parent=null,this.resolved=!1},l.prototype.resolve=function(){return this.resolved||this.root instanceof s&&(this.resolved=!0),this},l.prototype._resolveFeaturesRecursive=function(e){return this._resolveFeatures(this._edition||e)},l.prototype._resolveFeatures=function(e){if(!this._featuresResolved){var t={};if(!e)throw new Error("Unknown edition for "+this.fullName);var r=Object.assign(this.options?Object.assign({},this.options.features):{},this._inferLegacyProtoFeatures(e));if(this._edition){if("proto2"===e)t=Object.assign({},a);else if("proto3"===e)t=Object.assign({},c);else{if("2023"!==e)throw new Error("Unknown edition: "+e);t=Object.assign({},o)}return this._features=Object.assign(t,r||{}),void(this._featuresResolved=!0)}if(this.partOf instanceof n){var s=Object.assign({},this.partOf._features);this._features=Object.assign(s,r||{})}else if(this.declaringField);else{if(!this.parent)throw new Error("Unable to find a parent for "+this.fullName);var i=Object.assign({},this.parent._features);this._features=Object.assign(i,r||{})}this.extensionField&&(this.extensionField._features=this._features),this._featuresResolved=!0}},l.prototype._inferLegacyProtoFeatures=function(){return{}},l.prototype.getOption=function(e){if(this.options)return this.options[e]},l.prototype.setOption=function(e,t,r){return this.options||(this.options={}),/^features\./.test(e)?i.setProperty(this.options,e,t,r):r&&void 0!==this.options[e]||(this.getOption(e)!==t&&(this.resolved=!1),this.options[e]=t),this},l.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var s=n.find(function(t){return Object.prototype.hasOwnProperty.call(t,e)});if(s){var o=s[e];i.setProperty(o,r,t)}else(s={})[e]=i.setProperty({},r,t),n.push(s)}else{var a={};a[e]=t,n.push(a)}return this},l.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n<r.length;++n)this.setOption(r[n],e[r[n]],t);return this},l.prototype.toString=function(){var e=this.constructor.className,t=this.fullName;return t.length?e+" "+t:e},l.prototype._editionToJSON=function(){if(this._edition&&"proto3"!==this._edition)return this._edition},l._configure=function(e){s=e}},7595:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(s.prototype=Object.create(n.EventEmitter.prototype)).constructor=s,s.prototype.rpcCall=function e(t,r,s,i,o){if(!i)throw TypeError("request must be specified");var a=this;if(!o)return n.asPromise(e,a,t,r,s,i);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(e,r){if(e)return a.emit("error",e,t),o(e);if(null!==r){if(!(r instanceof s))try{r=s[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),o(e)}return a.emit("data",r,t),o(null,r)}a.end(!0)})}catch(e){return a.emit("error",e,t),void setTimeout(function(){o(e)},0)}else setTimeout(function(){o(Error("already ended"))},0)},s.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},7728:(e,t,r)=>{"use strict";e.exports=function(e){for(var t=i.codegen(["r","l","e"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter(function(e){return e.map}).length?",k,value":""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){"),r=0;r<e.fieldsArray.length;++r){var a=e._fieldsArray[r].resolve(),c=a.resolvedType instanceof n?"int32":a.type,l="m"+i.safeProp(a.name);t("case %i: {",a.id),a.map?(t("if(%s===util.emptyObject)",l)("%s={}",l)("var c2 = r.uint32()+r.pos"),void 0!==s.defaults[a.keyType]?t("k=%j",s.defaults[a.keyType]):t("k=null"),void 0!==s.defaults[c]?t("value=%j",s.defaults[c]):t("value=null"),t("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===s.basic[c]?t("value=types[%i].decode(r,r.uint32())",r):t("value=r.%s()",c),t("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),void 0!==s.long[a.keyType]?t('%s[typeof k==="object"?util.longToHash(k):k]=value',l):t("%s[k]=value",l)):a.repeated?(t("if(!(%s&&%s.length))",l,l)("%s=[]",l),void 0!==s.packed[c]&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",l,c)("}else"),void 0===s.basic[c]?t(a.delimited?"%s.push(types[%i].decode(r,undefined,((t&~7)|4)))":"%s.push(types[%i].decode(r,r.uint32()))",l,r):t("%s.push(r.%s())",l,c)):void 0===s.basic[c]?t(a.delimited?"%s=types[%i].decode(r,undefined,((t&~7)|4))":"%s=types[%i].decode(r,r.uint32())",l,r):t("%s=r.%s()",l,c),t("break")("}")}for(t("default:")("r.skipType(t&7)")("break")("}")("}"),r=0;r<e._fieldsArray.length;++r){var u=e._fieldsArray[r];u.required&&t("if(!m.hasOwnProperty(%j))",u.name)("throw util.ProtocolError(%j,{instance:m})",o(u))}return t("return m")};var n=r(5643),s=r(361),i=r(3262);function o(e){return"missing required '"+e.name+"'"}},7833:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))}),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},7882:(e,t,r)=>{"use strict";e.exports=b;var n=r(8923);((b.prototype=Object.create(n.prototype)).constructor=b).className="Type";var s=r(5643),i=r(1457),o=r(1344),a=r(8252),c=r(9687),l=r(2551),u=r(6237),h=r(3449),d=r(3262),p=r(1080),f=r(7728),g=r(420),m=r(744),y=r(6434);function b(e,t){n.call(this,e,t),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function w(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(b.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t<e.length;++t){var r=this.fields[e[t]],n=r.id;if(this._fieldsById[n])throw Error("duplicate id "+n+" in "+this);this._fieldsById[n]=r}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=d.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=d.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=b.generateConstructor(this)())},set:function(e){var t=e.prototype;t instanceof l||((e.prototype=new l).constructor=e,d.merge(e.prototype,t)),e.$type=e.prototype.$type=this,d.merge(e,l,!0),this._ctor=e;for(var r=0;r<this.fieldsArray.length;++r)this._fieldsArray[r].resolve();var n={};for(r=0;r<this.oneofsArray.length;++r)n[this._oneofsArray[r].resolve().name]={get:d.oneOfGetter(this._oneofsArray[r].oneof),set:d.oneOfSetter(this._oneofsArray[r].oneof)};r&&Object.defineProperties(e.prototype,n)}}}),b.generateConstructor=function(e){for(var t,r=d.codegen(["p"],e.name),n=0;n<e.fieldsArray.length;++n)(t=e._fieldsArray[n]).map?r("this%s={}",d.safeProp(t.name)):t.repeated&&r("this%s=[]",d.safeProp(t.name));return r("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")},b.fromJSON=function(e,t){var r=new b(e,t.options);r.extensions=t.extensions,r.reserved=t.reserved;for(var l=Object.keys(t.fields),u=0;u<l.length;++u)r.add((void 0!==t.fields[l[u]].keyType?a.fromJSON:o.fromJSON)(l[u],t.fields[l[u]]));if(t.oneofs)for(l=Object.keys(t.oneofs),u=0;u<l.length;++u)r.add(i.fromJSON(l[u],t.oneofs[l[u]]));if(t.nested)for(l=Object.keys(t.nested),u=0;u<l.length;++u){var h=t.nested[l[u]];r.add((void 0!==h.id?o.fromJSON:void 0!==h.fields?b.fromJSON:void 0!==h.values?s.fromJSON:void 0!==h.methods?c.fromJSON:n.fromJSON)(l[u],h))}return t.extensions&&t.extensions.length&&(r.extensions=t.extensions),t.reserved&&t.reserved.length&&(r.reserved=t.reserved),t.group&&(r.group=!0),t.comment&&(r.comment=t.comment),t.edition&&(r._edition=t.edition),r._defaultEdition="proto3",r},b.prototype.toJSON=function(e){var t=n.prototype.toJSON.call(this,e),r=!!e&&Boolean(e.keepComments);return d.toObject(["edition",this._editionToJSON(),"options",t&&t.options||void 0,"oneofs",n.arrayToJSON(this.oneofsArray,e),"fields",n.arrayToJSON(this.fieldsArray.filter(function(e){return!e.declaringField}),e)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:void 0,"reserved",this.reserved&&this.reserved.length?this.reserved:void 0,"group",this.group||void 0,"nested",t&&t.nested||void 0,"comment",r?this.comment:void 0])},b.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;n.prototype.resolveAll.call(this);var e=this.oneofsArray;for(r=0;r<e.length;)e[r++].resolve();for(var t=this.fieldsArray,r=0;r<t.length;)t[r++].resolve();return this},b.prototype._resolveFeaturesRecursive=function(e){return this._needsRecursiveFeatureResolution?(e=this._edition||e,n.prototype._resolveFeaturesRecursive.call(this,e),this.oneofsArray.forEach(t=>{t._resolveFeatures(e)}),this.fieldsArray.forEach(t=>{t._resolveFeatures(e)}),this):this},b.prototype.get=function(e){return this.fields[e]||this.oneofs&&this.oneofs[e]||this.nested&&this.nested[e]||null},b.prototype.add=function(e){if(this.get(e.name))throw Error("duplicate name '"+e.name+"' in "+this);if(e instanceof o&&void 0===e.extend){if(this._fieldsById?this._fieldsById[e.id]:this.fieldsById[e.id])throw Error("duplicate id "+e.id+" in "+this);if(this.isReservedId(e.id))throw Error("id "+e.id+" is reserved in "+this);if(this.isReservedName(e.name))throw Error("name '"+e.name+"' is reserved in "+this);return e.parent&&e.parent.remove(e),this.fields[e.name]=e,e.message=this,e.onAdd(this),w(this)}return e instanceof i?(this.oneofs||(this.oneofs={}),this.oneofs[e.name]=e,e.onAdd(this),w(this)):n.prototype.add.call(this,e)},b.prototype.remove=function(e){if(e instanceof o&&void 0===e.extend){if(!this.fields||this.fields[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.fields[e.name],e.parent=null,e.onRemove(this),w(this)}if(e instanceof i){if(!this.oneofs||this.oneofs[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.oneofs[e.name],e.parent=null,e.onRemove(this),w(this)}return n.prototype.remove.call(this,e)},b.prototype.isReservedId=function(e){return n.isReservedId(this.reserved,e)},b.prototype.isReservedName=function(e){return n.isReservedName(this.reserved,e)},b.prototype.create=function(e){return new this.ctor(e)},b.prototype.setup=function(){for(var e=this.fullName,t=[],r=0;r<this.fieldsArray.length;++r)t.push(this._fieldsArray[r].resolve().resolvedType);this.encode=p(this)({Writer:h,types:t,util:d}),this.decode=f(this)({Reader:u,types:t,util:d}),this.verify=g(this)({types:t,util:d}),this.fromObject=m.fromObject(this)({types:t,util:d}),this.toObject=m.toObject(this)({types:t,util:d});var n=y[e];if(n){var s=Object.create(this);s.fromObject=this.fromObject,this.fromObject=n.fromObject.bind(s),s.toObject=this.toObject,this.toObject=n.toObject.bind(s)}return this},b.prototype.encode=function(e,t){return this.setup().encode(e,t)},b.prototype.encodeDelimited=function(e,t){return this.encode(e,t&&t.len?t.fork():t).ldelim()},b.prototype.decode=function(e,t){return this.setup().decode(e,t)},b.prototype.decodeDelimited=function(e){return e instanceof u||(e=u.create(e)),this.decode(e,e.uint32())},b.prototype.verify=function(e){return this.setup().verify(e)},b.prototype.fromObject=function(e){return this.setup().fromObject(e)},b.prototype.toObject=function(e,t){return this.setup().toObject(e,t)},b.d=function(e){return function(t){d.decorateType(t,e)}}},8045:e=>{"use strict";e.exports=function(e,t){for(var r=new Array(arguments.length-1),n=0,s=2,i=!0;s<arguments.length;)r[n++]=arguments[s++];return new Promise(function(s,o){r[n]=function(e){if(i)if(i=!1,e)o(e);else{for(var t=new Array(arguments.length-1),r=0;r<t.length;)t[r++]=arguments[r];s.apply(null,t)}};try{e.apply(t||null,r)}catch(e){i&&(i=!1,o(e))}})}},8252:(e,t,r)=>{"use strict";e.exports=o;var n=r(1344);((o.prototype=Object.create(n.prototype)).constructor=o).className="MapField";var s=r(361),i=r(3262);function o(e,t,r,s,o,a){if(n.call(this,e,t,s,void 0,void 0,o,a),!i.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}o.fromJSON=function(e,t){return new o(e,t.id,t.keyType,t.type,t.options,t.comment)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return i.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},o.prototype.resolve=function(){if(this.resolved)return this;if(void 0===s.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},o.d=function(e,t,r){return"function"==typeof r?r=i.decorateType(r).name:r&&"object"==typeof r&&(r=i.decorateEnum(r).name),function(n,s){i.decorateType(n.constructor).add(new o(s,e,t,r))}}},8303:(e,t,r)=>{var n=r(3961);t.operation=function(e){var r=t.timeouts(e);return new n(r,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},t.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],s=0;s<t.retries;s++)n.push(this.createTimeout(s,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(s,t)),n.sort(function(e,t){return e-t}),n},t.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(n,t.maxTimeout)},t.wrap=function(e,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var s in n=[],e)"function"==typeof e[s]&&n.push(s);for(var i=0;i<n.length;i++){var o=n[i],a=e[o];e[o]=function(n){var s=t.operation(r),i=Array.prototype.slice.call(arguments,1),o=i.pop();i.push(function(e){s.retry(e)||(e&&(arguments[0]=s.mainError()),o.apply(this,arguments))}),s.attempt(function(){n.apply(e,i)})}.bind(e,a),e[o].options=r}}},8561:e=>{"use strict";function t(e,r){"string"==typeof e&&(r=e,e=void 0);var n=[];function s(e){if("string"!=typeof e){var r=i();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var o=Object.keys(e),a=new Array(o.length+1),c=new Array(o.length),l=0;l<o.length;)a[l]=o[l],c[l]=e[o[l++]];return a[l]=r,Function.apply(null,a).apply(null,c)}return Function(r)()}for(var u=new Array(arguments.length-1),h=0;h<u.length;)u[h]=arguments[++h];if(h=0,e=e.replace(/%([%dfijs])/g,function(e,t){var r=u[h++];switch(t){case"d":case"f":return String(Number(r));case"i":return String(Math.floor(r));case"j":return JSON.stringify(r);case"s":return String(r)}return"%"}),h!==u.length)throw Error("parameter count mismatch");return n.push(e),s}function i(t){return"function "+(t||r||"")+"("+(e&&e.join(",")||"")+"){\n "+n.join("\n ")+"\n}"}return s.toString=i,s}e.exports=t,t.verbose=!1},8811:(e,t,r)=>{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="Method";var s=r(3262);function i(e,t,r,i,o,a,c,l,u){if(s.isObject(o)?(c=o,o=a=void 0):s.isObject(a)&&(c=a,a=void 0),void 0!==t&&!s.isString(t))throw TypeError("type must be a string");if(!s.isString(r))throw TypeError("requestType must be a string");if(!s.isString(i))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!o||void 0,this.responseType=i,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}i.fromJSON=function(e,t){return new i(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",t?this.comment:void 0,"parsedOptions",this.parsedOptions])},i.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},8839:(e,t)=>{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),s=new Array(123),i=0;i<64;)s[n[i]=i<26?i+65:i<52?i+71:i<62?i-4:i-59|43]=i++;r.encode=function(e,t,r){for(var s,i=null,o=[],a=0,c=0;t<r;){var l=e[t++];switch(c){case 0:o[a++]=n[l>>2],s=(3&l)<<4,c=1;break;case 1:o[a++]=n[s|l>>4],s=(15&l)<<2,c=2;break;case 2:o[a++]=n[s|l>>6],o[a++]=n[63&l],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0)}return c&&(o[a++]=n[s],o[a++]=61,1===c&&(o[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var o="invalid encoding";r.decode=function(e,t,r){for(var n,i=r,a=0,c=0;c<e.length;){var l=e.charCodeAt(c++);if(61===l&&a>1)break;if(void 0===(l=s[l]))throw Error(o);switch(a){case 0:n=l,a=1;break;case 1:t[r++]=n<<2|(48&l)>>4,n=l,a=2;break;case 2:t[r++]=(15&n)<<4|(60&l)>>2,n=l,a=3;break;case 3:t[r++]=(3&n)<<6|l,a=0}}if(1===a)throw Error(o);return r-i},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},8923:(e,t,r)=>{"use strict";e.exports=h;var n=r(7209);((h.prototype=Object.create(n.prototype)).constructor=h).className="Namespace";var s,i,o,a=r(1344),c=r(3262),l=r(1457);function u(e,t){if(e&&e.length){for(var r={},n=0;n<e.length;++n)r[e[n].name]=e[n].toJSON(t);return r}}function h(e,t){n.call(this,e,t),this.nested=void 0,this._nestedArray=null,this._lookupCache={},this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0}function d(e){e._nestedArray=null,e._lookupCache={};for(var t=e;t=t.parent;)t._lookupCache={};return e}h.fromJSON=function(e,t){return new h(e,t.options).addJSON(t.nested)},h.arrayToJSON=u,h.isReservedId=function(e,t){if(e)for(var r=0;r<e.length;++r)if("string"!=typeof e[r]&&e[r][0]<=t&&e[r][1]>t)return!0;return!1},h.isReservedName=function(e,t){if(e)for(var r=0;r<e.length;++r)if(e[r]===t)return!0;return!1},Object.defineProperty(h.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=c.toArray(this.nested))}}),h.prototype.toJSON=function(e){return c.toObject(["options",this.options,"nested",u(this.nestedArray,e)])},h.prototype.addJSON=function(e){if(e)for(var t,r=Object.keys(e),n=0;n<r.length;++n)t=e[r[n]],this.add((void 0!==t.fields?s.fromJSON:void 0!==t.values?o.fromJSON:void 0!==t.methods?i.fromJSON:void 0!==t.id?a.fromJSON:h.fromJSON)(r[n],t));return this},h.prototype.get=function(e){return this.nested&&this.nested[e]||null},h.prototype.getEnum=function(e){if(this.nested&&this.nested[e]instanceof o)return this.nested[e].values;throw Error("no such enum: "+e)},h.prototype.add=function(e){if(!(e instanceof a&&void 0!==e.extend||e instanceof s||e instanceof l||e instanceof o||e instanceof i||e instanceof h))throw TypeError("object must be a valid nested object");if(this.nested){var t=this.get(e.name);if(t){if(!(t instanceof h&&e instanceof h)||t instanceof s||t instanceof i)throw Error("duplicate name '"+e.name+"' in "+this);for(var r=t.nestedArray,n=0;n<r.length;++n)e.add(r[n]);this.remove(t),this.nested||(this.nested={}),e.setOptions(t.options,!0)}}else this.nested={};this.nested[e.name]=e,this instanceof s||this instanceof i||this instanceof o||this instanceof a||e._edition||(e._edition=e._defaultEdition),this._needsRecursiveFeatureResolution=!0,this._needsRecursiveResolve=!0;for(var c=this;c=c.parent;)c._needsRecursiveFeatureResolution=!0,c._needsRecursiveResolve=!0;return e.onAdd(this),d(this)},h.prototype.remove=function(e){if(!(e instanceof n))throw TypeError("object must be a ReflectionObject");if(e.parent!==this)throw Error(e+" is not a member of "+this);return delete this.nested[e.name],Object.keys(this.nested).length||(this.nested=void 0),e.onRemove(this),d(this)},h.prototype.define=function(e,t){if(c.isString(e))e=e.split(".");else if(!Array.isArray(e))throw TypeError("illegal path");if(e&&e.length&&""===e[0])throw Error("path must be relative");for(var r=this;e.length>0;){var n=e.shift();if(r.nested&&r.nested[n]){if(!((r=r.nested[n])instanceof h))throw Error("path conflicts with non-namespace objects")}else r.add(r=new h(n))}return t&&r.addJSON(t),r},h.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;this._resolveFeaturesRecursive(this._edition);var e=this.nestedArray,t=0;for(this.resolve();t<e.length;)e[t]instanceof h?e[t++].resolveAll():e[t++].resolve();return this._needsRecursiveResolve=!1,this},h.prototype._resolveFeaturesRecursive=function(e){return this._needsRecursiveFeatureResolution?(this._needsRecursiveFeatureResolution=!1,e=this._edition||e,n.prototype._resolveFeaturesRecursive.call(this,e),this.nestedArray.forEach(t=>{t._resolveFeaturesRecursive(e)}),this):this},h.prototype.lookup=function(e,t,r){if("boolean"==typeof t?(r=t,t=void 0):t&&!Array.isArray(t)&&(t=[t]),c.isString(e)&&e.length){if("."===e)return this.root;e=e.split(".")}else if(!e.length)return this;var n=e.join(".");if(""===e[0])return this.root.lookup(e.slice(1),t);var s=this.root._fullyQualifiedObjects&&this.root._fullyQualifiedObjects["."+n];if(s&&(!t||t.indexOf(s.constructor)>-1))return s;if((s=this._lookupImpl(e,n))&&(!t||t.indexOf(s.constructor)>-1))return s;if(r)return null;for(var i=this;i.parent;){if((s=i.parent._lookupImpl(e,n))&&(!t||t.indexOf(s.constructor)>-1))return s;i=i.parent}return null},h.prototype._lookupImpl=function(e,t){if(Object.prototype.hasOwnProperty.call(this._lookupCache,t))return this._lookupCache[t];var r=this.get(e[0]),n=null;if(r)1===e.length?n=r:r instanceof h&&(e=e.slice(1),n=r._lookupImpl(e,e.join(".")));else for(var s=0;s<this.nestedArray.length;++s)this._nestedArray[s]instanceof h&&(r=this._nestedArray[s]._lookupImpl(e,t))&&(n=r);return this._lookupCache[t]=n,n},h.prototype.lookupType=function(e){var t=this.lookup(e,[s]);if(!t)throw Error("no such type: "+e);return t},h.prototype.lookupEnum=function(e){var t=this.lookup(e,[o]);if(!t)throw Error("no such Enum '"+e+"' in "+this);return t},h.prototype.lookupTypeOrEnum=function(e){var t=this.lookup(e,[s,o]);if(!t)throw Error("no such Type or Enum '"+e+"' in "+this);return t},h.prototype.lookupService=function(e){var t=this.lookup(e,[i]);if(!t)throw Error("no such Service '"+e+"' in "+this);return t},h._configure=function(e,t,r){s=e,i=t,o=r}},9100:(e,t,r)=>{"use strict";var n=e.exports=r(5325);n.build="full",n.tokenize=r(527),n.parse=r(4863),n.common=r(5095),n.Root._configure(n.Type,n.parse,n.common)},9207:(e,t)=>{"use strict";var r=t,n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},s=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e),s="";r&&(s=t.shift()+"/");for(var i=0;i<t.length;)".."===t[i]?i>0&&".."!==t[i-1]?t.splice(--i,2):r?t.splice(i,1):++i:"."===t[i]?t.splice(i,1):++i;return s+t.join("/")};r.resolve=function(e,t,r){return r||(t=s(t)),n(t)?t:(r||(e=s(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?s(e+"/"+t):t)}},9390:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,s=n>>>1,i=null,o=n;return function(r){if(r<1||r>s)return e(r);o+r>n&&(i=e(n),o=0);var a=t.call(i,o,o+=r);return 7&o&&(o=1+(7|o)),a}}},9410:e=>{"use strict";function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function s(e,n,s){t[0]=e,n[s]=r[0],n[s+1]=r[1],n[s+2]=r[2],n[s+3]=r[3]}function i(e,n,s){t[0]=e,n[s]=r[3],n[s+1]=r[2],n[s+2]=r[1],n[s+3]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?s:i,e.writeFloatBE=n?i:s,e.readFloatLE=n?o:a,e.readFloatBE=n?a:o}():function(){function t(e,t,r,n){var s=t<0?1:0;if(s&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((s<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((s<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var i=Math.floor(Math.log(t)/Math.LN2);e((s<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,r,n)}}function o(e,t,r){var n=e(t,r),s=2*(n>>31)+1,i=n>>>23&255,o=8388607&n;return 255===i?o?NaN:s*(1/0):0===i?1401298464324817e-60*s*o:s*Math.pow(2,i-150)*(o+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=o.bind(null,s),e.readFloatBE=o.bind(null,i)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function s(e,n,s){t[0]=e,n[s]=r[0],n[s+1]=r[1],n[s+2]=r[2],n[s+3]=r[3],n[s+4]=r[4],n[s+5]=r[5],n[s+6]=r[6],n[s+7]=r[7]}function i(e,n,s){t[0]=e,n[s]=r[7],n[s+1]=r[6],n[s+2]=r[5],n[s+3]=r[4],n[s+4]=r[3],n[s+5]=r[2],n[s+6]=r[1],n[s+7]=r[0]}function o(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?s:i,e.writeDoubleBE=n?i:s,e.readDoubleLE=n?o:a,e.readDoubleBE=n?a:o}():function(){function t(e,t,r,n,s,i){var o=n<0?1:0;if(o&&(n=-n),0===n)e(0,s,i+t),e(1/n>0?0:2147483648,s,i+r);else if(isNaN(n))e(0,s,i+t),e(2146959360,s,i+r);else if(n>17976931348623157e292)e(0,s,i+t),e((o<<31|2146435072)>>>0,s,i+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,s,i+t),e((o<<31|a/4294967296)>>>0,s,i+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,s,i+t),e((o<<31|c+1023<<20|1048576*a&1048575)>>>0,s,i+r)}}}function o(e,t,r,n,s){var i=e(n,s+t),o=e(n,s+r),a=2*(o>>31)+1,c=o>>>20&2047,l=4294967296*(1048575&o)+i;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=o.bind(null,s,0,4),e.readDoubleBE=o.bind(null,i,4,0)}(),e}function r(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function i(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},9687:(e,t,r)=>{"use strict";e.exports=a;var n=r(8923);((a.prototype=Object.create(n.prototype)).constructor=a).className="Service";var s=r(8811),i=r(3262),o=r(5047);function a(e,t){n.call(this,e,t),this.methods={},this._methodsArray=null}function c(e){return e._methodsArray=null,e}a.fromJSON=function(e,t){var r=new a(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),i=0;i<n.length;++i)r.add(s.fromJSON(n[i],t.methods[n[i]]));return t.nested&&r.addJSON(t.nested),t.edition&&(r._edition=t.edition),r.comment=t.comment,r._defaultEdition="proto3",r},a.prototype.toJSON=function(e){var t=n.prototype.toJSON.call(this,e),r=!!e&&Boolean(e.keepComments);return i.toObject(["edition",this._editionToJSON(),"options",t&&t.options||void 0,"methods",n.arrayToJSON(this.methodsArray,e)||{},"nested",t&&t.nested||void 0,"comment",r?this.comment:void 0])},Object.defineProperty(a.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=i.toArray(this.methods))}}),a.prototype.get=function(e){return this.methods[e]||n.prototype.get.call(this,e)},a.prototype.resolveAll=function(){if(!this._needsRecursiveResolve)return this;n.prototype.resolve.call(this);for(var e=this.methodsArray,t=0;t<e.length;++t)e[t].resolve();return this},a.prototype._resolveFeaturesRecursive=function(e){return this._needsRecursiveFeatureResolution?(e=this._edition||e,n.prototype._resolveFeaturesRecursive.call(this,e),this.methodsArray.forEach(t=>{t._resolveFeaturesRecursive(e)}),this):this},a.prototype.add=function(e){if(this.get(e.name))throw Error("duplicate name '"+e.name+"' in "+this);return e instanceof s?(this.methods[e.name]=e,e.parent=this,c(this)):n.prototype.add.call(this,e)},a.prototype.remove=function(e){if(e instanceof s){if(this.methods[e.name]!==e)throw Error(e+" is not a member of "+this);return delete this.methods[e.name],e.parent=null,c(this)}return n.prototype.remove.call(this,e)},a.prototype.create=function(e,t,r){for(var n,s=new o.Service(e,t,r),a=0;a<this.methodsArray.length;++a){var c=i.lcFirst((n=this._methodsArray[a]).resolve().name).replace(/[^$\w_]/g,"");s[c]=i.codegen(["r","c"],i.isReserved(c)?c+"_":c)("return this.rpcCall(m,q,s,r,c)")({m:n,q:n.resolvedRequestType.ctor,s:n.resolvedResponseType.ctor})}return s}},9939:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{const t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{this.pullQueue.push({resolve:e,reject:t})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class n{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){const s=new r;s.highWaterMark=t,s.lowWaterMark=n,s.removeCallback=e({push:e=>s.push(e),stop:()=>s.stop(),fail:e=>s.fail(e),on:(e,t)=>{s.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>s[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.amdO={},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var r=Object.create(null);__webpack_require__.r(r);var n={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&t&&e;("object"==typeof s||"function"==typeof s)&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach(t=>n[t]=()=>e[t]);return n.default=()=>e,__webpack_require__.d(r,n),r},__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{"use strict";var e={};__webpack_require__.r(e),__webpack_require__.d(e,{base10:()=>re});var t={};__webpack_require__.r(t),__webpack_require__.d(t,{base16:()=>ne,base16upper:()=>se});var r={};__webpack_require__.r(r),__webpack_require__.d(r,{base2:()=>ie});var n={};__webpack_require__.r(n),__webpack_require__.d(n,{base256emoji:()=>le});var s={};__webpack_require__.r(s),__webpack_require__.d(s,{base32:()=>ue,base32hex:()=>fe,base32hexpad:()=>me,base32hexpadupper:()=>ye,base32hexupper:()=>ge,base32pad:()=>de,base32padupper:()=>pe,base32upper:()=>he,base32z:()=>be});var i={};__webpack_require__.r(i),__webpack_require__.d(i,{base36:()=>we,base36upper:()=>ve});var o={};__webpack_require__.r(o),__webpack_require__.d(o,{base58btc:()=>Ee,base58flickr:()=>Se});var a={};__webpack_require__.r(a),__webpack_require__.d(a,{base64:()=>Ae,base64pad:()=>Ie,base64url:()=>ke,base64urlpad:()=>xe});var c={};__webpack_require__.r(c),__webpack_require__.d(c,{base8:()=>Ce});var l={};__webpack_require__.r(l),__webpack_require__.d(l,{identity:()=>_e});var u={};__webpack_require__.r(u),__webpack_require__.d(u,{code:()=>Oe,decode:()=>De,encode:()=>Le,name:()=>Re});var h={};__webpack_require__.r(h),__webpack_require__.d(h,{code:()=>Me,decode:()=>Be,encode:()=>Fe,name:()=>Ne});var d={};__webpack_require__.r(d),__webpack_require__.d(d,{identity:()=>at});var p={};function f(e=0){return new Uint8Array(e)}function g(e=0){return new Uint8Array(e)}__webpack_require__.r(p),__webpack_require__.d(p,{sha256:()=>ht,sha512:()=>dt});const m=Math.pow(2,7),y=Math.pow(2,14),b=Math.pow(2,21),w=Math.pow(2,28),v=Math.pow(2,35),E=Math.pow(2,42),S=Math.pow(2,49),A=128,I=127;function k(e){if(e<m)return 1;if(e<y)return 2;if(e<b)return 3;if(e<w)return 4;if(e<v)return 5;if(e<E)return 6;if(e<S)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function x(e,t,r=0){switch(k(e)){case 8:t[r++]=255&e|A,e/=128;case 7:t[r++]=255&e|A,e/=128;case 6:t[r++]=255&e|A,e/=128;case 5:t[r++]=255&e|A,e/=128;case 4:t[r++]=255&e|A,e>>>=7;case 3:t[r++]=255&e|A,e>>>=7;case 2:t[r++]=255&e|A,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function C(e,t){let r=e[t],n=0;if(n+=r&I,r<A)return n;if(r=e[t+1],n+=(r&I)<<7,r<A)return n;if(r=e[t+2],n+=(r&I)<<14,r<A)return n;if(r=e[t+3],n+=(r&I)<<21,r<A)return n;if(r=e[t+4],n+=(r&I)*w,r<A)return n;if(r=e[t+5],n+=(r&I)*v,r<A)return n;if(r=e[t+6],n+=(r&I)*E,r<A)return n;if(r=e[t+7],n+=(r&I)*S,r<A)return n;throw new RangeError("Could not decode varint")}function _(e,t,r=0){return null==t&&(t=g(k(e))),t instanceof Uint8Array?x(e,t,r):function(e,t,r=0){switch(k(e)){case 8:t.set(r++,255&e|A),e/=128;case 7:t.set(r++,255&e|A),e/=128;case 6:t.set(r++,255&e|A),e/=128;case 5:t.set(r++,255&e|A),e/=128;case 4:t.set(r++,255&e|A),e>>>=7;case 3:t.set(r++,255&e|A),e>>>=7;case 2:t.set(r++,255&e|A),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function T(e,t=0){return e instanceof Uint8Array?C(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&I,r<A)return n;if(r=e.get(t+1),n+=(r&I)<<7,r<A)return n;if(r=e.get(t+2),n+=(r&I)<<14,r<A)return n;if(r=e.get(t+3),n+=(r&I)<<21,r<A)return n;if(r=e.get(t+4),n+=(r&I)*w,r<A)return n;if(r=e.get(t+5),n+=(r&I)*v,r<A)return n;if(r=e.get(t+6),n+=(r&I)*E,r<A)return n;if(r=e.get(t+7),n+=(r&I)*S,r<A)return n;throw new RangeError("Could not decode varint")}(e,t)}const P=new Float32Array([-0]),R=new Uint8Array(P.buffer);function O(e,t,r){P[0]=e,t[r]=R[0],t[r+1]=R[1],t[r+2]=R[2],t[r+3]=R[3]}const L=new Float64Array([-0]),D=new Uint8Array(L.buffer);function N(e,t,r){L[0]=e,t[r]=D[0],t[r+1]=D[1],t[r+2]=D[2],t[r+3]=D[3],t[r+4]=D[4],t[r+5]=D[5],t[r+6]=D[6],t[r+7]=D[7]}const M=BigInt(Number.MAX_SAFE_INTEGER),F=BigInt(Number.MIN_SAFE_INTEGER);class B{lo;hi;constructor(e,t){this.lo=0|e,this.hi=0|t}toNumber(e=!1){if(!e&&this.hi>>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return U;if(e<M&&e>F)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>$&&(n=0n,++r>$&&(r=0n))),new B(Number(n),Number(r))}static fromNumber(e){if(0===e)return U;const t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new B(r,n)}static from(e){return"number"==typeof e?B.fromNumber(e):"bigint"==typeof e?B.fromBigInt(e):"string"==typeof e?B.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new B(e.low>>>0,e.high>>>0):U}}const U=new B(0,0);U.toBigInt=function(){return 0n},U.zzEncode=U.zzDecode=function(){return this},U.length=function(){return 1};const $=4294967296n;function q(e,t,r){const n=r;let s,i;for(let n=0;n<e.length;++n)s=e.charCodeAt(n),s<128?t[r++]=s:s<2048?(t[r++]=s>>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(i=e.charCodeAt(n+1)))?(s=65536+((1023&s)<<10)+(1023&i),++n,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-n}function j(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function z(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class K{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,j(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw j(this,4);return z(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw j(this,4);return 0|z(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw j(this,4);const e=(t=this.buf,r=this.pos,R[0]=t[r],R[1]=t[r+1],R[2]=t[r+2],R[3]=t[r+3],P[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw j(this,4);const e=(t=this.buf,r=this.pos,D[0]=t[r],D[1]=t[r+1],D[2]=t[r+2],D[3]=t[r+3],D[4]=t[r+4],D[5]=t[r+5],D[6]=t[r+6],D[7]=t[r+7],L[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw j(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const s=[];let i,o=0;for(;t<r;)i=e[t++],i<128?s[o++]=i:i>191&&i<224?s[o++]=(31&i)<<6|63&e[t++]:i>239&&i<365?(i=((7&i)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[o++]=55296+(i>>10),s[o++]=56320+(1023&i)):s[o++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),o=0);return null!=n?(o>0&&n.push(String.fromCharCode.apply(String,s.slice(0,o))),n.join("")):String.fromCharCode.apply(String,s.slice(0,o))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw j(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw j(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new B(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw j(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw j(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw j(this,8);const e=z(this.buf,this.pos+=4),t=z(this.buf,this.pos+=4);return new B(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=C(this.buf,this.pos);return this.pos+=k(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function V(e,t,r){const n=function(e){return new K(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function H(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}new Uint8Array(0);const G=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var s=0;s<e.length;s++){var i=e.charAt(s),o=i.charCodeAt(0);if(255!==r[o])throw new TypeError(i+" is ambiguous");r[o]=s}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,s=0;e[t]===c;)n++,t++;for(var i=(e.length-t)*l+1>>>0,o=new Uint8Array(i);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=i-1;(0!==u||h<s)&&-1!==d;d--,h++)u+=a*o[d]>>>0,o[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");s=h,t++}if(" "!==e[t]){for(var p=i-s;p!==i&&0===o[p];)p++;for(var f=new Uint8Array(n+(i-p)),g=n;p!==i;)f[g++]=o[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,s=0,i=t.length;s!==i&&0===t[s];)s++,r++;for(var o=(i-s)*u+1>>>0,l=new Uint8Array(o);s!==i;){for(var h=t[s],d=0,p=o-1;(0!==h||d<n)&&-1!==p;p--,d++)h+=256*l[p]>>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,s++}for(var f=o-n;f!==o&&0===l[f];)f++;for(var g=c.repeat(r);f<o;++f)g+=e.charAt(l[f]);return g},decodeUnsafe:h,decode:function(e){var r=h(e);if(r)return r;throw new Error(`Non-${t} character`)}}};class W{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class X{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;const n=t.codePointAt(0);if(void 0===n)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return Y(this,e)}}class J{decoders;constructor(e){this.decoders=e}or(e){return Y(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function Y(e,t){return new J({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class Z{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new W(e,t,r),this.decoder=new X(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function Q({name:e,prefix:t,encode:r,decode:n}){return new Z(e,t,r,n)}function ee({name:e,prefix:t,alphabet:r}){const{encode:n,decode:s}=G(r,e);return Q({prefix:t,name:e,encode:n,decode:e=>H(s(e))})}function te({name:e,prefix:t,bitsPerChar:r,alphabet:n}){const s=function(e){const t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}(n);return Q({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],s=(1<<r)-1;let i="",o=0,a=0;for(let n=0;n<e.length;++n)for(a=a<<8|e[n],o+=8;o>r;)o-=r,i+=t[s&a>>o];if(0!==o&&(i+=t[s&a<<r-o]),n)for(;i.length*r&7;)i+="=";return i}(e,n,r),decode:t=>function(e,t,r,n){let s=e.length;for(;"="===e[s-1];)--s;const i=new Uint8Array(s*r/8|0);let o=0,a=0,c=0;for(let l=0;l<s;++l){const s=t[e[l]];if(void 0===s)throw new SyntaxError(`Non-${n} character`);a=a<<r|s,o+=r,o>=8&&(o-=8,i[c++]=255&a>>o)}if(o>=r||255&a<<8-o)throw new SyntaxError("Unexpected end of data");return i}(t,s,r,e)})}const re=ee({prefix:"9",name:"base10",alphabet:"0123456789"}),ne=te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),se=te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),ie=te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),oe=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ae=oe.reduce((e,t,r)=>(e[r]=t,e),[]),ce=oe.reduce((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]),le=Q({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+ae[t],"")},decode:function(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw new Error(`Invalid character: ${r}`);const n=ce[e];if(null==n)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}}),ue=te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),he=te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),de=te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pe=te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fe=te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ge=te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),me=te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ye=te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),be=te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),we=ee({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ve=ee({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Ee=ee({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Se=ee({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Ae=te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ie=te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ke=te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),xe=te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Ce=te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),_e=Q({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)}),Te=new TextEncoder,Pe=new TextDecoder,Re="json",Oe=512;function Le(e){return Te.encode(JSON.stringify(e))}function De(e){return JSON.parse(Pe.decode(e))}const Ne="raw",Me=85;function Fe(e){return H(e)}function Be(e){return H(e)}var Ue=128,$e=-128,qe=Math.pow(2,31),je=128,ze=127,Ke=Math.pow(2,7),Ve=Math.pow(2,14),He=Math.pow(2,21),Ge=Math.pow(2,28),We=Math.pow(2,35),Xe=Math.pow(2,42),Je=Math.pow(2,49),Ye=Math.pow(2,56),Ze=Math.pow(2,63);const Qe={encode:function e(t,r,n){r=r||[];for(var s=n=n||0;t>=qe;)r[n++]=255&t|Ue,t/=128;for(;t&$e;)r[n++]=255&t|Ue,t>>>=7;return r[n]=0|t,e.bytes=n-s+1,r},decode:function e(t,r){var n,s=0,i=0,o=r=r||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],s+=i<28?(n&ze)<<i:(n&ze)*Math.pow(2,i),i+=7}while(n>=je);return e.bytes=o-r,s},encodingLength:function(e){return e<Ke?1:e<Ve?2:e<He?3:e<Ge?4:e<We?5:e<Xe?6:e<Je?7:e<Ye?8:e<Ze?9:10}};function et(e,t=0){return[Qe.decode(e,t),Qe.decode.bytes]}function tt(e,t,r=0){return Qe.encode(e,t,r),t}function rt(e){return Qe.encodingLength(e)}function nt(e,t){const r=t.byteLength,n=rt(e),s=n+rt(r),i=new Uint8Array(s+r);return tt(e,i,0),tt(r,i,n),i.set(t,s),new it(e,r,t,i)}function st(e){const t=H(e),[r,n]=et(t),[s,i]=et(t.subarray(n)),o=t.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new it(r,s,o,t)}class it{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}const ot=H,at={code:0,name:"identity",encode:ot,digest:function(e){return nt(0,ot(e))}};function ct({name:e,code:t,encode:r}){return new lt(e,t,r)}class lt{name;code;encode;constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?nt(this.code,t):t.then(e=>nt(this.code,e))}throw Error("Unknown type, must be binary type")}}function ut(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const ht=ct({name:"sha2-256",code:18,encode:ut("SHA-256")}),dt=ct({name:"sha2-512",code:19,encode:ut("SHA-512")});function pt(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==Ee.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const s=t.get(n);if(null==s){const s=r.encode(e).slice(1);return t.set(n,s),s}return s}(r,gt(e),t??Ee.encoder):function(e,t,r){const{prefix:n}=r,s=t.get(n);if(null==s){const s=r.encode(e);return t.set(n,s),s}return s}(r,gt(e),t??ue.encoder)}const ft=new WeakMap;function gt(e){const t=ft.get(e);if(null==t){const t=new Map;return ft.set(e,t),t}return t}class mt{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:t}=this;if(e!==yt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==bt)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return mt.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,r=nt(e,t);return mt.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return mt.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&function(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e.bytes,r.bytes)}}(e.multihash,r.multihash)}toString(e){return pt(this,e)}toJSON(){return{"/":pt(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(null==e)return null;const t=e;if(t instanceof mt)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){const{version:e,code:r,multihash:n,bytes:s}=t;return new mt(e,r,n,s??wt(e,r,n.bytes))}if(!0===t[vt]){const{version:e,multihash:r,code:n}=t,s=st(r);return mt.create(e,n,s)}return null}static create(e,t,r){if("number"!=typeof t)throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:if(t!==yt)throw new Error(`Version 0 CID must use dag-pb (code: ${yt}) block encoding`);return new mt(e,t,r,r.bytes);case 1:{const n=wt(e,t,r.bytes);return new mt(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return mt.create(0,yt,e)}static createV1(e,t){return mt.create(1,e,t)}static decode(e){const[t,r]=mt.decodeFirst(e);if(0!==r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){const t=mt.inspectBytes(e),r=t.size-t.multihashSize,n=H(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");const s=n.subarray(t.multihashSize-t.digestSize),i=new it(t.multihashCode,t.digestSize,s,n);return[0===t.version?mt.createV0(i):mt.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=et(e.subarray(t));return t+=n,r};let n=r(),s=yt;if(18===n?(n=0,t=0):s=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const i=t,o=r(),a=r(),c=t+a;return{version:n,codec:s,multihashCode:o,digestSize:a,multihashSize:c-i,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??Ee;return[Ee.prefix,r.decode(`${Ee.prefix}${e}`)]}case Ee.prefix:{const r=t??Ee;return[Ee.prefix,r.decode(e)]}case ue.prefix:{const r=t??ue;return[ue.prefix,r.decode(e)]}case we.prefix:{const r=t??we;return[we.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),s=mt.decode(n);if(0===s.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return gt(s).set(r,e),s}}const yt=112,bt=18;function wt(e,t,r){const n=rt(e),s=n+rt(t),i=new Uint8Array(s+r.byteLength);return tt(e,i,0),tt(t,i,n),i.set(r,s),i}const vt=Symbol.for("@ipld/js-cid/CID"),Et={...l,...r,...c,...e,...t,...s,...i,...o,...a,...n};function St(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const At=St("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>(new TextEncoder).encode(e.substring(1))),It=St("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{const t=g((e=e.substring(1)).length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),kt={utf8:At,"utf-8":At,hex:Et.base16,latin1:It,ascii:It,binary:It,...Et};function xt(e,t="utf8"){const r=kt[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}class Ct{fn;len;next;val;constructor(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}}function _t(){}class Tt{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}}const Pt=function(){const e=8192;let t,r=e;return function(n){if(n<1||n>4096)return g(n);r+n>e&&(t=g(e),r=0);const s=t.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),s}}();class Rt{len;head;tail;states;constructor(){this.len=0,this.head=new Ct(_t,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Ct(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Dt((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Nt,10,B.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=B.fromBigInt(e);return this._push(Nt,t.length(),t)}uint64Number(e){return this._push(x,k(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=B.fromBigInt(e).zzEncode();return this._push(Nt,t.length(),t)}sint64Number(e){const t=B.fromNumber(e).zzEncode();return this._push(Nt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ot,1,e?1:0)}fixed32(e){return this._push(Mt,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=B.fromBigInt(e);return this._push(Mt,4,t.lo)._push(Mt,4,t.hi)}fixed64Number(e){const t=B.fromNumber(e);return this._push(Mt,4,t.lo)._push(Mt,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(O,4,e)}double(e){return this._push(N,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Ot,1,0):this.uint32(t)._push(Ft,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(q,t,e):this._push(Ot,1,0)}fork(){return this.states=new Tt(this),this.head=this.tail=new Ct(_t,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ct(_t,0,0),this.len=0),this}ldelim(){const e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next;const t=(r=this.len,null!=globalThis.Buffer?g(r):Pt(r));var r;let n=0;for(;null!=e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}}function Ot(e,t,r){t[r]=255&e}function Lt(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class Dt extends Ct{next;constructor(e,t){super(Lt,e,t),this.next=void 0}}function Nt(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function Mt(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function Ft(e,t,r){t.set(e,r)}function Bt(e,t,r){t.set(e,r)}function Ut(e,t,r){e.length<40?q(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(xt(e),r)}function $t(e,t){const r=new Rt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var qt,jt,zt,Kt,Vt,Ht,Gt,Wt,Xt,Jt,Yt,Zt,Qt,er,tr,rr,nr,sr,ir,or,ar,cr,lr,ur,hr,dr,pr,fr,gr,mr,yr,br,wr,vr;function Er(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Sr(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Er("enum",qt.VARINT,function(e,r){const n=t(e);r.int32(n)},function(e){return t(e.int32())})}function Ar(e,t){return Er("message",qt.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Rt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Bt,t,e),this},Rt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Ut,t,e),this}),function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"}(qt||(qt={})),Error;class Ir extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class kr extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function xr(e){return Boolean(e)}!function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={proof:f(0),merkleRoot:f(0),epoch:f(0),shareX:f(0),shareY:f(0),nullifier:f(0),rlnIdentifier:f(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(jt||(jt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),jt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={payload:f(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=jt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(zt||(zt={})),function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();t>>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(t=e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==r&&(r=Ar((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()},(t,r,n={})=>{const s={subscribe:!1,topic:"",contentFilters:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.subscribe=t.bool();break;case 2:s.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&s.contentFilters.length===n.limits.contentFilters)throw new Ir('Decode error - map field "contentFilters" had too many elements');s.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return s})),r),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Kt||(Kt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),Wt.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new Ir('Decode error - map field "messages" had too many elements');n.messages.push(Wt.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Vt||(Vt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),Kt.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),Vt.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=Kt.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=Vt.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Ht||(Ht={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={proof:f(0),merkleRoot:f(0),epoch:f(0),shareX:f(0),shareY:f(0),nullifier:f(0),rlnIdentifier:f(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Gt||(Gt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Gt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={payload:f(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Gt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Wt||(Wt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();t>>>3==2?n.contentTopic=e.string():e.skipType(7&t)}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Xt||(Xt={})),function(e){let t,r,n;!function(e){e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),function(e){e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"}(r||(r={})),function(e){e.codec=()=>Sr(r)}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=Ar((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==s.lengthDelimited&&n.ldelim()},(r,n,s={})=>{const i={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},o=null==n?r.len:r.pos+n;for(;r.pos<o;){const t=r.uint32();switch(t>>>3){case 1:i.requestId=r.string();break;case 2:i.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:i.pubsubTopic=r.string();break;case 11:if(null!=s.limits?.contentTopics&&i.contentTopics.length===s.limits.contentTopics)throw new Ir('Decode error - map field "contentTopics" had too many elements');i.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return i})),n),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Jt||(Jt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={requestId:"",statusCode:0},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Yt||(Yt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),er.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.wakuMessage=er.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Zt||(Zt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={proof:f(0),merkleRoot:f(0),epoch:f(0),shareX:f(0),shareY:f(0),nullifier:f(0),rlnIdentifier:f(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Qt||(Qt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Qt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={payload:f(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Qt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(er||(er={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(10),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(18),ar.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=ar.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(tr||(tr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.isSuccess&&!1!==e.isSuccess&&(t.uint32(8),t.bool(e.isSuccess)),null!=e.info&&(t.uint32(18),t.string(e.info)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={isSuccess:!1},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.isSuccess=e.bool();break;case 2:n.info=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 12:n.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(rr||(rr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),tr.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),rr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.request=tr.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=rr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(nr||(nr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.pubsubTopic&&(t.uint32(162),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(170),ar.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 20:n.pubsubTopic=e.string();break;case 21:n.message=ar.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(sr||(sr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.relayPeerCount&&(t.uint32(96),t.uint32(e.relayPeerCount)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={requestId:"",statusCode:0},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 12:n.relayPeerCount=e.uint32();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(ir||(ir={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={proof:f(0),merkleRoot:f(0),epoch:f(0),shareX:f(0),shareY:f(0),nullifier:f(0),rlnIdentifier:f(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(or||(or={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),or.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={payload:f(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=or.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(ar||(ar={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageHash&&(t.uint32(10),t.bytes(e.messageHash)),null!=e.message&&(t.uint32(18),dr.codec().encode(e.message,t)),null!=e.pubsubTopic&&(t.uint32(26),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.messageHash=e.bytes();break;case 2:n.message=dr.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;case 3:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(cr||(cr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.includeData&&!1!==e.includeData&&(t.uint32(16),t.bool(e.includeData)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(const r of e.contentTopics)t.uint32(90),t.string(r);if(null!=e.timeStart&&(t.uint32(96),t.sint64(e.timeStart)),null!=e.timeEnd&&(t.uint32(104),t.sint64(e.timeEnd)),null!=e.messageHashes)for(const r of e.messageHashes)t.uint32(162),t.bytes(r);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),null!=e.paginationForward&&!1!==e.paginationForward&&(t.uint32(416),t.bool(e.paginationForward)),null!=e.paginationLimit&&(t.uint32(424),t.uint64(e.paginationLimit)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 2:n.includeData=e.bool();break;case 10:n.pubsubTopic=e.string();break;case 11:if(null!=r.limits?.contentTopics&&n.contentTopics.length===r.limits.contentTopics)throw new Ir('Decode error - map field "contentTopics" had too many elements');n.contentTopics.push(e.string());break;case 12:n.timeStart=e.sint64();break;case 13:n.timeEnd=e.sint64();break;case 20:if(null!=r.limits?.messageHashes&&n.messageHashes.length===r.limits.messageHashes)throw new Ir('Decode error - map field "messageHashes" had too many elements');n.messageHashes.push(e.bytes());break;case 51:n.paginationCursor=e.bytes();break;case 52:n.paginationForward=e.bool();break;case 53:n.paginationLimit=e.uint64();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(lr||(lr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.messages)for(const r of e.messages)t.uint32(162),cr.codec().encode(r,t);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={requestId:"",messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 20:if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new Ir('Decode error - map field "messages" had too many elements');n.messages.push(cr.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 51:n.paginationCursor=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(ur||(ur={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={proof:f(0),merkleRoot:f(0),epoch:f(0),shareX:f(0),shareY:f(0),nullifier:f(0),rlnIdentifier:f(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(hr||(hr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),hr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={payload:f(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=hr.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(dr||(dr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();t>>>3==1?n.enr=e.bytes():e.skipType(7&t)}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(pr||(pr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();t>>>3==1?n.numPeers=e.uint64():e.skipType(7&t)}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(fr||(fr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),pr.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={peerInfos:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();if(t>>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new Ir('Decode error - map field "peerInfos" had too many elements');n.peerInfos.push(pr.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(gr||(gr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),fr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),gr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.query=fr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=gr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(mr||(mr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new Ir('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(yr||(yr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new Ir('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(br||(br={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageId&&""!==e.messageId&&(t.uint32(10),t.string(e.messageId)),null!=e.retrievalHint&&(t.uint32(18),t.bytes(e.retrievalHint)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={messageId:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.messageId=e.string();break;case 2:n.retrievalHint=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(wr||(wr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messageId&&""!==e.messageId&&(t.uint32(18),t.string(e.messageId)),null!=e.channelId&&""!==e.channelId&&(t.uint32(26),t.string(e.channelId)),null!=e.lamportTimestamp&&(t.uint32(80),t.int32(e.lamportTimestamp)),null!=e.causalHistory)for(const r of e.causalHistory)t.uint32(90),wr.codec().encode(r,t);null!=e.bloomFilter&&(t.uint32(98),t.bytes(e.bloomFilter)),null!=e.content&&(t.uint32(162),t.bytes(e.content)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={messageId:"",channelId:"",causalHistory:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 2:n.messageId=e.string();break;case 3:n.channelId=e.string();break;case 10:n.lamportTimestamp=e.int32();break;case 11:if(null!=r.limits?.causalHistory&&n.causalHistory.length===r.limits.causalHistory)throw new Ir('Decode error - map field "causalHistory" had too many elements');n.causalHistory.push(wr.codec().decode(e,e.uint32(),{limits:r.limits?.causalHistory$}));break;case 12:n.bloomFilter=e.bytes();break;case 20:n.content=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(vr||(vr={}));const Cr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function _r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Tr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Pr(e,...t){if(!_r(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Rr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Tr(e.outputLen),Tr(e.blockLen)}function Or(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Lr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Dr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Nr(e,t){return e<<32-t|e>>>t}const Mr=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Fr=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Br(e){if(Pr(e),Mr)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Fr[e[r]];return t}function Ur(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function $r(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Mr)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=Ur(e.charCodeAt(s)),i=Ur(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}function qr(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function jr(e){return"string"==typeof e&&(e=qr(e)),Pr(e),e}function zr(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];Pr(n),t+=n.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}class Kr{}function Vr(e){const t=t=>e().update(jr(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Hr(e=32){if(Cr&&"function"==typeof Cr.getRandomValues)return Cr.getRandomValues(new Uint8Array(e));if(Cr&&"function"==typeof Cr.randomBytes)return Uint8Array.from(Cr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Gr(e,t,r){return e&t^~e&r}function Wr(e,t,r){return e&t^e&r^t&r}class Xr extends Kr{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Dr(this.buffer)}update(e){Or(this),Pr(e=jr(e));const{view:t,buffer:r,blockLen:n}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(n-this.pos,s-i);if(o===n){const t=Dr(e);for(;n<=s-i;i+=n)this.process(t,i);continue}r.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Or(this),function(e,t){Pr(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:s}=this;let{pos:i}=this;t[i++]=128,Lr(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let e=i;e<n;e++)t[e]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const o=Dr(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],s)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:s,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=s,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Jr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Yr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Zr=BigInt(2**32-1),Qr=BigInt(32);function en(e,t=!1){return t?{h:Number(e&Zr),l:Number(e>>Qr&Zr)}:{h:0|Number(e>>Qr&Zr),l:0|Number(e&Zr)}}const tn=(e,t,r)=>e>>>r,rn=(e,t,r)=>e<<32-r|t>>>r,nn=(e,t,r)=>e>>>r|t<<32-r,sn=(e,t,r)=>e<<32-r|t>>>r,on=(e,t,r)=>e<<64-r|t>>>r-32,an=(e,t,r)=>e>>>r-32|t<<64-r;function cn(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}}const ln=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),un=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,hn=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),dn=(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,pn=(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0),fn=(e,t,r,n,s,i)=>t+r+n+s+i+(e/2**32|0)|0,gn=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),mn=new Uint32Array(64);class yn extends Xr{constructor(e=32){super(64,e,8,!1),this.A=0|Jr[0],this.B=0|Jr[1],this.C=0|Jr[2],this.D=0|Jr[3],this.E=0|Jr[4],this.F=0|Jr[5],this.G=0|Jr[6],this.H=0|Jr[7]}get(){const{A:e,B:t,C:r,D:n,E:s,F:i,G:o,H:a}=this;return[e,t,r,n,s,i,o,a]}set(e,t,r,n,s,i,o,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|s,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)mn[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=mn[e-15],r=mn[e-2],n=Nr(t,7)^Nr(t,18)^t>>>3,s=Nr(r,17)^Nr(r,19)^r>>>10;mn[e]=s+mn[e-7]+n+mn[e-16]|0}let{A:r,B:n,C:s,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Nr(o,6)^Nr(o,11)^Nr(o,25))+Gr(o,a,c)+gn[e]+mn[e]|0,u=(Nr(r,2)^Nr(r,13)^Nr(r,22))+Wr(r,n,s)|0;l=c,c=a,a=o,o=i+t|0,i=s,s=n,n=r,r=t+u|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,i,o,a,c,l)}roundClean(){Lr(mn)}destroy(){this.set(0,0,0,0,0,0,0,0),Lr(this.buffer)}}const bn=(()=>function(e,t=!1){const r=e.length;let n=new Uint32Array(r),s=new Uint32Array(r);for(let i=0;i<r;i++){const{h:r,l:o}=en(e[i],t);[n[i],s[i]]=[r,o]}return[n,s]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),wn=(()=>bn[0])(),vn=(()=>bn[1])(),En=new Uint32Array(80),Sn=new Uint32Array(80);class An extends Xr{constructor(e=64){super(128,e,16,!1),this.Ah=0|Yr[0],this.Al=0|Yr[1],this.Bh=0|Yr[2],this.Bl=0|Yr[3],this.Ch=0|Yr[4],this.Cl=0|Yr[5],this.Dh=0|Yr[6],this.Dl=0|Yr[7],this.Eh=0|Yr[8],this.El=0|Yr[9],this.Fh=0|Yr[10],this.Fl=0|Yr[11],this.Gh=0|Yr[12],this.Gl=0|Yr[13],this.Hh=0|Yr[14],this.Hl=0|Yr[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:i,Dh:o,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,s,i,o,a,c,l,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|s,this.Cl=0|i,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)En[r]=e.getUint32(t),Sn[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|En[e-15],r=0|Sn[e-15],n=nn(t,r,1)^nn(t,r,8)^tn(t,0,7),s=sn(t,r,1)^sn(t,r,8)^rn(t,r,7),i=0|En[e-2],o=0|Sn[e-2],a=nn(i,o,19)^on(i,o,61)^tn(i,0,6),c=sn(i,o,19)^an(i,o,61)^rn(i,o,6),l=hn(s,c,Sn[e-7],Sn[e-16]),u=dn(l,n,a,En[e-7],En[e-16]);En[e]=0|u,Sn[e]=0|l}let{Ah:r,Al:n,Bh:s,Bl:i,Ch:o,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=nn(u,h,14)^nn(u,h,18)^on(u,h,41),b=sn(u,h,14)^sn(u,h,18)^an(u,h,41),w=u&d^~u&f,v=pn(y,b,h&p^~h&g,vn[e],Sn[e]),E=fn(v,m,t,w,wn[e],En[e]),S=0|v,A=nn(r,n,28)^on(r,n,34)^on(r,n,39),I=sn(r,n,28)^an(r,n,34)^an(r,n,39),k=r&s^r&o^s&o,x=n&i^n&a^i&a;m=0|f,y=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=cn(0|c,0|l,0|E,0|S)),c=0|o,l=0|a,o=0|s,a=0|i,s=0|r,i=0|n;const C=ln(S,I,x);r=un(C,E,A,k),n=0|C}({h:r,l:n}=cn(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:i}=cn(0|this.Bh,0|this.Bl,0|s,0|i)),({h:o,l:a}=cn(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l}=cn(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=cn(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=cn(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=cn(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=cn(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(r,n,s,i,o,a,c,l,u,h,d,p,f,g,m,y)}roundClean(){Lr(En,Sn)}destroy(){Lr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const In=Vr(()=>new yn),kn=Vr(()=>new An),xn=In;var Cn,_n,Tn;!function(e){e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"}(Cn||(Cn={})),function(e){e.GENERIC_FAIL="Generic error",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.DECODE_FAILED="Failed to decode",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.ENCODE_FAILED="Failed to encode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.STREAM_ABORTED="Stream aborted",e.RLN_PROOF_GENERATION="Proof generation failed",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics"}(_n||(_n={})),function(e){e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.LOCAL="local-peer-cache"}(Tn||(Tn={}));const Pn="locked",Rn={clusterId:1,shards:[0,1,2,3,4,5,6,7,8]};var On;function Ln(e,t="utf8"){const r=kt[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function Dn(e){return"string"==typeof e?xt(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}!function(e){e.Unhealthy="Unhealthy",e.MinimallyHealthy="MinimallyHealthy",e.SufficientlyHealthy="SufficientlyHealthy"}(On||(On={}));const Nn=e=>Ln(e,"base16"),Mn=e=>Ln(e,"utf8"),Fn=e=>xt(e,"utf8");function Bn(e,t){const r=t??e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(r);let s=0;for(const t of e)n.set(t,s),s+=t.length;return n}const Un=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw new Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw new Error("Invalid clusterId or shard");return{clusterId:r,shard:n}};function $n(e,t=8){const{application:r,version:n}=function(e){const t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid");let r=0;if(6==t.length){if(r=parseInt(t[1]),isNaN(r))throw new Error("Invalid generation field in content topic");if(r>0)throw new Error("Generation greater than 0 is not supported")}const n=t.splice(-4);if(0==n[0].length)throw new Error("Application field cannot be empty");if(0==n[1].length)throw new Error("Version field cannot be empty");if(0==n[2].length)throw new Error("Topic name field cannot be empty");if(0==n[3].length)throw new Error("Encoding field cannot be empty");return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}(e),s=xn(Bn([Fn(r),Fn(n)])),i=new DataView(s.buffer.slice(-8));return Number(i.getBigUint64(0,!1)%BigInt(t))}function qn(e,t){return"string"==typeof t?t:void 0!==t?.shard?(e=>{if(void 0===e.shard)throw new Error("Invalid shard");return`/waku/2/rs/${e.clusterId??1}/${e.shard}`})(t):function(e,t=1,r=8){if(!e)throw Error("Content topic must be specified");return`/waku/2/rs/${t}/${$n(e,r)}`}(e,t?.clusterId??1)}const jn=e=>{if((e=new Uint8Array(e)).length<3)throw new Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,s=7-e%8;t.getUint8(r)&1<<s&&n.push(e)}else{const r=t.getUint8(2);for(let s=0,i=3;s<r;s++,i+=2){if(i+1>=e.length)throw new Error("Unexpected end of data");n.push(t.getUint16(i))}}return{clusterId:r,shards:n}},zn=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,s=new ArrayBuffer(n),i=new DataView(s);if(i.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;i.setUint8(t,i.getUint8(t)|1<<r)}else{i.setUint8(2,r.length);for(let e=0,t=3;e<r.length;e++,t+=2)i.setUint16(t,r[e])}return new Uint8Array(s)};var Kn=__webpack_require__(7833);const Vn="waku";class Hn{_info;_warn;_error;static createDebugNamespace(e,t){return t?`${Vn}:${t}:${e}`:`${Vn}:${e}`}constructor(e){this._info=Kn(Hn.createDebugNamespace("info",e)),this._warn=Kn(Hn.createDebugNamespace("warn",e)),this._error=Kn(Hn.createDebugNamespace("error",e))}get info(){return this._info}get warn(){return this._warn}get error(){return this._error}log(e,...t){(this[e]||this.log)(...t)}}const Gn=new Hn("message:version-0"),Wn=BigInt(1e6);class Xn{pubsubTopic;proto;constructor(e,t){this.pubsubTopic=e,this.proto=t}get ephemeral(){return Boolean(this.proto.ephemeral)}get payload(){return this.proto.payload}get contentTopic(){return this.proto.contentTopic}get timestamp(){try{if(this.proto.timestamp){const e=this.proto.timestamp/Wn;return new Date(Number(e))}return}catch(e){return}}get meta(){return this.proto.meta}get version(){return this.proto.version??0}get rateLimitProof(){return this.proto.rateLimitProof}}class Jn{contentTopic;ephemeral;pubsubTopic;metaSetter;constructor(e,t=!1,r,n){if(this.contentTopic=e,this.ephemeral=t,this.pubsubTopic=r,this.metaSetter=n,!e||""===e)throw new Error("Content topic must be specified")}async toWire(e){return zt.encode(await this.toProtoObj(e))}async toProtoObj(e){const t=e.timestamp??new Date,r={payload:e.payload,version:0,contentTopic:this.contentTopic,timestamp:BigInt(t.valueOf())*Wn,meta:void 0,rateLimitProof:e.rateLimitProof,ephemeral:this.ephemeral};if(this.metaSetter){const e=this.metaSetter(r);return{...r,meta:e}}return r}}function Yn({pubsubTopic:e,pubsubTopicShardInfo:t,contentTopic:r,ephemeral:n,metaSetter:s}){return new Jn(r,n,qn(r,e??t),s)}class Zn{pubsubTopic;contentTopic;constructor(e,t){if(this.pubsubTopic=e,this.contentTopic=t,!t||""===t)throw new Error("Content topic must be specified")}fromWireToProtoObj(e){const t=zt.decode(e);return Promise.resolve({payload:t.payload,contentTopic:t.contentTopic,version:t.version??void 0,timestamp:t.timestamp??void 0,meta:t.meta??void 0,rateLimitProof:t.rateLimitProof??void 0,ephemeral:t.ephemeral??!1})}async fromProtoObj(e,t){return t.version?(Gn.error("Failed to decode due to incorrect version, expected:",0,", actual:",t.version),Promise.resolve(void 0)):new Xn(e,t)}}function Qn(e,t){return new Zn(qn(e,t),e)}const es=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t};function ts(e,t){null==t&&(t=e.reduce((e,t)=>e+t.length,0));const r=g(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function rs(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}const ns=Symbol.for("@achingbrain/uint8arraylist");function ss(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");let r=0;for(const n of e){const e=r+n.byteLength;if(t<e)return{buf:n,index:t-r};r=e}throw new RangeError("index is out of bounds")}function is(e){return Boolean(e?.[ns])}class os{bufs;length;[ns]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!is(r))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!is(r))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=ss(this.bufs,e);return t.buf[t.index]}set(e,t){const r=ss(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else{if(!is(e))throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(let r=0;r<e.length;r++)this.set(t+r,e.get(r))}}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return ts(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:ts(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),s=new os;return s.length=n,s.bufs=[...r],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let s=0;s<this.bufs.length;s++){const i=this.bufs[s],o=n,a=o+i.byteLength;if(n=a,e>=a)continue;const c=e>=o&&e<a,l=t>o&&t<=a;if(c&&l){if(e===o&&t===a){r.push(i);break}const n=e-o;r.push(i.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(i);continue}r.push(i.subarray(e-o))}else{if(l){if(t===a){r.push(i);break}r.push(i.subarray(0,t-o));break}r.push(i)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(is(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e<n;e++)s[r[e]]=e;const i=s,o=this.byteLength-r.byteLength,a=r.byteLength-1;let c;for(let e=t;e<=o;e+=c){c=0;for(let t=a;t>=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-i[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=g(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=f(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=f(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=f(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=g(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=f(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=f(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=f(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=f(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=f(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof os))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!rs(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){const r=new os;return r.bufs=e,null==t&&(t=e.reduce((e,t)=>e+t.byteLength,0)),r.length=t,r}}function as(e){return null!=e[Symbol.asyncIterator]}const cs=e=>{const t=k(e),r=g(t);return _(e,r),cs.bytes=t,r};function ls(e,t){const r=(t=t??{}).lengthEncoder??cs;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return as(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}cs.bytes=0,ls.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??cs;return new os(r(e.byteLength),e)};class us extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class hs extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class ds extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}class ps extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}var fs;!function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(fs||(fs={}));const gs=e=>{const t=T(e);return gs.bytes=k(t),t};function ms(e,t){const r=new os;let n=fs.LENGTH,s=-1;const i=t?.lengthDecoder??gs,o=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===fs.LENGTH)try{if(s=i(r),s<0)throw new us("Invalid message length");if(s>a)throw new hs("Message length too long");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=fs.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw new ds("Message length length too long");break}throw e}if(n===fs.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=fs.LENGTH}}}return as(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new ps("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new ps("Unexpected end of input")}()}function ys(){const e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}gs.bytes=0,ms.fromReader=(e,t)=>{let r=1;return ms(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength:e=>{r=e}})};class bs{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class ws{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new bs(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){if(null!=e?.value&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new bs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class vs extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Es(e={}){return function(e,t){let r,n,s,i=(t=t??{}).onEnd,o=new ws,a=ys();const c=e=>null!=n?n(e):(o.push(e),r),l=e=>{if(s)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},u=e=>s?r:(s=!0,null!=e?(e=>(o=new ws,null!=n?n({error:e}):(o.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return o.isEmpty()?s?{done:!0}:await new Promise((t,s)=>{n=i=>{n=null,o.push(i);try{t(e(o))}catch(e){s(e)}return r}}):e(o)}finally{o.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ys()})}},return:()=>(o=new ws,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return o.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),o.isEmpty())return;let r,n;null!=t&&(r=new Promise((e,r)=>{n=()=>{r(new vs)},t.addEventListener("abort",n)}));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==i)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=i&&(i(e),i=void 0),{done:!0}),return:()=>(h.return(),null!=i&&(i(),i=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=i&&(i(e),i=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}(e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}},e)}class Ss extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}}async function As(e,t,r){if(null==t)return e;if(t.aborted)return e.catch(()=>{}),Promise.reject(new Ss(r?.errorMessage,r?.errorCode,r?.errorName));let n;const s=new Ss(r?.errorMessage,r?.errorCode,r?.errorName);try{return await Promise.race([e,new Promise((e,r)=>{n=()=>{r(s)},t.addEventListener("abort",n)})])}finally{null!=n&&t.removeEventListener("abort",n)}}class Is{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ys(),this.haveNext=ys()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ys(),e}async throw(e){return this.ended=!0,this.error=e,null!=e&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){const e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ys(),await As(this.readNext.promise,t?.signal,t)}}function ks(){return new Is}function xs(e){return null!=e[Symbol.asyncIterator]}const Cs=function(...e){const t=[];for(const r of e)xs(r)||t.push(r);return t.length===e.length?function*(e){for(const t of e)yield*t}(t):async function*(e){const t=new AbortController,r=ks();(async function(e,t,r){try{await Promise.all(e.map(async e=>{for await(const n of e)await t.push(n,{signal:r}),r.throwIfAborted()})),await t.end(void 0,{signal:r})}catch(e){await t.end(e,{signal:r}).catch(()=>{})}})(e,r,t.signal).catch(()=>{});try{yield*r}finally{t.abort()}}(e)};function _s(e,...t){if(null==e)throw new Error("Empty pipeline");if(Os(e)){const t=e;e=()=>t.source}else if(Rs(e)||Ps(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&Os(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e<r.length-1;e++)Os(r[e])&&(r[e]=Ls(r[e]));return Ts(...r)}const Ts=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},Ps=e=>null!=e?.[Symbol.asyncIterator],Rs=e=>null!=e?.[Symbol.iterator],Os=e=>null!=e&&null!=e.sink&&null!=e.source,Ls=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=Es({objectMode:!0});let n;r.then(()=>{t.end()},e=>{t.end(e)});const s=e.source;if(Ps(s))n=async function*(){yield*s,t.end()};else{if(!Rs(s))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*s,t.end()}}return Cs(t,n())}return e.source};function Ds(e){return e.filter(e=>"open"===e.status).sort((e,t)=>t.timeline.open-e.timeline.open).at(0)}const Ns="consumed";class Ms{multicodec;libp2p;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t){this.multicodec=e,this.libp2p=t,this.log=new Hn(`stream-manager:${e}`),this.libp2p.events.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){const t=e.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);let n=this.getOpenStreamForCodec(e);return n?(this.log.info(`Found existing stream peerId=${t} multicodec=${this.multicodec}`),this.lockStream(t,n),n):(n=await this.createStream(e),this.lockStream(t,n),n)}async createStream(e,t=0){const r=Ds(this.libp2p.connectionManager.getConnections(e));if(!r)throw new Error(`Failed to get a connection to the peer peerId=${e.toString()} multicodec=${this.multicodec}`);let n,s;for(let i=0;i<t+1;i++)try{this.log.info(`Attempting to create a stream for peerId=${e.toString()} multicodec=${this.multicodec}`),s=await r.newStream(this.multicodec),this.log.info(`Created stream for peerId=${e.toString()} multicodec=${this.multicodec}`);break}catch(e){n=e}if(!s)throw new Error(`Failed to create a new stream for ${e.toString()} -- `+n);return s}async createStreamWithLock(e){const t=e.id.toString();if(this.ongoingCreation.has(t))this.log.info(`Skipping creation of a stream due to lock for peerId=${t} multicodec=${this.multicodec}`);else try{this.ongoingCreation.add(t),await this.createStream(e.id)}catch(e){this.log.error("Failed to createStreamWithLock:",e)}finally{this.ongoingCreation.delete(t)}}handlePeerUpdateStreamPool=e=>{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=Ds(this.libp2p.connectionManager.getConnections(e));if(!t)return;const r=t.streams.find(e=>e.protocol===this.multicodec);return r?["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void 0:r:void 0}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[Ns]=!0}isStreamLocked(e){return!!e.metadata[Ns]}}const Fs={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let Bs;const Us=new Uint8Array(16);function $s(){if(!Bs&&(Bs="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Bs))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Bs(Us)}const qs=[];for(let e=0;e<256;++e)qs.push((e+256).toString(16).slice(1));const js=function(e,t,r){if(Fs.randomUUID&&!t&&!e)return Fs.randomUUID();const n=(e=e||{}).random||(e.rng||$s)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(let e=0;e<16;++e)t[r+e]=n[e];return t}return function(e,t=0){return qs[e[t+0]]+qs[e[t+1]]+qs[e[t+2]]+qs[e[t+3]]+"-"+qs[e[t+4]]+qs[e[t+5]]+"-"+qs[e[t+6]]+qs[e[t+7]]+"-"+qs[e[t+8]]+qs[e[t+9]]+"-"+qs[e[t+10]]+qs[e[t+11]]+qs[e[t+12]]+qs[e[t+13]]+qs[e[t+14]]+qs[e[t+15]]}(n)};class zs{proto;constructor(e){this.proto=e}static decode(e){const t=Zt.decode(e);return new zs(t)}encode(){return Zt.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class Ks{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new Ks({requestId:js(),filterSubscribeType:Jt.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new Ks({requestId:js(),filterSubscribeType:Jt.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new Ks({requestId:js(),filterSubscribeType:Jt.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new Ks({requestId:js(),filterSubscribeType:Jt.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const t=Jt.decode(e);return new Ks(t)}encode(){return Jt.encode(this.proto)}get filterSubscribeType(){return this.proto.filterSubscribeType}get requestId(){return this.proto.requestId}get pubsubTopic(){return this.proto.pubsubTopic}get contentTopics(){return this.proto.contentTopics}}class Vs{proto;constructor(e){this.proto=e}static decode(e){const t=Yt.decode(e);return new Vs(t)}encode(){return Yt.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const Hs=new Hn("filter-core"),Gs="/vac/waku/filter-subscribe/2.0.0-beta1",Ws="/vac/waku/filter-push/2.0.0-beta1";class Xs{handleIncomingMessage;streamManager;multicodec=Gs;constructor(e,t){this.handleIncomingMessage=e,this.streamManager=new Ms(Gs,t.components),t.handle(Ws,this.onRequest.bind(this),{maxInboundStreams:100}).catch(e=>{Hs.error("Failed to register ",Ws,e)})}async subscribe(e,t,r){const n=await this.streamManager.getStream(t),s=Ks.createSubscribeRequest(e,r);let i;try{if(i=await _s([s.encode()],ls,n,ms,async e=>await es(e)),!i?.length)throw Error("Received no response from subscription request.")}catch(e){return Hs.error("Failed to send subscribe request",e),{success:null,failure:{error:_n.GENERIC_FAIL,peerId:t}}}const{statusCode:o,requestId:a,statusDesc:c}=Vs.decode(i[0].slice());return o<200||o>=300?(Hs.error(`Filter subscribe request ${a} failed with status code ${o}: ${c}`),{failure:{error:_n.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async unsubscribe(e,t,r){let n;try{n=await this.streamManager.getStream(t)}catch(e){return Hs.error(`Failed to get a stream for remote peer${t.toString()}`,e),{success:null,failure:{error:_n.NO_STREAM_AVAILABLE,peerId:t}}}const s=Ks.createUnsubscribeRequest(e,r);try{await _s([s.encode()],ls,n.sink)}catch(e){return Hs.error("Failed to send unsubscribe request",e),{success:null,failure:{error:_n.GENERIC_FAIL,peerId:t}}}return{success:t,failure:null}}async unsubscribeAll(e,t){const r=await this.streamManager.getStream(t),n=Ks.createUnsubscribeAllRequest(e),s=await _s([n.encode()],ls,r,ms,async e=>await es(e));if(!s||!s.length)return{failure:{error:_n.NO_RESPONSE,peerId:t},success:null};const{statusCode:i,requestId:o,statusDesc:a}=Vs.decode(s[0].slice());return i<200||i>=300?(Hs.error(`Filter unsubscribe all request ${o} failed with status code ${i}: ${a}`),{failure:{error:_n.REMOTE_PEER_REJECTED,peerId:t},success:null}):{failure:null,success:t}}async ping(e){let t;try{t=await this.streamManager.getStream(e)}catch(t){return Hs.error(`Failed to get a stream for remote peer${e.toString()}`,t),{success:null,failure:{error:_n.NO_STREAM_AVAILABLE,peerId:e}}}const r=Ks.createSubscriberPingRequest();let n;try{n=await _s([r.encode()],ls,t,ms,async e=>await es(e))}catch(t){return Hs.error("Failed to send ping request",t),{success:null,failure:{error:_n.GENERIC_FAIL,peerId:e}}}if(!n||!n.length)return{success:null,failure:{error:_n.NO_RESPONSE,peerId:e}};const{statusCode:s,requestId:i,statusDesc:o}=Vs.decode(n[0].slice());return s<200||s>=300?(Hs.error(`Filter ping request ${i} failed with status code ${s}: ${o}`),{success:null,failure:{error:_n.REMOTE_PEER_REJECTED,peerId:e}}):{success:e,failure:null}}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;Hs.info(`Received message from ${n.toString()}`);try{_s(r,ms,async e=>{for await(const r of e){const e=zs.decode(r.slice()),{pubsubTopic:n,wakuMessage:s}=e;if(!s)return void Hs.error("Received empty message");if(!n)return void Hs.error("Pubsub topic missing from push message");await this.handleIncomingMessage(n,s,t.remotePeer.toString())}}).then(()=>{Hs.info("Receiving pipe closed.")},async e=>{Hs.error(`Error with receiving pipe on peer:${t.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,e)})}catch(e){Hs.error("Error decoding message",e)}}}class Js{proto;constructor(e){this.proto=e}static createRequest(e,t){return new Js({requestId:js(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=nr.decode(e);return new Js(t)}encode(){return nr.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const Ys=new Hn("light-push"),Zs="/vac/waku/lightpush/2.0.0-beta1";class Qs{streamManager;multicodec=Zs;constructor(e){this.streamManager=new Ms(Zs,e.components)}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return Ys.error("Failed to send waku light push: payload is empty"),{query:null,error:_n.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return Ys.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:_n.SIZE_TOO_BIG};const r=await e.toProtoObj(t);return r?{query:Js.createRequest(r,e.pubsubTopic),error:null}:(Ys.error("Failed to encode to protoMessage, aborting push"),{query:null,error:_n.ENCODE_FAILED})}catch(e){return Ys.error("Failed to prepare push message",e),{query:null,error:_n.GENERIC_FAIL}}}async send(e,t,r){const{query:n,error:s}=await this.preparePushMessage(e,t);if(s||!n)return{success:null,failure:{error:s,peerId:r}};let i,o;try{i=await this.streamManager.getStream(r)}catch(e){return Ys.error("Failed to get stream",e),{success:null,failure:{error:_n.NO_STREAM_AVAILABLE,peerId:r}}}try{o=await _s([n.encode()],ls,i,ms,async e=>await es(e))}catch(e){return Ys.error("Failed to send waku light push request",e),{success:null,failure:{error:_n.STREAM_ABORTED,peerId:r}}}const a=new os;let c;o.forEach(e=>{a.append(e)});try{c=Js.decode(a).response}catch(e){return Ys.error("Failed to decode push reply",e),{success:null,failure:{error:_n.DECODE_FAILED,peerId:r}}}return c?(l=c.info)&&(l.includes("could not generate rln proof")||l.includes("could not get new message id to generate an rln proof")||l.includes("RLN validation failed"))?(Ys.error("Remote peer fault: RLN generation"),{success:null,failure:{error:_n.RLN_PROOF_GENERATION,peerId:r}}):c.isSuccess?{success:r,failure:null}:(Ys.error("Remote peer rejected the message: ",c.info),{success:null,failure:{error:_n.REMOTE_PEER_REJECTED,peerId:r}}):(Ys.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:_n.NO_RESPONSE,peerId:r}});var l}}const ei={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},ti=1e6;class ri{proto;constructor(e){this.proto=e}static create(e){const t=new ri({...e,contentTopics:e.contentTopics||[],requestId:js(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*ti):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*ti):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0}),r=e.messageHashes&&e.messageHashes.length>0,n=e.contentTopics&&e.contentTopics.length>0,s=e.timeStart||e.timeEnd;if(r){if(n||s)throw new Error("Message hash lookup queries cannot include content filter criteria (contentTopics, timeStart, or timeEnd)")}else if(e.pubsubTopic&&(!e.contentTopics||0===e.contentTopics.length)||!e.pubsubTopic&&e.contentTopics&&e.contentTopics.length>0)throw new Error("Both pubsubTopic and contentTopics must be set together for content-filtered queries");return t}static decode(e){const t=lr.decode(e);return new ri(t)}encode(){return lr.encode(this.proto)}}class ni{proto;constructor(e){this.proto=e}static decode(e){const t=ur.decode(e);return new ni(t)}encode(){return ur.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const si=new Hn("store"),ii="/vac/waku/store-query/3.0.0";class oi{streamManager;multicodec=ii;constructor(e){this.streamManager=new Ms(ii,e.components)}async*queryPerPage(e,t,r){if(!(e.messageHashes&&e.messageHashes.length>0)&&e.contentTopics&&e.contentTopics.toString()!==Array.from(t.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let n=e.paginationCursor;for(;;){const s=ri.create({...e,paginationCursor:n});let i;si.info("Sending store query request:",{hasMessageHashes:!!e.messageHashes?.length,messageHashCount:e.messageHashes?.length,pubsubTopic:e.pubsubTopic,contentTopics:e.contentTopics});try{i=await this.streamManager.getStream(r)}catch(e){si.error("Failed to get stream",e);break}const o=await _s([s.encode()],ls,i,ms,async e=>await es(e)),a=new os;o.forEach(e=>{a.append(e)});const c=ni.decode(a);if(!c.statusCode||c.statusCode>=300){const e=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw si.error(e),new Error(e)}if(!c.messages||!c.messages.length){si.warn("Stopping pagination due to empty messages in response");break}si.info(`${c.messages.length} messages retrieved from store`);const l=c.messages.map(e=>{if(!e.message)return Promise.resolve(void 0);const r=e.message.contentTopic;if(r){const s=t.get(r);if(s)return s.fromProtoObj(e.pubsubTopic||"",(n=e.message,{...ei,...n}))}var n;return Promise.resolve(void 0)});if(yield l,n=e.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(e.paginationLimit||20))break}}}const ai=new Hn("connection-limiter");class ci{libp2p;events;networkMonitor;dialer;connectionMonitorInterval=null;options;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.networkMonitor=e.networkMonitor,this.dialer=e.dialer,this.options=e.options,this.onWakuConnectionEvent=this.onWakuConnectionEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this)}start(){this.dialPeersFromStore(),this.options.enableAutoRecovery&&null===this.connectionMonitorInterval&&(this.connectionMonitorInterval=setInterval(()=>{this.maintainConnections()},5e3)),this.events.addEventListener("waku:connection",this.onWakuConnectionEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent)}stop(){this.events.removeEventListener("waku:connection",this.onWakuConnectionEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent),this.connectionMonitorInterval&&(clearInterval(this.connectionMonitorInterval),this.connectionMonitorInterval=null)}onWakuConnectionEvent(){this.options.enableAutoRecovery?this.networkMonitor.isBrowserConnected()&&this.dialPeersFromStore():ai.info("Auto recovery is disabled, skipping")}async maintainConnections(){await this.maintainConnectionsCount(),await this.maintainBootstrapConnections()}async onDisconnectedEvent(){0===this.libp2p.getConnections().length&&(ai.info("No connections, dialing peers from store"),await this.dialPeersFromStore())}async maintainConnectionsCount(){ai.info("Maintaining connections count");const e=this.libp2p.getConnections();if(e.length<=this.options.maxConnections){ai.info(`Node has less than max connections ${this.options.maxConnections}, trying to dial more peers`);const t=await this.getPrioritizedPeers();if(0===t.length)return void ai.info("No peers to dial, node is utilizing all known peers");const r=t.slice(0,this.options.maxConnections-e.length).map(e=>this.dialer.dial(e.id));return void await Promise.all(r)}ai.info(`Node has more than max connections ${this.options.maxConnections}, dropping connections`);try{const t=e.filter(e=>!e.tags.includes(Pn)).slice(this.options.maxConnections);if(0===t.length)return void ai.info("No connections to drop, skipping");const r=t.map(e=>this.libp2p.hangUp(e.remotePeer));await Promise.all(r),ai.info(`Dropped ${t.length} connections`)}catch(e){ai.error("Unexpected error while maintaining connections",e)}}async maintainBootstrapConnections(){ai.info("Maintaining bootstrap connections");const e=await this.getBootstrapPeers();if(!(e.length<=this.options.maxBootstrapPeers))try{const t=e.slice(this.options.maxBootstrapPeers);ai.info(`Dropping ${t.length} bootstrap connections because node has more than max bootstrap connections ${this.options.maxBootstrapPeers}`);const r=t.map(e=>this.libp2p.hangUp(e.id));await Promise.all(r),ai.info(`Dropped ${t.length} bootstrap connections`)}catch(e){ai.error("Unexpected error while maintaining bootstrap connections",e)}}async dialPeersFromStore(){ai.info("Dialing peers from store");try{const e=await this.getPrioritizedPeers();if(0===e.length)return void ai.info("No peers to dial, skipping");const t=e.map(e=>this.dialer.dial(e.id));ai.info(`Dialing ${e.length} peers from store`),await Promise.all(t),ai.info(`Dialed ${t.length} peers from store`)}catch(e){ai.error("Unexpected error while dialing peer store peers",e)}}async getPrioritizedPeers(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections();ai.info(`Found ${e.length} peers in store, and found ${t.length} connections`);const r=e.filter(e=>!t.some(t=>t.remotePeer.equals(e.id))&&e.addresses.some(e=>e.multiaddr.toString().includes("wss")||e.multiaddr.toString().includes("ws")));return[...r.filter(e=>e.tags.has(Tn.BOOTSTRAP)),...r.filter(e=>e.tags.has(Tn.PEER_EXCHANGE)),...r.filter(e=>e.tags.has(Tn.LOCAL))]}async getBootstrapPeers(){return(await Promise.all(this.libp2p.getConnections().map(e=>e.remotePeer).map(e=>this.getPeer(e)))).filter(e=>e&&e.tags.has(Tn.BOOTSTRAP))}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return ai.error(`Failed to get peer ${e}, error: ${t}`),null}}}const li=new Hn("dialer");class ui{libp2p;shardReader;options;dialingQueue=[];dialHistory=new Map;failedDials=new Map;dialingInterval=null;isProcessing=!1;isImmediateDialing=!1;constructor(e){this.libp2p=e.libp2p,this.shardReader=e.shardReader,this.options=e.options}start(){li.info("Starting dialer"),this.dialingInterval||(this.dialingInterval=setInterval(()=>{this.processQueue()},500)),this.dialHistory.clear(),this.failedDials.clear()}stop(){li.info("Stopping dialer"),this.dialingInterval&&(clearInterval(this.dialingInterval),this.dialingInterval=null),this.dialHistory.clear(),this.failedDials.clear()}async dial(e){if(await this.shouldSkipPeer(e))return void li.info(`Skipping peer: ${e}`);const t=0===this.dialingQueue.length,r=!this.isProcessing&&!this.isImmediateDialing;t&&r?(this.isImmediateDialing=!0,li.info("Dialed peer immediately"),await this.dialPeer(e),this.isImmediateDialing=!1,li.info("Released immediate dial lock")):(this.dialingQueue.push(e),li.info(`Added peer to dialing queue, queue size: ${this.dialingQueue.length}`))}async processQueue(){if(0!==this.dialingQueue.length&&!this.isProcessing){this.isProcessing=!0;try{const e=this.dialingQueue.slice(0,this.options.maxDialingPeers);this.dialingQueue=this.dialingQueue.slice(e.length),li.info(`Processing dial queue: dialing ${e.length} peers, ${this.dialingQueue.length} remaining in queue`),await Promise.all(e.map(e=>this.dialPeer(e)))}finally{this.isProcessing=!1}}}async dialPeer(e){try{li.info(`Dialing peer from queue: ${e}`),await this.libp2p.dial(e),this.dialHistory.set(e.toString(),Date.now()),this.failedDials.delete(e.toString()),li.info(`Successfully dialed peer from queue: ${e}`)}catch(t){li.error(`Error dialing peer ${e}`,t),this.failedDials.set(e.toString(),Date.now())}}async shouldSkipPeer(e){if(this.libp2p.getPeers().some(t=>t.equals(e)))return li.info(`Skipping peer ${e} - already connected`),!0;if(this.isRecentlyDialed(e))return li.info(`Skipping peer ${e} - already dialed in the last 10 seconds`),!0;if(this.isRecentlyFailed(e))return li.info(`Skipping peer ${e} - recently failed to dial`),!0;try{return await this.shardReader.hasShardInfo(e)?!await this.shardReader.isPeerOnNetwork(e)&&(li.info(`Skipping peer ${e} - not on same shard`),!0):(li.info(`Skipping peer ${e} - no shard info`),!1)}catch(t){return li.error(`Error checking shard info for peer ${e}`,t),!0}}isRecentlyDialed(e){const t=this.dialHistory.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.dialCooldown)}isRecentlyFailed(e){const t=this.failedDials.get(e.toString());return!!(t&&Date.now()-t<1e3*this.options.failedDialCooldown)}}const hi=new Hn("discovery-dialer");class di{libp2p;dialer;constructor(e){this.libp2p=e.libp2p,this.dialer=e.dialer,this.onPeerDiscovery=this.onPeerDiscovery.bind(this)}start(){this.libp2p.addEventListener("peer:discovery",this.onPeerDiscovery)}stop(){this.libp2p.removeEventListener("peer:discovery",this.onPeerDiscovery)}async onPeerDiscovery(e){const t=e.detail.id;hi.info(`Discovered new peer: ${t}`);try{await this.updatePeerStore(t,e.detail.multiaddrs),await this.dialer.dial(t)}catch(e){hi.error(`Error dialing peer ${t}`,e)}}async updatePeerStore(e,t){try{hi.info(`Updating peer store for ${e}`);const r=await this.getPeer(e);if(!r)return hi.info(`Peer ${e} not found in store, saving`),void await this.libp2p.peerStore.save(e,{multiaddrs:t});if(t.every(e=>r.addresses.some(t=>t.multiaddr.equals(e))))return void hi.info(`Peer ${e} has same addresses in peer store, skipping`);hi.info(`Merging peer ${e} addresses in peer store`),await this.libp2p.peerStore.merge(e,{multiaddrs:t})}catch(t){hi.error(`Error updating peer store for ${e}`,t)}}async getPeer(e){try{return await this.libp2p.peerStore.get(e)}catch(t){return void hi.error(`Error getting peer info for ${e}`,t)}}}const pi=new Hn("keep-alive");class fi{relay;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:e,relay:t,libp2p:r}){this.options=e,this.relay=t,this.libp2p=r,this.onPeerConnect=this.onPeerConnect.bind(this),this.onPeerDisconnect=this.onPeerDisconnect.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onPeerConnect),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnect)}stop(){this.libp2p.removeEventListener("peer:connect",this.onPeerConnect),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnect);for(const e of this.pingKeepAliveTimers.values())clearInterval(e);for(const e of this.relayKeepAliveTimers.values())for(const t of e)clearInterval(t);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}onPeerConnect(e){const t=e.detail;this.startPingForPeer(t)}onPeerDisconnect(e){const t=e.detail;this.stopPingForPeer(t)}startPingForPeer(e){this.stopPingForPeer(e),this.startLibp2pPing(e),this.startRelayPing(e)}stopPingForPeer(e){this.stopLibp2pPing(e),this.stopRelayPing(e)}startLibp2pPing(e){if(0===this.options.pingKeepAlive)return void pi.warn(`Ping keep alive is disabled pingKeepAlive:${this.options.pingKeepAlive}, skipping start for libp2p ping`);const t=e.toString();if(this.pingKeepAliveTimers.has(t))return void pi.warn(`Ping already started for peer: ${t}, skipping start for libp2p ping`);const r=setInterval(()=>{this.pingLibp2p(e)},1e3*this.options.pingKeepAlive);this.pingKeepAliveTimers.set(t,r)}stopLibp2pPing(e){const t=e.toString();this.pingKeepAliveTimers.has(t)?(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)):pi.warn(`Ping not started for peer: ${t}, skipping stop for ping`)}startRelayPing(e){if(!this.relay)return;if(0===this.options.relayKeepAlive)return void pi.warn(`Relay keep alive is disabled relayKeepAlive:${this.options.relayKeepAlive}, skipping start for relay ping`);if(this.relayKeepAliveTimers.has(e.toString()))return void pi.warn(`Relay ping already started for peer: ${e.toString()}, skipping start for relay ping`);const t=[];for(const r of this.relay.pubsubTopics){if(!this.relay.getMeshPeers(r).includes(e.toString())){pi.warn(`Peer: ${e.toString()} is not in the mesh for topic: ${r}, skipping start for relay ping`);continue}const n=Yn({pubsubTopicShardInfo:Un(r),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),s=setInterval(()=>{this.pingRelay(n)},1e3*this.options.relayKeepAlive);t.push(s)}this.relayKeepAliveTimers.set(e.toString(),t)}stopRelayPing(e){if(!this.relay)return;const t=e.toString();this.relayKeepAliveTimers.has(t)?(this.relayKeepAliveTimers.get(t)?.map(clearInterval),this.relayKeepAliveTimers.delete(t)):pi.warn(`Relay ping not started for peer: ${t}, skipping stop for relay ping`)}async pingRelay(e){try{pi.info("Sending Waku Relay ping message"),await this.relay.send(e,{payload:new Uint8Array([1])})}catch(e){pi.error("Failed to send relay ping",e)}}async pingLibp2p(e){try{pi.info(`Pinging libp2p peer (${e.toString()})`);const t=await this.libp2p.services.ping.ping(e);pi.info(`Ping succeeded (${e.toString()})`,t),await this.libp2p.peerStore.merge(e,{metadata:{ping:Fn(t.toString())}}),pi.info(`Ping updated for peer (${e.toString()})`)}catch(t){pi.error(`Ping failed for peer (${e.toString()})`,t)}}}class gi{libp2p;events;isNetworkConnected=!1;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onConnectedEvent=this.onConnectedEvent.bind(this),this.onDisconnectedEvent=this.onDisconnectedEvent.bind(this),this.dispatchNetworkEvent=this.dispatchNetworkEvent.bind(this)}start(){this.libp2p.addEventListener("peer:connect",this.onConnectedEvent),this.libp2p.addEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.addEventListener("online",this.dispatchNetworkEvent),globalThis.addEventListener("offline",this.dispatchNetworkEvent)}catch(e){}}stop(){this.libp2p.removeEventListener("peer:connect",this.onConnectedEvent),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnectedEvent);try{globalThis.removeEventListener("online",this.dispatchNetworkEvent),globalThis.removeEventListener("offline",this.dispatchNetworkEvent)}catch(e){}}isConnected(){return!!this.isBrowserConnected()&&this.isP2PConnected()}isP2PConnected(){return this.isNetworkConnected}isBrowserConnected(){try{if(globalThis?.navigator&&!globalThis?.navigator?.onLine)return!1}catch(e){}return!0}onConnectedEvent(){this.isNetworkConnected||(this.isNetworkConnected=!0,this.dispatchNetworkEvent())}onDisconnectedEvent(){this.isNetworkConnected&&0===this.libp2p.getConnections().length&&(this.isNetworkConnected=!1,this.dispatchNetworkEvent())}dispatchNetworkEvent(){this.events.dispatchEvent(new CustomEvent("waku:connection",{detail:this.isConnected()}))}}const mi=new Hn("shard-reader");class yi{libp2p;staticShard;constructor(e){this.libp2p=e.libp2p,this.staticShard=this.getStaticShardFromNetworkConfig(e.networkConfig)}async isPeerOnNetwork(e){const t=await this.getShardInfo(e);if(!t)return!1;const r=t.clusterId===this.staticShard.clusterId,n=this.staticShard.shards.some(e=>t.shards.includes(e));return r&&n}async hasShardInfo(e){return!!await this.getShardInfo(e)}async isPeerOnTopic(e,t){try{const r=Un(t);return await this.isPeerOnShard(e,r)}catch(r){return mi.error(`Error comparing pubsub topic ${t} with shard info for ${e}`,r),!1}}async isPeerOnShard(e,t){const r=await this.getShardInfo(e);return!(!r||void 0===t.shard)&&r.clusterId===t.clusterId&&r.shards.includes(t.shard)}async getShardInfo(e){try{const t=(await this.libp2p.peerStore.get(e)).metadata.get("shardInfo");if(!t)return;return jn(t)}catch(t){return void mi.error(`Error getting shard info for ${e}`,t)}}getStaticShardFromNetworkConfig(e){if("shards"in e)return e;const t=e.contentTopics.map(e=>$n(e));return{clusterId:e.clusterId,shards:t}}}const bi=Symbol.for("@libp2p/peer-id");function wi(e){return Boolean(e?.[bi])}class vi extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class Ei extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}class Si extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}}class Ai extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Ii extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class ki extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}Error;class xi extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}}class Ci extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class _i extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class Ti extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class Pi extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class Ri extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class Oi extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}}class Li extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}class Di extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}}class Ni extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class Mi extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class Fi extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class Bi extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}class Ui extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}}class $i extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}}class qi extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}Error;class ji extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}Error;class zi extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class Ki extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class Vi extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class Hi extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}Error;const Gi=parseInt("11111",2),Wi=parseInt("10000000",2),Xi=parseInt("01111111",2),Ji={0:Qi,1:Qi,2:function(e,t){const r=Zi(e,t),n=t.offset,s=t.offset+r,i=[];for(let t=n;t<s;t++)t===n&&0===e[t]||i.push(e[t]);return t.offset+=r,Uint8Array.from(i)},3:function(e,t){const r=Zi(e,t),n=e[t.offset];t.offset++;const s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw new Error("Unused bits in bit string is unimplemented");return s},4:function(e,t){const r=Zi(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:function(e,t){return t.offset++,null},6:function(e,t){const r=Zi(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let i=0,o=0;s<40?(i=0,o=s):s<80?(i=1,o=s-40):(i=2,o=s-80);let a=`${i}.${o}`,c=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,c.push(127&r),r<128){c.reverse();let e=0;for(let t=0;t<c.length;t++)e+=c[t]<<7*t;a+=`.${e}`,c=[]}}return a},16:Qi,22:Qi,48:Qi};function Yi(e,t={offset:0}){const r=e[t.offset]&Gi;if(t.offset++,null!=Ji[r])return Ji[r](e,t);throw new Error("No decoder for tag "+r)}function Zi(e,t){let r=0;if((e[t.offset]&Wi)===Wi){const n=e[t.offset]Ξlet s="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function Qi(e,t){Zi(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=Yi(e,t);if(null===n)break;r.push(n)}return r}function eo(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new os;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new os(Uint8Array.from([t.byteLength|Wi]),t)}function to(e){const t=new os;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new os(Uint8Array.from([2]),eo(t),t)}function ro(e){const t=Uint8Array.from([0]),r=new os(t,e);return new os(Uint8Array.from([3]),eo(r),r)}function no(e,t=48){const r=new os;for(const t of e)r.append(t);return new os(Uint8Array.from([t]),eo(r),r)}class so{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){var e;return null==this._raw&&(this._raw=(e=this.jwk,no([to(Uint8Array.from([1])),no([fo(e.crv)],160),no([ro(new os(Uint8Array.from([4]),xt(e.x??"","base64url"),xt(e.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return at.digest(Kc(this))}toCID(){return mt.createV1(114,this.toMultihash())}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){const s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}class io{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new so({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){var e,t;return null==this._raw&&(this._raw=(e=this.jwk,no([to(Uint8Array.from([1])),(t=xt(e.d??"","base64url"),new os(Uint8Array.from([4]),eo(t),t)),no([fo(e.crv)],160),no([ro(new os(Uint8Array.from([4]),xt(e.x??"","base64url"),xt(e.y??"","base64url")))],161)]).subarray())),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}async sign(e,t){return async function(e,t,r){const n=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["sign"]);r?.signal?.throwIfAborted();const s=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,t.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}(this.jwk,e,t)}}const oo=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ao=Uint8Array.from([6,5,43,129,4,0,34]),co=Uint8Array.from([6,5,43,129,4,0,35]),lo={ext:!0,kty:"EC",crv:"P-256"},uo={ext:!0,kty:"EC",crv:"P-384"},ho={ext:!0,kty:"EC",crv:"P-521"};function po(e){return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=Ln(t.subarray(1,33),"base64url"),n=Ln(t.subarray(33),"base64url"),new so({...lo,key_ops:["verify"],x:r,y:n});if(97===t.byteLength)return r=Ln(t.subarray(1,49),"base64url"),n=Ln(t.subarray(49),"base64url"),new so({...uo,key_ops:["verify"],x:r,y:n});if(133===t.byteLength)return r=Ln(t.subarray(1,67),"base64url"),n=Ln(t.subarray(67),"base64url"),new so({...ho,key_ops:["verify"],x:r,y:n});throw new Ai(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(Yi(e))}function fo(e){if("P-256"===e)return oo;if("P-384"===e)return ao;if("P-521"===e)return co;throw new Ai(`Invalid curve ${e}`)}function go(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const mo=BigInt(0),yo=BigInt(1);function bo(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function wo(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function vo(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?mo:BigInt("0x"+e)}function Eo(e){return vo(Br(e))}function So(e){return Pr(e),vo(Br(Uint8Array.from(e).reverse()))}function Ao(e,t){return $r(e.toString(16).padStart(2*t,"0"))}function Io(e,t){return Ao(e,t).reverse()}function ko(e,t,r){let n;if("string"==typeof t)try{n=$r(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!_r(t))throw new Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const s=n.length;if("number"==typeof r&&s!==r)throw new Error(e+" of length "+r+" expected, got "+s);return n}const xo=e=>"bigint"==typeof e&&mo<=e;function Co(e,t,r,n){if(!function(e,t,r){return xo(e)&&xo(t)&&xo(r)&&t<=e&&e<r}(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function _o(e){let t;for(t=0;e>mo;e>>=yo,t+=1);return t}const To=e=>(yo<<BigInt(e))-yo;function Po(e,t,r={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function n(t,r,n){const s=e[t];if(n&&void 0===s)return;const i=typeof s;if(i!==r||null===s)throw new Error(`param "${t}" is invalid: expected ${r}, got ${i}`)}Object.entries(t).forEach(([e,t])=>n(e,t,!1)),Object.entries(r).forEach(([e,t])=>n(e,t,!0))}function Ro(e){const t=new WeakMap;return(r,...n)=>{const s=t.get(r);if(void 0!==s)return s;const i=e(r,...n);return t.set(r,i),i}}const Oo=BigInt(0),Lo=BigInt(1),Do=BigInt(2),No=BigInt(3),Mo=BigInt(4),Fo=BigInt(5),Bo=BigInt(7),Uo=BigInt(8),$o=BigInt(9),qo=BigInt(16);function jo(e,t){const r=e%t;return r>=Oo?r:t+r}function zo(e,t,r){let n=e;for(;t-- >Oo;)n*=n,n%=r;return n}function Ko(e,t){if(e===Oo)throw new Error("invert: expected non-zero number");if(t<=Oo)throw new Error("invert: expected positive modulus, got "+t);let r=jo(e,t),n=t,s=Oo,i=Lo,o=Lo,a=Oo;for(;r!==Oo;){const e=n/r,t=n%r,c=s-o*e,l=i-a*e;n=r,r=t,s=o,i=a,o=c,a=l}if(n!==Lo)throw new Error("invert: does not exist");return jo(s,t)}function Vo(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Ho(e,t){const r=(e.ORDER+Lo)/Mo,n=e.pow(t,r);return Vo(e,n,t),n}function Go(e,t){const r=(e.ORDER-Fo)/Uo,n=e.mul(t,Do),s=e.pow(n,r),i=e.mul(t,s),o=e.mul(e.mul(i,Do),s),a=e.mul(i,e.sub(o,e.ONE));return Vo(e,a,t),a}function Wo(e){if(e<No)throw new Error("sqrt is not defined for small field");let t=e-Lo,r=0;for(;t%Do===Oo;)t/=Do,r++;let n=Do;const s=Qo(e);for(;1===Zo(s,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return Ho;let i=s.pow(n,t);const o=(t+Lo)/Do;return function(e,n){if(e.is0(n))return n;if(1!==Zo(e,n))throw new Error("Cannot find square root");let s=r,a=e.mul(e.ONE,i),c=e.pow(n,t),l=e.pow(n,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,r=e.sqr(c);for(;!e.eql(r,e.ONE);)if(t++,r=e.sqr(r),t===s)throw new Error("Cannot find square root");const n=Lo<<BigInt(s-t-1),i=e.pow(a,n);s=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}const Xo=(e,t)=>(jo(e,t)&Lo)===Lo,Jo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yo(e,t,r=!1){const n=new Array(t.length).fill(r?e.ZERO:void 0),s=t.reduce((t,r,s)=>e.is0(r)?t:(n[s]=t,e.mul(t,r)),e.ONE),i=e.inv(s);return t.reduceRight((t,r,s)=>e.is0(r)?t:(n[s]=e.mul(t,n[s]),e.mul(t,r)),i),n}function Zo(e,t){const r=(e.ORDER-Lo)/Do,n=e.pow(t,r),s=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Qo(e,t,r=!1,n={}){if(e<=Oo)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,i,o,a=!1;if("object"==typeof t&&null!=t){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(s=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(r=e.isLE),"boolean"==typeof e.modOnDecode&&(a=e.modOnDecode),o=e.allowedLengths}else"number"==typeof t&&(s=t),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=function(e,t){void 0!==t&&Tr(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}(e,s);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:l,MASK:To(c),ZERO:Oo,ONE:Lo,allowedLengths:o,create:t=>jo(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Oo<=t&&t<e},is0:e=>e===Oo,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&Lo)===Lo,neg:t=>jo(-t,e),eql:(e,t)=>e===t,sqr:t=>jo(t*t,e),add:(t,r)=>jo(t+r,e),sub:(t,r)=>jo(t-r,e),mul:(t,r)=>jo(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Oo)throw new Error("invalid exponent, negatives unsupported");if(r===Oo)return e.ONE;if(r===Lo)return t;let n=e.ONE,s=t;for(;r>Oo;)r&Lo&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Lo;return n}(h,e,t),div:(t,r)=>jo(t*Ko(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Ko(t,e),sqrt:i||(t=>{return u||(u=(r=e)%Mo===No?Ho:r%Uo===Fo?Go:r%qo===$o?function(e){const t=Qo(e),r=Wo(e),n=r(t,t.neg(t.ONE)),s=r(t,n),i=r(t,t.neg(n)),o=(e+Bo)/qo;return(e,t)=>{let r=e.pow(t,o),a=e.mul(r,n);const c=e.mul(r,s),l=e.mul(r,i),u=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);r=e.cmov(r,a,u),a=e.cmov(l,c,h);const d=e.eql(e.sqr(a),t),p=e.cmov(r,a,d);return Vo(e,p,t),p}}(r):Wo(r)),u(h,t);var r}),toBytes:e=>r?Io(e,l):Ao(e,l),fromBytes:(t,n=!0)=>{if(o){if(!o.includes(t.length)||t.length>l)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,r?0:e.length-t.length),t=e}if(t.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let s=r?So(t):Eo(t);if(a&&(s=jo(s,e)),!n&&!h.isValid(s))throw new Error("invalid field element: outside of range 0..ORDER");return s},invertBatch:e=>Yo(h,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(h)}function ea(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function ta(e){const t=ea(e);return t+Math.ceil(t/2)}const ra=BigInt(0),na=BigInt(1);function sa(e,t){const r=t.negate();return e?r:t}function ia(e,t){const r=Yo(e.Fp,t.map(e=>e.Z));return t.map((t,n)=>e.fromAffine(t.toAffine(r[n])))}function oa(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function aa(e,t){oa(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:To(e),maxNumber:r,shiftBy:BigInt(e)}}function ca(e,t,r){const{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=r;let a=Number(e&s),c=e>>o;a>n&&(a-=i,c+=na);const l=t*n;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const la=new WeakMap,ua=new WeakMap;function ha(e){return ua.get(e)||1}function da(e){if(e!==ra)throw new Error("invalid wNAF")}class pa{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>ra;)t&na&&(r=r.add(n)),n=n.double(),t>>=na;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=aa(t,this.bits),s=[];let i=e,o=i;for(let e=0;e<r;e++){o=i,s.push(o);for(let e=1;e<n;e++)o=o.add(i),s.push(o);i=o.double()}return s}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,s=this.BASE;const i=aa(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:h}=ca(r,e,i);r=o,c?s=s.add(sa(u,t[h])):n=n.add(sa(l,t[a]))}return da(r),{p:n,f:s}}wNAFUnsafe(e,t,r,n=this.ZERO){const s=aa(e,this.bits);for(let e=0;e<s.windows&&r!==ra;e++){const{nextN:i,offset:o,isZero:a,isNeg:c}=ca(r,e,s);if(r=i,!a){const e=t[o];n=n.add(c?e.negate():e)}}return da(r),n}getPrecomputes(e,t,r){let n=la.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),la.set(t,n))),n}cached(e,t,r){const n=ha(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const s=ha(e);return 1===s?this._unsafeLadder(e,t,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),t,n)}createCache(e,t){oa(t,this.bits),ua.set(e,t),la.delete(e)}hasCache(e){return 1!==ha(e)}}function fa(e,t,r,n){(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,r)=>{if(!(e instanceof t))throw new Error("invalid point at index "+r)})})(r,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,r)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+r)})}(n,t);const s=r.length,i=n.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=_o(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=To(c),u=new Array(Number(l)+1).fill(o);let h=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(o);for(let t=0;t<i;t++){const s=n[t],i=Number(s>>BigInt(e)&l);u[i]=u[i].add(r[t])}let t=o;for(let e=u.length-1,r=o;e>0;e--)r=r.add(u[e]),t=t.add(r);if(h=h.add(t),0!==e)for(let e=0;e<c;e++)h=h.double()}return h}function ga(e,t){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){const t=Jo.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});Po(e,t)}(t),t}return Qo(e)}function ma(e,t,r={}){if(!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const r=t[e];if(!("bigint"==typeof r&&r>ra))throw new Error(`CURVE.${e} must be positive bigint`)}const n=ga(t.p,r.Fp),s=ga(t.n,r.Fn),i=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of i)if(!n.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{Fp:n,Fn:s}}const ya=BigInt(0),ba=BigInt(1),wa=BigInt(2),va=BigInt(8);class Ea{constructor(e){this.ep=e}static fromBytes(e){throw new Error("fromBytes must be implemented by subclass")}static fromHex(e){throw new Error("fromHex must be implemented by subclass")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toRawBytes(){return this.toBytes()}toHex(){return Br(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}}function Sa(e){const{CURVE:t,curveOpts:r,hash:n,eddsaOpts:s}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r={Fp:e.Fp,Fn:Qo(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},n={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:r,hash:e.hash,eddsaOpts:n}}(e),i=function(e,t={}){const{Fp:r,Fn:n}=ma("edwards",e,t),{h:s,n:i}=e;Po(t,{},{uvRatio:"function"});const o=wa<<BigInt(8*n.BYTES)-ba,a=e=>r.create(e),c=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:r.sqrt(r.div(e,t))}}catch(e){return{isValid:!1,value:ya}}});if(!function(e,t,r,n){const s=e.sqr(r),i=e.sqr(n),o=e.add(e.mul(t.a,s),i),a=e.add(e.ONE,e.mul(t.d,e.mul(s,i)));return e.eql(o,a)}(r,e,e.Gx,e.Gy))throw new Error("bad curve params: generator point");function l(e,t,r=!1){return Co("coordinate "+e,t,r?ba:ya,o),t}function u(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const h=Ro((e,t)=>{const{X:n,Y:s,Z:i}=e,o=e.is0();null==t&&(t=o?va:r.inv(i));const c=a(n*t),l=a(s*t),u=r.mul(i,t);if(o)return{x:ya,y:ba};if(u!==ba)throw new Error("invZ was invalid");return{x:c,y:l}}),d=Ro(t=>{const{a:r,d:n}=e;if(t.is0())throw new Error("bad point: ZERO");const{X:s,Y:i,Z:o,T:c}=t,l=a(s*s),u=a(i*i),h=a(o*o),d=a(h*h),p=a(l*r);if(a(h*a(p+u))!==a(d+a(n*a(l*u))))throw new Error("bad point: equation left != right (1)");if(a(s*i)!==a(o*c))throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(e,t,r,n){this.X=l("x",e),this.Y=l("y",t),this.Z=l("z",r,!0),this.T=l("t",n),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return ia(p,e)}static msm(e,t){return fa(p,n,e,t)}_setWindowSize(e){this.precompute(e)}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};return l("x",t),l("y",r),new p(t,r,ba,a(t*r))}precompute(e=8,t=!0){return f.createCache(this,e),t||this.multiply(wa),this}assertValidity(){d(this)}equals(e){u(e);const{X:t,Y:r,Z:n}=this,{X:s,Y:i,Z:o}=e,c=a(t*o),l=a(s*n),h=a(r*o),d=a(i*n);return c===l&&h===d}is0(){return this.equals(p.ZERO)}negate(){return new p(a(-this.X),this.Y,this.Z,a(-this.T))}double(){const{a:t}=e,{X:r,Y:n,Z:s}=this,i=a(r*r),o=a(n*n),c=a(wa*a(s*s)),l=a(t*i),u=r+n,h=a(a(u*u)-i-o),d=l+o,f=d-c,g=l-o,m=a(h*f),y=a(d*g),b=a(h*g),w=a(f*d);return new p(m,y,w,b)}add(t){u(t);const{a:r,d:n}=e,{X:s,Y:i,Z:o,T:c}=this,{X:l,Y:h,Z:d,T:f}=t,g=a(s*l),m=a(i*h),y=a(c*n*f),b=a(o*d),w=a((s+i)*(l+h)-g-m),v=b-y,E=b+y,S=a(m-r*g),A=a(w*v),I=a(E*S),k=a(w*S),x=a(v*E);return new p(A,I,x,k)}subtract(e){return this.add(e.negate())}multiply(e){const t=e;Co("scalar",t,ba,i);const{p:r,f:n}=f.cached(this,t,e=>ia(p,e));return ia(p,[r,n])[0]}multiplyUnsafe(e,t=p.ZERO){const r=e;return Co("scalar",r,ya,i),r===ya?p.ZERO:this.is0()||r===ba?this:f.unsafe(this,r,e=>ia(p,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return f.unsafe(this,i).is0()}toAffine(e){return h(this,e)}clearCofactor(){return s===ba?this:this.multiplyUnsafe(s)}static fromBytes(e,t=!1){return Pr(e),p.fromHex(e,t)}static fromHex(t,n=!1){const{d:s,a:i}=e,l=r.BYTES;t=ko("pointHex",t,l),bo("zip215",n);const u=t.slice(),h=t[l-1];u[l-1]=-129&h;const d=So(u),f=n?o:r.ORDER;Co("pointHex.y",d,ya,f);const g=a(d*d),m=a(g-ba),y=a(s*g-i);let{isValid:b,value:w}=c(m,y);if(!b)throw new Error("Point.fromHex: invalid y coordinate");const v=(w&ba)===ba,E=!!(128&h);if(!n&&w===ya&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(w=a(-w)),p.fromAffine({x:w,y:d})}toBytes(){const{x:e,y:t}=this.toAffine(),n=Io(t,r.BYTES);return n[n.length-1]|=e&ba?128:0,n}toRawBytes(){return this.toBytes()}toHex(){return Br(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}p.BASE=new p(e.Gx,e.Gy,ba,a(e.Gx*e.Gy)),p.ZERO=new p(ya,ba,ba,ya),p.Fp=r,p.Fn=n;const f=new pa(p,8*n.BYTES);return p}(t,r);return function(e,t){return Object.assign({},t,{ExtendedPoint:t.Point,CURVE:e})}(e,function(e,t,r){if("function"!=typeof t)throw new Error('"hash" function param is required');Po(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:s,Fp:i,Fn:o}=e,a=o.ORDER,c=r.randomBytes||Hr,l=r.adjustScalarBytes||(e=>e),u=r.domain||((e,t,r)=>{if(bo("phflag",r),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function h(e){return o.create(e)}function d(e){return h(So(e))}function p(e){const{head:r,prefix:n,scalar:o}=function(e){const r=i.BYTES;e=ko("private key",e,r);const n=ko("hashed private key",t(e),2*r),s=l(n.slice(0,r));return{head:s,prefix:n.slice(r,2*r),scalar:d(s)}}(e),a=s.multiply(o),c=a.toBytes();return{head:r,prefix:n,scalar:o,point:a,pointBytes:c}}function f(e){return p(e).pointBytes}function g(e=Uint8Array.of(),...r){const s=zr(...r);return d(t(u(s,ko("context",e),!!n)))}const m={zip215:!0};s.precompute(8);const y=i.BYTES,b={secret:y,public:y,signature:2*y,seed:y};function w(e=c(b.seed)){return e}const v={getExtendedPublicKey:p,randomSecretKey:w,isValidSecretKey:function(e){try{return!!o.fromBytes(e,!1)}catch(e){return!1}},isValidPublicKey:function(t,r){try{return!!e.fromBytes(t,r)}catch(e){return!1}},randomPrivateKey:w,toMontgomery(t){const{y:r}=e.fromBytes(t),n=32===y;if(!n&&57!==y)throw new Error("only defined for 25519 and 448");const s=n?i.div(ba+r,ba-r):i.div(r-ba,r+ba);return i.toBytes(s)},toMontgomeryPriv(e){Pr(e,y);const r=t(e.subarray(0,y));return l(r).subarray(0,y)},precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=v.randomSecretKey(e);return{secretKey:t,publicKey:f(t)}},getPublicKey:f,sign:function(e,t,r={}){e=ko("message",e),n&&(e=n(e));const{prefix:o,scalar:c,pointBytes:l}=p(t),u=g(r.context,o,e),d=s.multiply(u).toBytes(),f=h(u+g(r.context,d,l,e)*c);Co("signature.s",f,ya,a);const m=i.BYTES;return ko("result",zr(d,Io(f,m)),2*m)},verify:function(t,r,o,a=m){const{context:c,zip215:l}=a,u=i.BYTES;t=ko("signature",t,2*u),r=ko("message",r),o=ko("publicKey",o,u),void 0!==l&&bo("zip215",l),n&&(r=n(r));const h=So(t.slice(u,2*u));let d,p,f;try{d=e.fromHex(o,l),p=e.fromHex(t.slice(0,u),l),f=s.multiplyUnsafe(h)}catch(e){return!1}if(!l&&d.isSmallOrder())return!1;const y=g(c,p.toBytes(),d.toBytes(),r);return p.add(d.multiplyUnsafe(y)).subtract(f).clearCofactor().is0()},utils:v,Point:e,info:{type:"edwards",lengths:b}})}(i,n,s))}qr("HashToScalar-");const Aa=BigInt(0),Ia=BigInt(1),ka=BigInt(2);const xa=BigInt(0),Ca=BigInt(1),_a=BigInt(2),Ta=BigInt(3),Pa=BigInt(5),Ra=BigInt(8),Oa={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ra,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function La(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),i=Oa.p,o=e*e%i*e%i,a=zo(o,_a,i)*o%i,c=zo(a,Ca,i)*e%i,l=zo(c,Pa,i)*c%i,u=zo(l,t,i)*l%i,h=zo(u,r,i)*u%i,d=zo(h,n,i)*h%i,p=zo(d,s,i)*d%i,f=zo(p,s,i)*d%i,g=zo(f,t,i)*l%i;return{pow_p_5_8:zo(g,_a,i)*e%i,b2:o}}function Da(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Na=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ma(e,t){const r=Oa.p,n=jo(t*t*t,r),s=jo(n*n*t,r);let i=jo(e*n*La(e*s).pow_p_5_8,r);const o=jo(t*i*i,r),a=i,c=jo(i*Na,r),l=o===e,u=o===jo(-e,r),h=o===jo(-e*Na,r);return l&&(i=a),(u||h)&&(i=c),Xo(i,r)&&(i=jo(-i,r)),{isValid:l||u,value:i}}const Fa=(()=>Qo(Oa.p,{isLE:!0}))(),Ba=(()=>Qo(Oa.n,{isLE:!0}))(),Ua=(()=>({...Oa,Fp:Fa,hash:kn,adjustScalarBytes:Da,uvRatio:Ma}))(),$a=(()=>Sa(Ua))(),qa=(()=>{const e=Oa.p;return function(e){const t=(Po(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r}));var r;const{P:n,type:s,adjustScalarBytes:i,powPminus2:o,randomBytes:a}=t,c="x25519"===s;if(!c&&"x448"!==s)throw new Error("invalid type");const l=a||Hr,u=c?255:448,h=c?32:56,d=c?BigInt(9):BigInt(5),p=c?BigInt(121665):BigInt(39081),f=c?ka**BigInt(254):ka**BigInt(447),g=c?BigInt(8)*ka**BigInt(251)-Ia:BigInt(4)*ka**BigInt(445)-Ia,m=f+g+Ia,y=e=>jo(e,n),b=w(d);function w(e){return Io(y(e),h)}function v(e,t){const r=function(e,t){Co("u",e,Aa,n),Co("scalar",t,f,m);const r=t,s=e;let i=Ia,a=Aa,c=e,l=Ia,h=Aa;for(let e=BigInt(u-1);e>=Aa;e--){const t=r>>e&Ia;h^=t,({x_2:i,x_3:c}=S(h,i,c)),({x_2:a,x_3:l}=S(h,a,l)),h=t;const n=i+a,o=y(n*n),u=i-a,d=y(u*u),f=o-d,g=c+l,m=y((c-l)*n),b=y(g*u),w=m+b,v=m-b;c=y(w*w),l=y(s*y(v*v)),i=y(o*d),a=y(f*(o+y(p*f)))}({x_2:i,x_3:c}=S(h,i,c)),({x_2:a,x_3:l}=S(h,a,l));const d=o(a);return y(i*d)}(function(e){const t=ko("u coordinate",e,h);return c&&(t[31]&=127),y(So(t))}(t),function(e){return So(i(ko("scalar",e,h)))}(e));if(r===Aa)throw new Error("invalid private or public key received");return w(r)}function E(e){return v(e,b)}function S(e,t,r){const n=y(e*(t-r));return{x_2:t=y(t-n),x_3:r=y(r+n)}}const A=(e=l(h))=>e,I={randomSecretKey:A,randomPrivateKey:A},k={secret:h,public:h,seed:h};return{keygen:function(e){const t=I.randomSecretKey(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>v(e,t),getPublicKey:e=>E(e),scalarMult:v,scalarMultBase:E,utils:I,GuBytes:b.slice(),info:{type:"montgomery",lengths:k}}}({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:r,b2:n}=La(t);return jo(zo(r,Ta,e)*n,e)},adjustScalarBytes:Da})})(),ja=Na,za=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ka=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Va=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Ha=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Ga=e=>Ma(Ca,e),Wa=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Xa=e=>$a.CURVE.Fp.create(So(e)&Wa);function Ja(e){const{d:t}=$a.CURVE,r=$a.CURVE.Fp.ORDER,n=$a.CURVE.Fp.create,s=n(ja*e*e),i=n((s+Ca)*Va);let o=BigInt(-1);const a=n((o-t*s)*n(s+t));let{isValid:c,value:l}=Ma(i,a),u=n(l*e);Xo(u,r)||(u=n(-u)),c||(l=u),c||(o=s);const h=n(o*(s-Ca)*Ha-a),d=l*l,p=n((l+l)*a),f=n(h*za),g=n(Ca-d),m=n(Ca+d);return new $a.Point(n(p*m),n(g*f),n(f*m),n(p*g))}class Ya extends Ea{constructor(e){super(e)}static fromAffine(e){return new Ya($a.Point.fromAffine(e))}assertSame(e){if(!(e instanceof Ya))throw new Error("RistrettoPoint expected")}init(e){return new Ya(e)}static hashToCurve(e){return function(e){Pr(e,64);const t=Ja(Xa(e.subarray(0,32))),r=Ja(Xa(e.subarray(32,64)));return new Ya(t.add(r))}(ko("ristrettoHash",e,64))}static fromBytes(e){Pr(e,32);const{a:t,d:r}=$a.CURVE,n=Fa.ORDER,s=Fa.create,i=Xa(e);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(Io(i,32),e)||Xo(i,n))throw new Error("invalid ristretto255 encoding 1");const o=s(i*i),a=s(Ca+t*o),c=s(Ca-t*o),l=s(a*a),u=s(c*c),h=s(t*r*l-u),{isValid:d,value:p}=Ga(s(h*u)),f=s(p*c),g=s(p*f*h);let m=s((i+i)*f);Xo(m,n)&&(m=s(-m));const y=s(a*g),b=s(m*y);if(!d||Xo(b,n)||y===xa)throw new Error("invalid ristretto255 encoding 2");return new Ya(new $a.Point(m,y,Ca,b))}static fromHex(e){return Ya.fromBytes(ko("ristrettoHex",e,32))}static msm(e,t){return fa(Ya,$a.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:r,T:n}=this.ep;const s=Fa.ORDER,i=Fa.create,o=i(i(r+t)*i(r-t)),a=i(e*t),c=i(a*a),{value:l}=Ga(i(o*c)),u=i(l*o),h=i(l*a),d=i(u*h*n);let p;if(Xo(n*d,s)){let r=i(t*ja),n=i(e*ja);e=r,t=n,p=i(u*Ka)}else p=h;Xo(e*d,s)&&(t=i(-t));let f=i((r-t)*p);return Xo(f,s)&&(f=i(-f)),Io(f,32)}equals(e){this.assertSame(e);const{X:t,Y:r}=this.ep,{X:n,Y:s}=e.ep,i=Fa.create,o=i(t*s)===i(r*n),a=i(r*s)===i(t*n);return o||a}is0(){return this.equals(Ya.ZERO)}}Ya.BASE=(()=>new Ya($a.Point.BASE))(),Ya.ZERO=(()=>new Ya($a.Point.ZERO))(),Ya.Fp=Fa,Ya.Fn=Ba;class Za extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}}class Qa extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class ec extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const tc={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new ec("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let rc;const nc=(async()=>{try{return await tc.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function sc(e,t){const r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}class ic{type="Ed25519";raw;constructor(e){this.raw=cc(e,32)}toMultihash(){return at.digest(Kc(this))}toCID(){return mt.createV1(114,this.toMultihash())}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();const n=async function(e,t,r){return null==rc&&(rc=await nc),rc?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await tc.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await tc.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return $a.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return go(n)?n.then(e=>(r?.signal?.throwIfAborted(),e)):n}}class oc{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=cc(e,64),this.publicKey=new ic(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();const r=async function(e,t){return null==rc&&(rc=await nc),rc?async function(e,t){let r;r=64===e.length?e.subarray(0,32):e;const n={crv:"Ed25519",kty:"OKP",x:Ln(e.subarray(32),"base64url"),d:Ln(r,"base64url"),ext:!0,key_ops:["sign"]},s=await tc.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),i=await tc.get().subtle.sign({name:"Ed25519"},s,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(i,0,i.byteLength)}(e,t):function(e,t){const r=e.subarray(0,32);return $a.sign(t instanceof Uint8Array?t:t.subarray(),r)}(e,t)}(this.raw,e);return go(r)?r.then(e=>(t?.signal?.throwIfAborted(),e)):(t?.signal?.throwIfAborted(),r)}}function ac(e){return e=cc(e,32),new ic(e)}function cc(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ai(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var lc,uc,hc,dc;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(lc||(lc={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(uc||(uc={})),function(e){e.codec=()=>Sr(uc)}(lc||(lc={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),lc.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.Type=lc.codec().decode(e);break;case 2:n.Data=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(hc||(hc={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),lc.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.Type=lc.codec().decode(e);break;case 2:n.Data=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(dc||(dc={}));class pc{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=mc(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return mt.createV1(114,this._multihash)}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){const s=await tc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const i=await tc.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}class fc{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e||null==e.d||null==e.p||null==e.q||null==e.dp||null==e.dq||null==e.qi)throw new Ai("JWK was missing components");return no([to(Uint8Array.from([0])),to(xt(e.n,"base64url")),to(xt(e.e,"base64url")),to(xt(e.d,"base64url")),to(xt(e.p,"base64url")),to(xt(e.q,"base64url")),to(xt(e.dp,"base64url")),to(xt(e.dq,"base64url")),to(xt(e.qi,"base64url"))]).subarray()}(this.jwk)),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}sign(e,t){return async function(e,t,r){const n=await tc.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();const s=await tc.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(s,0,s.byteLength)}(this.jwk,e,t)}}const gc=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function mc(e){if(null==e.n||null==e.e)throw new Ai("JWK was missing components");return no([gc,ro(no([to(xt(e.n,"base64url")),to(xt(e.e,"base64url"))]))]).subarray()}function yc(e,t){if(e.byteLength>=1062)throw new Ii("Key size is too large");return function(e,t,r){const n=function(e){const t=Yi(e[1],{offset:0});return{kty:"RSA",n:Ln(t[0],"base64url"),e:Ln(t[1],"base64url")}}(e);return null==r&&(r=nt(18,xn(hc.encode({Type:lc.RSA,Data:t})))),new pc(n,r)}(Yi(e,{offset:0}),e,t)}class bc extends Kr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Rr(e);const r=jr(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;e<s.length;e++)s[e]^=54;this.iHash.update(s),this.oHash=e.create();for(let e=0;e<s.length;e++)s[e]^=106;this.oHash.update(s),Lr(s)}update(e){return Or(this),this.iHash.update(e),this}digestInto(e){Or(this),Pr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:s,blockLen:i,outputLen:o}=this;return e.finished=n,e.destroyed=s,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const wc=(e,t,r)=>new bc(e,t).update(r).digest();wc.create=(e,t)=>new bc(e,t);const vc=(e,t)=>(e+(e>=0?t:-t)/xc)/t;function Ec(e){void 0!==e.lowS&&bo("lowS",e.lowS),void 0!==e.prehash&&bo("prehash",e.prehash)}class Sc extends Error{constructor(e=""){super(e)}}const Ac={Err:Sc,_tlv:{encode:(e,t)=>{const{Err:r}=Ac;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,s=wo(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const i=n>127?wo(s.length/2|128):"";return wo(e)+i+s+t},decode(e,t){const{Err:r}=Ac;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const s=t[n++];let i=0;if(128&s){const e=127&s;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const o=t.subarray(n,n+e);if(o.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===o[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of o)i=i<<8|e;if(n+=e,i<128)throw new r("tlv.decode(long): not minimal encoding")}else i=s;const o=t.subarray(n,n+i);if(o.length!==i)throw new r("tlv.decode: wrong value length");return{v:o,l:t.subarray(n+i)}}},_int:{encode(e){const{Err:t}=Ac;if(e<Ic)throw new t("integer: negative integers are not allowed");let r=wo(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=Ac;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Eo(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=Ac,s=ko("signature",e),{v:i,l:o}=n.decode(48,s);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=Ac,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}},Ic=BigInt(0),kc=BigInt(1),xc=BigInt(2),Cc=BigInt(3),_c=BigInt(4);function Tc(e,t){const{BYTES:r}=e;let n;if("bigint"==typeof t)n=t;else{let s=ko("private key",t);try{n=e.fromBytes(s)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Pc(e){return Uint8Array.of(e?2:3)}function Rc(e,t,r={}){Rr(t),Po(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||Hr,s=r.hmac||((e,...r)=>wc(t,e,zr(...r))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o,l=ta(a),u={secret:o.BYTES,public:1+i.BYTES,publicUncompressed:1+2*i.BYTES,signature:2*o.BYTES,seed:l};function h(e){return e>a>>kc}function d(e,t){if(!o.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..CURVE.n`)}class p{constructor(e,t,r){d("r",e),d("s",t),this.r=e,this.s=t,null!=r&&(this.recovery=r),Object.freeze(this)}static fromBytes(e,t="compact"){if("compact"===t){const t=o.BYTES;Pr(e,2*t);const r=e.subarray(0,t),n=e.subarray(t,2*t);return new p(o.fromBytes(r),o.fromBytes(n))}if("der"===t){Pr(e);const{r:t,s:r}=Ac.toSig(e);return new p(t,r)}throw new Error("invalid format")}static fromHex(e,t){return this.fromBytes($r(e),t)}addRecoveryBit(e){return new p(this.r,this.s,e)}recoverPublicKey(t){const r=i.ORDER,{r:n,s,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*xc<r&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?n+a:n;if(!i.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=i.toBytes(l),h=e.fromHex(zr(Pc(!(1&c)),u)),d=o.inv(l),p=v(ko("msgHash",t)),f=o.create(-p*d),g=o.create(s*d),m=e.BASE.multiplyUnsafe(f).add(h.multiplyUnsafe(g));if(m.is0())throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new p(this.r,o.neg(this.s),this.recovery):this}toBytes(e="compact"){if("compact"===e)return zr(o.toBytes(this.r),o.toBytes(this.s));if("der"===e)return $r(Ac.hexFromSig(this));throw new Error("invalid format")}toHex(e){return Br(this.toBytes(e))}assertValidity(){}static fromCompact(e){return p.fromBytes(ko("sig",e),"compact")}static fromDER(e){return p.fromBytes(ko("sig",e),"der")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Br(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Br(this.toBytes("compact"))}}function f(e){try{return!!Tc(o,e)}catch(e){return!1}}function g(e=n(l)){return function(e,t,r=!1){const n=e.length,s=ea(t),i=ta(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=jo(r?So(e):Eo(e),t-Lo)+Lo;return r?Io(o,s):Ao(o,s)}(e,a)}const m={isValidSecretKey:f,isValidPublicKey:function(t,r){try{const n=t.length;return!(!0===r&&n!==u.public||!1===r&&n!==u.publicUncompressed||!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:g,isValidPrivateKey:f,randomPrivateKey:g,normPrivateKeyToScalar:e=>Tc(o,e),precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};function y(t,r=!0){return e.BASE.multiply(Tc(o,t)).toBytes(r)}function b(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;if(o.allowedLengths||u.secret===u.public)return;const r=ko("key",t).length;return r===u.public||r===u.publicUncompressed}const w=r.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Eo(e),r=8*e.length-c;return r>0?t>>BigInt(r):t},v=r.bits2int_modN||function(e){return o.create(w(e))},E=To(c);function S(e){return Co("num < 2^"+c,e,Ic,E),o.toBytes(e)}const A={lowS:r.lowS,prehash:!1},I={lowS:r.lowS,prehash:!1};return e.BASE.precompute(8),Object.freeze({keygen:function(e){const t=m.randomSecretKey(e);return{secretKey:t,publicKey:y(t)}},getPublicKey:y,sign:function(r,i,a=A){const{seed:c,k2sig:l}=function(r,s,i=A){if(["recovered","canonical"].some(e=>e in i))throw new Error("sign() legacy options not supported");let{lowS:a,prehash:c,extraEntropy:l}=i;null==a&&(a=!0),r=ko("msgHash",r),Ec(i),c&&(r=ko("prehashed msgHash",t(r)));const d=v(r),f=Tc(o,s),g=[S(f),S(d)];if(null!=l&&!1!==l){const e=!0===l?n(u.secret):l;g.push(ko("extraEntropy",e))}const m=zr(...g),y=d;return{seed:m,k2sig:function(t){const r=w(t);if(!o.isValidNot0(r))return;const n=o.inv(r),s=e.BASE.multiply(r).toAffine(),i=o.create(s.x);if(i===Ic)return;const c=o.create(n*o.create(y+i*f));if(c===Ic)return;let l=(s.x===i?0:2)|Number(s.y&kc),u=c;return a&&h(c)&&(u=function(e){return h(e)?o.neg(e):e}(c),l^=1),new p(i,u,l)}}}(r,i,a),d=function(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");const n=e=>new Uint8Array(e),s=e=>Uint8Array.of(e);let i=n(e),o=n(e),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...e)=>r(o,i,...e),u=(e=n(0))=>{o=l(s(0),e),i=l(),0!==e.length&&(o=l(s(1),e),i=l())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){i=l();const t=i.slice();r.push(t),e+=i.length}return zr(...r)};return(e,t)=>{let r;for(c(),u(e);!(r=t(h()));)u();return c(),r}}(t.outputLen,o.BYTES,s);return d(c,l)},verify:function(r,n,s,i=I){const a=r;n=ko("msgHash",n),s=ko("publicKey",s),Ec(i);const{lowS:c,prehash:l,format:u}=i;if("strict"in i)throw new Error("options.strict was renamed to lowS");let h,d;if(void 0===u){const e="string"==typeof a||_r(a),t=!e&&null!==a&&"object"==typeof a&&"bigint"==typeof a.r&&"bigint"==typeof a.s;if(!e&&!t)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(t)h=new p(a.r,a.s);else if(e){try{h=p.fromDER(a)}catch(e){if(!(e instanceof Ac.Err))throw e}if(!h)try{h=p.fromCompact(a)}catch(e){return!1}}}else if("compact"===u||"der"===u){if("string"!=typeof a&&!_r(a))throw new Error('"der" / "compact" format expects Uint8Array signature');h=p.fromBytes(ko("sig",a),u)}else{if("js"!==u)throw new Error('format must be "compact", "der" or "js"');if(!(a instanceof p))throw new Error('"js" format expects Signature instance');h=a}if(!h)return!1;try{if(d=e.fromHex(s),c&&h.hasHighS())return!1;l&&(n=t(n));const{r,s:i}=h,a=v(n),u=o.inv(i),p=o.create(a*u),f=o.create(r*u),g=e.BASE.multiplyUnsafe(p).add(d.multiplyUnsafe(f));return!g.is0()&&o.create(g.x)===r}catch(e){return!1}},getSharedSecret:function(t,r,n=!0){if(!0===b(t))throw new Error("first arg must be private key");if(!1===b(r))throw new Error("second arg must be public key");const s=Tc(o,t);return e.fromHex(r).multiply(s).toBytes(n)},utils:m,Point:e,Signature:p,info:{type:"weierstrass",lengths:u,publicKeyHasPrefix:!0}})}function Oc(e){const{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:s}=function(e){const{CURVE:t,curveOpts:r}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp;let n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:r,Fn:Qo(t.n,{BITS:e.nBitLength,allowedLengths:n,modOnDecode:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}(e);return function(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}(e,Rc(function(e,t={}){const{Fp:r,Fn:n}=ma("weierstrass",e,t),{h:s,n:i}=e;Po(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=t;if(o&&(!r.is0(e.a)||"bigint"!=typeof o.beta||!Array.isArray(o.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');function a(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const c=t.toBytes||function(e,t,n){const{x:s,y:i}=t.toAffine(),o=r.toBytes(s);return bo("isCompressed",n),n?(a(),zr(Pc(!r.isOdd(i)),o)):zr(Uint8Array.of(4),o,r.toBytes(i))},l=t.fromBytes||function(e){Pr(e);const t=r.BYTES,n=t+1,s=2*t+1,i=e.length,o=e[0],c=e.subarray(1);if(i!==n||2!==o&&3!==o){if(i===s&&4===o){const e=r.fromBytes(c.subarray(0*t,1*t)),n=r.fromBytes(c.subarray(1*t,2*t));if(!h(e,n))throw new Error("bad point: is not on curve");return{x:e,y:n}}throw new Error(`bad point: got length ${i}, expected compressed=${n} or uncompressed=${s}`)}{const e=r.fromBytes(c);if(!r.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=u(e);let n;try{n=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}return a(),!(1&~o)!==r.isOdd(n)&&(n=r.neg(n)),{x:e,y:n}}},u=function(e,t,r){return function(n){const s=e.sqr(n),i=e.mul(s,n);return e.add(e.add(i,e.mul(n,t)),r)}}(r,e.a,e.b);function h(e,t){const n=r.sqr(t),s=u(e);return r.eql(n,s)}if(!h(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const d=r.mul(r.pow(e.a,Cc),_c),p=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(d,p)))throw new Error("bad curve params: a or b");function f(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function g(e){if(!(e instanceof v))throw new Error("ProjectivePoint expected")}function m(e){if(!o||!o.basises)throw new Error("no endo");return function(e,t,r){const[[n,s],[i,o]]=t,a=vc(o*e,r),c=vc(-s*e,r);let l=e-a*n-c*i,u=-a*s-c*o;const h=l<Ic,d=u<Ic;h&&(l=-l),d&&(u=-u);const p=To(Math.ceil(_o(r)/2))+kc;if(l<Ic||l>=p||u<Ic||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}(e,o.basises,n.ORDER)}const y=Ro((e,t)=>{const{X:n,Y:s,Z:i}=e;if(r.eql(i,r.ONE))return{x:n,y:s};const o=e.is0();null==t&&(t=o?r.ONE:r.inv(i));const a=r.mul(n,t),c=r.mul(s,t),l=r.mul(i,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),b=Ro(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:s}=e.toAffine();if(!r.isValid(n)||!r.isValid(s))throw new Error("bad point: x or y not field elements");if(!h(n,s))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function w(e,t,n,s,i){return n=new v(r.mul(n.X,e),n.Y,n.Z),t=sa(s,t),n=sa(i,n),t.add(n)}class v{constructor(e,t,r){this.X=f("x",e),this.Y=f("y",t,!0),this.Z=f("z",r),Object.freeze(this)}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof v)throw new Error("projective point not allowed");return r.is0(t)&&r.is0(n)?v.ZERO:new v(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}static normalizeZ(e){return ia(v,e)}static fromBytes(e){return Pr(e),v.fromHex(e)}static fromHex(e){const t=v.fromAffine(l(ko("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return v.BASE.multiply(Tc(n,e))}static msm(e,t){return fa(v,n,e,t)}_setWindowSize(e){this.precompute(e)}precompute(e=8,t=!0){return S.createCache(this,e),t||this.multiply(Cc),this}assertValidity(){b(this)}hasEvenY(){const{y:e}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(e)}equals(e){g(e);const{X:t,Y:n,Z:s}=this,{X:i,Y:o,Z:a}=e,c=r.eql(r.mul(t,a),r.mul(i,s)),l=r.eql(r.mul(n,a),r.mul(o,s));return c&&l}negate(){return new v(this.X,r.neg(this.Y),this.Z)}double(){const{a:t,b:n}=e,s=r.mul(n,Cc),{X:i,Y:o,Z:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,h=r.mul(i,i),d=r.mul(o,o),p=r.mul(a,a),f=r.mul(i,o);return f=r.add(f,f),u=r.mul(i,a),u=r.add(u,u),c=r.mul(t,u),l=r.mul(s,p),l=r.add(c,l),c=r.sub(d,l),l=r.add(d,l),l=r.mul(c,l),c=r.mul(f,c),u=r.mul(s,u),p=r.mul(t,p),f=r.sub(h,p),f=r.mul(t,f),f=r.add(f,u),u=r.add(h,h),h=r.add(u,h),h=r.add(h,p),h=r.mul(h,f),l=r.add(l,h),p=r.mul(o,a),p=r.add(p,p),h=r.mul(p,f),c=r.sub(c,h),u=r.mul(p,d),u=r.add(u,u),u=r.add(u,u),new v(c,l,u)}add(t){g(t);const{X:n,Y:s,Z:i}=this,{X:o,Y:a,Z:c}=t;let l=r.ZERO,u=r.ZERO,h=r.ZERO;const d=e.a,p=r.mul(e.b,Cc);let f=r.mul(n,o),m=r.mul(s,a),y=r.mul(i,c),b=r.add(n,s),w=r.add(o,a);b=r.mul(b,w),w=r.add(f,m),b=r.sub(b,w),w=r.add(n,i);let E=r.add(o,c);return w=r.mul(w,E),E=r.add(f,y),w=r.sub(w,E),E=r.add(s,i),l=r.add(a,c),E=r.mul(E,l),l=r.add(m,y),E=r.sub(E,l),h=r.mul(d,w),l=r.mul(p,y),h=r.add(l,h),l=r.sub(m,h),h=r.add(m,h),u=r.mul(l,h),m=r.add(f,f),m=r.add(m,f),y=r.mul(d,y),w=r.mul(p,w),m=r.add(m,y),y=r.sub(f,y),y=r.mul(d,y),w=r.add(w,y),f=r.mul(m,w),u=r.add(u,f),f=r.mul(E,w),l=r.mul(b,l),l=r.sub(l,f),f=r.mul(b,m),h=r.mul(E,h),h=r.add(h,f),new v(l,u,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(v.ZERO)}multiply(e){const{endo:r}=t;if(!n.isValidNot0(e))throw new Error("invalid scalar: out of range");let s,i;const o=e=>S.cached(this,e,e=>ia(v,e));if(r){const{k1neg:t,k1:n,k2neg:a,k2:c}=m(e),{p:l,f:u}=o(n),{p:h,f:d}=o(c);i=u.add(d),s=w(r.beta,l,h,t,a)}else{const{p:t,f:r}=o(e);s=t,i=r}return ia(v,[s,i])[0]}multiplyUnsafe(e){const{endo:r}=t,s=this;if(!n.isValid(e))throw new Error("invalid scalar: out of range");if(e===Ic||s.is0())return v.ZERO;if(e===kc)return s;if(S.hasCache(this))return this.multiply(e);if(r){const{k1neg:t,k1:n,k2neg:i,k2:o}=m(e),{p1:a,p2:c}=function(e,t,r,n){let s=t,i=e.ZERO,o=e.ZERO;for(;r>ra||n>ra;)r&na&&(i=i.add(s)),n&na&&(o=o.add(s)),s=s.double(),r>>=na,n>>=na;return{p1:i,p2:o}}(v,s,n,o);return w(r.beta,a,c,t,i)}return S.unsafe(s,e)}multiplyAndAddUnsafe(e,t,r){const n=this.multiplyUnsafe(t).add(e.multiplyUnsafe(r));return n.is0()?void 0:n}toAffine(e){return y(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===kc||(e?e(v,this):S.unsafe(this,i).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===kc?this:e?e(v,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return bo("isCompressed",e),this.assertValidity(),c(v,this,e)}toRawBytes(e=!0){return this.toBytes(e)}toHex(e=!0){return Br(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}v.BASE=new v(e.Gx,e.Gy,r.ONE),v.ZERO=new v(r.ZERO,r.ONE,r.ZERO),v.Fp=r,v.Fn=n;const E=n.BITS,S=new pa(v,t.endo?Math.ceil(E/2):E);return v}(t,r),n,s))}const Lc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Dc={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Nc=BigInt(2);const Mc=Qo(Lc.p,void 0,void 0,{sqrt:function(e){const t=Lc.p,r=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=zo(u,r,t)*u%t,d=zo(h,r,t)*u%t,p=zo(d,Nc,t)*l%t,f=zo(p,s,t)*p%t,g=zo(f,i,t)*f%t,m=zo(g,a,t)*g%t,y=zo(m,c,t)*m%t,b=zo(y,a,t)*g%t,w=zo(b,r,t)*u%t,v=zo(w,o,t)*f%t,E=zo(v,n,t)*l%t,S=zo(E,Nc,t);if(!Mc.eql(Mc.sqr(S),e))throw new Error("Cannot find square root");return S}}),Fc=function(e,t){const r=t=>Oc({...e,hash:t});return{...r(t),create:r}}({...Lc,Fp:Mc,lowS:!0,endo:Dc},In);class Bc{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return Fc.ProjectivePoint.fromHex(e),e}catch(e){throw new Ii(String(e))}}(e),this.raw=function(e){return Fc.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return at.digest(Kc(this))}toCID(){return mt.createV1(114,this.toMultihash())}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const s=ht.digest(r instanceof Uint8Array?r:r.subarray());if(go(s))return s.then(({digest:r})=>(n?.signal?.throwIfAborted(),Fc.verify(t,r,e))).catch(e=>{if("AbortError"===e.name)throw e;throw new Qa(String(e))});try{return n?.signal?.throwIfAborted(),Fc.verify(t,s.digest,e)}catch(e){throw new Qa(String(e))}}(this._key,t,e,r)}}class Uc{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=function(e){try{return Fc.getPublicKey(e,!0),e}catch(e){throw new ki(String(e))}}(e),this.publicKey=new Bc(t??function(e){try{return Fc.getPublicKey(e,!0)}catch(e){throw new ki(String(e))}}(e))}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}sign(e,t){return function(e,t,r){const n=ht.digest(t instanceof Uint8Array?t:t.subarray());if(go(n))return n.then(({digest:t})=>(r?.signal?.throwIfAborted(),Fc.sign(t,e).toDERRawBytes())).catch(e=>{if("AbortError"===e.name)throw e;throw new Za(String(e))});try{return Fc.sign(n.digest,e).toDERRawBytes()}catch(e){throw new Za(String(e))}}(this.raw,e,t)}}function $c(e){return new Bc(e)}async function qc(e,t){if("Ed25519"===e)return async function(){const{privateKey:e,publicKey:t}=function(){const e=$a.utils.randomPrivateKey(),t=$a.getPublicKey(e);return{privateKey:sc(e,t),publicKey:t}}();return new oc(e,t)}();if("secp256k1"===e)return async function(){const e=Fc.utils.randomPrivateKey();return new Uc(e)}();if("RSA"===e)return async function(e){if(e>8192)throw new Ai("Key size is too large");const t=await async function(e,t){const r=await tc.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();const n=await async function(e,t){if(null==e.privateKey||null==e.publicKey)throw new Ai("Private and public key are required");const r=await Promise.all([tc.get().subtle.exportKey("jwk",e.privateKey),tc.get().subtle.exportKey("jwk",e.publicKey)]);return t?.signal?.throwIfAborted(),r}(r,t);return{privateKey:n[0],publicKey:n[1]}}(e),r=nt(18,xn(hc.encode({Type:lc.RSA,Data:mc(t.publicKey)})));return new fc(t.privateKey,new pc(t.publicKey,r))}(function(e){return null==e?2048:parseInt(e,10)}(t));if("ECDSA"===e)return async function(e="P-256"){const t=await async function(e="P-256"){const t=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:e},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",t.publicKey),privateKey:await crypto.subtle.exportKey("jwk",t.privateKey)}}(e);return new io(t.privateKey)}(function(e){if("P-256"===e||null==e)return"P-256";if("P-384"===e)return"P-384";if("P-521"===e)return"P-521";throw new Ai("Unsupported curve, should be P-256, P-384 or P-521")}(t));throw new Hi}async function jc(e,t){if("Ed25519"!==e)throw new Hi("Seed key derivation only supported for Ed25519 keys");return async function(e){const{privateKey:t,publicKey:r}=function(e){if(32!==e.length)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=$a.getPublicKey(t);return{privateKey:sc(t,r),publicKey:r}}(e);return new oc(t,r)}(t)}function zc(e,t){const{Type:r,Data:n}=hc.decode(e),s=n??new Uint8Array;switch(r){case lc.RSA:return yc(s,t);case lc.Ed25519:return ac(s);case lc.secp256k1:return $c(s);case lc.ECDSA:return po(s);default:throw new Hi}}function Kc(e){return hc.encode({Type:lc[e.type],Data:e.raw})}const Vc=Symbol.for("nodejs.util.inspect.custom");class Hc{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[bi]=!0;toString(){return null==this.string&&(this.string=Ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return mt.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return rs(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return rs(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Vc](){return`PeerId(${this.toString()})`}}class Gc extends Hc{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class Wc extends Hc{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Xc extends Hc{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}class Jc{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=at.digest(xt(this.url))}[Vc](){return`PeerId(${this.url})`}[bi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return mt.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=Ln(e)),e.toString()===this.toString())}}function Yc(e,t){let r;if("1"===e.charAt(0)||"Q"===e.charAt(0))r=st(Ee.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return el(mt.parse(e));if(null==t)throw new Ai('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=st(t.decode(e))}return Qc(r)}function Zc(e){if("Ed25519"===e.type)return new Wc({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Xc({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Gc({multihash:e.toCID().multihash,publicKey:e});throw new Hi}function Qc(e){if(function(e){return e.code===ht.code}(e))return new Gc({multihash:e});if(function(e){return e.code===at.code}(e))try{const t=function(e){const{Type:t,Data:r}=hc.decode(e.digest),n=r??new Uint8Array;switch(t){case lc.Ed25519:return ac(n);case lc.secp256k1:return $c(n);case lc.ECDSA:return po(n);default:throw new Hi}}(e);if("Ed25519"===t.type)return new Wc({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Xc({multihash:e,publicKey:t})}catch(t){const r=Ln(e.digest);return new Jc(new URL(r))}throw new Mi("Supplied PeerID Multihash is invalid")}function el(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new Ni("Supplied PeerID CID is invalid");if(2336===e.code){const t=Ln(e.multihash.digest);return new Jc(new URL(t))}return Qc(e.multihash)}class tl extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"}class rl extends Error{static name="ValidationError";name="ValidationError"}class nl extends Error{static name="InvalidParametersError";name="InvalidParametersError"}class sl extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}const il=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically(()=>{const t=this.readChar();if(t===e)return t})}readSeparator(e,t,r){return this.readAtomically(()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()})}readNumber(e,t,r,n){return this.readAtomically(()=>{let s=0,i=0;const o=this.peekChar();if(void 0===o)return;const a="0"===o,c=2**(8*n)-1;for(;;){const r=this.readAtomically(()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r});if(void 0===r)break;if(s*=e,s+=r,s>c)return;if(i+=1,void 0!==t&&i>t)return}return 0===i||!r&&a&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{const e=new Uint8Array(4);for(let t=0;t<e.length;t++){const r=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(void 0===r)return;e[t]=r}return e})}readIPv6Addr(){const e=e=>{for(let t=0;t<e.length/2;t++){const r=2*t;if(t<e.length-3){const n=this.readSeparator(":",t,()=>this.readIPv4Addr());if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}const n=this.readSeparator(":",t,()=>this.readNumber(16,4,!0,2));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically(()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const s=new Uint8Array(14),i=16-(r+2),[o]=e(s.subarray(0,i));return t.set(s.subarray(0,o),16-o),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function ol(e){if(!(e.length>15))return il.new(e).parseWith(()=>il.readIPv4Addr())}function al(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return il.new(e).parseWith(()=>il.readIPv6Addr())}function cl(e,t=!1){if(e.includes("%")&&(e=e.split("%")[0]),e.length>45)return;const r=il.new(e).parseWith(()=>il.readIPAddr());return r?t&&4===r.length?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,r[0],r[1],r[2],r[3]]):r:void 0}function ll(e){return Boolean(ol(e))}function ul(e){return Boolean(al(e))}const hl=41,dl=42;function pl(e){return t=>Ln(t,e)}function fl(e){return t=>xt(t,e)}function gl(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function ml(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function yl(e){const t=e.subarray(0,e.length-2),r=e.subarray(e.length-2);return`${Ln(t,"base32")}:${gl(r)}`}const bl=function(e){e=e.toString().trim();const t=new Uint8Array(4);return e.split(/\./g).forEach((e,r)=>{const n=parseInt(e,10);if(isNaN(n)||n<0||n>255)throw new tl("Invalid byte value in IP address");t[r]=n}),t},wl=Object.values(Et).map(e=>e.decoder),vl=function(){let e=wl[0].or(wl[1]);return wl.slice(2).forEach(t=>e=e.or(t)),e}(),El=function(...e){return t=>{for(const r of e)r(t)}}(function(e){if(parseInt(e).toString()!==e)throw new rl("Value must be an integer")},function(e){if(e<0)throw new rl("Value must be a positive integer, or zero")},e=>{if(e>65535)throw new rl("Value must be smaller than or equal to 65535")});const Sl=-1,Al=new class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e),null==t)throw new sl(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){const t=this.protocolsByCode.get(e);null!=t&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(e=>{this.protocolsByName.delete(e)}))}};var Il;function kl(e,t,r){return null==e.size||0===e.size?0:e.size>0?e.size/8:T(t,r)}[{code:4,name:"ip4",size:32,valueToBytes:bl,bytesToValue:function(e){if(4!==e.byteLength)throw new tl("IPv4 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate:e=>{if(!ll(e))throw new rl(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:ml,bytesToValue:gl,validate:El},{code:273,name:"udp",size:16,valueToBytes:ml,bytesToValue:gl,validate:El},{code:33,name:"dccp",size:16,valueToBytes:ml,bytesToValue:gl,validate:El},{code:hl,name:"ip6",size:128,valueToBytes:function(e){let t=0;const r=(e=e.toString().trim()).split(":",8);let n;for(n=0;n<r.length;n++){let e;ll(r[n])&&(e=bl(r[n]),r[n]=Ln(e.subarray(0,2),"base16")),null!=e&&++n<8&&r.splice(n,0,Ln(e.subarray(2,4),"base16"))}if(""===r[0])for(;r.length<8;)r.unshift("0");else if(""===r[r.length-1])for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&""!==r[n];n++);const e=[n,1];for(n=9-r.length;n>0;n--)e.push("0");r.splice.apply(r,e)}const s=new Uint8Array(t+16);for(n=0;n<r.length;n++){""===r[n]&&(r[n]="0");const e=parseInt(r[n],16);if(isNaN(e)||e<0||e>65535)throw new tl("Invalid byte value in IP address");s[t++]=e>>8&255,s[t++]=255&e}return s},bytesToValue:function(e){if(16!==e.byteLength)throw new tl("IPv6 address was incorrect length");const t=[];for(let r=0;r<e.byteLength;r+=2){const n=e[r],s=e[r+1],i=`${n.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}const r=t.join(":");try{const e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new tl(`Invalid IPv6 address "${r}"`)}},stringToValue:function(e){try{const t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new tl(`Invalid IPv6 address "${e}"`)}},validate:e=>{if(!ul(e))throw new rl(`Invalid IPv6 address "${e}"`)}},{code:dl,name:"ip6zone",size:Sl},{code:43,name:"ipcidr",size:8,bytesToValue:pl("base10"),valueToBytes:fl("base10")},{code:53,name:"dns",size:Sl,resolvable:!0},{code:54,name:"dns4",size:Sl,resolvable:!0},{code:55,name:"dns6",size:Sl,resolvable:!0},{code:56,name:"dnsaddr",size:Sl,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:ml,bytesToValue:gl,validate:El},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Sl,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:Sl,bytesToValue:pl("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?fl("base58btc")(e):mt.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:yl,valueToBytes:function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(16!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);const r=xt(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const s=ml(n);return ts([r,s],r.length+s.length)}},{code:445,name:"onion3",size:296,bytesToValue:yl,valueToBytes:function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=ue.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const s=ml(n);return ts([r,s],r.length+s.length)}},{code:446,name:"garlic64",size:Sl},{code:447,name:"garlic32",size:Sl},{code:448,name:"tls"},{code:449,name:"sni",size:Sl},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Sl,bytesToValue:(Il=ke,e=>Il.encoder.encode(e)),valueToBytes:function(e){return vl.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:Sl,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:Sl}].forEach(e=>{Al.addProtocol(e)});const xl=Symbol.for("nodejs.util.inspect.custom"),Cl=Symbol.for("@multiformats/multiaddr"),_l=[53,54,55,56];class Tl extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}class Pl{[Cl]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=function(e){if(null==e&&(e="/"),Ul(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){const t=[];let r=0;for(;r<e.length;){const n=T(e,r),s=Al.getProtocol(n),i=k(n),o=kl(s,e,r+i);let a=0;o>0&&s.size===Sl&&(a=k(o));const c=i+a+o,l={code:n,name:s.name,bytes:e.subarray(r,r+c)};if(o>0){const t=r+i+a,n=e.subarray(t,t+o);l.value=s.bytesToValue?.(n)??Ln(n)}t.push(l),r+=c}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new tl('String multiaddr must start with "/"');const t=[];let r="protocol",n="",s="";for(let i=1;i<e.length;i++){const o=e.charAt(i);"/"!==o&&("protocol"===r?s+=e.charAt(i):n+=e.charAt(i));const a=i===e.length-1;if("/"===o||a){const e=Al.getProtocol(s);if("protocol"===r){if(null==e.size||0===e.size){t.push({code:e.code,name:e.name}),n="",s="",r="protocol";continue}if(a)throw new tl(`Component ${s} was missing value`);r="value"}else if("value"===r){const i={code:e.code,name:e.name};if(null!=e.size&&0!==e.size){if(""===n)throw new tl(`Component ${s} was missing value`);i.value=e.stringToValue?.(n)??n}t.push(i),n="",s="",r="protocol"}}}if(""!==s&&""!==n)throw new tl("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new tl("Must be a string, Uint8Array, Component[], or another Multiaddr")}(e),!1!==t.validate&&function(e){e.getComponents().forEach(e=>{const t=Al.getProtocol(e.code);null!=e.value&&t.validate?.(e.value)})}(this)}get bytes(){return null==this.#r&&(this.#r=function(e){let t=0;const r=[];for(const n of e){if(null==n.bytes){const e=Al.getProtocol(n.code),t=k(n.code);let r,s=0,i=0;null!=n.value&&(r=e.valueToBytes?.(n.value)??xt(n.value),s=r.byteLength,e.size===Sl&&(i=k(s)));const o=new Uint8Array(t+i+s);let a=0;x(n.code,o,a),a+=t,null!=r&&(e.size===Sl&&(x(s,o,a),a+=i),o.set(r,a)),n.bytes=o}r.push(n.bytes),t+=n.bytes.byteLength}return ts(r,t)}(this.#e)),this.#r}toString(){return null==this.#t&&(this.#t=`/${this.#e.flatMap(e=>{if(null==e.value)return e.name;const t=Al.getProtocol(e.code);if(null==t)throw new tl(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,r,n,s="";for(const{code:i,name:o,value:a}of this.#e)i===dl&&(s=`%${a??""}`),_l.includes(i)&&(t="tcp",n=443,r=`${a??""}${s}`,e=55===i?6:4),6!==i&&273!==i||(t="tcp"===o?"tcp":"udp",n=parseInt(a??"")),4!==i&&i!==hl||(t="tcp",r=`${a??""}${s}`,e=i===hl?6:4);if(null==e||null==t||null==r||null==n)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{const r=Al.getProtocol(e);return{code:e,size:r.size??0,name:r.name,resolvable:Boolean(r.resolvable),path:Boolean(r.path)}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(null==t)return[e];const r=Al.getProtocol(e),n=[e];return null!=t&&n.push(r.valueToBytes?.(t)??xt(t)),n})}stringTuples(){return this.#e.map(({code:e,value:t})=>null==t?[e]:[e,t])}encapsulate(e){const t=new Pl(e);return new Pl([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new nl(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new Pl(r.slice(0,n),{validate:!1})}decapsulateCode(e){let t;for(let r=this.#e.length-1;r>-1;r--)if(this.#e[r].code===e){t=r;break}return new Pl(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:t,value:r})=>{421===t&&e.push([t,r]),290===t&&(e=[])});const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?Ln(Ee.decode(`z${e}`),"base58btc"):Ln(mt.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){for(const e of this.#e)if(Al.getProtocol(e.code).path)return e.value??null;return null}equals(e){return rs(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find(e=>e.resolvable);if(null==t)return[this];const r=Bl.get(t.name);if(null==r)throw new Tl(`no available resolver for ${t.name}`);return(await r(this,e)).map(e=>$l(e))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(2!==this.#e.length||4!==this.#e[0].code&&this.#e[0].code!==hl||6!==this.#e[1].code&&273!==this.#e[1].code)}[xl](){return`Multiaddr(${this.toString()})`}}const Rl=(parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]));function Ol(e,t){16===t.length&&4===e.length&&function(e){let t=0;for(const r of e)if(!(t<0)){if(t>11)break;if(255!==r)return!1;t++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t){let r=0;for(const n of e)if(!(r<0)){if(r>11)break;if(n!==t[r])return!1;r++}return!0}(e,Rl)&&(e=e.slice(12));const r=e.length;if(r!=t.length)throw new Error("Failed to mask ip");const n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e[s]&t[s];return n}function Ll(e,t){if(32!==t&&128!==t)throw new Error("Invalid CIDR mask");if(e<0||e>t)throw new Error("Invalid CIDR mask");const r=t/8,n=new Uint8Array(r);for(let t=0;t<r;t++)e>=8?(n[t]=255,e-=8):(n[t]=255-(255>>e),e=0);return n}class Dl{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){const[t,r]=e.split("/");if(!t||!r)throw new Error("Failed to parse given CIDR: "+e);let n=4,s=ol(t);if(null==s&&(n=16,s=al(t),null==s))throw new Error("Failed to parse given CIDR: "+e);const i=parseInt(r,10);if(Number.isNaN(i)||String(i).length!==r.length||i<0||i>8*n)throw new Error("Failed to parse given CIDR: "+e);const o=Ll(i,8*n);return{network:Ol(s,o),mask:o}}(e));else{const r=cl(e);if(null==r)throw new Error("Failed to parse network");t=String(t);const n=parseInt(t,10);if(Number.isNaN(n)||String(n).length!==t.length||n<0||n>8*r.length){const e=cl(t);if(null==e)throw new Error("Failed to parse mask");this.mask=e}else this.mask=Ll(n,8*r.length);this.network=Ol(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=cl(t)),null==t)throw new Error("Invalid ip");if(t.length!==e.network.length)return!1;for(let r=0;r<t.length;r++)if((e.network[r]&e.mask[r])!==(t[r]&e.mask[r]))return!1;return!0}({network:this.network,mask:this.mask},e)}toString(){const e=function(e){let t=0;for(let[r,n]of e.entries()){if(255!==n){for(;128&n;)t++,n<<=1;if(128&n)return-1;for(let t=r+1;t<e.length;t++)if(0!=e[t])return-1;break}t+=8}return t}(this.mask),t=-1!==e?String(e):function(e){let t="0x";for(const r of e)t+=(r>>4).toString(16)+(15&r).toString(16);return t}(this.mask);return function(e){switch(e.length){case 4:return e.join(".");case 16:{const t=[];for(let r=0;r<e.length;r++)r%2==0&&t.push(e[r].toString(16).padStart(2,"0")+e[r+1].toString(16).padStart(2,"0"));return t.join(":")}default:throw new Error("Invalid ip length")}}(this.network)+"/"+t}}function Nl(e,t){return new Dl(e).contains(t)}function Ml(e,t){const r=Al.getProtocol(e);return r.bytesToValue?.(t)??Ln(t,"base16")}function Fl(e,t){const r=Al.getProtocol(e);return r.valueToBytes?.(t)??xt(t,"base16")}const Bl=new Map;function Ul(e){return Boolean(e?.[Cl])}function $l(e){return new Pl(e)}function ql(e){const t=Al.getProtocol(e);return{code:t.code,size:t.size??0,name:t.name,resolvable:Boolean(t.resolvable),path:Boolean(t.path)}}const jl=e=>{if(!e)return-1;try{const t=e.metadata.get("ping");return t?Number(Mn(t)):-1}catch(e){return-1}},zl=new Hn("connection-manager");class Kl{keepAliveManager;discoveryDialer;dialer;shardReader;networkMonitor;connectionLimiter;options;libp2p;constructor(e){this.libp2p=e.libp2p,this.options={maxBootstrapPeers:3,maxConnections:10,pingKeepAlive:300,relayKeepAlive:300,enableAutoRecovery:!0,maxDialingPeers:3,failedDialCooldown:60,dialCooldown:10,...e.config},this.keepAliveManager=new fi({relay:e.relay,libp2p:e.libp2p,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.shardReader=new yi({libp2p:e.libp2p,networkConfig:e.networkConfig}),this.dialer=new ui({libp2p:e.libp2p,shardReader:this.shardReader,options:this.options}),this.discoveryDialer=new di({libp2p:e.libp2p,dialer:this.dialer}),this.networkMonitor=new gi({libp2p:e.libp2p,events:e.events}),this.connectionLimiter=new ci({libp2p:e.libp2p,events:e.events,networkMonitor:this.networkMonitor,dialer:this.dialer,options:this.options})}start(){this.dialer.start(),this.networkMonitor.start(),this.discoveryDialer.start(),this.keepAliveManager.start(),this.connectionLimiter.start()}stop(){this.dialer.stop(),this.networkMonitor.stop(),this.discoveryDialer.stop(),this.keepAliveManager.stop(),this.connectionLimiter.stop()}isConnected(){return this.networkMonitor.isConnected()}async dial(e,t){const r=wi(n=e)?n:$l(n);var n;zl.info(`Dialing peer ${r.toString()} with protocols ${t}`);const s=await this.libp2p.dialProtocol(r,t);return zl.info(`Dialed peer ${r.toString()} with protocols ${t}`),s}async hangUp(e){const t=wi(r=e)?r:Yc($l(r).getPeerId());var r;try{return zl.info(`Dropping connection with peer ${t.toString()}`),await this.libp2p.hangUp(t),zl.info(`Dropped connection with peer ${t.toString()}`),!0}catch(e){return zl.error(`Error dropping connection with peer ${t.toString()} - ${e}`),!1}}async getConnectedPeers(e){const t=this.libp2p.getPeers();if(zl.info(`Getting connected peers for codec ${e}`),0===t.length)return zl.info("No connected peers"),[];const r=(await Promise.all(t.map(async e=>{try{return await this.libp2p.peerStore.get(e)}catch(e){return null}}))).filter(e=>!!e).filter(t=>!e||t.protocols.includes(e)).sort((e,t)=>jl(e)-jl(t));return zl.info(`Found ${r.length} connected peers for codec ${e}`),r}async hasShardInfo(e){return this.shardReader.hasShardInfo(e)}async isPeerOnTopic(e,t){return this.shardReader.isPeerOnTopic(e,t)}}const Vl=new Hn("metadata"),Hl="/vac/waku/metadata/1.0.0";class Gl{clusterId;streamManager;libp2pComponents;handshakesConfirmed=new Map;multicodec=Hl;constructor(e,t){this.clusterId=e,this.streamManager=new Ms(Hl,t),this.libp2pComponents=t,t.registrar.handle(Hl,e=>{this.onRequest(e)})}async query(e){const t=yr.encode({clusterId:this.clusterId,shards:[]});if(!await this.libp2pComponents.peerStore.get(e))return{shardInfo:null,error:_n.NO_PEER_AVAILABLE};let r;try{r=await this.streamManager.getStream(e)}catch(s){return Vl.error("Failed to get stream",s),{shardInfo:null,error:_n.NO_STREAM_AVAILABLE}}const n=await _s([t],ls,r,ms,async e=>await es(e)),{error:s,shardInfo:i}=this.decodeMetadataResponse(n);return s?{shardInfo:null,error:s}:(await this.savePeerShardInfo(e,i),{shardInfo:i,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}async onRequest(e){try{const{stream:t,connection:r}=e,n=br.encode({clusterId:this.clusterId,shards:[]}),s=await _s([n],ls,t,ms,async e=>await es(e)),{error:i,shardInfo:o}=this.decodeMetadataResponse(s);if(i)return;await this.savePeerShardInfo(r.remotePeer,o)}catch(e){Vl.error("Error handling metadata request",e)}}decodeMetadataResponse(e){const t=new os;e.forEach(e=>{t.append(e)});const r=br.decode(t);return r?{shardInfo:r,error:null}:(Vl.error("Error decoding metadata response"),{shardInfo:null,error:_n.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:zn(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function Wl(e){return t=>new Gl(e,t)}function Xl(e,t){const r=Fn(e),n=Fn(t.contentTopic),s=function(e){if(!e)return;let t;return t="bigint"==typeof e?e:1000000n*BigInt(e.valueOf()),function(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}(t)}(t.timestamp),i=Bn([r,t.payload,n,t.meta,s].filter(xr));return xn(i)}function Jl(e,t){const r=Xl(e,t);return Nn(r)}function Yl(){}class Zl extends EventTarget{#n=new Map;constructor(){super()}listenerCount(e){const t=this.#n.get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#n.get(e);null==n&&(n=[],this.#n.set(e,n)),n.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#n.get(e);null!=n&&(n=n.filter(({callback:e})=>e!==t),this.#n.set(e,n))}dispatchEvent(e){const t=super.dispatchEvent(e);let r=this.#n.get(e.type);return null==r||(r=r.filter(({once:e})=>!e),this.#n.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}const Ql=new Hn("peer-manager");var eu;!function(e){e.Connect="filter:connect",e.Disconnect="filter:disconnect"}(eu||(eu={}));class tu{events=new Zl;numPeersToUse;libp2p;connectionManager;lockedPeers=new Set;unlockedPeers=new Map;constructor(e){this.onConnected=this.onConnected.bind(this),this.onDisconnected=this.onDisconnected.bind(this),this.numPeersToUse=e?.config?.numPeersToUse||2,this.libp2p=e.libp2p,this.connectionManager=e.connectionManager}start(){this.libp2p.addEventListener("peer:identify",this.onConnected),this.libp2p.addEventListener("peer:disconnect",this.onDisconnected)}stop(){this.libp2p.removeEventListener("peer:identify",this.onConnected),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnected)}async getPeers(e){Ql.info(`Getting peers for protocol: ${e.protocol}, pubsubTopic: ${e.pubsubTopic}`);const t=await this.connectionManager.getConnectedPeers();Ql.info(`Found ${t.length} connected peers`);let r=[];for(const n of t){const t=this.hasPeerProtocol(n,e.protocol),s=await this.connectionManager.isPeerOnTopic(n.id,e.pubsubTopic),i=this.isPeerAvailableForUse(n.id);t&&s&&i&&(r.push(n),Ql.info(`Peer ${n.id} qualifies for protocol ${e.protocol}`))}const n=r.filter(e=>this.isPeerLocked(e.id));if(Ql.info(`Found ${n.length} locked peers out of ${r.length} qualifying peers`),n.length>=this.numPeersToUse){const e=n.slice(0,this.numPeersToUse).map(e=>e.id);return Ql.info(`Using ${e.length} locked peers: ${e.map(e=>e.toString())}`),e}const s=r.filter(e=>!this.isPeerLocked(e.id));Ql.info(`Found ${s.length} unlocked peers, need ${this.numPeersToUse-n.length} more`),r=[...n,...s].slice(0,this.numPeersToUse).map(e=>(this.lockPeer(e.id),e));const i=r.map(e=>e.id);return Ql.info(`Selected ${i.length} peers: ${i.map(e=>e.toString())}`),i}async renewPeer(e,t){Ql.info(`Renewing peer ${e} for protocol: ${t.protocol}, pubsubTopic: ${t.pubsubTopic}`);const r=(await this.connectionManager.getConnectedPeers()).find(t=>t.id.equals(e));r?(Ql.info(`Found peer ${e} in connected peers, unlocking and getting new peers`),this.unlockPeer(r.id),await this.getPeers(t)):Ql.warn(`Cannot renew peer:${e}, no connection to the peer.`)}async isPeerOnPubsub(e,t){return!await this.connectionManager.hasShardInfo(e)||this.connectionManager.isPeerOnTopic(e,t)}async onConnected(e){const t=e.detail;t.protocols.includes(this.matchProtocolToCodec(Cn.Filter))&&this.dispatchFilterPeerConnect(t.peerId)}async onDisconnected(e){const t=e.detail;try{const e=await this.libp2p.peerStore.get(t);this.hasPeerProtocol(e,Cn.Filter)&&this.dispatchFilterPeerDisconnect(e.id)}catch(e){Ql.error(`Failed to dispatch Filter disconnect event:${e}`)}}hasPeerProtocol(e,t){return e.protocols.includes(this.matchProtocolToCodec(t))}lockPeer(e){Ql.info(`Locking peer ${e}`),this.lockedPeers.add(e.toString()),this.libp2p.getConnections().filter(t=>t.remotePeer.equals(e)).forEach(e=>e.tags.push(Pn)),this.unlockedPeers.delete(e.toString())}isPeerLocked(e){return this.lockedPeers.has(e.toString())}unlockPeer(e){Ql.info(`Unlocking peer ${e}`),this.lockedPeers.delete(e.toString()),this.libp2p.getConnections().filter(t=>t.remotePeer.equals(e)).forEach(e=>{e.tags=e.tags.filter(e=>e!==Pn)}),this.unlockedPeers.set(e.toString(),Date.now())}isPeerAvailableForUse(e){const t=this.unlockedPeers.get(e.toString());if(!t)return!0;const r=new Date(t).getTime();return Date.now()-r>=1e4}dispatchFilterPeerConnect(e){this.events.dispatchEvent(new CustomEvent(eu.Connect,{detail:e}))}dispatchFilterPeerDisconnect(e){this.events.dispatchEvent(new CustomEvent(eu.Disconnect,{detail:e}))}matchProtocolToCodec(e){return{[Cn.Filter]:Gs,[Cn.LightPush]:Zs,[Cn.Store]:ii,[Cn.Relay]:""}[e]}}class ru{ttlMs;cleanupIntervalId=null;entryTimestamps=new Map;constructor(e,t=5e3){this.ttlMs=e,this.startCleanupInterval(t)}dispose(){null!==this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null),this.entryTimestamps.clear()}add(e){return this.entryTimestamps.set(e,Date.now()),this}has(e){return this.entryTimestamps.has(e)}startCleanupInterval(e){this.cleanupIntervalId=setInterval(()=>{this.removeExpiredEntries()},e)}removeExpiredEntries(){const e=Date.now();for(const[t,r]of this.entryTimestamps.entries())e-r>this.ttlMs&&this.entryTimestamps.delete(t)}}const nu=new Hn("sdk:filter-subscription");class su{pubsubTopic;protocol;peerManager;config;isStarted=!1;inProgress=!1;peers=new Map;peerFailures=new Map;receivedMessages=new ru(6e4);callbacks=new Map;messageEmitter=new Zl;toSubscribeContentTopics=new Set;toUnsubscribeContentTopics=new Set;subscribeIntervalId=null;keepAliveIntervalId=null;get contentTopics(){const e=Array.from(this.callbacks.keys()).map(e=>e.contentTopic),t=new Set(e).values();return Array.from(t)}constructor(e){this.config=e.config,this.pubsubTopic=e.pubsubTopic,this.protocol=e.protocol,this.peerManager=e.peerManager,this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}start(){nu.info(`Starting subscription for pubsubTopic: ${this.pubsubTopic}`),this.isStarted||this.inProgress?nu.info("Subscription already started or in progress, skipping start"):(this.inProgress=!0,this.attemptSubscribe({useNewContentTopics:!1}),this.setupSubscriptionInterval(),this.setupKeepAliveInterval(),this.setupEventListeners(),this.isStarted=!0,this.inProgress=!1,nu.info(`Subscription started for pubsubTopic: ${this.pubsubTopic}`))}stop(){nu.info(`Stopping subscription for pubsubTopic: ${this.pubsubTopic}`),this.isStarted&&!this.inProgress?(this.inProgress=!0,this.disposeEventListeners(),this.disposeIntervals(),this.disposePeers(),this.disposeHandlers(),this.receivedMessages.dispose(),this.inProgress=!1,this.isStarted=!1,nu.info(`Subscription stopped for pubsubTopic: ${this.pubsubTopic}`)):nu.info("Subscription not started or stop in progress, skipping stop")}isEmpty(){return 0===this.callbacks.size}async add(e,t){const r=Array.isArray(e)?e:[e];for(const e of r)this.addSingle(e,t);return!(this.toSubscribeContentTopics.size>0)||await this.attemptSubscribe({useNewContentTopics:!0})}async remove(e){const t=Array.isArray(e)?e:[e];for(const e of t)this.removeSingle(e);return!(this.toUnsubscribeContentTopics.size>0)||await this.attemptUnsubscribe({useNewContentTopics:!0})}invoke(e,t){this.isMessageReceived(e)?nu.info(`Skipping invoking callbacks for already received message: pubsubTopic:${this.pubsubTopic}, peerId:${t.toString()}, contentTopic:${e.contentTopic}`):(nu.info(`Invoking message for contentTopic: ${e.contentTopic}`),this.messageEmitter.dispatchEvent(new CustomEvent(e.contentTopic,{detail:e})))}addSingle(e,t){nu.info(`Adding subscription for contentTopic: ${e.contentTopic}`);const r=!this.contentTopics.includes(e.contentTopic);if(r&&this.toSubscribeContentTopics.add(e.contentTopic),this.callbacks.has(e)){nu.warn(`Replacing callback associated associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`);const t=this.callbacks.get(e);this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t)}const n=r=>{(async()=>{try{const n=await e.fromProtoObj(e.pubsubTopic,r.detail);t(n)}catch(e){nu.error("Error decoding message",e)}})()};this.callbacks.set(e,n),this.messageEmitter.addEventListener(e.contentTopic,n),nu.info(`Subscription added for contentTopic: ${e.contentTopic}, isNewContentTopic: ${r}`)}removeSingle(e){nu.info(`Removing subscription for contentTopic: ${e.contentTopic}`);const t=this.callbacks.get(e);t||nu.warn(`No callback associated with decoder with pubsubTopic:${e.pubsubTopic} and contentTopic:${e.contentTopic}`),this.callbacks.delete(e),this.messageEmitter.removeEventListener(e.contentTopic,t);const r=!this.contentTopics.includes(e.contentTopic);r&&this.toUnsubscribeContentTopics.add(e.contentTopic),nu.info(`Subscription removed for contentTopic: ${e.contentTopic}, isCompletelyRemoved: ${r}`)}isMessageReceived(e){try{const t=Jl(this.pubsubTopic,e);if(this.receivedMessages.has(t))return!0;this.receivedMessages.add(t)}catch(e){}return!1}setupSubscriptionInterval(){nu.info("Setting up subscription interval with period 1000ms"),this.subscribeIntervalId=setInterval(()=>{(async()=>{this.toSubscribeContentTopics.size>0&&(nu.info(`Subscription interval: ${this.toSubscribeContentTopics.size} topics to subscribe`),await this.attemptSubscribe({useNewContentTopics:!0})),this.toUnsubscribeContentTopics.size>0&&(nu.info(`Subscription interval: ${this.toUnsubscribeContentTopics.size} topics to unsubscribe`),await this.attemptUnsubscribe({useNewContentTopics:!0}))})()},1e3)}setupKeepAliveInterval(){nu.info(`Setting up keep-alive interval with period ${this.config.keepAliveIntervalMs}ms`),this.keepAliveIntervalId=setInterval(()=>{(async()=>{nu.info(`Keep-alive interval running for ${this.peers.size} peers`);let e=await Promise.all(Array.from(this.peers.values()).map(async e=>{if((await this.protocol.ping(e)).success)return nu.info(`Ping successful for peer: ${e.toString()}`),void this.peerFailures.set(e.toString(),0);let t=this.peerFailures.get(e.toString())||0;return t+=1,this.peerFailures.set(e.toString(),t),nu.warn(`Ping failed for peer: ${e.toString()}, failures: ${t}/${this.config.pingsBeforePeerRenewed}`),t<this.config.pingsBeforePeerRenewed?void 0:(nu.info(`Peer ${e.toString()} exceeded max failures (${this.config.pingsBeforePeerRenewed}), will be replaced`),e)}));e=e.filter(e=>!!e),await Promise.all(e.map(e=>(this.peers.delete(e?.toString()),this.peerFailures.delete(e?.toString()),this.requestUnsubscribe(e,this.contentTopics)))),e.length>0&&(nu.info(`Replacing ${e.length} failed peers`),await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}))})()},this.config.keepAliveIntervalMs)}setupEventListeners(){this.peerManager.events.addEventListener(eu.Connect,this.onPeerConnected),this.peerManager.events.addEventListener(eu.Disconnect,this.onPeerDisconnected)}disposeIntervals(){this.subscribeIntervalId&&clearInterval(this.subscribeIntervalId),this.keepAliveIntervalId&&clearInterval(this.keepAliveIntervalId)}disposeHandlers(){for(const[e,t]of this.callbacks.entries())this.messageEmitter.removeEventListener(e.contentTopic,t);this.callbacks.clear()}async disposePeers(){await this.attemptUnsubscribe({useNewContentTopics:!1}),this.peers.clear(),this.peerFailures=new Map}disposeEventListeners(){this.peerManager.events.removeEventListener(eu.Connect,this.onPeerConnected),this.peerManager.events.removeEventListener(eu.Disconnect,this.onPeerDisconnected)}async onPeerConnected(e){const t=e.detail?.toString();nu.info(`Peer connected: ${t}`),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(t)?nu.info(`Peer ${t} already subscribed, skipping`):await this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0}):nu.info(`Peer ${t} doesn't support pubsubTopic:${this.pubsubTopic}`)}async onPeerDisconnected(e){const t=e.detail?.toString();nu.info(`Peer disconnected: ${t}`),await this.peerManager.isPeerOnPubsub(e.detail,this.pubsubTopic)?this.peers.has(t)?(nu.info(`Active peer ${t} disconnected, removing from peers list`),this.peers.delete(t),this.attemptSubscribe({useNewContentTopics:!1,useOnlyNewPeers:!0})):nu.info(`Disconnected peer ${t} not in use, ignoring`):nu.info(`Peer ${t} doesn't support pubsubTopic:${this.pubsubTopic}`)}async attemptSubscribe(e){const{useNewContentTopics:t,useOnlyNewPeers:r=!1}=e,n=t?Array.from(this.toSubscribeContentTopics):this.contentTopics;if(nu.info(`Attempting to subscribe: useNewContentTopics=${t}, useOnlyNewPeers=${r}, contentTopics=${n.length}`),!n.length)return nu.warn("Requested content topics is an empty array, skipping"),!1;const s=new Set(this.peers.keys()),i=await this.peerManager.getPeers({protocol:Cn.Filter,pubsubTopic:this.pubsubTopic});for(const e of i){if(this.peers.size>=this.config.numPeersToUse)break;this.peers.set(e.toString(),e)}const o=r?Array.from(this.peers.values()).filter(e=>!s.has(e.toString())):Array.from(this.peers.values());if(nu.info(`Subscribing with ${o.length} peers for ${n.length} content topics`),r&&0===o.length)return nu.warn("Requested to use only new peers, but no peers found, skipping"),!1;const a=await Promise.all(o.map(e=>this.requestSubscribe(e,n))),c=a.filter(e=>e).length;return nu.info(`Subscribe attempts completed: ${c}/${a.length} successful`),t&&(this.toSubscribeContentTopics=new Set),a.some(e=>e)}async requestSubscribe(e,t){if(nu.info(`requestSubscribe: pubsubTopic:${this.pubsubTopic}\tcontentTopics:${t.join(",")}`),!t.length||!this.pubsubTopic)return nu.warn("requestSubscribe: no contentTopics or pubsubTopic provided, not sending subscribe request"),!1;const r=await this.protocol.subscribe(this.pubsubTopic,e,t);return r.failure?(nu.warn(`requestSubscribe: Failed to subscribe ${this.pubsubTopic} to ${e.toString()} with error:${r.failure.error} for contentTopics:${t}`),!1):(nu.info(`requestSubscribe: Subscribed ${this.pubsubTopic} to ${e.toString()} for contentTopics:${t}`),!0)}async attemptUnsubscribe(e){const{useNewContentTopics:t}=e,r=t?Array.from(this.toUnsubscribeContentTopics):this.contentTopics;if(nu.info(`Attempting to unsubscribe: useNewContentTopics=${t}, contentTopics=${r.length}`),!r.length)return nu.warn("Requested content topics is an empty array, skipping"),!1;const n=Array.from(this.peers.values()),s=await Promise.all(n.map(e=>this.requestUnsubscribe(e,t?r:void 0))),i=s.filter(e=>e).length;return nu.info(`Unsubscribe attempts completed: ${i}/${s.length} successful`),t&&(this.toUnsubscribeContentTopics=new Set),s.some(e=>e)}async requestUnsubscribe(e,t){const r=t?await this.protocol.unsubscribe(this.pubsubTopic,e,t):await this.protocol.unsubscribeAll(this.pubsubTopic,e);return r.failure?(nu.warn(`requestUnsubscribe: Failed to unsubscribe for pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} with error:${r.failure?.error} for contentTopics:${t}`),!1):(nu.info(`requestUnsubscribe: Unsubscribed pubsubTopic:${this.pubsubTopic} from peerId:${e.toString()} for contentTopics:${t}`),!0)}}const iu=new Hn("sdk:filter");class ou{protocol;peerManager;config;subscriptions=new Map;constructor(e){this.config={numPeersToUse:2,pingsBeforePeerRenewed:3,keepAliveIntervalMs:6e4,...e.options},this.peerManager=e.peerManager,this.protocol=new Xs(this.onIncomingMessage.bind(this),e.libp2p)}get multicodec(){return this.protocol.multicodec}unsubscribeAll(){for(const e of this.subscriptions.values())e.stop();this.subscriptions.clear()}async subscribe(e,t){const r=Array.isArray(e)?e:[e];if(0===r.length)throw Error("Cannot subscribe with 0 decoders.");const n=r.map(e=>e.pubsubTopic),s=n[0],i=r.map(e=>e.contentTopic);iu.info(`Subscribing to contentTopics: ${i}, pubsubTopic: ${s}`),this.throwIfTopicNotSame(n);let o=this.subscriptions.get(s);o||(o=new su({pubsubTopic:s,protocol:this.protocol,config:this.config,peerManager:this.peerManager}),o.start());const a=await o.add(r,t);return this.subscriptions.set(s,o),iu.info(`Subscription ${a?"successful":"failed"} for content topic: ${i}`),a}async unsubscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw Error("Cannot unsubscribe with 0 decoders.");const r=t.map(e=>e.pubsubTopic),n=r[0],s=t.map(e=>e.contentTopic);iu.info(`Unsubscribing from contentTopics: ${s}, pubsubTopic: ${n}`),this.throwIfTopicNotSame(r);const i=this.subscriptions.get(n);if(!i)return iu.warn("No subscriptions associated with the decoder."),!1;const o=await i.remove(t);return i.isEmpty()&&(iu.warn("Subscription has no decoders anymore, terminating it."),i.stop(),this.subscriptions.delete(n)),iu.info(`Unsubscribing ${o?"successful":"failed"} for content topic: ${s}`),o}async onIncomingMessage(e,t,r){iu.info(`Received message for pubsubTopic:${e}, contentTopic:${t.contentTopic}, peerId:${r.toString()}`);const n=this.subscriptions.get(e);n?n.invoke(t,r):iu.error(`No subscription locally registered for topic ${e}`)}throwIfTopicNotSame(e){const t=e[0];if(!e.every(e=>e===t))throw Error(`Cannot subscribe to more than one pubsub topic at the same time, got pubsubTopics:${e}`)}}const au=new Hn("health-indicator");class cu{libp2p;events;value=On.Unhealthy;constructor(e){this.libp2p=e.libp2p,this.events=e.events,this.onPeerIdentify=this.onPeerIdentify.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}start(){au.info("start: adding listeners to libp2p"),this.libp2p.addEventListener("peer:identify",this.onPeerIdentify),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnected)}stop(){au.info("stop: removing listeners to libp2p"),this.libp2p.removeEventListener("peer:identify",this.onPeerIdentify),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnected)}toValue(){return this.value}async onPeerDisconnected(e){au.info("onPeerDisconnected: received libp2p event"),this.libp2p.getConnections().length>0&&au.info("onPeerDisconnected: has connections, ignoring"),this.value=On.Unhealthy,au.info(`onPeerDisconnected: node identified as ${this.value}`),this.dispatchHealthEvent()}async onPeerIdentify(e){au.info("onPeerIdentify: received libp2p event");const t=this.libp2p.getConnections(),r=await Promise.all(t.map(async e=>{try{return await this.libp2p.peerStore.get(e.remotePeer)}catch(e){return null}})),n=r.filter(e=>e?.protocols.includes(Gs)).length,s=r.filter(e=>e?.protocols.includes(Zs)).length;0===n||0===s?this.value=On.Unhealthy:n>=2&&s>=2?this.value=On.SufficientlyHealthy:1===n&&1===s?this.value=On.MinimallyHealthy:au.error(`onPeerChange: unexpected state, cannot identify health status of the node: Filter:${n}; LightPush:${s}`),au.info(`onPeerChange: node identified as ${this.value}`),this.dispatchHealthEvent()}dispatchHealthEvent(){this.events.dispatchEvent(new CustomEvent("waku:health",{detail:this.value}))}}const lu=e=>new Promise((t,r)=>setTimeout(()=>r(new Error("Task timeout")),e)),uu=new Hn("sdk:retry-manager");class hu{intervalID=null;retryIntervalMs;inProgress=0;queue=[];peerManager;constructor(e){this.peerManager=e.peerManager,this.retryIntervalMs=e.retryIntervalMs||1e3}start(){this.intervalID=setInterval(()=>{this.processQueue()},this.retryIntervalMs)}stop(){this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}push(e,t,r){this.queue.push({maxAttempts:t,callback:e,pubsubTopic:r})}processQueue(){if(0!==this.queue.length)for(;this.queue.length&&this.inProgress<5;){const e=this.queue.shift();e&&this.scheduleTask(e)}}scheduleTask(e){setTimeout(async()=>this.taskExecutor(e),100)}async taskExecutor(e){if(e.maxAttempts<=0)return void uu.warn("scheduleTask: max attempts has reached, removing from queue");const t=(await this.peerManager.getPeers({protocol:Cn.LightPush,pubsubTopic:e.pubsubTopic}))[0];if(!t)return uu.warn("scheduleTask: no peers, putting back to queue"),void this.queue.push({...e,maxAttempts:e.maxAttempts-1});try{this.inProgress+=1;const r=await Promise.race([lu(1e4),e.callback(t)]);if(r?.failure)throw Error(r.failure.error);if(uu.info("scheduleTask: executed successfully"),0===e.maxAttempts)return void uu.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...e,maxAttempts:e.maxAttempts-1})}catch(n){const s=n;if(uu.error("scheduleTask: task execution failed with error:",s),((r=s.message)===_n.REMOTE_PEER_REJECTED||r===_n.NO_RESPONSE||r===_n.RLN_PROOF_GENERATION||r===_n.NO_PEER_AVAILABLE)&&await this.peerManager.renewPeer(t,{protocol:Cn.LightPush,pubsubTopic:e.pubsubTopic}),0===e.maxAttempts)return void uu.warn("scheduleTask: discarded a task due to limit of max attempts");this.queue.push({...e,maxAttempts:e.maxAttempts-1})}finally{this.inProgress-=1}var r}}const du=new Hn("sdk:light-push"),pu={autoRetry:!0,retryIntervalMs:1e3,maxAttempts:3,numPeersToUse:1};class fu{config;retryManager;peerManager;protocol;constructor(e){this.config={...pu,...e.options||{}},this.peerManager=e.peerManager,this.protocol=new Qs(e.libp2p),this.retryManager=new hu({peerManager:e.peerManager,retryIntervalMs:this.config.retryIntervalMs})}get multicodec(){return this.protocol.multicodec}start(){this.retryManager.start()}stop(){this.retryManager.stop()}async send(e,t,r={}){r={...this.config,...r};const{pubsubTopic:n}=e;du.info("send: attempting to send a message to pubsubTopic:",n);const s=await this.peerManager.getPeers({protocol:Cn.LightPush,pubsubTopic:e.pubsubTopic}),i=s?.length>0?await Promise.all(s.map(r=>this.protocol.send(e,t,r).catch(e=>({success:null,failure:{error:_n.GENERIC_FAIL}})))):[],o=i.length?{successes:i.filter(e=>e.success).map(e=>e.success),failures:i.filter(e=>e.failure).map(e=>e.failure)}:{successes:[],failures:[{error:_n.NO_PEER_AVAILABLE}]};if(r.autoRetry&&0===o.successes.length){const n=r=>this.protocol.send(e,t,r);this.retryManager.push(n.bind(this),r.maxAttempts||3,e.pubsubTopic)}return o}}const gu=new Hn("waku:store:sdk");class mu{options;libp2p;peerManager;protocol;constructor(e){this.options=e.options||{},this.peerManager=e.peerManager,this.libp2p=e.libp2p,this.protocol=new oi(e.libp2p)}get multicodec(){return this.protocol.multicodec}async*queryGenerator(e,t){let r,n,s;if(t?.messageHashes&&t.messageHashes.length>0)r=t.pubsubTopic||e[0]?.pubsubTopic||"",n=[],s=new Map,e.forEach(e=>{s.set(e.contentTopic,e)});else{const t=this.validateDecodersAndPubsubTopic(e);r=t.pubsubTopic,n=t.contentTopics,s=t.decodersAsMap}const i={pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t},o=await this.getPeerToUse(r);if(!o)throw gu.error("No peers available to query"),new Error("No peers available to query");gu.info(`Querying store with options: ${JSON.stringify(t)}`);const a=this.protocol.queryPerPage(i,s,o);for await(const e of a)yield e}async queryWithOrderedCallback(e,t,r){gu.info("Querying store with ordered callback");for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t))break}async queryWithPromiseCallback(e,t,r){gu.info("Querying store with promise callback");let n=!1;for await(const s of this.queryGenerator(e,r)){const e=s.map(async e=>{n||(n=Boolean(await t(e)))});if(await Promise.all(e),n)break}}async processMessages(e,t){let r=!1;const n=(await Promise.all(e)).filter(xr);return await Promise.all(n.map(async e=>{e&&!r&&(r=Boolean(await t(e)))})),r}createCursor(e){return Xl(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(0===e.length)throw gu.error("No decoders provided"),new Error("No decoders provided");const t=Array.from(new Set(e.map(e=>e.pubsubTopic)));if(t.length>1)throw gu.error("API does not support querying multiple pubsub topics at once"),new Error("API does not support querying multiple pubsub topics at once");const r=t[0],n=new Map;e.forEach(e=>{if(n.has(e.contentTopic))throw gu.error("API does not support different decoder per content topic"),new Error("API does not support different decoder per content topic");n.set(e.contentTopic,e)});const s=e.filter(e=>e.pubsubTopic===r).map(e=>e.contentTopic);if(0===s.length)throw gu.error(`No decoders found for topic ${r}`),new Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:s,decodersAsMap:n}}async getPeerToUse(e){const t=await this.peerManager.getPeers({protocol:Cn.Store,pubsubTopic:e});return this.options.peers?await this.getPeerFromConfigurationOrFirst(t,this.options.peers):t[0]}async getPeerFromConfigurationOrFirst(e,t){const r=t.map($l),n=[];for(const t of r){const r=e.find(e=>e.toString()===t.getPeerId()?.toString());if(r)return r;n.push(t)}for(;n.length;){const e=n.pop();if(!e)return;try{if(await this.libp2p.dial(e))return Yc(e.getPeerId())}catch(t){gu.warn(`Failed to dial peer from options.peers list for Store protocol. Peer:${e.getPeerId()}, error:${t}`)}}return gu.warn(`Passed node to use for Store not found: ${t.toString()}. Attempting to use first available peers.`),e[0]}}const yu=(e,t)=>{const r=e.shardInfo?.clusterId||t.clusterId,n=e.shardInfo&&"shardsUnderCluster"in e.shardInfo?e.shardInfo.shardsUnderCluster:8;return{clusterId:r,shard:e.shardInfo&&"shard"in e.shardInfo?e.shardInfo.shard:$n(e.contentTopic,n)}},bu=(e,t)=>t.clusterId===e.clusterId&&!("shards"in t&&!t.shards.includes(e.shard)),wu=new Hn("wait-for-remote-peer");async function vu(e,t){const r=[];return e.relay&&t.includes(Cn.Relay)&&r.push(e.relay.waitForPeers()),e.store&&t.includes(Cn.Store)&&r.push(Eu(ii,e.libp2p)),e.lightPush&&t.includes(Cn.LightPush)&&r.push(Eu(Zs,e.libp2p)),e.filter&&t.includes(Cn.Filter)&&r.push(Eu(Gs,e.libp2p)),Promise.all(r)}async function Eu(e,t){wu.info(`Waiting for ${e} peer.`),await new Promise(r=>{const n=async s=>{if(s.detail?.protocols?.includes(e)){const e=t.services.metadata;if(!e)return t.removeEventListener("peer:identify",n),void r();try{await e.confirmOrAttemptHandshake(s.detail.peerId),t.removeEventListener("peer:identify",n),r()}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&wu.error("Connection closed. Some peers can be on different shard."),wu.error(`Error waiting for metadata: ${e}`)}}};t.addEventListener("peer:identify",n)})}const Su=(e,t)=>new Promise((r,n)=>setTimeout(()=>n(Error(t)),e)),Au=new Hn("waku");class Iu{libp2p;relay;store;filter;lightPush;events=new Zl;networkConfig;_nodeStateLock=!1;_nodeStarted=!1;connectionManager;peerManager;healthIndicator;constructor(e,t,r,n){this.relay=n,this.libp2p=t,this.networkConfig=e.networkConfig||Rn,r={filter:!1,lightpush:!1,store:!1,...r};const s=this.libp2p.peerId.toString();this.connectionManager=new Kl({libp2p:t,relay:this.relay,events:this.events,networkConfig:this.networkConfig,config:e?.connectionManager}),this.peerManager=new tu({libp2p:t,config:{numPeersToUse:e.numPeersToUse},connectionManager:this.connectionManager}),this.healthIndicator=new cu({libp2p:t,events:this.events}),r.store&&(this.store=new mu({libp2p:t,peerManager:this.peerManager,options:e?.store})),r.lightpush&&(this.lightPush=new fu({libp2p:t,peerManager:this.peerManager,options:e?.lightPush})),r.filter&&(this.filter=new ou({libp2p:t,peerManager:this.peerManager,options:e.filter})),Au.info("Waku node created",s,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}get health(){return this.healthIndicator.toValue()}async dial(e,t){const r=t??[];void 0===t&&(this.relay&&r.push(Cn.Relay),this.store&&r.push(Cn.Store),this.filter&&r.push(Cn.Filter),this.lightPush&&r.push(Cn.LightPush));const n=[];return r.includes(Cn.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach(e=>n.push(e)):Au.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(Cn.Store)&&(this.store?n.push(this.store.multicodec):Au.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(Cn.LightPush)&&(this.lightPush?n.push(this.lightPush.multicodec):Au.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(Cn.Filter)&&(this.filter?n.push(this.filter.multicodec):Au.error("Filter codec not included in dial codec: protocol not mounted locally")),Au.info(`Dialing to ${e?.toString()} with protocols ${r}`),await this.connectionManager.dial(e,n)}async hangUp(e){return Au.info(`Hanging up peer:${e?.toString()}.`),this.connectionManager.hangUp(e)}async start(){this._nodeStateLock||this.isStarted()||(this._nodeStateLock=!0,await this.libp2p.start(),this.connectionManager.start(),this.peerManager.start(),this.healthIndicator.start(),this.lightPush?.start(),this._nodeStateLock=!1,this._nodeStarted=!0)}async stop(){!this._nodeStateLock&&this.isStarted()&&(this._nodeStateLock=!0,this.lightPush?.stop(),this.healthIndicator.stop(),this.peerManager.stop(),this.connectionManager.stop(),await this.libp2p.stop(),this._nodeStateLock=!1,this._nodeStarted=!1)}async getConnectedPeers(){return this.connectionManager.getConnectedPeers()}async waitForPeers(e,t){return async function(e,t,r){t=t?.length?t:function(e){const t=[];return e.relay&&t.push(Cn.Relay),e.filter&&t.push(Cn.Filter),e.store&&t.push(Cn.Store),e.lightPush&&t.push(Cn.LightPush),t}(e);const n=e.libp2p.getConnections();if(!e.isStarted())throw Error("Waku node is not started");for(const r of t)switch(r){case Cn.Relay:if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");break;case Cn.LightPush:if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");break;case Cn.Store:if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");break;case Cn.Filter:if(!e.filter)throw Error("Cannot wait for Filter peer: protocol not mounted")}const s=[vu(e,t)];n.length>0&&!t.includes(Cn.Relay)&&s.push(async function(e,t){const r=e.libp2p.getPeers(),n=e.libp2p.services.metadata,s=function(e){const t=new Map,r={[Cn.Filter]:Gs,[Cn.LightPush]:Zs,[Cn.Store]:ii};for(const n of e)r[n]&&t.set(r[n],!1);return t}(t);if(r.length&&n)for(const t of r)try{const r=await e.libp2p.peerStore.get(t);if(r.protocols.some(e=>s.has(e))&&!(await n.confirmOrAttemptHandshake(t)).error&&(r.protocols.forEach(e=>{s.has(e)&&s.set(e,!0)}),Array.from(s.values()).every(e=>e)))return}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&wu.error("Connection closed. Some peers can be on different shard."),wu.error(`Error while iterating through peers: ${e}`);continue}else wu.info(`Skipping waitForMetadata due to missing connections:${r.length} or metadataService:${!!n}`)}(e,t)),r?await async function(e,t){await Promise.race([e,Su(t,"Timed out waiting for a remote peer.")])}(Promise.any(s),r):await Promise.any(s)}(this,e,t)}isStarted(){return this._nodeStarted&&"started"===this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}createDecoder(e){const t=yu(e,this.networkConfig);if(Au.info(`Creating Decoder with input:${JSON.stringify(e.shardInfo)}, determined:${JSON.stringify(t)}, expected:${JSON.stringify(this.networkConfig)}.`),!bu(t,this.networkConfig))throw Error("Cannot create decoder: incompatible shard configuration.");return Qn(e.contentTopic,t)}createEncoder(e){const t=yu(e,this.networkConfig);if(Au.info(`Creating Encoder with input:${JSON.stringify(e.shardInfo)}, determined:${JSON.stringify(t)}, expected:${JSON.stringify(this.networkConfig)}.`),!bu(t,this.networkConfig))throw Error("Cannot create encoder: incompatible shard configuration.");return Yn({contentTopic:e.contentTopic,ephemeral:e.ephemeral,pubsubTopicShardInfo:t})}}const ku=Symbol.for("@libp2p/service-capabilities"),xu=Symbol.for("@libp2p/service-dependencies"),Cu=4194304;class _u extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Tu extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Pu extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}class Ru extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}function Ou(e){return null!=e[Symbol.asyncIterator]}function Lu(e,t){if(e.byteLength>t)throw new Tu("Message length too long")}const Du=e=>{const t=k(e),r=g(t);return _(e,r),Du.bytes=t,r};function Nu(e,t){const r=(t=t??{}).lengthEncoder??Du,n=t?.maxDataLength??Cu;function*s(e){Lu(e,n);const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Ou(e)?async function*(){for await(const t of e)yield*s(t)}():function*(){for(const t of e)yield*s(t)}()}var Mu;Du.bytes=0,Nu.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Du;return Lu(e,t?.maxDataLength??Cu),new os(r(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Mu||(Mu={}));const Fu=e=>{const t=T(e);return Fu.bytes=k(t),t};function Bu(e,t){const r=new os;let n=Mu.LENGTH,s=-1;const i=t?.lengthDecoder??Fu,o=t?.maxLengthLength??8,a=t?.maxDataLength??Cu;function*c(){for(;r.byteLength>0;){if(n===Mu.LENGTH)try{if(s=i(r),s<0)throw new _u("Invalid message length");if(s>a)throw new Tu("Message length too long");const e=i.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=Mu.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>o)throw new Pu("Message length length too long");break}throw e}if(n===Mu.DATA){if(r.byteLength<s)break;const e=r.sublist(0,s);r.consume(s),null!=t?.onData&&t.onData(e),yield e,n=Mu.LENGTH}}}return Ou(e)?async function*(){for await(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Ru("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Ru("Unexpected end of input")}()}Fu.bytes=0,Bu.fromReader=(e,t)=>{let r=1;return Bu(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength:e=>{r=e}})};class Uu extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}function $u(e,t){const r=ks();e.sink(r).catch(async e=>{await r.end(e)}),e.sink=async e=>{for await(const t of e)await r.push(t);await r.end()};let n=e.source;null!=e.source[Symbol.iterator]?n=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(n=e.source[Symbol.asyncIterator]());const s=new os;return{read:async e=>{if(e?.signal?.throwIfAborted(),null==e?.bytes){const{done:t,value:r}=await As(n.next(),e?.signal);return!0===t?null:r}for(;s.byteLength<e.bytes;){const{value:t,done:r}=await As(n.next(),e?.signal);if(!0===r)throw new Uu("unexpected end of input");s.append(t)}const t=s.sublist(0,e.bytes);return s.consume(e.bytes),t},write:async(e,t)=>{t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap:()=>{if(s.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield s:yield*s,yield*r}()}return e}}}class qu extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class ju extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class zu extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function Ku(e,t={}){const r=$u(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=k(t.maxDataLength));const n=t?.lengthDecoder??T,s=t?.lengthEncoder??_;return{read:async e=>{let s=-1;const i=new os;for(;;){i.append(await r.read({...e,bytes:1}));try{s=n(i)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new qu("Invalid message length");if(null!=t?.maxLengthLength&&i.byteLength>t.maxLengthLength)throw new zu("message length length too long");if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new ju("message length too long");return r.read({...e,bytes:s})},write:async(e,t)=>{await r.write(new os(s(e.byteLength),e),t)},writeV:async(e,t)=>{const n=new os(...e.flatMap(e=>[s(e.byteLength),e]));await r.write(n,t)},unwrap:()=>r.unwrap()}}function Vu(){const e=ys();let t=!1;return{sink:async r=>{if(t)throw new Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const Hu=65535,Gu=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function Wu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Xu(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Ju(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Yu(e,...t){if(!Wu(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Zu(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Qu(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function eh(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const th=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function rh(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Wu(e))throw new Error("Uint8Array expected, got "+typeof e);e=oh(e)}return e}const nh=(e,t)=>{function r(r,...n){if(Yu(r),!th)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=n[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?Yu(t):Yu(t,e.nonceLength)}const s=e.tagLength;s&&void 0!==n[1]&&Yu(n[1]);const i=t(r,...n),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");Yu(t)}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,Yu(e),o(i.encrypt.length,t),i.encrypt(e,t)},decrypt(e,t){if(Yu(e),s&&e.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return o(i.decrypt.length,t),i.decrypt(e,t)}}}return Object.assign(r,e),r};function sh(e,t,r=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(r&&t.byteOffset%4!=0)throw new Error("invalid output, must be aligned");return t}function ih(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),i=BigInt(4294967295),o=Number(r>>s&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+l,a,n)}function oh(e){return Uint8Array.from(e)}const ah=e=>Uint8Array.from(e.split("").map(e=>e.charCodeAt(0))),ch=ah("expand 16-byte k"),lh=ah("expand 32-byte k"),uh=Qu(ch),hh=Qu(lh);function dh(e,t){return e<<t|e>>>32-t}function ph(e){return e.byteOffset%4==0}const fh=2**32-1,gh=new Uint32Array;function mh(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:i,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw new Error("core must be a function");return Ju(s),Ju(o),Xu(i),Xu(r),(t,a,c,l,u=0)=>{Yu(t),Yu(a),Yu(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),Yu(l),Ju(u),u<0||u>=fh)throw new Error("arx: counter overflow");if(l.length<h)throw new Error(`arx: output (${l.length}) is shorter than data (${h})`);const d=[];let p,f,g=t.length;if(32===g)d.push(p=oh(t)),f=hh;else{if(16!==g||!r)throw new Error(`arx: invalid 32-byte key, got length=${g}`);p=new Uint8Array(32),p.set(t),p.set(t,16),f=uh,d.push(p)}ph(a)||d.push(a=oh(a));const m=Qu(p);if(n){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");n(f,m,Qu(a.subarray(0,16)),m),a=a.subarray(16)}const y=16-s;if(y!==a.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(12!==y){const e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,d.push(a)}const b=Qu(a);return function(e,t,r,n,s,i,o,a){const c=s.length,l=new Uint8Array(64),u=Qu(l),h=ph(s)&&ph(i),d=h?Qu(s):gh,p=h?Qu(i):gh;for(let f=0;f<c;o++){if(e(t,r,n,u,o,a),o>=fh)throw new Error("arx: counter overflow");const g=Math.min(64,c-f);if(h&&64===g){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,r=0;r<16;r++)t=e+r,p[t]=d[t]^u[r];f+=64;continue}for(let e,t=0;t<g;t++)e=f+t,i[e]=s[e]^l[t];f+=g}}(e,f,m,b,c,l,u,o),eh(...d),l}}const yh=(e,t)=>255&e[t++]|(255&e[t++])<<8;class bh{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,Yu(e=rh(e),32);const t=yh(e,0),r=yh(e,2),n=yh(e,4),s=yh(e,6),i=yh(e,8),o=yh(e,10),a=yh(e,12),c=yh(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|s<<9),this.r[4]=255&(s>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=yh(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:s,r:i}=this,o=i[0],a=i[1],c=i[2],l=i[3],u=i[4],h=i[5],d=i[6],p=i[7],f=i[8],g=i[9],m=yh(e,t+0),y=yh(e,t+2),b=yh(e,t+4),w=yh(e,t+6),v=yh(e,t+8),E=yh(e,t+10),S=yh(e,t+12),A=yh(e,t+14);let I=s[0]+(8191&m),k=s[1]+(8191&(m>>>13|y<<3)),x=s[2]+(8191&(y>>>10|b<<6)),C=s[3]+(8191&(b>>>7|w<<9)),_=s[4]+(8191&(w>>>4|v<<12)),T=s[5]+(v>>>1&8191),P=s[6]+(8191&(v>>>14|E<<2)),R=s[7]+(8191&(E>>>11|S<<5)),O=s[8]+(8191&(S>>>8|A<<8)),L=s[9]+(A>>>5|n),D=0,N=D+I*o+k*(5*g)+x*(5*f)+C*(5*p)+_*(5*d);D=N>>>13,N&=8191,N+=T*(5*h)+P*(5*u)+R*(5*l)+O*(5*c)+L*(5*a),D+=N>>>13,N&=8191;let M=D+I*a+k*o+x*(5*g)+C*(5*f)+_*(5*p);D=M>>>13,M&=8191,M+=T*(5*d)+P*(5*h)+R*(5*u)+O*(5*l)+L*(5*c),D+=M>>>13,M&=8191;let F=D+I*c+k*a+x*o+C*(5*g)+_*(5*f);D=F>>>13,F&=8191,F+=T*(5*p)+P*(5*d)+R*(5*h)+O*(5*u)+L*(5*l),D+=F>>>13,F&=8191;let B=D+I*l+k*c+x*a+C*o+_*(5*g);D=B>>>13,B&=8191,B+=T*(5*f)+P*(5*p)+R*(5*d)+O*(5*h)+L*(5*u),D+=B>>>13,B&=8191;let U=D+I*u+k*l+x*c+C*a+_*o;D=U>>>13,U&=8191,U+=T*(5*g)+P*(5*f)+R*(5*p)+O*(5*d)+L*(5*h),D+=U>>>13,U&=8191;let $=D+I*h+k*u+x*l+C*c+_*a;D=$>>>13,$&=8191,$+=T*o+P*(5*g)+R*(5*f)+O*(5*p)+L*(5*d),D+=$>>>13,$&=8191;let q=D+I*d+k*h+x*u+C*l+_*c;D=q>>>13,q&=8191,q+=T*a+P*o+R*(5*g)+O*(5*f)+L*(5*p),D+=q>>>13,q&=8191;let j=D+I*p+k*d+x*h+C*u+_*l;D=j>>>13,j&=8191,j+=T*c+P*a+R*o+O*(5*g)+L*(5*f),D+=j>>>13,j&=8191;let z=D+I*f+k*p+x*d+C*h+_*u;D=z>>>13,z&=8191,z+=T*l+P*c+R*a+O*o+L*(5*g),D+=z>>>13,z&=8191;let K=D+I*g+k*f+x*p+C*d+_*h;D=K>>>13,K&=8191,K+=T*u+P*l+R*c+O*a+L*o,D+=K>>>13,K&=8191,D=(D<<2)+D|0,D=D+N|0,N=8191&D,D>>>=13,M+=D,s[0]=N,s[1]=M,s[2]=F,s[3]=B,s[4]=U,s[5]=$,s[6]=q,s[7]=j,s[8]=z,s[9]=K}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let s=(1^n)-1;for(let e=0;e<10;e++)r[e]&=s;s=~s;for(let t=0;t<10;t++)e[t]=e[t]&s|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let r=1;r<8;r++)i=(e[r]+t[r]|0)+(i>>>16)|0,e[r]=65535&i;eh(r)}update(e){Zu(this),Yu(e=rh(e));const{buffer:t,blockLen:r}=this,n=e.length;for(let s=0;s<n;){const i=Math.min(r-this.pos,n-s);if(i!==r)t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-s;s+=r)this.process(e,s)}return this}destroy(){eh(this.h,this.r,this.buffer,this.pad)}digestInto(e){Zu(this),function(e,t){Yu(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;const{buffer:t,h:r}=this;let{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let t=0;t<8;t++)e[s++]=r[t]>>>0,e[s++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}const wh=function(e){const t=(t,r)=>e(r).update(rh(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}(e=>new bh(e));function vh(e,t,r,n,s,i=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],m=t[6],y=t[7],b=s,w=r[0],v=r[1],E=r[2],S=o,A=a,I=c,k=l,x=u,C=h,_=d,T=p,P=f,R=g,O=m,L=y,D=b,N=w,M=v,F=E;for(let e=0;e<i;e+=2)S=S+x|0,D=dh(D^S,16),P=P+D|0,x=dh(x^P,12),S=S+x|0,D=dh(D^S,8),P=P+D|0,x=dh(x^P,7),A=A+C|0,N=dh(N^A,16),R=R+N|0,C=dh(C^R,12),A=A+C|0,N=dh(N^A,8),R=R+N|0,C=dh(C^R,7),I=I+_|0,M=dh(M^I,16),O=O+M|0,_=dh(_^O,12),I=I+_|0,M=dh(M^I,8),O=O+M|0,_=dh(_^O,7),k=k+T|0,F=dh(F^k,16),L=L+F|0,T=dh(T^L,12),k=k+T|0,F=dh(F^k,8),L=L+F|0,T=dh(T^L,7),S=S+C|0,F=dh(F^S,16),O=O+F|0,C=dh(C^O,12),S=S+C|0,F=dh(F^S,8),O=O+F|0,C=dh(C^O,7),A=A+_|0,D=dh(D^A,16),L=L+D|0,_=dh(_^L,12),A=A+_|0,D=dh(D^A,8),L=L+D|0,_=dh(_^L,7),I=I+T|0,N=dh(N^I,16),P=P+N|0,T=dh(T^P,12),I=I+T|0,N=dh(N^I,8),P=P+N|0,T=dh(T^P,7),k=k+x|0,M=dh(M^k,16),R=R+M|0,x=dh(x^R,12),k=k+x|0,M=dh(M^k,8),R=R+M|0,x=dh(x^R,7);let B=0;n[B++]=o+S|0,n[B++]=a+A|0,n[B++]=c+I|0,n[B++]=l+k|0,n[B++]=u+x|0,n[B++]=h+C|0,n[B++]=d+_|0,n[B++]=p+T|0,n[B++]=f+P|0,n[B++]=g+R|0,n[B++]=m+O|0,n[B++]=y+L|0,n[B++]=b+D|0,n[B++]=w+N|0,n[B++]=v+M|0,n[B++]=E+F|0}const Eh=mh(vh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Sh=mh(vh,{counterRight:!1,counterLength:8,extendNonceFn:function(e,t,r,n){let s=e[0],i=e[1],o=e[2],a=e[3],c=t[0],l=t[1],u=t[2],h=t[3],d=t[4],p=t[5],f=t[6],g=t[7],m=r[0],y=r[1],b=r[2],w=r[3];for(let e=0;e<20;e+=2)s=s+c|0,m=dh(m^s,16),d=d+m|0,c=dh(c^d,12),s=s+c|0,m=dh(m^s,8),d=d+m|0,c=dh(c^d,7),i=i+l|0,y=dh(y^i,16),p=p+y|0,l=dh(l^p,12),i=i+l|0,y=dh(y^i,8),p=p+y|0,l=dh(l^p,7),o=o+u|0,b=dh(b^o,16),f=f+b|0,u=dh(u^f,12),o=o+u|0,b=dh(b^o,8),f=f+b|0,u=dh(u^f,7),a=a+h|0,w=dh(w^a,16),g=g+w|0,h=dh(h^g,12),a=a+h|0,w=dh(w^a,8),g=g+w|0,h=dh(h^g,7),s=s+l|0,w=dh(w^s,16),f=f+w|0,l=dh(l^f,12),s=s+l|0,w=dh(w^s,8),f=f+w|0,l=dh(l^f,7),i=i+u|0,m=dh(m^i,16),g=g+m|0,u=dh(u^g,12),i=i+u|0,m=dh(m^i,8),g=g+m|0,u=dh(u^g,7),o=o+h|0,y=dh(y^o,16),d=d+y|0,h=dh(h^d,12),o=o+h|0,y=dh(y^o,8),d=d+y|0,h=dh(h^d,7),a=a+c|0,b=dh(b^a,16),p=p+b|0,c=dh(c^p,12),a=a+c|0,b=dh(b^a,8),p=p+b|0,c=dh(c^p,7);let v=0;n[v++]=s,n[v++]=i,n[v++]=o,n[v++]=a,n[v++]=m,n[v++]=y,n[v++]=b,n[v++]=w},allowShortKeys:!1}),Ah=new Uint8Array(16),Ih=(e,t)=>{e.update(t);const r=t.length%16;r&&e.update(Ah.subarray(r))},kh=new Uint8Array(32);function xh(e,t,r,n,s){const i=e(t,r,kh),o=wh.create(i);s&&Ih(o,s),Ih(o,n);const a=function(e,t,r){Xu(r);const n=new Uint8Array(16),s=(i=n,new DataView(i.buffer,i.byteOffset,i.byteLength));var i;return ih(s,0,BigInt(t),r),ih(s,8,BigInt(e),r),n}(n.length,s?s.length:0,!0);o.update(a);const c=o.digest();return eh(i,a),c}const Ch=e=>(t,r,n)=>({encrypt(s,i){const o=s.length;(i=sh(o+16,i,!1)).set(s);const a=i.subarray(0,-16);e(t,r,a,a,1);const c=xh(e,t,r,a,n);return i.set(c,o),eh(c),i},decrypt(s,i){i=sh(s.length-16,i,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=xh(e,t,r,o,n);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(a,c))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,r,i,i,1),eh(c),i}}),_h=nh({blockSize:64,nonceLength:12,tagLength:16},Ch(Eh));Ch(Sh);const Th=Uint8Array.from([0]),Ph=Uint8Array.of();const Rh={hashSHA256:e=>xn(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return Rr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),wc(e,jr(r),jr(t))}(xn,t,e),n=function(e,t,r,n=32){Rr(e),Tr(n);const s=e.outputLen;if(n>255*s)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/s);void 0===r&&(r=Ph);const o=new Uint8Array(i*s),a=wc.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let e=0;e<i;e++)Th[0]=e+1,c.update(0===e?Ph:l).update(r).update(Th).digestInto(l),o.set(l,s*e),a._cloneInto(c);return a.destroy(),c.destroy(),Lr(l,Th),o.slice(0,n)}(xn,r,void 0,96);return[n.subarray(0,32),n.subarray(32,64),n.subarray(64,96)]},generateX25519KeyPair(){const e=qa.utils.randomPrivateKey();return{publicKey:qa.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:qa.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>qa.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>_h(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,s)=>_h(n,t,r).decrypt(e.subarray(),s)},Oh=e=>{const t=g(2);return t[0]=e>>8,t[1]=e,t};Oh.bytes=2;const Lh=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function Dh(e,t){t.enabled&&Gu&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${Ln(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${Ln(e.privateKey,"hex")}`)):t("Missing local static keys."))}function Nh(e,t){t.enabled&&Gu&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Ln(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Ln(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Mh(e,t){t.enabled&&Gu&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Ln(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Fh(e,t,r){r.enabled&&Gu&&(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&Ln(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&Ln(t.k,"hex")}`))}Lh.bytes=2;class Bh extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=Bh.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class Uh{n;bytes;view;constructor(e=0){this.n=e,this.bytes=f(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const $h=f(0);class qh{k;n;crypto;constructor(e,t=void 0,r=0){this.crypto=e,this.k=t,this.n=new Uh(r)}hasKey(){return Boolean(this.k)}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class jh{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const r=xt(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=f(32);return e.set(t),e}return e.hash(t)}(e,r),this.ck=this.h,this.cs=new qh(e)}mixKey(e){const[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new qh(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new os(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,$h);return[new qh(this.crypto,e),new qh(this.crypto,t)]}}class zh{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:r,prologue:n,initiator:s,s:i,e:o,rs:a,re:c}=e;this.crypto=t,this.ss=new jh(t,r),this.ss.mixHash(n),this.initiator=s,this.s=i,this.e=o,this.rs=a,this.re=c}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");const r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw new Error("message is not long enough");const n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class Kh extends zh{writeMessageA(e){return new os(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){const t=this.writeE();this.writeEE();const r=this.writeS();return this.writeES(),new os(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){const t=this.writeS();return this.writeSE(),new os(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Bh(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();const t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new Bh(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(e){try{const t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new Bh(`handshake stage 2 validation fail: ${e.message}`)}}}var Vh,Hh;async function Gh(e,t,r){const n=await e.sign(Xh(t));return Hh.encode({identityKey:Kc(e.publicKey),identitySig:n,extensions:r})}async function Wh(e,t,r){try{const n=Hh.decode(e),s=zc(n.identityKey);if(!1===r?.equals(s))throw new Error(`Payload identity key ${s} does not match expected remote identity key ${r}`);if(!t)throw new Error("Remote static does not exist");const i=Xh(t);if(!await s.verify(i,n.identitySig))throw new Error("Invalid payload signature");return n}catch(e){throw new Ei(e.message)}}function Xh(e){const t=xt("noise-libp2p-static-key:");return e instanceof Uint8Array?ts([t,e],t.length+e.length):(e.prepend(t),e)}!function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);if(null!=e.streamMuxers)for(const r of e.streamMuxers)t.uint32(18),t.string(r);!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={webtransportCerthashes:[],streamMuxers:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:if(null!=r.limits?.webtransportCerthashes&&n.webtransportCerthashes.length===r.limits.webtransportCerthashes)throw new Ir('Decode error - map field "webtransportCerthashes" had too many elements');n.webtransportCerthashes.push(e.bytes());break;case 2:if(null!=r.limits?.streamMuxers&&n.streamMuxers.length===r.limits.streamMuxers)throw new Ir('Decode error - map field "streamMuxers" had too many elements');n.streamMuxers.push(e.string());break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Vh||(Vh={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),Vh.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={identityKey:f(0),identitySig:f(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.identityKey=e.bytes();break;case 2:n.identitySig=e.bytes();break;case 4:n.extensions=Vh.codec().decode(e,e.uint32(),{limits:r.limits?.extensions});break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Hh||(Hh={}));class Jh{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:s,prologueBytes:i}=t,{metrics:o}=e;this.components=e;const a=s??Rh;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(a),this.extensions={webtransportCerthashes:[],...n},this.metrics=o?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(o):void 0,this.staticKey=r?a.generateX25519KeyPairFromSeed(r):a.generateX25519KeyPair(),this.prologue=i??f(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[ku]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const r=Ku(e,{lengthEncoder:Oh,lengthDecoder:Lh,maxDataLength:Hu}),n=await this.performHandshakeInitiator(r,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(r,n);e.source=s.source,e.sink=s.sink;const i=zc(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:Zc(i),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(null==e||0===e.length)return;const t=this.components.upgrader.getStreamMuxers();if(null!=t)for(const r of e){const e=t.get(r);if(null!=e)return e}if(e.length)throw new Si("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){const r=Ku(e,{lengthEncoder:Oh,lengthDecoder:Lh,maxDataLength:Hu}),n=await this.performHandshakeResponder(r,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(r,n);e.source=s.source,e.sink=s.sink;const i=zc(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:Zc(i),streamMuxer:!0===t?.skipStreamMuxerNegotiation?void 0:this.getStreamMuxer(n.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,r,n){let s;const i=!0===n?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=e,u=await Gh(i,a.publicKey,l),h=new Kh({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:o,s:a});Dh(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA($h),t),r.trace("Stage 0 - Initiator finished sending first message."),Nh(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const d=h.readMessageB(await n.read(t));var p,f;r.trace("Stage 1 - Initiator received the message."),Mh(h.re,r),p=h.rs,(f=r).enabled&&Gu&&f(p?`REMOTE_STATIC_PUBLIC_KEY ${Ln(p.subarray(),"hex")}`:"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");const g=await Wh(d,h.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");const[m,y]=h.ss.split();return Fh(m,y,r),{payload:g,encrypt:e=>m.encryptWithAd($h,e),decrypt:(e,t)=>y.decryptWithAd($h,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async performHandshakeResponder(e,t,r,n){let s;const i=!0===n?.skipStreamMuxerNegotiation?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:i,prologue:o,s:a,remoteIdentityKey:c,extensions:l}=e,u=await Gh(i,a.publicKey,l),h=new Kh({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:o,s:a});Dh(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),Mh(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Nh(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const d=h.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");const p=await Wh(d,h.rs,c),[f,g]=h.ss.split();return Fh(f,g,r),{payload:p,encrypt:e=>g.encryptWithAd($h,e),decrypt:(e,t)=>f.decryptWithAd($h,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:i,webtransportCerthashes:[],...this.extensions}},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async createSecureConnection(e,t){const[r,n]=function(){const e=Vu(),t=Vu();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),s=e.unwrap();return await _s(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=65519){let s,i=r+65519;i>n.length&&(i=n.length),s=n instanceof Uint8Array?e.encrypt(n.subarray(r,i)):e.encrypt(n.sublist(r,i)),t?.encryptedPackets.increment(),yield new os(Oh(s.byteLength),s)}}}(t,this.metrics),s,e=>Bu(e,{lengthDecoder:Lh}),function(e,t){return async function*(r){for await(const n of r)for(let r=0;r<n.length;r+=Hu){let s=r+Hu;if(s>n.length&&(s=n.length),s-16<r)throw new Error("Invalid chunk");const i=n.sublist(r,s),o=n.subarray(r,s-16);try{const r=e.decrypt(i,o);t?.decryptedPackets.increment(),yield r}catch(e){throw t?.decryptErrors.increment(),e}}}}(t,this.metrics),r),n}}function Yh(e={}){return t=>new Jh(t,e)}const Zh=Symbol.for("@libp2p/peer-discovery"),Qh=Pd("dns4"),ed=Pd("dns6"),td=Pd("dnsaddr"),rd=Td(Pd("dns"),td,Qh,ed),nd=Td(Pd("ip4"),Pd("ip6")),sd=Td(_d(nd,Pd("tcp")),_d(rd,Pd("tcp"))),id=_d(nd,Pd("udp")),od=_d(id,Pd("utp")),ad=_d(id,Pd("quic")),cd=_d(id,Pd("quic-v1")),ld=Td(_d(sd,Pd("ws")),_d(rd,Pd("ws"))),ud=Td(_d(ld,Pd("p2p")),ld),hd=Td(_d(sd,Pd("wss")),_d(rd,Pd("wss")),_d(sd,Pd("tls"),Pd("ws")),_d(rd,Pd("tls"),Pd("ws"))),dd=Td(_d(hd,Pd("p2p")),hd),pd=Td(_d(sd,Pd("http")),_d(nd,Pd("http")),_d(rd,Pd("http"))),fd=Td(_d(sd,Pd("https")),_d(nd,Pd("https")),_d(rd,Pd("https"))),gd=_d(id,Pd("webrtc-direct"),Pd("certhash")),md=Td(_d(gd,Pd("p2p")),gd),yd=_d(cd,Pd("webtransport"),Pd("certhash"),Pd("certhash")),bd=Td(_d(yd,Pd("p2p")),yd),wd=Td(_d(ud,Pd("p2p-webrtc-star"),Pd("p2p")),_d(dd,Pd("p2p-webrtc-star"),Pd("p2p")),_d(ud,Pd("p2p-webrtc-star")),_d(dd,Pd("p2p-webrtc-star"))),vd=(Td(_d(ud,Pd("p2p-websocket-star"),Pd("p2p")),_d(dd,Pd("p2p-websocket-star"),Pd("p2p")),_d(ud,Pd("p2p-websocket-star")),_d(dd,Pd("p2p-websocket-star"))),Td(_d(pd,Pd("p2p-webrtc-direct"),Pd("p2p")),_d(fd,Pd("p2p-webrtc-direct"),Pd("p2p")),_d(pd,Pd("p2p-webrtc-direct")),_d(fd,Pd("p2p-webrtc-direct")))),Ed=Td(ld,hd,pd,fd,wd,vd,sd,od,ad,rd,md,bd),Sd=(Td(_d(Ed,Pd("p2p-stardust"),Pd("p2p")),_d(Ed,Pd("p2p-stardust"))),Td(_d(Ed,Pd("p2p")),wd,vd,md,bd,Pd("p2p"))),Ad=Td(_d(Sd,Pd("p2p-circuit"),Sd),_d(Sd,Pd("p2p-circuit")),_d(Pd("p2p-circuit"),Sd),_d(Ed,Pd("p2p-circuit")),_d(Pd("p2p-circuit"),Ed),Pd("p2p-circuit")),Id=()=>Td(_d(Ad,Id),Ad),kd=Id(),xd=Td(_d(kd,Sd,kd),_d(Sd,kd),_d(kd,Sd),kd,Sd);function Cd(e){return function(t){let r;try{r=$l(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function _d(...e){function t(t){if(t.length<e.length)return null;let r=t;return e.some(e=>(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r)),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:Cd(t),partialMatch:t}}function Td(...e){function t(t){let r=null;return e.some(e=>{const n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)}),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:Cd(t),partialMatch:t}}function Pd(e){const t=e;return{toString:function(){return t},matches:function(e){let r;try{r=$l(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:function(e){return 0===e.length?null:e[0]===t?e.slice(1):null}}}Td(_d(kd,Pd("webrtc"),Pd("p2p")),_d(kd,Pd("webrtc")),_d(Ed,Pd("webrtc"),Pd("p2p")),_d(Ed,Pd("webrtc")),Pd("webrtc"));class Rd extends Zl{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[];for(const e of t.list){if(!xd.matches(e)){this.log.error("Invalid multiaddr");continue}const t=$l(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:Yc(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[Zh]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[ku]=["@libp2p/peer-discovery"];isStarted(){return Boolean(this.timer)}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error(e)})},this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p",e.id,t)})}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}const Od=Uint8Array.from([3,1]);var Ld,Dd;!function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={multiaddr:f(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();t>>>3==1?n.multiaddr=e.bytes():e.skipType(7&t)}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(t=e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==r&&(r=Ar((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()},(t,r,n={})=>{const s={peerId:f(0),seq:0n,addresses:[]},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:s.peerId=t.bytes();break;case 2:s.seq=t.uint64();break;case 3:if(null!=n.limits?.addresses&&s.addresses.length===n.limits.addresses)throw new Ir('Decode error - map field "addresses" had too many elements');s.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;default:t.skipType(7&r)}}return s})),r),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Ld||(Ld={}));class Nd{static createFromProtobuf=e=>{const t=Ld.decode(e),r=Qc(st(t.peerId)),n=(t.addresses??[]).map(e=>$l(e.multiaddr)),s=t.seq;return new Nd({peerId:r,multiaddrs:n,seqNumber:s})};static DOMAIN="libp2p-peer-record";static CODEC=Od;peerId;multiaddrs;seqNumber;domain=Nd.DOMAIN;codec=Nd.CODEC;marshaled;constructor(e){const{peerId:t,multiaddrs:r,seqNumber:n}=e;this.peerId=t,this.multiaddrs=r??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=Ld.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return e instanceof Nd&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every((e,r)=>t[r].equals(e)))}(this.multiaddrs,e.multiaddrs)}}!function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={publicKey:f(0),payloadType:f(0),payload:f(0),signature:f(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.publicKey=e.bytes();break;case 2:n.payloadType=e.bytes();break;case 3:n.payload=e.bytes();break;case 5:n.signature=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Dd||(Dd={}));class Md extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class Fd{static createFromProtobuf=e=>{const t=Dd.decode(e),r=zc(t.publicKey);return new Fd({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,r)=>{if(null==t)throw new Error("Missing private key");const n=e.domain,s=e.codec,i=e.marshal(),o=Bd(n,s,i),a=await t.sign(o.subarray(),r);return new Fd({publicKey:t.publicKey,payloadType:s,payload:i,signature:a})};static openAndCertify=async(e,t,r)=>{const n=Fd.createFromProtobuf(e);if(!await n.validate(t,r))throw new Md("Envelope signature is not valid for the given domain");return n};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:r,payload:n,signature:s}=e;this.publicKey=t,this.payloadType=r,this.payload=n,this.signature=s}marshal(){return null==this.marshaled&&(this.marshaled=Dd.encode({publicKey:Kc(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&rs(this.marshal(),e.marshal())}async validate(e,t){const r=Bd(e,this.payloadType,this.payload);return this.publicKey.verify(r.subarray(),this.signature,t)}}const Bd=(e,t,r)=>{const n=xt(e),s=_(n.byteLength),i=_(t.length),o=_(r.length);return new os(s,n,i,t,o,r)};var Ud=__webpack_require__(5507);const $d=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map(e=>new Ud.Netmask(e));function qd(e){for(const t of $d)if(t.contains(e))return!0;return!1}function jd(e){return ll(e)?qd(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return qd(`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}`)}(e):/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)?function(e){const t=e.split(":");return qd(t[t.length-1])}(e):ul(e)?function(e){return/^::$/.test(e)||/^::1$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}(e):void 0}function zd(e){try{for(const{code:t}of e.getComponents())if(t!==dl)return 4===t||t===hl}catch{}return!1}function Kd(e){try{if(!zd(e))return!1;const[[,t]]=e.stringTuples();return null!=t&&(jd(t)??!1)}catch{}return!0}const Vd=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),Hd=e=>({match:t=>Vd(t=>t===e).match(t),pattern:e}),Gd=()=>({match:e=>Vd(e=>"string"==typeof e).match(e),pattern:"{string}"}),Wd=()=>({match:e=>Vd(e=>!isNaN(parseInt(e))).match(e),pattern:"{number}"}),Xd=()=>({match:e=>{if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{Ee.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),Jd=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{ke.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),Yd=e=>({match:t=>{const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),Zd=(...e)=>({match:t=>{let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.length<r.length)&&(r=e)}return null!=r&&r},pattern:`or(${e.map(e=>e.pattern).join(", ")})`}),Qd=(...e)=>({match:t=>{for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map(e=>e.pattern).join(", ")})`});function ep(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matchers:e,matches:function(e){return!1!==t(e)},exactMatch:function(e){const r=t(e);return!1!==r&&0===r.length}}}const tp=ep(Xd()),rp=Qd(Hd("dns4"),Gd()),np=Qd(Hd("dns6"),Gd()),sp=Qd(Hd("dnsaddr"),Gd()),ip=Qd(Hd("dns"),Gd()),op=(ep(rp,Yd(Xd())),ep(np,Yd(Xd())),ep(sp,Yd(Xd())),ep(Zd(ip,sp,rp,np),Yd(Xd())),Qd(Hd("ip4"),Vd(ll))),ap=Qd(Hd("ip6"),Vd(ul)),cp=Zd(op,ap),lp=Zd(cp,ip,rp,np,sp),up=ep(Zd(cp,Qd(Zd(ip,sp,rp,np),Yd(Xd())))),hp=ep(op),dp=ep(ap),pp=(ep(cp),Qd(lp,Hd("tcp"),Wd())),fp=Qd(lp,Hd("udp"),Wd()),gp=ep(Qd(pp,Yd(Xd()))),mp=(ep(fp),Qd(fp,Hd("quic"),Yd(Xd()))),yp=Qd(fp,Hd("quic-v1"),Yd(Xd())),bp=Zd(mp,yp),wp=(ep(mp),ep(yp)),vp=Zd(lp,pp,fp,mp,yp),Ep=Zd(Qd(vp,Hd("ws"),Yd(Xd()))),Sp=ep(Ep),Ap=Zd(Qd(vp,Hd("wss"),Yd(Xd())),Qd(vp,Hd("tls"),Yd(Qd(Hd("sni"),Gd())),Hd("ws"),Yd(Xd()))),Ip=ep(Ap),kp=Qd(fp,Hd("webrtc-direct"),Yd(Jd()),Yd(Jd()),Yd(Xd())),xp=ep(kp),Cp=Qd(yp,Hd("webtransport"),Yd(Jd()),Yd(Jd()),Yd(Xd())),_p=ep(Cp),Tp=Zd(Ep,Ap,Qd(pp,Yd(Xd())),Qd(bp,Yd(Xd())),Qd(lp,Yd(Xd())),kp,Cp,Xd()),Pp=(ep(Tp),ep(Qd(Tp,Hd("p2p-circuit"),Xd()))),Rp=ep(Zd(Qd(Tp,Hd("p2p-circuit"),Hd("webrtc"),Yd(Xd())),Qd(Tp,Hd("webrtc"),Yd(Xd())),Qd(Hd("webrtc"),Yd(Xd()))));function Op(e,t){const r=Ku(e,t),n={read:async(e,t)=>{const n=await r.read(t);return e.decode(n)},write:async(e,t,n)=>{await r.write(t.encode(e),n)},writeV:async(e,t,n)=>{await r.writeV(e.map(e=>t.encode(e)),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Lp;ep(Zd(Qd(lp,Hd("tcp"),Wd(),Hd("http"),Yd(Xd())),Qd(lp,Hd("http"),Yd(Xd())))),ep(Zd(Qd(lp,Hd("tcp"),Zd(Qd(Hd("443"),Hd("http")),Qd(Wd(),Hd("https")),Qd(Wd(),Hd("tls"),Hd("http"))),Yd(Xd())),Qd(lp,Hd("tls"),Hd("http"),Yd(Xd())),Qd(lp,Hd("https"),Yd(Xd())))),ep(Zd(Qd(Hd("memory"),Gd(),Yd(Xd())))),ep(Zd(Qd(Hd("unix"),Gd(),Yd(Xd())))),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const r of e.listenAddrs)t.uint32(18),t.bytes(r);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const r of e.protocols)t.uint32(26),t.string(r);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={listenAddrs:[],protocols:[]},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:if(null!=r.limits?.listenAddrs&&n.listenAddrs.length===r.limits.listenAddrs)throw new Ir('Decode error - map field "listenAddrs" had too many elements');n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:if(null!=r.limits?.protocols&&n.protocols.length===r.limits.protocols)throw new Ir('Decode error - map field "protocols" had too many elements');n.protocols.push(e.string());break;case 8:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Lp||(Lp={}));const Dp="ipfs",Np=5e3,Mp=1,Fp=1,Bp=10,Up=8192,$p=!0,qp=!0;class jp{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,t){var r,n;this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??Np,this.maxInboundStreams=t.maxInboundStreams??Mp,this.maxOutboundStreams=t.maxOutboundStreams??Fp,this.maxMessageSize=t.maxMessageSize??Up,this.maxObservedAddresses=t.maxObservedAddresses??Bp,this.runOnLimitedConnection=t.runOnLimitedConnection??qp,this.host={protocolVersion:`${t.protocolPrefix??Dp}/0.1.0`,agentVersion:(r=e.nodeInfo,n=t.agentVersion,null!=n?n:r.userAgent)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:xt(this.host.agentVersion),ProtocolVersion:xt(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,e=>{this.handleProtocol(e).catch(e=>{this.log.error(e)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}class zp extends jp{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Dp}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??$p)&&e.events.addEventListener("connection:open",e=>{const t=e.detail;this.identify(t).catch(e=>{e.name!==Fi.name&&this.log.error("error during identify trigged by connection:open",e)})})}[ku]=["@libp2p/identify"];async _identify(e,t={}){let r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const n=Op(r,{maxDataLength:this.maxMessageSize}).pb(Lp),s=await n.read(t);return await r.close(t),s}catch(e){throw r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:s,observedAddr:i}=r;if(null==n)throw new Bi("public key was missing from identify message");const o=el(zc(n).toCID());if(!e.remotePeer.equals(o))throw new Bi("identified peer does not match the expected peer");if(this.peerId.equals(o))throw new Bi("identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("identify completed for peer %p and protocols %o",o,s),async function(e,t,r,n,s){if(r("received identify from %p",n.remotePeer),null==s)throw new Bi("message was null or undefined");const i={};if(s.listenAddrs.length>0&&(i.addresses=s.listenAddrs.map(e=>({isCertified:!1,multiaddr:$l(e)}))),s.protocols.length>0&&(i.protocols=s.protocols),null!=s.publicKey){const e=zc(s.publicKey);if(!Zc(e).equals(n.remotePeer))throw new Bi("public key did not match remote PeerId");i.publicKey=e}let o;if(null!=s.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);let t=s.signedPeerRecord;const a=await Fd.openAndCertify(t,Nd.DOMAIN);let c=Nd.createFromProtobuf(a.payload);const l=el(a.publicKey.toCID());if(!c.peerId.equals(l))throw new Bi("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(c.peerId))throw new Bi("signing key does not match remote PeerId");let u;try{u=await e.get(c.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u&&(i.metadata=u.metadata,null!=u.peerRecordEnvelope)){const e=Fd.createFromProtobuf(u.peerRecordEnvelope),n=Nd.createFromProtobuf(e.payload);n.seqNumber>=c.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",n.seqNumber,c.seqNumber),c=n,t=u.peerRecordEnvelope)}i.peerRecordEnvelope=t,i.addresses=c.multiaddrs.map(e=>({isCertified:!0,multiaddr:e})),o={seq:c.seqNumber,addresses:c.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,i),await e.patch(n.remotePeer,i),null!=s.agentVersion||null!=s.protocolVersion){const t={};null!=s.agentVersion&&(t.AgentVersion=xt(s.agentVersion)),null!=s.protocolVersion&&(t.ProtocolVersion=xt(s.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,t),await e.merge(n.remotePeer,{metadata:t})}const a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map(e=>$l(e)),observedAddr:null==s.observedAddr?void 0:$l(s.observedAddr),protocols:s.protocols,signedPeerRecord:o,connection:n};return t.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,e,r)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return $l(e)}catch{}}(e);if(null==t)return;if(this.log.trace("our observed address was %a",t),Kd(t))return void this.log.trace("our observed address was private");const r=t.getComponents();r[0].code!==hl&&(r[0].code!==dl||r[1].code!==hl)||function(e){try{for(const{code:t,value:r}of e.getComponents())if(null!=r&&t===hl)return Nl("2000::/3",r)}catch{}return!1}(t)?gp.exactMatch(t)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address")}async handleProtocol(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=await this.peerStore.get(this.peerId),s=this.addressManager.getAddresses().map(e=>e.decapsulateCode(ql("p2p").code));let i=e.peerRecordEnvelope;if(s.length>0&&null==i){const e=new Nd({peerId:this.peerId,multiaddrs:s});i=(await Fd.seal(e,this.privateKey)).marshal().subarray()}let o=t.remoteAddr.bytes;up.matches(t.remoteAddr)||(o=void 0);const a=Op(r).pb(Lp);await a.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Kc(this.privateKey.publicKey),listenAddrs:s.map(e=>e.bytes),signedPeerRecord:i,observedAddr:o,protocols:e.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}}function Kp(e={}){return t=>new zp(t,e)}function Vp(e,t){const r=function(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw new Error("argument is not an iterator or iterable")}(e).return?.();var n;null!=(n=r)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&r.catch(e=>{t.error("could not cause iterator to return",e)})}const Hp=()=>{const e=new Error("Delay aborted");return e.name="AbortError",e},Gp=new WeakMap,Wp=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(Hp());let i,o,a;const c=e??clearTimeout,l=()=>{c(i),a(Hp())},u=new Promise((e,c)=>{o=()=>{s&&s.removeEventListener("abort",l),e(n)},a=c,i=(t??setTimeout)(o,r)});return s&&s.addEventListener("abort",l,{once:!0}),Gp.set(u,()=>{c(i),i=null,o()}),u}}();class Xp extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}class Jp extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class Yp{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??1e3*this.duration/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Zp}async consume(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r);let i=this.memoryStorage.incrby(n,t,s);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(n,i.consumedPoints,this.blockDuration)),new Xp("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let e=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));e<this.execEvenlyMinDelayMs&&(e=i.consumedPoints*this.execEvenlyMinDelayMs),await Wp(e)}return i}penalty(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r),i=this.memoryStorage.incrby(n,-t,s);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){const r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t,r=0){const n=1e3*(r>=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=e?.customDuration&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class Zp{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const s=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||s>0?(n.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,s=this.storage.get(e);null!=s&&clearTimeout(s.timeoutId);const i={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,i),n>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},n),null!=i.timeoutId.unref&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:i.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var Qp;!function(e){e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"}(Qp||(Qp={}));const ef=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),tf=Object.freeze({NEW_STREAM:Qp.NEW_STREAM,MESSAGE:Qp.MESSAGE_INITIATOR,CLOSE:Qp.CLOSE_INITIATOR,RESET:Qp.RESET_INITIATOR}),rf=Object.freeze({MESSAGE:Qp.MESSAGE_RECEIVER,CLOSE:Qp.CLOSE_RECEIVER,RESET:Qp.RESET_RECEIVER}),nf=1<<20;class sf{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=nf,t=4194304){this._buffer=new os,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new Bi("Unprocessed message queue size too large!");const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("InvalidMessageError"===e.name)throw e;break}const{id:e,type:r,length:n,offset:s}=this._headerInfo;if(this._buffer.length-s<n)break;const i={id:e,type:r};r!==Qp.NEW_STREAM&&r!==Qp.MESSAGE_INITIATOR&&r!==Qp.MESSAGE_RECEIVER||(i.data=this._buffer.sublist(s,s+n)),t.push(i),this._buffer.consume(s+n),this._headerInfo=null}return t}_decodeHeader(e){const{value:t,offset:r}=cf(e),{value:n,offset:s}=cf(e,r),i=7&t;if(null==ef[i])throw new Error(`Invalid type received: ${i}`);if(n>this._maxMessageSize)throw new Bi("Message size too large");return{id:t>>3,type:i,offset:r+s,length:n}}}const of=128,af=127;function cf(e,t=0){let r,n=0,s=0,i=t;const o=e.length;do{if(i>=o||s>49)throw t=0,new RangeError("Could not decode varint");r=e.get(i++),n+=s<28?(r&af)<<s:(r&af)*Math.pow(2,s),s+=7}while(r>=of);return{value:n,offset:t=i-t}}const lf=10240,uf=new class{_pool;_poolOffset;constructor(){this._pool=g(lf),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;_(e.id<<3|e.type,r,n),n+=k(e.id<<3|e.type),e.type!==Qp.NEW_STREAM&&e.type!==Qp.MESSAGE_INITIATOR&&e.type!==Qp.MESSAGE_RECEIVER||null==e.data?(_(0,r,n),n+=k(0)):(_(e.data.length,r,n),n+=k(e.data.length));const s=r.subarray(this._poolOffset,n);lf-n<100?(this._pool=g(lf),this._poolOffset=0):this._poolOffset=n,t.append(s),e.type!==Qp.NEW_STREAM&&e.type!==Qp.MESSAGE_INITIATOR&&e.type!==Qp.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};class hf extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}}function df(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class pf{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=ys(),this.closed=ys(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??5e3,this.onEnd=e.onEnd,this.onCloseRead=e.onCloseRead,this.onCloseWrite=e.onCloseWrite,this.onReset=e.onReset,this.onAbort=e.onAbort,this.source=this.streamSource=Es({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(e){if("ready"!==this.writeStatus)throw new Ri(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);df(e)&&await e}const r=()=>{Vp(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new os(r):r;const e=this.sendData(r,t);df(e)&&(this.sendingData=ys(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseRead?.(),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseWrite?.(),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){"open"===this.status&&(this.log.trace("closing gracefully"),this.status="closing",await As(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const t=this.readStatus;this.readStatus="closing","reset"!==this.status&&"aborted"!==this.status&&null==this.timeline.closeRead&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),"ready"===t&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),"ready"===this.writeStatus&&(this.log.trace("sink was never sunk, sink an empty array"),await As(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await As(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await As(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",e),this.log("try to send reset to remote");const t=this.sendReset();df(t)&&t.catch(e=>{this.log.error("error sending reset message",e)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;const e=new Pi("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class ff extends pf{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?tf:rf,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:tf.NEW_STREAM,data:new os(xt(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function gf(e){const t={...e,type:`${ef[e.type]} (${e.type})`};return e.type===Qp.NEW_STREAM&&(t.data=Ln(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==Qp.MESSAGE_INITIATOR&&e.type!==Qp.MESSAGE_RECEIVER||(t.data=Ln(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class mf{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??500,this.sink=this._createSink(),this._source=Es({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=_s(this._source,e=>async function*(e){for await(const t of e){const e=new os;uf.write(t,e),yield e}}(e)),this.closeController=new AbortController,this.rateLimiter=new Yp({points:t.disconnectThreshold??5,duration:1})}get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Ti("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async e=>e.close({signal:t}))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(e){this.abort(e)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach(t=>{t.abort(e)}),this.closeController.abort(e))}_newReceiverStream(e){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:s}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new Vi("Too many outbound streams open");if(s.has(t))throw new Error(`${n} stream ${t} already exists!`);const i=function(e){const{id:t,name:r,send:n,onEnd:s,type:i="initiator",maxMsgSize:o=nf}=e;return new ff({id:"initiator"===i?`i${t}`:`r${t}`,streamId:t,name:`${r??t}`,direction:"initiator"===i?"outbound":"inbound",maxDataSize:o,onEnd:s,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${i}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,gf(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,i.protocol),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(i)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(t,i),i}_createSink(){return async e=>{const t=()=>{Vp(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new sf(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const e of t.write(r))await this._handleIncoming(e);this._source.end()}catch(e){this.log("error in sink",e),this._source.end(e)}finally{this.closeController.signal.removeEventListener("abort",t)}}}async _handleIncoming(e){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",gf(e)),e.type===Qp.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:Qp.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{return this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void this.abort(new Error("Too many open streams"))}return}const r=this._newReceiverStream({id:t,name:Ln(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const n=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==n){this.log("missing stream %s for message type %s",t,ef[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(new Error("Too many messages for missing streams"))}return}const s=this._init.maxStreamBufferSize??4194304;try{switch(r){case Qp.MESSAGE_INITIATOR:case Qp.MESSAGE_RECEIVER:if(n.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===Qp.MESSAGE_INITIATOR?Qp.RESET_RECEIVER:Qp.RESET_INITIATOR}),new hf("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");n.sourcePush(e.data);break;case Qp.CLOSE_INITIATOR:case Qp.CLOSE_RECEIVER:n.remoteCloseWrite();break;case Qp.RESET_INITIATOR:case Qp.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),n.abort(e)}}}class yf{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[ku]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new mf(this.components,{...e,...this._init})}}function bf(e={}){return t=>new yf(t,e)}function wf(e){if(isNaN(e)||e<=0)throw new Ai("random bytes length must be a Number bigger than 0");return Hr(e)}class vf{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[ku]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);const{stream:t}=e,r=Date.now(),n=$u(t);let s=!1;Promise.resolve().then(async()=>{for(;;){const e=AbortSignal.timeout(this.timeout);Yl(),e.addEventListener("abort",()=>{t?.abort(new $i("ping timeout"))});const r=await n.read({bytes:32,signal:e});await n.write(r,{signal:e}),s=!0}}).catch(r=>{s&&"UnexpectedEOFError"===r.name&&"ready"!==t.readStatus||(this.log.error("incoming ping from %p failed with error - %e",e.connection.remotePeer,r),t?.abort(r))}).finally(()=>{const n=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,n);const s=AbortSignal.timeout(this.timeout);t.close({signal:s}).catch(r=>{this.log.error("error closing ping stream from %p - %e",e.connection.remotePeer,r),t?.abort(r)})})}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=wf(32),s=await this.components.connectionManager.openConnection(e,t);let i;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{i=await s.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const e=$u(i),[,o]=await Promise.all([e.write(n,t),e.read({...t,bytes:32})]),a=Date.now()-r;if(!rs(n,o.subarray()))throw new Ui(`Received wrong ping ack after ${a}ms`);return this.log("ping %p complete in %dms",s.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",s.remotePeer,e),i?.abort(e),e}finally{null!=i&&await i.close(t)}}}function Ef(e={}){return t=>new vf(t,e)}const Sf=Symbol.for("@libp2p/transport");var Af;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Af||(Af={}));const If=[6,53,56,54,55];function kf(e){return Cf("sni",e)?.value}function xf(e){const t=Cf("tcp",e)?.value;return null==t?"":`:${t}`}function Cf(e,t){return t.find(t=>t.name===e)}function _f(e){return e.some(({code:e})=>448===e)}function Tf(e,t){const r=Pf[e.name];if(null==r)throw new Error(`Can't interpret protocol ${e.name}`);const n=r(e,t);return e.code===hl?`[${n}]`:n}const Pf={ip4:(e,t)=>e.value,ip6:(e,t)=>0===t.length?e.value:`[${e.value}]`,tcp:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`tcp://${Tf(r,t)}:${e.value}`},udp:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`udp://${Tf(r,t)}:${e.value}`},dnsaddr:(e,t)=>e.value,dns4:(e,t)=>e.value,dns6:(e,t)=>e.value,dns:(e,t)=>e.value,ipfs:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`${Tf(r,t)}`},p2p:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`${Tf(r,t)}`},http:(e,t)=>{const r=_f(t),n=kf(t),s=xf(t);if(r&&null!=n)return`https://${n}${s}`;const i=r?"https://":"http://",o=t.pop();if(null==o)throw new Error("Unexpected end of multiaddr");let a=Tf(o,t);return a=a?.replace("tcp://",""),`${i}${a}`},"http-path":(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`${Tf(r,t)}${decodeURIComponent(e.value??"")}`},tls:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return Tf(r,t)},sni:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return Tf(r,t)},https:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");let n=Tf(r,t);return n=n?.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{const r=_f(t),n=kf(t),s=xf(t);if(r&&null!=n)return`wss://${n}${s}`;const i=r?"wss://":"ws://",o=t.pop();if(null==o)throw new Error("Unexpected end of multiaddr");let a=Tf(o,t);return a=a?.replace("tcp://",""),`${i}${a}`},wss:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");let n=Tf(r,t);return n=n?.replace("tcp://",""),`wss://${n}`}},Rf=async e=>{if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&await new Promise((t,r)=>{function n(){e.removeEventListener("open",s),e.removeEventListener("error",i)}function s(){n(),t()}function i(t){n(),r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",s),e.addEventListener("error",i)})},Of=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await Rf(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise((t,r)=>{e.addEventListener("close",e=>{if(e.wasClean||1006===e.code)t();else{const t=Object.assign(new Error("ws error"),{event:e});r(t)}}),setTimeout(()=>{e.close()})})});var Lf=__webpack_require__(544);function Df(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}const Nf=WebSocket,Mf={"http:":"ws:","https:":"wss:"};function Ff(e,t){t=t??{};const r=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const r=t.protocol??"ws:",n=t.host,s=null!=t.port&&!0!==n?.endsWith(`:${t.port}`)?`:${t.port}`:"";e=`${r}//${n}${s}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(Mf))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise((t,r)=>{if(s)return void t();if(null!=n)return void r(n);const i=t=>{e.removeEventListener("open",o),e.removeEventListener("error",a),t()},o=()=>{i(t)},a=t=>{i(()=>{r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))})};e.addEventListener("open",o),e.addEventListener("error",a)})},r=async function*(){const r=new Lf.PP(({push:t,stop:r,fail:n})=>{const s=e=>{let r=null;"string"==typeof e.data&&(r=xt(e.data)),Df(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},i=e=>{n(e.error??new Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",i),e.addEventListener("close",r),()=>{e.removeEventListener("message",s),e.removeEventListener("error",i),e.removeEventListener("close",r)}},{highWaterMark:1/0});await t();for await(const e of r)yield Df(e)?new Uint8Array(e):e}();let n,s=1===e.readyState;return e.addEventListener("open",()=>{s=!0,n=null}),e.addEventListener("close",()=>{s=!1,n=null}),e.addEventListener("error",t=>{s||(n=t.error??new Error(`connect ECONNREFUSED ${e.url}`))}),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,s=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,s=parseInt(t.port,10)}catch{}if(null==n||null==s)throw new Error("Remote connection did not have address and/or port");return{sink:Of(e,t),source:r,connected:async()=>{await r.connected()},close:async()=>{e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||await new Promise(t=>{e.addEventListener("close",()=>{t()}),e.close()})},destroy:()=>{null!=e.terminate?e.terminate():e.close()},remoteAddress:n,remotePort:s,socket:e}})(new Nf(r.toString(),t.websocket),t)}class Bf extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Uf(e){return e.filter(e=>Ip.exactMatch(e)||Sp.exactMatch(e))}function $f(e){return e.filter(e=>Ip.exactMatch(e))}class qf{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Sf]=!0;[Symbol.toStringTag]="@libp2p/websockets";[ku]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),s=r.metrics,i=r.metricPrefix??"",o={log:n,async sink(t){try{await e.sink(async function*(){for await(const e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&n.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const s=()=>{const{host:e,port:t}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new vi("Socket close timeout"))};t.signal?.addEventListener("abort",s);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",s),o.timeline.close=Date.now()}},abort(t){const{host:r,port:a}=o.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,a,t),e.destroy(),o.timeline.close=Date.now(),s?.increment({[`${i}error`]:!0})}};return e.socket.addEventListener("close",()=>{s?.increment({[`${i}close`]:!0}),null==o.timeline.close&&(o.timeline.close=Date.now())},{once:!0}),o}(await this._connect(e,t),e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r,t);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){t?.signal?.throwIfAborted();const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=ys(),s=Ff(function(e){const t=$l(e).getComponents(),r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");const n=Pf[r.name];if(null==n)throw new Error(`No interpreter found for ${r.name}`);let s=n(r,t)??"";return If.includes(r.code)&&(s=s.replace(/^.*:\/\//,""),s="443"===r.value?`https://${s}`:`http://${s}`),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}(e),this.init);s.socket.addEventListener("error",()=>{const t=new _i(`Could not connect to ${e.toString()}`);this.log.error("connection error:",t),this.metrics?.dialerEvents.increment({error:!0}),n.reject(t)});try{t.onProgress?.(new Bf("websockets:open-connection")),await As(Promise.race([s.connected(),n.promise]),t.signal)}catch(e){throw t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),s.close().catch(e=>{this.log.error("error closing raw socket",e)}),e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),s}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):Uf(e)}dialFilter(e){return this.listenFilter(e)}}function jf(e={}){return t=>new qf(t,e)}function zf(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)}const{hasOwnProperty:Kf}=Object.prototype,{propertyIsEnumerable:Vf}=Object,Hf=(e,t,r)=>{Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})},Gf={concatArrays:!1,ignoreUndefined:!1},Wf=e=>{const t=[];for(const r in e)Kf.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)Vf.call(e,n)&&t.push(n)}return t};function Xf(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return Wf(e).forEach(r=>{Hf(t,r,Xf(e[r]))}),t}(e):zf(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return Wf(e).forEach(r=>{Hf(t,r,Xf(e[r]))}),t}(e):e}const Jf=(e,t,r,n)=>(r.forEach(r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?Hf(e,r,Zf(e[r],t[r],n)):Hf(e,r,Xf(t[r])))}),e),Yf=(e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach(t=>{const i=[];for(let r=0;r<t.length;r++)Kf.call(t,r)&&(i.push(String(r)),Hf(n,s++,t===e?t[r]:Xf(t[r])));n=Jf(n,t,Wf(t).filter(e=>!i.includes(e)),r)}),n};function Zf(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?Yf(e,t,r):zf(t)&&zf(e)?Jf(e,t,Wf(t),r):Xf(t)}function Qf(...e){const t=Zf(Xf(Gf),void 0!==this&&this||{},Gf);let r={_:{}};for(const n of e)if(void 0!==n){if(!zf(n))throw new TypeError("`"+n+"` is not an Option Object");r=Zf(r,{_:n},t)}return r._}var eg=__webpack_require__(228);class tg extends Error{constructor(e){super(e),this.name="TimeoutError"}}class rg extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}const ng=e=>void 0===globalThis.DOMException?new rg(e):new DOMException(e),sg=e=>{const t=void 0===e.reason?ng("This operation was aborted."):e.reason;return t instanceof Error?t:ng(t)};class ig{#s=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,id:t.id,run:e};if(0===this.size||this.#s[this.size-1].priority>=t.priority)return void this.#s.push(r);const n=function(e,t,r){let n=0,s=e.length;for(;s>0;){const i=Math.trunc(s/2);let o=n+i;r(e[o],t)<=0?(n=++o,s-=i+1):s=i}return n}(this.#s,r,(e,t)=>t.priority-e.priority);this.#s.splice(n,0,r)}setPriority(e,t){const r=this.#s.findIndex(t=>t.id===e);if(-1===r)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[n]=this.#s.splice(r,1);this.enqueue(n.run,{priority:t,id:e})}dequeue(){const e=this.#s.shift();return e?.run}filter(e){return this.#s.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this.#s.length}}class og extends eg{#i;#o;#a=0;#c;#l;#u=0;#h;#d;#s;#p;#f=0;#g;#m;#y;#b=1n;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:ig,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#i=e.carryoverConcurrencyCount,this.#o=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#c=e.intervalCap,this.#l=e.interval,this.#s=new e.queueClass,this.#p=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#y=!0===e.throwOnTimeout,this.#m=!1===e.autoStart}get#w(){return this.#o||this.#a<this.#c}get#v(){return this.#f<this.#g}#E(){this.#f--,this.#S(),this.emit("next")}#A(){this.#I(),this.#k(),this.#d=void 0}get#x(){const e=Date.now();if(void 0===this.#h){const t=this.#u-e;if(!(t<0))return void 0===this.#d&&(this.#d=setTimeout(()=>{this.#A()},t)),!0;this.#a=this.#i?this.#f:0}return!1}#S(){if(0===this.#s.size)return this.#h&&clearInterval(this.#h),this.#h=void 0,this.emit("empty"),0===this.#f&&this.emit("idle"),!1;if(!this.#m){const e=!this.#x;if(this.#w&&this.#v){const t=this.#s.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#k(),!0)}}return!1}#k(){this.#o||void 0!==this.#h||(this.#h=setInterval(()=>{this.#I()},this.#l),this.#u=Date.now()+this.#l)}#I(){0===this.#a&&0===this.#f&&this.#h&&(clearInterval(this.#h),this.#h=void 0),this.#a=this.#i?this.#f:0,this.#C()}#C(){for(;this.#S(););}get concurrency(){return this.#g}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#g=e,this.#C()}async#_(e){return new Promise((t,r)=>{e.addEventListener("abort",()=>{r(e.reason)},{once:!0})})}setPriority(e,t){this.#s.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#b++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#y,...t},new Promise((r,n)=>{this.#s.enqueue(async()=>{this.#f++,this.#a++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=function(e,t){const{milliseconds:r,fallback:n,message:s,customTimers:i={setTimeout,clearTimeout}}=t;let o,a;const c=new Promise((c,l)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&l(sg(e)),a=()=>{l(sg(e))},e.addEventListener("abort",a,{once:!0})}if(r===Number.POSITIVE_INFINITY)return void e.then(c,l);const u=new tg;o=i.setTimeout.call(void 0,()=>{if(n)try{c(n())}catch(e){l(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?c():s instanceof Error?l(s):(u.message=s??`Promise timed out after ${r} milliseconds`,l(u))},r),(async()=>{try{c(await e)}catch(e){l(e)}})()}).finally(()=>{c.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return c.clear=()=>{i.clearTimeout.call(void 0,o),o=void 0},c}(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#_(t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof tg&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#E()}},t),this.emit("add"),this.#S()})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this.#m?(this.#m=!1,this.#C(),this):this}pause(){this.#m=!0}clear(){this.#s=new this.#p}async onEmpty(){0!==this.#s.size&&await this.#T("empty")}async onSizeLessThan(e){this.#s.size<e||await this.#T("next",()=>this.#s.size<e)}async onIdle(){0===this.#f&&0===this.#s.size||await this.#T("idle")}async#T(e,t){return new Promise(r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)})}get size(){return this.#s.size}sizeBy(e){return this.#s.filter(e).length}get pending(){return this.#f}get isPaused(){return this.#m}}function ag(e){const t=[ug.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function cg(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map(e=>({name:e.name,type:ug[e.type]})),Answer:(e.Answer??e.answers??[]).map(e=>({name:e.name,type:ug[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?Ln(e.data):e.data}))}}function lg(e,t={}){const r=new og({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const s=new URLSearchParams;s.set("name",t),ag(n.types).forEach(e=>{s.append("type",ug[e])}),n.onProgress?.(new Bf("dns:query",{detail:t}));const i=await r.add(async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw new Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=cg(await t.json());return n.onProgress?.(new Bf("dns:response",{detail:r})),r},{signal:n.signal});if(null==i)throw new Error("No DNS response received");return i}}var ug,hg=__webpack_require__(194);class dg{lru;constructor(e){this.lru=hg(e)}get(e,t){let r=!0;const n=[];for(const s of t){const t=this.getAnswers(e,s);if(0===t.length){r=!1;break}n.push(...t)}if(r)return cg({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter(e=>e.expires>Date.now()).map(({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:ug[t.type]}));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class pg{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new dg(t)),Object.entries(e.resolvers??{}).forEach(([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=t}),null==this.resolvers["."]&&(this.resolvers["."]=[lg("https://cloudflare-dns.com/dns-query"),lg("https://dns.google/resolve")])}async query(e,t={}){const r=ag(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new Bf("dns:cache",{detail:n})),n;const s=`${e.split(".").pop()}.`,i=(this.resolvers[s]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),o=[];for(const n of i){if(!0===t.signal?.aborted)break;try{const s=await n(e,{...t,types:r});for(const t of s.Answer)this.cache.add(e,t);return s}catch(e){o.push(e),t.onProgress?.(new Bf("dns:error",{detail:e}))}}if(1===o.length)throw o[0];throw new AggregateError(o,`DNS lookup of ${e} ${r} failed`)}}!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(ug||(ug={}));const fg=-1,gg={},mg={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,fg,"ip6zone"],[43,8,"ipcidr"],[53,fg,"dns",!0],[54,fg,"dns4",!0],[55,fg,"dns6",!0],[56,fg,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,fg,"unix",!1,!0],[421,fg,"ipfs"],[421,fg,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,fg,"garlic64"],[448,0,"tls"],[449,fg,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,fg,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,fg,"http-path"],[777,fg,"memory"]].forEach(e=>{const t=function(e,t,r,n,s){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(s)}}(...e);mg[t.code]=t,gg[t.name]=t});const{code:yg}=function(e){if(null!=gg[e])return gg[e];throw new Error(`no protocol with name: ${e}`)}("dnsaddr");class bg extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const wg=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new bg("Max recursive depth reached");const[,n]=e.stringTuples().find(([e])=>e===yg)??[],s=t?.dns??function(e={}){return new pg(e)}(),i=await s.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[ug.TXT]}),o=e.getPeerId(),a=[];for(const e of i.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=o&&!n.includes(o))continue;const s=$l(n);if(n.startsWith("/dnsaddr")){const e=await s.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map(e=>e.toString()))}else a.push(s.toString())}return a},vg={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:wg}},transportManager:{faultTolerance:Af.FATAL_ALL}};async function Eg(e){const t=Qf(vg,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Ai("Private network is enforced, but no protector was provided");return t}const Sg=Symbol.for("@libp2p/content-routing"),Ag=Symbol.for("@libp2p/peer-routing"),Ig=1e3,kg=60*Ig,xg=60*kg,Cg=24*xg,_g=7*Cg,Tg=function(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e=String(e)).length>100)throw new Error("Value exceeds the maximum length of 100 characters.");const t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return NaN;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return r*_g;case"days":case"day":case"d":return r*Cg;case"hours":case"hour":case"hrs":case"hr":case"h":return r*xg;case"minutes":case"minute":case"mins":case"min":case"m":return r*kg;case"seconds":case"second":case"secs":case"sec":case"s":return r*Ig;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}(e);if("number"==typeof e&&isFinite(e))return t?.long?function(e){const t=Math.abs(e);return t>=Cg?Pg(e,t,Cg,"day"):t>=xg?Pg(e,t,xg,"hour"):t>=kg?Pg(e,t,kg,"minute"):t>=Ig?Pg(e,t,Ig,"second"):`${e} ms`}(e):function(e){const t=Math.abs(e);return t>=Cg?`${Math.round(e/Cg)}d`:t>=xg?`${Math.round(e/xg)}h`:t>=kg?`${Math.round(e/kg)}m`:t>=Ig?`${Math.round(e/Ig)}s`:`${e}ms`}(e);throw new Error("Value is not a string or number.")}catch(t){const r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?`${t.message}. value=${JSON.stringify(e)}`:"An unknown error has occured.";throw new Error(r)}};function Pg(e,t,r,n){const s=t>=1.5*r;return`${Math.round(e/r)} ${n}${s?"s":""}`}const Rg=function(){try{return localStorage}catch(e){}}(),Og=console.debug??console.log??(()=>{}),Lg=function(e){function t(e){let n,s,i,o=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),i=s-(n||s);r.diff=i,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(n,s)=>{if("%%"===n)return"%";o++;const i=t.formatters[s];if("function"==typeof i){const t=e[o];n=i.call(r,t),e.splice(o,1),o--}return n}),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(s!==t.namespaces&&(s=t.namespaces,i=t.enabled(e)),i),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack??e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r<s;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Tg,t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs:function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Tg(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(r++,"%c"===e&&(n=r))}),e.splice(n,0,t)},save:function(e){try{e?Rg?.setItem("debug",e):Rg?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=Rg?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement?.style?.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/))},setupFormatters:function(e){e.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],storage:Rg,log:Og}),Dg=Lg;function Ng(){return{forComponent:e=>function(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(`${e}:trace`);return Dg.enabled(`${e}:trace`)&&null!=Dg.names.map(e=>e.toString()).find(e=>e.includes(":trace"))&&(t=Dg(`${e}:trace`)),Object.assign(Dg(e),{error:Dg(`${e}:error`),trace:t})}(e)}}function Mg(e){if(null!=e&&0!==(e=e.trim()).length)return e}function Fg(e,t){const r={[Symbol.iterator]:()=>r,next:()=>{const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}function Bg(e){return Qc(st(Ee.decode(`z${e}`)))}Dg.formatters.b=e=>null==e?"undefined":Ee.baseEncode(e),Dg.formatters.t=e=>null==e?"undefined":ue.baseEncode(e),Dg.formatters.m=e=>null==e?"undefined":Ae.baseEncode(e),Dg.formatters.p=e=>null==e?"undefined":e.toString(),Dg.formatters.c=e=>null==e?"undefined":e.toString(),Dg.formatters.k=e=>null==e?"undefined":e.toString(),Dg.formatters.a=e=>null==e?"undefined":e.toString(),Dg.formatters.e=e=>null==e?"undefined":Mg(e.stack)??Mg(e.message)??e.toString();class Ug{set;constructor(e){if(this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Fg(this.set.entries(),e=>{const t=Bg(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{const r=Bg(t);e(r,r,this)})}has(e){return this.set.has(e.toString())}values(){return Fg(this.set.values(),e=>Bg(e))}intersection(e){const t=new Ug;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new Ug;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new Ug;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}class $g{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),{key:t,value:r})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Fg(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,r)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Fg(this.map.values(),e=>e.key)}values(){return Fg(this.map.values(),e=>e.value)}get size(){return this.map.size}}class qg extends $g{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}class jg extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}}async function zg(e,t,r,n){const s=new jg(n?.errorMessage);null!=n?.errorCode&&(s.code=n.errorCode);const i=n?.errorEvent??"error";return!0===r?.aborted?Promise.reject(s):new Promise((o,a)=>{function c(){Vg(r,"abort",h),Vg(e,t,l),Vg(e,i,u)}const l=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return c(),void a(e)}c(),o(e)},u=e=>{c(),e instanceof Error?a(e):a(e.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},h=()=>{c(),a(s)};Kg(r,"abort",h),Kg(e,t,l),Kg(e,i,u)})}function Kg(e,t,r){null!=e&&(Hg(e)?e.addListener(t,r):e.addEventListener(t,r))}function Vg(e,t,r){null!=e&&(Hg(e)?e.removeListener(t,r):e.removeEventListener(t,r))}function Hg(e){return"function"==typeof e.on&&"function"==typeof e.emit}class Gg extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class Wg{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new jg)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Xg{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((e,t)=>e&&!0===t.signal?.aborted,!0)&&(this.controller.abort(new jg),this.cleanup())}async join(e={}){const t=new Wg(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await As(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}}function Jg(e,t){let r;const n=function(){clearTimeout(r),r=setTimeout(function(){r=void 0,e()},t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}class Yg extends Zl{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Jg(this.emitEmpty.bind(this),1),this.emitIdle=Jg(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Gg;const r=new Xg(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),r.join(t).then(e=>(this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e)).catch(e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new jg)}),this.clear()}async onEmpty(e){0!==this.size&&await zg(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await zg(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await zg(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Es({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail.result)},s=e=>{r(e.detail.error)},i=()=>{r()},o=()=>{r(new jg("Queue aborted"))};this.addEventListener("success",n),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("success",n),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}}const Zg="lock:worker:request-read",Qg="lock:worker:abort-read-request",em="lock:worker:release-read",tm="lock:master:grant-read",rm="lock:master:error-read",nm="lock:worker:request-write",sm="lock:worker:abort-write-request",im="lock:worker:release-write",om="lock:master:grant-write",am="lock:master:error-write",cm="lock:worker:finalize",lm="mortice",um={singleProcess:!1},hm=(e,t,r,n,s,i,o,a,c)=>l=>{if(null==l.data)return;const u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===s&&e.safeDispatchEvent(r,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{t.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(e=>{const r=n=>{if(null==n?.data)return;const s=n.data.type,i=(n.data.name,n.data.identifier);s===a&&i===u.identifier&&(t.removeEventListener("message",r),e())};t.addEventListener("message",r)})},onError:e=>{t.postMessage({type:o,name:u.name,identifier:u.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),u.type===i&&e.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===cm&&e.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};class dm{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(lm)}readLock(e){return this.sendRequest(Zg,Qg,tm,rm,em,e)}writeLock(e){return this.sendRequest(nm,sm,om,am,im,e)}finalize(){this.channel.postMessage({type:cm,name:this.name}),this.channel.close()}async sendRequest(e,t,r,n,s,i){i?.signal?.throwIfAborted();const o=((e=10)=>Math.random().toString().substring(2,e+2))();return this.channel.postMessage({type:e,identifier:o,name:this.name}),new Promise((e,a)=>{const c=()=>{this.channel.postMessage({type:t,identifier:o,name:this.name})};i?.signal?.addEventListener("abort",c,{once:!0});const l=t=>{if(t.data?.identifier===o&&(t.data?.type===r&&(this.channel.removeEventListener("message",l),i?.signal?.removeEventListener("abort",c),e(()=>{this.channel.postMessage({type:s,identifier:o,name:this.name})})),t.data.type===n)){this.channel.removeEventListener("message",l),i?.signal?.removeEventListener("abort",c);const e=new Error;null!=t.data.error&&(e.message=t.data.error.message,e.name=t.data.error.name,e.stack=t.data.error.stack),a(e)}};this.channel.addEventListener("message",l)})}}const pm=new Map;let fm;function gm(e){return"function"==typeof e?.readLock&&"function"==typeof e?.writeLock}function mm(e){if(null==fm&&(fm=(e=>{if(e=Object.assign({},um,e),Boolean(globalThis.document)||e.singleProcess){const e=new BroadcastChannel(lm),t=new Zl;return e.addEventListener("message",hm(t,e,"requestReadLock","abortReadLockRequest",Zg,Qg,rm,em,tm)),e.addEventListener("message",hm(t,e,"requestWriteLock","abortWriteLockRequest",nm,sm,am,im,om)),t}return new dm(e.name)})(e),!gm(fm))){const e=fm;e.addEventListener("requestReadLock",t=>{const r=t.detail.name,n=t.detail.identifier,s=pm.get(r);if(null==s)return;const i=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&i.abort()};e.addEventListener("abortReadLockRequest",o),s.readLock({signal:i.signal}).then(async e=>{await t.detail.handler().finally(()=>{e()})}).catch(e=>{t.detail.onError(e)}).finally(()=>{e.removeEventListener("abortReadLockRequest",o)})}),e.addEventListener("requestWriteLock",t=>{const r=t.detail.name,n=t.detail.identifier,s=pm.get(r);if(null==s)return;const i=new AbortController,o=e=>{e.detail.name===r&&e.detail.identifier===n&&i.abort()};e.addEventListener("abortWriteLockRequest",o),s.writeLock({signal:i.signal}).then(async e=>{await t.detail.handler().finally(()=>{e()})}).catch(e=>{t.detail.onError(e)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",o)})}),e.addEventListener("finalizeRequest",e=>{const t=e.detail.name,r=pm.get(t);null!=r&&r.finalize()})}return fm}async function ym(e,t){let r,n;const s=new Promise((e,t)=>{r=e,n=t}),i=()=>{n(new jg)};return t?.signal?.addEventListener("abort",i,{once:!0}),e.add(async()=>{await new Promise(e=>{r(()=>{t?.signal?.removeEventListener("abort",i),e()})})},{signal:t?.signal}).catch(e=>{n(e)}),s}const bm={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function wm(e){const t=Object.assign({},bm,e);return((e,t)=>{let r=pm.get(e);if(null!=r)return r;const n=mm(t);if(gm(n))return r=n,pm.set(e,r),r;const s=new Yg({concurrency:1});let i;return r={async readLock(e){if(null!=i)return ym(i,e);i=new Yg({concurrency:t.concurrency,autoStart:!1});const r=i,n=ym(i,e);return s.add(async()=>{r.start(),await r.onIdle().then(()=>{i===r&&(i=null)})}),n},writeLock:async e=>(i=null,ym(s,e)),finalize:()=>{pm.delete(e)},queue:s},pm.set(e,r),!0===t.autoFinalize&&s.addEventListener("idle",()=>{r.finalize()},{once:!0}),r})(t.name,t)}var vm,Em,Sm;function Am(e,t){if(null!=e.publicKey||null==t.publicKey)return e;let r;return"RSA"===e.type&&(r=e.toMultihash()),Zc(zc(t.publicKey,r))}function Im(e,t,r){const n=new Map,s=BigInt(Date.now());for(const[e,r]of t.tags.entries())null!=r.expiry&&r.expiry<s||n.set(e,r);return{...t,id:Am(e,t),addresses:t.addresses.filter(({observed:e})=>null!=e&&e>Date.now()-r).map(({multiaddr:e,isCertified:t})=>({multiaddr:$l(e),isCertified:t??!1})),metadata:t.metadata,peerRecordEnvelope:t.peerRecordEnvelope??void 0,tags:n}}function km(e,t){return null==e&&null==t||null!=e&&null!=t&&rs(e,t)}function xm(e,t,r){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!r(e[n],t[n]))return!1;return!0}function Cm(e,t,r){if(e.size!==t.size)return!1;for(const[n,s]of e.entries()){const e=t.get(n);if(null==e)return!1;if(!r(s,e))return!1}return!0}!function(e){let t,r,n;!function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={key:"",value:f(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.key=e.string();break;case 2:n.value=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(t=e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),Sm.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={key:""},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.key=e.string();break;case 2:n.value=Sm.codec().decode(e,e.uint32(),{limits:r.limits?.value});break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(r=e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==n&&(n=Ar((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),Em.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,s]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:s},r);null!=t.updated&&(r.uint32(64),r.uint64Number(t.updated)),!1!==n.lengthDelimited&&r.ldelim()},(t,r,n={})=>{const s={addresses:[],protocols:[],metadata:new Map,tags:new Map},i=null==r?t.len:t.pos+r;for(;t.pos<i;){const r=t.uint32();switch(r>>>3){case 1:if(null!=n.limits?.addresses&&s.addresses.length===n.limits.addresses)throw new Ir('Decode error - map field "addresses" had too many elements');s.addresses.push(Em.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;case 2:if(null!=n.limits?.protocols&&s.protocols.length===n.limits.protocols)throw new Ir('Decode error - map field "protocols" had too many elements');s.protocols.push(t.string());break;case 4:s.publicKey=t.bytes();break;case 5:s.peerRecordEnvelope=t.bytes();break;case 6:{if(null!=n.limits?.metadata&&s.metadata.size===n.limits.metadata)throw new kr('Decode error - map field "metadata" had too many elements');const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());s.metadata.set(r.key,r.value);break}case 7:{if(null!=n.limits?.tags&&s.tags.size===n.limits.tags)throw new kr('Decode error - map field "tags" had too many elements');const r=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:n.limits?.tags$value}});s.tags.set(r.key,r.value);break}case 8:s.updated=t.uint64Number();break;default:t.skipType(7&r)}}return s})),n),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(vm||(vm={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),null!=e.observed&&(t.uint32(24),t.uint64Number(e.observed)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={multiaddr:f(0)},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.multiaddr=e.bytes();break;case 2:n.isCertified=e.bool();break;case 3:n.observed=e.uint64Number();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Em||(Em={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={value:0},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.value=e.uint32();break;case 2:n.expiry=e.uint64();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Sm||(Sm={}));const _m="/",Tm=(new TextEncoder).encode(_m),Pm=Tm[0];class Rm{_buf;constructor(e,t){if("string"==typeof e)this._buf=xt(e);else{if(!(e instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Pm)throw new Error("Invalid key")}toString(e="utf8"){return Ln(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Rm(e.join(_m))}static random(){return new Rm(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Rm(e):"function"==typeof e.uint8Array?new Rm(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Tm),this._buf[0]!==Pm){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Pm,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Pm;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;e<t.length;e++){if(r.length<e+1)return!1;const n=t[e],s=r[e];if(n<s)return!0;if(n>s)return!1}return t.length<r.length}reverse(){return Rm.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){const e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(_m).slice(1)}type(){return function(e){const t=e.split(":");return t.length<2?"":t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return function(e){const t=e.split(":");return t[t.length-1]}(this.baseNamespace())}instance(e){return new Rm(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(_m)||(e+=_m),e+=this.type(),new Rm(e)}parent(){const e=this.list();return 1===e.length?new Rm(_m):new Rm(e.slice(0,-1).join(_m))}child(e){return this.toString()===_m?e:e.toString()===_m?this:new Rm(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(...e){return Rm.withNamespaces([...this.namespaces(),...(t=e.map(e=>e.namespaces()),[].concat(...t))]);var t}}const Om="/peers/";function Lm(e){if(!wi(e)||null==e.type)throw new Ai("Invalid PeerId");const t=e.toCID().toString();return new Rm(`${Om}${t}`)}async function Dm(e,t,r,n,s){const i=new Map;for(const n of r){if(null==n)continue;if(n.multiaddr instanceof Uint8Array&&(n.multiaddr=$l(n.multiaddr)),!Ul(n.multiaddr))throw new Ai("Multiaddr was invalid");if(!await t(e,n.multiaddr,s))continue;const r=n.isCertified??!1,o=n.multiaddr.toString(),a=i.get(o);null!=a?n.isCertified=a.isCertified||r:i.set(o,{multiaddr:n.multiaddr,isCertified:r})}return[...i.values()].sort((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString())).map(({isCertified:t,multiaddr:r})=>{const n=r.getPeerId();return e.equals(n)&&(r=r.decapsulate($l(`/p2p/${e}`))),{isCertified:t,multiaddr:r.bytes}})}async function Nm(e,t,r,n){if(null==t)throw new Ai("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Ai("publicKey bytes do not match peer id publicKey bytes");const s=n.existingPeer?.peer;if(null!=s&&!e.equals(s.id))throw new Ai("peer id did not match existing peer id");let i,o=s?.addresses??[],a=new Set(s?.protocols??[]),c=s?.metadata??new Map,l=s?.tags??new Map,u=s?.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(o=[],null!=t.multiaddrs&&o.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&o.push(...t.addresses)),null!=t.protocols&&(a=new Set(t.protocols)),null!=t.metadata&&(c=Mm(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Fm})),null!=t.tags&&(l=Mm(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:Bm,map:Um})),null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&o.push(...t.multiaddrs.map(e=>({isCertified:!1,multiaddr:e}))),null!=t.addresses&&o.push(...t.addresses),null!=t.protocols&&(a=new Set([...a,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?c.delete(t):c.set(t,r);c=Mm([...c.entries()],{validate:Fm})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(l);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);l=Mm([...r.entries()],{validate:Bm,map:Um})}null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)}null!=s?.id.publicKey?i=Kc(s.id.publicKey):null!=t.publicKey?i=Kc(t.publicKey):null!=e.publicKey&&(i=Kc(e.publicKey));const h={addresses:await Dm(e,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...a.values()].sort((e,t)=>e.localeCompare(t)),metadata:c,tags:l,publicKey:i,peerRecordEnvelope:u};return h.addresses.forEach(e=>{e.observed=n.existingPeer?.peerPB.addresses?.find(e=>rs(e.multiaddr,e.multiaddr))?.observed??Date.now()}),"RSA"!==e.type&&delete h.publicKey,h}function Mm(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,s]of e.sort(([e],[t])=>e.localeCompare(t)))null!=s&&r.set(n,t.map?.(n,s)??s);return r}function Fm(e,t){if("string"!=typeof e)throw new Ai("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Ai("Metadata value must be a Uint8Array")}function Bm(e,t){if("string"!=typeof e)throw new Ai("Tag name must be a string");if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new Ai("Tag value must be an integer");if(t.value<0||t.value>100)throw new Ai("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new Ai("Tag ttl must be an integer");if(t.ttl<0)throw new Ai("Tag ttl must be between greater than 0")}}function Um(e,t){let r;null!=t.expiry&&(r=t.expiry),null!=t.ttl&&(r=BigInt(Date.now()+Number(t.ttl)));const n={value:t.value??0};return null!=r&&(n.expiry=r),n}function $m(e){const t=e.toString().split("/")[2];return el(mt.parse(t,ue))}function qm(e,t,r){return function(e,t,r){return Im(e,vm.decode(t),r)}($m(e),t,r)}class jm{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=function(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new qg({name:t,metrics:r}):new $g,n}({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return null==t&&(t={refs:0,lock:wm({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,0===t.refs&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){const r=this.getLock(e);try{const n=await r.lock.readLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async getWriteLock(e,t){const r=this.getLock(e);try{const n=await r.lock.writeLock(t);return()=>{n(),this.maybeRemoveLock(e,r)}}catch(t){throw this.maybeRemoveLock(e,r),t}}async has(e,t){try{return await this.load(e,t),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Lm(e),t)}async load(e,t){const r=Lm(e),n=await this.datastore.get(r,t),s=vm.decode(n);if(this.#P(e,s))throw await this.datastore.delete(r,t),new Oi;return Im(e,s,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,r){const n=await this.#R(e,r),s=await Nm(e,t,"patch",{...r,addressFilter:this.addressFilter});return this.#O(e,s,n)}async patch(e,t,r){const n=await this.#R(e,r),s=await Nm(e,t,"patch",{...r,addressFilter:this.addressFilter,existingPeer:n});return this.#O(e,s,n)}async merge(e,t,r){const n=await this.#R(e,r),s=await Nm(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#O(e,s,n)}async*all(e){for await(const{key:t,value:r}of this.datastore.query(function(e,t){return{prefix:Om,filters:(e.filters??[]).map(e=>({key:r,value:n})=>e(qm(r,n,t))),orders:(e.orders??[]).map(e=>(r,n)=>e(qm(r.key,r.value,t),qm(n.key,n.value,t)))}}(e??{},this.maxAddressAge),e)){const n=$m(t);if(n.equals(this.peerId))continue;const s=vm.decode(r);this.#P(n,s)?await this.datastore.delete(t,e):yield Im(n,s,this.peerId.equals(n)?1/0:this.maxAddressAge)}}async#R(e,t){try{const r=Lm(e),n=await this.datastore.get(r,t),s=vm.decode(n);if(this.#P(e,s))throw await this.datastore.delete(r,t),new Oi;return{peerPB:s,peer:Im(e,s,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}}async#O(e,t,r,n){t.updated=Date.now();const s=vm.encode(t);return await this.datastore.put(Lm(e),s,n),{peer:Im(e,t,this.maxAddressAge),previous:r?.peer,updated:null==r||(a=t,c=r.peerPB,!(xm(a.addresses,c.addresses,(e,t)=>e.isCertified===t.isCertified&&!!rs(e.multiaddr,t.multiaddr))&&xm(a.protocols,c.protocols,(e,t)=>e===t)&&km(a.publicKey,c.publicKey)&&km(a.peerRecordEnvelope,c.peerRecordEnvelope)&&Cm(a.metadata,c.metadata,(e,t)=>rs(e,t))&&(i=a.tags,o=c.tags,Cm(i,o,(e,t)=>e.value===t.value&&e.expiry===t.expiry))))};var i,o,a,c}#P(e,t){if(null==t.updated)return!0;if(this.peerId.equals(e))return!1;const r=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,s=t.addresses.filter(e=>null!=e.observed&&e.observed>n);return r&&0===s.length}}class zm{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new jm(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(const r of this.store.all(t))e(r)}async all(e){return es(this.store.all(e))}async delete(e,t){const r=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{r()}}async has(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),r?.()}}async get(e,t){const r=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{r?.()}}async getInfo(e,t){const r=await this.get(e,t);return{id:r.id,multiaddrs:r.addresses.map(({multiaddr:e})=>e)}}async save(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.save(e,t,r);return this.#L(e,n),n.peer}finally{n?.()}}async patch(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.patch(e,t,r);return this.#L(e,n),n.peer}finally{n?.()}}async merge(e,t,r){const n=await this.store.getWriteLock(e,r);try{const n=await this.store.merge(e,t,r);return this.#L(e,n),n.peer}finally{n?.()}}async consumePeerRecord(e,t,r){const n=wi(t)?t:wi(t?.expectedPeer)?t.expectedPeer:void 0,s=wi(t)||void 0===t?r:t,i=await Fd.openAndCertify(e,Nd.DOMAIN,s),o=el(i.publicKey.toCID());if(!1===n?.equals(o))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",n,o),!1;const a=Nd.createFromProtobuf(i.payload);let c;try{c=await this.get(o,s)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=c?.peerRecordEnvelope){const e=Fd.createFromProtobuf(c.peerRecordEnvelope),t=Nd.createFromProtobuf(e.payload);if(t.seqNumber>=a.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,a.seqNumber),!1}return await this.patch(a.peerId,{peerRecordEnvelope:e,addresses:a.multiaddrs.map(e=>({isCertified:!0,multiaddr:e}))},s),!0}#L(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}Error,Error,Error,Error,Error,Error;class Km extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=Km.name;code=Km.code;constructor(e="Not Found"){super(e)}}Error;const Vm=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);},Hm=function(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:e=>{n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}(e),{value:s,done:i}=n.next();if(!0===i)return function*(){}();const o=t(s,r++);if("function"==typeof o.then)return async function*(){await o&&(yield s);for(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===o&&(yield s);for(const e of n)a(e,r++)&&(yield e)}()},Gm=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await es(e);yield*r.sort(t)}():function*(){const r=es(e);yield*r.sort(t)}()},Wm=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()};class Xm{put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const r of e)await this.delete(r,t),yield r}batch(){let e=[],t=[];return{put(t,r){e.push({key:t,value:r})},delete(e){t.push(e)},commit:async r=>{await Vm(this.putMany(e,r)),e=[],await Vm(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=Hm(r,e=>e.key.toString().startsWith(t))}if(Array.isArray(e.filters)&&(r=e.filters.reduce((e,t)=>Hm(e,t),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((e,t)=>Gm(e,t),r)),null!=e.offset){let t=0;const n=e.offset;r=Hm(r,()=>t++>=n)}return null!=e.limit&&(r=Wm(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=Hm(r,e=>e.toString().startsWith(t))}if(Array.isArray(e.filters)&&(r=e.filters.reduce((e,t)=>Hm(e,t),r)),Array.isArray(e.orders)&&(r=e.orders.reduce((e,t)=>Gm(e,t),r)),null!=e.offset){const t=e.offset;let n=0;r=Hm(r,()=>n++>=t)}return null!=e.limit&&(r=Wm(r,e.limit)),r}}class Jm extends Xm{data;constructor(){super(),this.data=new Map}put(e,t,r){return r?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();const r=this.data.get(e.toString());if(null==r)throw new Km;return r}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(const[e,r]of this.data.entries())yield{key:new Rm(e),value:r},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(const e of this.data.keys())yield new Rm(e),t?.signal?.throwIfAborted()}}function Ym(e,t){let r;const n=function(){clearTimeout(r),r=setTimeout(function(){r=void 0,e()},t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}class Zm{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const s=t.hashV(e,r),i=f(n);for(let e=0;e<i.length;e++)i[e]=s[e];0===i.length&&(i[0]=7),this.fp=i,this.h=t,this.seed=r}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array&&rs(this.fp,e.fp)}}function Qm(e,t){return Math.floor(Math.random()*(t-e))+e}class ey{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof Zm))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof Zm))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof Zm))throw new TypeError("Invalid Fingerprint");const t=Qm(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof Zm))throw new TypeError("Invalid Fingerprint");const t=this.contents.findIndex(t=>e.equals(t));return t>-1&&(this.contents[t]=null,!0)}}const ty={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},ry={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},ny=new globalThis.TextEncoder;const sy={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!ty[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw new Error("The `utf8Buffer` option must have a length greater than zero");const n=ty[t];let s=ry[t],i=e;for(;i.length>0;){const e=ny.encodeInto(i,r);i=i.slice(e.read);for(let i=0;i<e.written;i++)s^=BigInt(r[i]),s=BigInt.asUintN(t,s*n)}return s}(e,t,r);e=ny.encode(e)}return function(e,t){const r=ty[t];let n=ry[t];for(let s=0;s<e.length;s++)n^=BigInt(e[s]),n=BigInt.asUintN(t,n*r);return n}(e,t)}(e,{size:32})),hashV:(e,t)=>function(e){let t=e.toString(16);return t.length%2==1&&(t=`0${t}`),xt(t,"base16")}(sy.hash(e,t))};class iy{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??sy,this.seed=e.seed??Qm(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=xt(e));const t=new Zm(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new ey(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new ey(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const s=[r,n];let i=s[Qm(0,s.length-1)];null==this.buckets[i]&&(this.buckets[i]=new ey(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[i].swap(t);if(null!=e&&(i=(i^e.hash())%this.filterSize,null==this.buckets[i]&&(this.buckets[i]=new ey(this.bucketSize)),this.buckets[i].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=xt(e));const t=new Zm(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;const s=(r^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){"string"==typeof e&&(e=xt(e));const t=new Zm(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const s=(r^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const oy={1:.5,2:.84,4:.95,8:.98};function ay(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t),n=oy[r];return{filterSize:Math.round(e/n),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}class cy{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??sy,this.seed=e.seed??Qm(0,Math.pow(2,10)),this.filterSeries=[new iy({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=xt(e)),this.has(e))return!0;let t=this.filterSeries.find(e=>e.reliable);if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new iy({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=xt(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=xt(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}}function ly(e,t=.001,r){return new cy({...ay(e,t),...r??{}})}class uy extends Map{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function hy(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new uy({name:t,metrics:r}):new Map,n}const dy=864e13;class py{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=hy({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){const t=this.findHost(e);for(const e of this.mappings.values())if(e.domain===t)return!0;return!1}add(e,t){t.forEach(t=>{this.log("add DNS mapping %s to %s",t,e);const r=!0===jd(t);this.mappings.set(t,{domain:e,verified:r,expires:r?dy-Date.now():0,lastVerified:r?dy-Date.now():void 0})})}remove(e){const t=this.findHost(e);let r=!1;for(const[e,n]of this.mappings.entries())n.domain===t&&(this.log("removing %s to %s DNS mapping %e",e,n.domain,new Error("where")),this.mappings.delete(e),r=r||n.verified);return r}getAll(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r].multiaddr.stringTuples(),s=n[0][1];if(null!=s)for(const[i,o]of this.mappings.entries())s===i&&this.maybeAddSNITuple(n,o.domain)&&(e.splice(r,1),r--,t.push({multiaddr:$l(`/${n.map(e=>[ql(e[0]).name,e[1]].join("/")).join("/")}`),verified:o.verified,type:"dns-mapping",expires:o.expires,lastVerified:o.lastVerified}))}return t}maybeAddSNITuple(e,t){for(let r=0;r<e.length;r++)if(448===e[r][0]&&449!==e[r+1]?.[0])return e.splice(r+1,0,[449,t]),!0;return!1}confirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,s]of this.mappings.entries())s.domain===r&&(this.log("marking %s to %s DNS mapping as verified",e,s.domain),n=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return n}unconfirm(e,t){const r=this.findHost(e);let n=!1;for(const[e,s]of this.mappings.entries())s.domain===r&&(this.log("removing verification of %s to %s DNS mapping",e,s.domain),n=n||s.verified,s.verified=!1,s.expires=Date.now()+t);return n}findHost(e){for(const t of e.stringTuples()){if(449===t[0])return t[1];if(53===t[0]||54===t[0]||55===t[0]||56===t[0])return t[1]}}}class fy{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=hy({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){const t=e.stringTuples();for(const e of this.mappings.values())for(const r of e)if(r.externalIp===t[0][1])return!0;return!1}add(e,t,r,n=t,s="tcp"){const i=`${e}-${t}-${s}`,o=this.mappings.get(i)??[],a={internalIp:e,internalPort:t,externalIp:r,externalPort:n,externalFamily:ll(r)?4:6,protocol:s,verified:!1,expires:0};o.push(a),this.mappings.set(i,o)}remove(e){const t=e.stringTuples(),r=t[0][1]??"",n=6===t[1][0]?"tcp":"udp",s=parseInt(t[1][1]??"0");let i=!1;for(const[e,t]of this.mappings.entries()){for(let e=0;e<t.length;e++){const o=t[e];o.externalIp===r&&o.externalPort===s&&o.protocol===n&&(this.log("removing %s:%s to %s:%s %s IP mapping",o.externalIp,o.externalPort,r,s,n),i=i||o.verified,t.splice(e,1),e--)}0===t.length&&this.mappings.delete(e)}return i}getAll(e){const t=[];for(const{multiaddr:r}of e){const e=r.stringTuples();let n;if(4!==e[0][0]&&41!==e[0][0]||6!==e[1][0]?4!==e[0][0]&&41!==e[0][0]||273!==e[1][0]||(n=`${e[0][1]}-${e[1][1]}-udp`):n=`${e[0][1]}-${e[1][1]}-tcp`,null==n)continue;const s=this.mappings.get(n);if(null!=s)for(const r of s)e[0][0]=4===r.externalFamily?4:41,e[0][1]=r.externalIp,e[1][1]=`${r.externalPort}`,t.push({multiaddr:$l(`/${e.map(e=>[ql(e[0]).name,e[1]].join("/")).join("/")}`),verified:r.verified,type:"ip-mapping",expires:r.expires,lastVerified:r.lastVerified})}return t}confirm(e,t){const r=e.stringTuples()[0][1];let n=!1;for(const e of this.mappings.values())for(const s of e)s.externalIp===r&&(this.log("marking %s to %s IP mapping as verified",s.internalIp,s.externalIp),n=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return n}unconfirm(e,t){const r=e.stringTuples(),n=r[0][1]??"",s=6===r[1][0]?"tcp":"udp",i=parseInt(r[1][1]??"0");let o=!1;for(const e of this.mappings.values())for(let r=0;r<e.length;r++){const a=e[r];a.externalIp===n&&a.externalPort===i&&a.protocol===s&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",a.externalIp,a.externalPort,n,i,s),o=o||a.verified,a.verified=!1,a.expires=Date.now()+t)}return o}}class gy{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=hy({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(const t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Kd(e)||function(e){try{for(const{code:t,value:r}of e.getComponents())if(t!==dl&&null!=r){if(4===t)return r.startsWith("169.254.");if(t===hl)return r.toLowerCase().startsWith("fe80")}}catch{}return!1}(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:$l(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){const t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){const r=e.toString(),n=this.addresses.get(r)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},s=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.log("marking observed address %a as verified",r),this.addresses.set(r,n),s}}const my=[4,hl,53,54,55,56];function yy(e){try{for(const{code:t}of e.getComponents())if(t!==dl)return my.includes(t)}catch{}return!1}class by{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=hy({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??10}get(e,t){if(Kd(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};const r=this.toKey(e);let n=this.addresses.get(r);return null==n&&(n={verified:!yy(e),expires:0},this.addresses.set(r,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){const t=this.toKey(e);return this.addresses.has(t)}remove(e){const t=this.toKey(e),r=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),r}confirm(e,t){const r=this.toKey(e),n=this.addresses.get(r)??{verified:!1,expires:0,lastVerified:0},s=n.verified;return n.verified=!0,n.expires=Date.now()+t,n.lastVerified=Date.now(),this.addresses.set(r,n),s}unconfirm(e,t){const r=this.toKey(e),n=this.addresses.get(r)??{verified:!1,expires:0},s=n.verified;return n.verified=!1,n.expires=Date.now()+t,this.addresses.set(r,n),s}toKey(e){if(yy(e)){const t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}}const wy=6e5,vy=3e5,Ey=e=>e;function Sy(e,t){const r=e.getPeerId();return null!=r&&Yc(r).equals(t)&&(e=e.decapsulate($l(`/p2p/${t.toString()}`))),e}class Ay{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){const{listen:r=[],announce:n=[],appendAnnounce:s=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map(e=>e.toString()),this.announce=new Set(n.map(e=>e.toString())),this.appendAnnounce=new Set(s.map(e=>e.toString())),this.observed=new gy(e,t),this.dnsMappings=new py(e,t),this.ipMappings=new fy(e,t),this.transportAddresses=new by(e,t),this.announceFilter=t.announceFilter??Ey,this.observedAddressFilter=ly(1024),this.addressVerificationTTL=t.addressVerificationTTL??wy,this.addressVerificationRetry=t.addressVerificationRetry??vy,this._updatePeerStoreAddresses=Ym(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAddresses().map(e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(e=>{this.log.error("error updating addresses",e)})}getListenAddrs(){return Array.from(this.listen).map(e=>$l(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>$l(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>$l(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){const t=e.stringTuples(),r=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(r)||(this.observedAddressFilter.add(r),e=Sy(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=Sy(e,this.components.peerId);let r=!0;("transport"===t?.type||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("dns-mapping"===t?.type||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("ip-mapping"===t?.type||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1),("observed"===t?.type||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),r=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&r&&(r=!1)),r||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=Sy(e,this.components.peerId);let r=!1;this.observed.has(e)&&!this.observed.remove(e)&&r&&(r=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&r&&(r=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&r&&(r=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&r&&(r=!1),r&&this._updatePeerStoreAddresses()}getAddresses(){const e=new Set,t=this.getAddressesWithMetadata().filter(t=>{if(!t.verified)return!1;const r=t.multiaddr.toString();return!e.has(r)&&(e.add(r),!0)}).map(e=>e.multiaddr);return this.announceFilter(t.map(e=>{const t=$l(e),r=t.getComponents().pop();return r?.value===this.components.peerId.toString()?t:t.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){const e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(t=>{t.updateAnnounceAddrs(e)}),e.map(e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(e=>this.transportAddresses.get(e,this.addressVerificationTTL)));const r=this.getAppendAnnounceAddrs();return r.length>0&&(this.components.transportManager.getListeners().forEach(e=>{e.updateAnnounceAddrs(r)}),t=t.concat(r.map(e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove($l(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,r,n=t,s="tcp"){this.ipMappings.add(e,t,r,n,s),this.observed.removePrefixed(`/ip${ll(r)?4:6}/${r}/${s}/${n}`)}removePublicAddressMapping(e,t,r,n=t,s="tcp"){this.ipMappings.remove($l(`/ip${ll(r)?4:6}/${r}/${s}/${n}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;const t=e.toOptions();if(6===t.family||"127.0.0.1"===t.host||!0===jd(t.host))return!1;const r=this.components.transportManager.getListeners(),n=[e=>Sp.exactMatch(e)||Ip.exactMatch(e),e=>gp.exactMatch(e),e=>wp.exactMatch(e)];for(const s of n){if(!s(e))continue;const n=r.filter(e=>e.getAddrs().filter(e=>4===e.toOptions().family&&s(e)).length>0);if(1!==n.length)continue;const i=n[0].getAddrs().filter(e=>"127.0.0.1"!==e.toOptions().host).pop();if(null==i)continue;const o=i.toOptions();return this.observed.remove(e),this.ipMappings.add(o.host,o.port,t.host,t.port,t.transport),!0}return!1}}function Iy(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}var ky;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(ky||(ky={}));class xy extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class Cy extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class _y extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class Ty extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class Py extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class Ry extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class Oy extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class Ly extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class Dy extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}}class Ny extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}}class My extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class Fy extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class By extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class Uy extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class $y extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class qy extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class jy{components={};_started=!1;constructor(e={}){this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=Ng())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(e=>Iy(e)).map(async t=>{await(t[e]?.())}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const zy=["metrics","connectionProtector","dns"],Ky=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Vy(e){return Array.isArray(e?.[ku])?e[ku]:[]}function Hy(e){return Array.isArray(e?.[xu])?e[xu]:[]}function Gy(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function Wy(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(Sp.matches(e))return!1;const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(jd(`${t[0][1]}`))},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}function Xy(e){if(wi(e))return{peerId:e,multiaddrs:[]};let t,r=Array.isArray(e)?e:[e];if(r.length>0){const e=r[0].getPeerId();t=null==e?void 0:Yc(e),r.forEach(e=>{if(!Ul(e))throw new Di("Invalid multiaddr");const r=e.getPeerId();if(null==r){if(null!=t)throw new Ai("Multiaddrs must all have the same peer id or have no peer id")}else{const e=Yc(r);if(!0!==t?.equals(e))throw new Ai("Multiaddrs must all have the same peer id or have no peer id")}})}return r=r.filter(e=>!tp.exactMatch(e)),{peerId:t,multiaddrs:r}}const Jy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Yy(e){try{let t;if(t="string"==typeof e?$l(e):e,!t.protoNames().includes("ipcidr")){const e=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(e)}return function(e){let t,r;if(e.getComponents().forEach(e=>{"ip4"!==e.name&&"ip6"!==e.name||(r=e.value),"ipcidr"===e.name&&(t=e.value)}),null==t||null==r)throw new Error("Invalid multiaddr");return new Dl(r,t)}(t)}catch(t){throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${e}`)}}class Zy{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(e=>Yy(e)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length,r=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,r),t<=r)return;const n=new $g;for(const t of e){const e=t.remotePeer;if(!n.has(e)){n.set(e,0);try{const t=await this.peerStore.get(e);n.set(e,[...t.tags.values()].reduce((e,t)=>e+t.value,0))}catch(e){"NotFoundError"!==e.name&&this.log.error("error loading peer tags",e)}}}const s=this.sortConnections(e,n),i=Math.max(t-r,0),o=[];for(const e of s)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some(t=>t.contains(e.remoteAddr.nodeAddress().address))||o.push(e),o.length===i)break;await Promise.all(o.map(async e=>{await async function(e,t){const r=e?.streams?.map(e=>e.protocol)??[],n=t?.closableProtocols??Jy;if(!(r.filter(e=>null!=e&&!n.includes(e)).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:o})}sortConnections(e,t){return e.sort((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-1:0}).sort((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0).sort((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0).sort((e,r)=>{const n=t.get(e.remotePeer)??0,s=t.get(r.remotePeer)??0;return n>s?1:n<s?-1:0})}}const Qy="last-dial-failure",eb="last-dial-success";class tb{deferred;signal;constructor(e){this.signal=e,this.deferred=ys(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new vi)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class rb{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((e,t)=>e&&!0===t.signal?.aborted,!0)&&(this.controller.abort(new vi),this.cleanup())}async join(e={}){const t=new tb(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await As(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}}class nb extends Zl{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,null!=e.metricName&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Ym(this.emitEmpty.bind(this),1),this.emitIdle=Ym(this.emitIdle.bind(this),1)}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(const t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Jp;const r=new rb(e,t);return this.enqueue(r),this.safeDispatchEvent("add"),this.tryToStartAnother(),r.join(t).then(e=>(this.safeDispatchEvent("completed",{detail:e}),this.safeDispatchEvent("success",{detail:{job:r,result:e}}),e)).catch(e=>{if("queued"===r.status)for(let e=0;e<this.queue.length;e++)if(this.queue[e]===r){this.queue.splice(e,1);break}throw this.safeDispatchEvent("error",{detail:e}),this.safeDispatchEvent("failure",{detail:{job:r,error:e}}),e})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new vi)}),this.clear()}async onEmpty(e){0!==this.size&&await zg(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await zg(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){0===this.pending&&0===this.size||await zg(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();const t=Es({objectMode:!0}),r=e=>{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},s=e=>{r(e.detail)},i=()=>{r()},o=()=>{r(new vi("Queue aborted"))};this.addEventListener("completed",n),this.addEventListener("error",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",o);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("error",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",o),r()}}}class sb extends nb{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0})}}function ib(e){const t=new globalThis.AbortController;function r(){t.abort();for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)}for(const t of e){if(!0===t?.aborted){r();break}null!=t?.addEventListener&&t.addEventListener("abort",r)}const n=t.signal;return n.clear=function(){for(const t of e)null!=t?.removeEventListener&&t.removeEventListener("abort",r)},n}function ob(e){if(!zd(e))return!1;const{address:t}=e.nodeAddress();return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r=t)||/^::1$/.test(r);var r}function ab(e,t){const r=gp.exactMatch(e.multiaddr),n=gp.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;const s=Ip.exactMatch(e.multiaddr),i=Ip.exactMatch(t.multiaddr);if(s&&!i)return-1;if(!s&&i)return 1;const o=Sp.exactMatch(e.multiaddr),a=Sp.exactMatch(t.multiaddr);if(o&&!a)return-1;if(!o&&a)return 1;const c=Rp.exactMatch(e.multiaddr),l=Rp.exactMatch(t.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;const u=xp.exactMatch(e.multiaddr),h=xp.exactMatch(t.multiaddr);if(u&&!h)return-1;if(!u&&h)return 1;const d=_p.exactMatch(e.multiaddr),p=_p.exactMatch(t.multiaddr);return d&&!p?-1:!d&&p?1:0}function cb(e,t){const r=ob(e.multiaddr),n=ob(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function lb(e,t){const r=Kd(e.multiaddr),n=Kd(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function ub(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function hb(e,t){const r=Pp.exactMatch(e.multiaddr),n=Pp.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}class db{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??25,this.maxDialQueueLength=t.maxDialQueueLength??500,this.dialTimeout=t.dialTimeout??1e4,this.connections=t.connections??new $g,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.shutDownController=new AbortController,this.shutDownController.signal;for(const[e,r]of Object.entries(t.resolvers??{}))Bl.set(e,r);this.queue=new sb({concurrency:t.maxParallelDials??50,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("error",e=>{e.detail?.name!==vi.name&&this.log.error("error in dial queue - %e",e.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=Xy(e),s=Array.from(this.connections.values()).flat().find(e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find(t=>t.equals(e.remoteAddr))));if("open"===s?.status)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new Bf("dial-queue:already-connected")),s;const i=this.queue.queue.find(e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1});if(null!=i){this.log("joining existing dial target for %p",r);for(const e of n)i.options.multiaddrs.add(e.toString());return t.onProgress?.(new Bf("dial-queue:already-in-dial-queue")),i.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new ji("Dial queue is full");return this.log("creating dial target for %p",r,n.map(e=>e.toString())),t.onProgress?.(new Bf("dial-queue:add-to-dial-queue")),this.queue.add(async e=>{e.onProgress?.(new Bf("dial-queue:start-dial"));const t=ib([this.shutDownController.signal,e.signal]);try{return await this.dialPeer(e,t)}finally{t.clear()}},{peerId:r,priority:t.priority??Sb,multiaddrs:new Set(n.map(e=>e.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){const r=e.peerId,n=e.multiaddrs,s=new Set;let i=0===e.multiaddrs.size,o=0,a=0;const c=[];for(this.log("starting dial to %p",r);i||n.size>0;){a++,i=!1;const l=[],u=new Set(e.multiaddrs);n.clear(),this.log("calculating addrs to dial %p from %s",r,[...u]);const h=await this.calculateMultiaddrs(r,u,{...e,signal:t});for(const e of h)s.has(e.multiaddr.toString())?this.log.trace("skipping previously failed multiaddr %a while dialing %p",e.multiaddr,r):l.push(e);this.log("%s dial to %p with %s",1===a?"starting":"continuing",r,l.map(e=>e.multiaddr.toString())),e?.onProgress?.(new Bf("dial-queue:calculated-addresses",l));for(const n of l){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,e.peerId),new ji("Peer had more than maxPeerAddrsToDial");o++;try{const s=await this.components.transportManager.dial(n.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",n.multiaddr);try{await this.components.peerStore.merge(s.remotePeer,{multiaddrs:[s.remoteAddr],metadata:{[eb]:xt(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}return s}catch(e){if(this.log.error("dial failed to %a",n.multiaddr,e),s.add(n.multiaddr.toString()),null!=r)try{await this.components.peerStore.merge(r,{metadata:{[Qy]:xt(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new $i(e.message);c.push(e)}}}if(1===c.length)throw c[0];throw new AggregateError(c,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map(e=>({multiaddr:$l(e),isCertified:!1}));if(null!=e){if(this.components.peerId.equals(e))throw new ji("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new Ly("The dial request is blocked by gater.allowDialPeer");if(0===n.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map(({multiaddr:e})=>e.toString()))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e,r);this.log("found multiaddrs for %p in the peer routing",e,n.map(({multiaddr:e})=>e.toString())),n.push(...t.multiaddrs.map(e=>({multiaddr:e,isCertified:!1})))}catch(t){"NoPeerRoutersError"===t.name?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,t)}}}let s=(await Promise.all(n.map(async e=>{const t=await async function(e,t){let r=!1;for(const t of Bl.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map(e=>e.toString())),n}(e.multiaddr,{dns:this.components.dns,...r,log:this.log});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map(e=>({multiaddr:e,isCertified:!1}))}))).flat();if(null!=e){const t=`/p2p/${e.toString()}`;s=s.map(e=>{const r=e.multiaddr.getComponents().pop();return"p2p"!==r?.name?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e})}const i=s.filter(t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)}),o=new Map;for(const e of i){const t=e.multiaddr.toString(),r=o.get(t);null==r?o.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...o.values()];if(0===a.length)throw new My("The dial request has no valid addresses");const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=null==this.addressSorter?c.sort(ab).sort(ub).sort(hb).sort(lb).sort(cb):c.sort(this.addressSorter);if(0===l.length)throw new Ly("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map(({multiaddr:e})=>e.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map(({multiaddr:e})=>e.toString())),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map(e=>e.toString())),t);return!1!==t.runOnLimitedConnection||null!=r.find(e=>!Pp.matches(e.multiaddr))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}const pb="keep-alive";class fb extends nb{has(e){return null!=this.find(e)}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}}var gb=__webpack_require__(5617);const mb=Object.prototype.toString,yb=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);class bb extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const wb=(e,t,r)=>{const n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};class vb{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new fb({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",e=>{this.maybeReconnect(e.detail).catch(t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)})})}async maybeReconnect(e){if(!this.started)return;const t=await this.peerStore.get(e);Eb(t)&&(this.queue.has(e)||this.queue.add(async t=>{await async function(e,t){return new Promise((r,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const s=gb.operation(t),i=()=>{s.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",i,{once:!0});const o=()=>{t.signal?.removeEventListener("abort",i),s.stop()};s.attempt(async i=>{try{const t=await e(i);o(),r(t)}catch(e){try{if(!(e instanceof Error))throw new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(e instanceof bb)throw e.originalError;if(e instanceof TypeError&&!function(e){var t;return!(!e||(t=e,"[object Error]"!==mb.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:yb.has(e.message))}(e))throw e;if(wb(e,i,t),await t.shouldRetry(e)||(s.stop(),n(e)),await t.onFailedAttempt(e),!s.retry(e))throw s.mainError()}catch(e){wb(e,i,t),o(),n(e)}}})})}(async r=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:t?.signal})}catch(t){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,r,this.retries,t),t}},{signal:t?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async r=>{this.log.error("failed to reconnect to %p - %e",e,r);const n={};[...t.tags.keys()].forEach(e=>{e.startsWith(pb)&&(n[e]=void 0)}),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async t=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,t)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{const e=await this.peerStore.all({filters:[e=>Eb(e)]});await Promise.all(e.map(async e=>{await this.connectionManager.openConnection(e.id).catch(e=>{this.log.error(e)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}}function Eb(e){for(const t of e.tags.keys())if(t.startsWith(pb))return!0;return!1}const Sb=50;class Ab{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??100,this.maxConnections<1)throw new Ai("Connection Manager maxConnections must be greater than 0");this.connections=new $g,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(e=>Yy(e)),this.deny=(t.deny??[]).map(e=>Yy(e)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Yp({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new Zy({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(e=>$l(e))}),this.dialQueue=new db(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:wg},connections:this.connections}),this.reconnectQueue=new vb({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const t of this.connections.values())for(const r of t)e[r.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const r=`${t.direction} ${t.protocol??"unnegotiated"}`;e[r]=(e[r]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort((e,t)=>e-t);const e=Math.floor(.9*n.length);t[r]=n[e]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)Iy(r)&&t.push(r);await Promise.all(t.map(async e=>{null!=e.beforeStart&&await e.beforeStart()})),await Promise.all(t.map(async e=>{await e.start()})),await Promise.all(t.map(async e=>{null!=e.afterStart&&await e.afterStart()}))}(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)Iy(r)&&t.push(r);await Promise.all(t.map(async e=>{null!=e.beforeStop&&await e.beforeStop()})),await Promise.all(t.map(async e=>{await e.stop()})),await Promise.all(t.map(async e=>{null!=e.afterStop&&await e.afterStop()}))}(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new Ai("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(e=>{this.log.error(e)})}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();if("open"!==t.status)return;const r=t.remotePeer,n=!this.connections.has(r),s=this.connections.get(r)??[];s.push(t),this.connections.set(r,s),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),n&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e,r=t.remotePeer,n=(this.connections.get(r)??[]).filter(e=>e.id!==t.id);this.connections.set(r,n),0===n.length&&(this.log("onDisconnect remove all connections for peer %p",r),this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new qi("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:r}=Xy(e);if(this.peerId.equals(r))throw new Li("Can not dial self");if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find(e=>null==e.limits);if(null!=e)return this.log("had an existing non-limited connection to %p",r),t.onProgress?.(new Bf("dial-queue:already-connected")),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??Sb});if("open"!==n.status)throw new Ci("Remote closed connection during opening");let s=this.connections.get(n.remotePeer);null==s&&(s=[],this.connections.set(n.remotePeer,s));let i=!1;for(const e of s)if(e.id===n.id&&(i=!0),!0!==t.force&&e.id!==n.id&&e.remoteAddr.equals(n.remoteAddr))return n.abort(new Di("Duplicate multiaddr connection")),e;return i||s.push(n),n}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){const r=this.connections.get(e)??[];await Promise.all(r.map(async e=>{try{await e.close(t)}catch(t){e.abort(t)}}))}async acceptIncomingConnection(e){if(this.deny.some(t=>t.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(t=>t.contains(e.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const t=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(t,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){const e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(e=>$l(e))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Ib{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(null!=this.previousTime){const r=this.alpha(t,this.previousTime),n=e-this.movingAverage,s=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class kb{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){const t=e.interval??5e3;this.success=new Ib(t),this.failure=new Ib(t),this.next=new Ib(t),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??5e3,this.maxTimeout=e.maxTimeout??6e4,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);const r=AbortSignal.timeout(t),n=ib([e.signal,r]);return n.start=Date.now(),n.timeout=t,n}cleanUp(e){const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class xb{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??!0,this.timeout=new kb({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[ku]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{const r=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=$u(await e.newStream(this.protocol,{signal:r,runOnLimitedConnection:!0}));t=Date.now(),await Promise.all([n.write(wf(32),{signal:r}),n.read({bytes:32,signal:r})]),e.rtt=Date.now()-t,await n.unwrap().close({signal:r})}catch(r){if("UnsupportedProtocolError"!==r.name)throw r;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class Cb{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()}),getAttributesFromYieldedValue:(e,t)=>({...t,providers:[...Array.isArray(t.providers)?t.providers:[],e.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,cid:e.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([e])=>({key:Ln(e,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([e])=>({key:Ln(e,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new _y("No content routers available");const r=this,n=new Ug;for await(const s of Cs(...r.routers.filter(e=>e.findProviders instanceof Function).map(r=>r.findProviders(e,t))))null!=s&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),n.has(s.id)||(n.add(s.id),yield s))}async provide(e,t={}){if(0===this.routers.length)throw new _y("No content routers available");await Promise.all(this.routers.filter(e=>e.provide instanceof Function).map(async r=>{await r.provide(e,t)}))}async cancelReprovide(e,t={}){if(0===this.routers.length)throw new _y("No content routers available");await Promise.all(this.routers.filter(e=>e.cancelReprovide instanceof Function).map(async r=>{await r.cancelReprovide(e,t)}))}async put(e,t,r){if(!this.isStarted())throw new qi;await Promise.all(this.routers.filter(e=>e.put instanceof Function).map(async n=>{await n.put(e,t,r)}))}async get(e,t){if(!this.isStarted())throw new qi;return Promise.any(this.routers.filter(e=>e.get instanceof Function).map(async r=>r.get(e,t)))}}const _b=globalThis.CustomEvent??Event;class Tb{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,peer:e.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([e],t)=>({...t,key:Ln(e,"base36")}),getAttributesFromYieldedValue:(e,t)=>({...t,peers:[...Array.isArray(t.peers)?t.peers:[],e.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new Ty("No peer routers available");if(e.toString()===this.peerId.toString())throw new Py("Should not try to find self");const r=this,n=Cs(...this.routers.filter(e=>e.findPeer instanceof Function).map(n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}()));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs},t),e;throw new Oi}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Ty("No peer routers available");const r=this,n=ly(1024);for await(const s of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=t.ordered??!1,s=new EventTarget,i=[];let o,a=ys(),c=ys(),l=!1,u=!1;function h(){return n?i[0]?.done:Boolean(i.find(e=>e.done))}function*d(){for(;i.length>0&&i[0].done;){const e=i[0];if(i.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e<i.length;e++)if(i[e].done){const t=i[e];if(i.splice(e,1),e--,!t.ok)throw u=!0,a.resolve(),t.err;yield t.value,a.resolve()}}for(s.addEventListener("task-complete",()=>{c.resolve()}),Promise.resolve().then(async()=>{try{for await(const t of e){if(i.length===r&&(a=ys(),await a.promise),u)break;const e={done:!1};i.push(e),t().then(t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new _b("task-complete"))},t=>{e.done=!0,e.err=t,s.dispatchEvent(new _b("task-complete"))})}l=!0,s.dispatchEvent(new _b("task-complete"))}catch(e){o=e,s.dispatchEvent(new _b("task-complete"))}});;){if(h()||(c=ys(),await c.promise),null!=o)throw o;if(n?yield*d():yield*p(),null!=o)throw o;if(l&&0===i.length)break}}(async function*(){const n=Cs(...r.routers.filter(e=>e.getClosestPeers instanceof Function).map(r=>r.getClosestPeers(e,t)));for await(let e of n)yield async()=>{if(0===e.multiaddrs.length)try{e=await r.findPeer(e.id,{...t,useCache:!1})}catch(e){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=s&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs},t),n.has(s.id.toMultihash().bytes)||(n.add(s.id.toMultihash().bytes),yield s))}}class Pb extends Zl{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=ib([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=ys();const e=await zg(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=ib([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{const t=wf(32);let n=Date.now();for await(const s of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:s}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await As(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("random walk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")}).catch(e=>{this.log.error("random walk errored",e)}).finally(()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1})}}class Rb{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{const e={};for(const[t,r]of this.topologies)e[t]=r.size;return e}}),this.handlers=hy({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new Ry(`No handler registered for protocol ${e}`);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e)&&!0!==r?.force)throw new Oy(`Handler already registered for protocol ${e}`);const n=Qf.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},r)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(e=>{this.handlers.delete(e)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(null==t)throw new Ai("invalid topology");const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail,r={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,r).then(e=>{for(const r of e.protocols){const e=this.topologies.get(r);if(null!=e)for(const r of e.values())!1!==r.filter?.has(t)&&(r.filter?.remove(t),r.onDisconnect?.(t))}}).catch(e=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)})}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter(e=>!t.protocols.includes(e));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())null!=r.limits&&!0!==e.notifyOnLimitedConnection||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class Ob{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=hy({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=hy({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Af.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Ai("Transport must have a valid tag");if(this.transports.has(t))throw new Ai(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new qy(`No transport available for address ${String(e)}`);return t?.onProgress?.(new Bf("transport-manager:selected-transport",r[Symbol.toStringTag])),r.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new qi("Not started");if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(e=>{t.errors.set(e.toString(),new Dy)});const r=[];for(const[n,s]of this.transports.entries()){const i=s.listenFilter(e);for(const e of i){this.log("creating listener for %s on %a",n,e);const i=s.createListener({upgrader:this.components.upgrader});let o=this.listeners.get(n)??[];null==o&&(o=[],this.listeners.set(n,o)),o.push(i),i.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:i})}),i.addEventListener("close",()=>{const e=o.findIndex(e=>e===i);o.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:i})}),hp.matches(e)?t.ipv4.attempts++:dp.matches(e)&&t.ipv6.attempts++,r.push(i.listen(e).then(()=>{t.errors.delete(e.toString()),hp.matches(e)&&t.ipv4.success++,dp.matches(e)&&t.ipv6.success++},r=>{throw this.log.error("transport %s could not listen on address %a - %e",n,e,r),t.errors.set(e.toString(),r),r}))}}const n=await Promise.allSettled(r);if(!(n.length>0&&n.every(e=>"fulfilled"===e.status)))if(this.ipv6Unsupported(t))this.log("all IPv4 addresses succeed but all IPv6 failed");else{if(this.faultTolerance!==Af.NO_FATAL)throw new Ny(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:\n${[...t.errors.entries()].map(([e,t])=>`\n ${e}: ${`${t.stack??t}`.split("\n").join("\n ")}\n`).join("")}`);this.log("failed to listen on any address but fault tolerance allows this")}}ipv6Unsupported(e){if(0===e.ipv4.attempts||0===e.ipv6.attempts)return!1;const t=e.ipv4.attempts===e.ipv4.success,r=0===e.ipv6.success;return t&&r}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const Lb="/multistream/1.0.0",Db=1024,Nb=xt("\n");async function Mb(e,t,r){await e.write(t,r)}async function Fb(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==Nb[0])throw t.log.error("Invalid mss message - missing newline",r),new Bi("Missing newline");return r.sublist(0,-1)}(e,t);return Ln(r.subarray())}async function Bb(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=Ku(e,{...r,maxDataLength:Db,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await Fb(n,r);if(r.log.trace('handle: read "%s"',e),e!==Lb){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await Mb(n,xt(`${e}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"===e){const s=new os(...t.map(e=>Nu.single(xt(`${e}\n`))),xt("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await Mb(n,s,r),r.log.trace('handle: responded with "%s" for %s',t,e);continue}r.log.trace('handle: respond with "na" for "%s"',e),await Mb(n,xt("na\n"),r),r.log('handle: responded with "na" for "%s"',e)}else r.log.trace('handle: respond with "%s" for "%s"',Lb,e),await Mb(n,xt(`${Lb}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',Lb,e)}}async function Ub(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),s=e.source;let i=!1,o=!1;const a=ys();let c=!1,l=!1;const u=ys();let h=!1,d=!1;const p=ys(),f=Ku({sink:n,source:s},{...r,maxDataLength:Db});async function g(){if(o)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;o=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',Lb,t),await f.writeV([xt(`${Lb}\n`),xt(`${t}\n`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',Lb,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await Fb(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===Lb&&(e=await Fb(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new Fi("protocol selection failed")}finally{h=!0,d=!1,p.resolve()}}}())}finally{o=!1,i=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const s of e){if(l&&await u.promise,c)yield s;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Lb,t,s.byteLength);const e=`${t}\n`;yield new os(Uint8Array.from([19]),xt(`${Lb}\n`),_(e.length),xt(e),s).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Lb,t,s.byteLength),c=!0,l=!1,u.resolve(),g().catch(e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)})}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){const t=e.closeRead.bind(e);e.closeRead=async e=>{i||await g().catch(e=>{r.log.error("could not negotiate protocol before close read",e)}),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{i||await g().catch(e=>{r.log.error("could not negotiate protocol before close write",e)}),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await As(Promise.all(r),e?.signal):(i=!0,o=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=Ku(e,{...r,maxDataLength:Db}),s=t.shift();if(null==s)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',Lb,s);const i=xt(`${Lb}\n`),o=xt(`${s}\n`);await async function(e,t,r){await e.writeV(t,r)}(n,[i,o],r),r.log.trace("select: reading multistream-select header");let a=await Fb(n,r);if(r.log.trace('select: read "%s"',a),a===Lb&&(r.log.trace("select: reading protocol response"),a=await Fb(n,r),r.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(const e of t){r.log.trace('select: write "%s"',e),await Mb(n,xt(`${e}\n`),r),r.log.trace("select: reading protocol response");const t=await Fb(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new Fi("protocol selection failed")}const $b=Symbol.for("@libp2p/connection");class qb{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:s,abort:i,getStreams:o}=e;this.id=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=n,this._close=s,this._abort=i,this._getStreams=o,this.tags=[]}[Symbol.toStringTag]="Connection";[$b]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new xi("the connection is being closed");if("closed"===this.status)throw new Ci("the connection is closed");if(Array.isArray(e)||(e=[e]),null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new zi("Cannot open protocol stream on limited connection");const r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){const t=AbortSignal.timeout(500);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(e){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}}function jb(e,t,r){let n=0;return r.streams.forEach(r=>{r.direction===t&&r.protocol===e&&n++}),n}class zb{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=hy({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(e=>{this.connectionEncrypters.set(e.protocol,e)}),this.streamMuxers=hy({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(e=>{this.streamMuxers.set(e.protocol,e)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){const r=this.components.connectionGater[e];if(null!=r&&!0===await r.apply(this.components.connectionGater,t))throw new Fy(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){return ib([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}async upgradeInbound(e,t){let r=!1;const n=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),r=await As(this.components.connectionManager.acceptIncomingConnection(e),n),!r)throw new By("Connection denied");await As(this.shouldBlockConnection("denyInboundConnection",e),n),await this._performUpgrade(e,"inbound",{...t,signal:n})}catch(e){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[e.name??"Error"]:!0}),e}finally{n.clear(),r&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});const r=e.remoteAddr.getPeerId();let n;null!=r&&(n=Yc(r),await As(this.shouldBlockConnection("denyOutboundConnection",n,e),t.signal));let s="outbound";return!1===t.initiator&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(e){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[e.name??"Error"]:!0}),e}}async _performUpgrade(e,t,r){let n,s,i,o,a;this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let c=e;if(!0!==r?.skipProtection){const n=this.components.connectionProtector;null!=n&&(e.log("protecting the %s connection",t),c=await n.protect(e,r))}try{if(n=c,!0!==r?.skipEncryption){r?.onProgress?.(new Bf(`upgrader:encrypt-${t}-connection`)),({conn:n,remotePeer:s,protocol:a,streamMuxer:o}=await("inbound"===t?this._encryptInbound(c,r):this._encryptOutbound(c,r)));const e={...c,...n};await this.shouldBlockConnection("inbound"===t?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e)}else{const r=e.remoteAddr.getPeerId();if(null==r)throw new Di(`${t} connection that skipped encryption must have a peer id`);const n=Yc(r);a="native",s=n}if(s.equals(this.components.peerId)){const t=new Li("Can not dial self");throw e.abort(t),t}if(i=n,null!=r?.muxerFactory)o=r.muxerFactory;else if(null==o&&this.streamMuxers.size>0){r?.onProgress?.(new Bf(`upgrader:multiplex-${t}-connection`));const e=await("inbound"===t?this._multiplexInbound({...c,...n},this.streamMuxers,r):this._multiplexOutbound({...c,...n},this.streamMuxers,r));o=e.muxerFactory,i=e.stream}}catch(r){throw e.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===t?"from":"to",e.remoteAddr,r),r}return await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:a,direction:t,maConn:e,upgradedConn:i,muxerFactory:o,remotePeer:s,limits:r?.limits})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:s,remotePeer:i,muxerFactory:o,limits:a}=e;let c,l,u;null!=o&&(c=o.createStreamMuxer({direction:r,onIncomingStream:e=>{if(null==u)return;const t=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);Promise.resolve().then(async()=>{const r=this.components.registrar.getProtocols(),{stream:n,protocol:s}=await Bb(e,r,{signal:t,log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",s);const o=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(s,this.components.registrar);if(jb(s,"inbound",u)===o){const t=new Ki(`Too many inbound protocol streams for protocol "${s}" - limit ${o}`);throw e.abort(t),t}e.source=n.source,e.sink=n.sink,e.protocol=s,null!=n.closeWrite&&(e.closeWrite=n.closeWrite),null!=n.closeRead&&(e.closeRead=n.closeRead),null!=n.close&&(e.close=n.close),await this.components.peerStore.merge(i,{protocols:[s]},{signal:t}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:s})}).catch(async r=>{u.log.error("error handling incoming stream id %s - %e",e.id,r),null==e.timeline.close&&await e.close({signal:t}).catch(t=>e.abort(t))})}}),l=async(t,n={})=>{if(null==c)throw new Uy("Connection is not multiplexed");u.log.trace("starting new stream for protocols %s",t);const s=await c.newStream();u.log.trace("started new stream %s for protocols %s",s.id,t);try{if(null==n.signal){s.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);const e=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);n={...n,signal:e}}s.log.trace("selecting protocol from protocols %s",t);const{stream:e,protocol:r}=await Ub(s,t,{...n,log:s.log,yieldBytes:!0});s.log.trace("selected protocol %s",r);const o=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return r.maxOutboundStreams??64}(r,this.components.registrar,n),a=jb(r,"outbound",u);if(a>=o){const e=new Vi(`Too many outbound protocol streams for protocol "${r}" - ${a}/${o}`);throw s.abort(e),e}return await this.components.peerStore.merge(i,{protocols:[r]}),s.source=e.source,s.sink=e.sink,s.protocol=r,null!=e.closeWrite&&(s.closeWrite=e.closeWrite),null!=e.closeRead&&(s.closeRead=e.closeRead),null!=e.close&&(s.close=e.close),this.components.metrics?.trackProtocolStream(s,u),s}catch(n){throw u.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===r?"from":"to",e.maConn.remoteAddr,t,n),null==s.timeline.close&&s.abort(n),n}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch(e=>{u.log.error("error piping data through muxer - %e",e)}));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>("close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close %e",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch(e=>{u.log.error("error thrown while dispatching connection:close event %e",e)}),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:i,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,limits:a,logger:this.components.logger,newStream:l??(()=>{throw new Uy("Connection is not multiplexed")}),getStreams:()=>c?.streams??[],close:async e=>{await(c?.close(e)),await n.close(e)},abort:e=>{n.abort(e),c?.abort(e)}},u=new qb(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u.__maConnTimeline=h,u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:s,options:i}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==i.runOnLimitedConnection)throw new zi("Cannot open protocol stream on limited connection");s({connection:t,stream:r})}async _encryptInbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{const{stream:n,protocol:s}=await Bb(e,r,{...t,log:e.log}),i=this.connectionEncrypters.get(s);if(null==i)throw new $y(`no crypto module found for ${s}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,s),{...await i.secureInbound(n,t),protocol:s}}catch(t){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,t),new $y(t.message)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:s}=await Ub(e,r,{...t,log:e.log,yieldBytes:!0}),i=this.connectionEncrypters.get(s);if(null==i)throw new $y(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,s),{...await i.secureOutbound(n,t),protocol:s}}catch(t){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,t),new $y(t.message)}}async _multiplexOutbound(e,t,r){const n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);const{stream:s,protocol:i}=await Ub(e,n,{...r,log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",i),{stream:s,muxerFactory:t.get(i)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new Uy(String(t))}}async _multiplexInbound(e,t,r){const n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{const{stream:s,protocol:i}=await Bb(e,n,{...r,log:e.log});return{stream:s,muxerFactory:t.get(i)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new Uy(String(t))}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}const Kb="2.8.11",Vb="js-libp2p";class Hb extends Zl{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new Zl,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??Ng(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=e.nodeInfo?.name??Vb,s=e.nodeInfo?.version??Kb,i=this.components=function(e={}){const t=new jy(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!Ky.includes(r)){const e=t.components[r];if(null==e&&!zy.includes(r))throw new xy(`${r} not set`);return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:n,version:s,userAgent:e.nodeInfo?.userAgent??(o=n,a=s,`${o??Vb}/${a??Kb} browser/${globalThis.navigator.userAgent}`)},logger:this.logger,events:t,datastore:e.datastore??new Jm,connectionGater:Wy(e.connectionGater),dns:e.dns});var o,a;null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new zm(e,t)}(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",e=>{if(null==e.detail.previous){const t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map(e=>e.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:t})}}),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new zb(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((e,t)=>this.configureComponent(`connection-encryption-${t}`,e(this.components))),streamMuxers:(e.streamMuxers??[]).map((e,t)=>this.configureComponent(`stream-muxers-${t}`,e(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout??e.connectionManager?.protocolNegotiationTimeout}),this.configureComponent("transportManager",new Ob(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ab(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new xb(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Rb(this.components)),this.configureComponent("addressManager",new Ay(this.components,e.addresses));const c=(e.peerRouters??[]).map((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new Tb(this.components,{routers:c}));const l=(e.contentRouters??[]).map((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Cb(this.components,{routers:l})),this.configureComponent("randomWalk",new Pb(this.components)),(e.peerDiscovery??[]).forEach((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",e=>{this.#D(e)})}),e.transports?.forEach((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))}),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[Sg]&&(this.log("registering service %s for content routing",t),l.push(r[Sg])),null!=r[Ag]&&(this.log("registering service %s for peer routing",t),c.push(r[Ag])),null!=r[Zh]&&(this.log("registering service %s for peer discovery",t),r[Zh].addEventListener?.("peer",e=>{this.#D(e)}))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const r of Object.values(e.components))for(const e of Vy(r))t[e]=!0;for(const r of Object.values(e.components))for(const e of Hy(r))if(!0!==t[e])throw new Cy(`Service "${Gy(r)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(i)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{await(this.components.beforeStart?.()),await this.components.start(),await(this.components.afterStart?.()),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(this.components.beforeStop?.()),await this.components.stop(),await(this.components.afterStop?.()),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new Ug;for(const t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,r={}){if(null==t)throw new Ai("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Ai("no protocols were provided to open a stream");return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Ul(e)&&(e=Yc(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{const r=await this.peerStore.get(e,t);if(null!=r.id.publicKey)return r.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}const r=ts([xt("/pk/"),e.toMultihash().bytes]),n=zc(await this.contentRouting.get(r,t));return await this.peerStore.patch(e,{publicKey:n},t),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async e=>{await this.components.registrar.handle(e,t,r)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async e=>{await this.components.registrar.unhandle(e,t)}))}async register(e,t,r){return this.components.registrar.register(e,t,r)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#D(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(e=>{this.log.error(e)}):this.log.error("peer discovery mechanism discovered self")}}function Gb(){try{return!1}catch(e){return!1}}const Wb=Tn.BOOTSTRAP,Xb={store:1,filter:2,lightPush:2};var Jb=__webpack_require__(495),Yb=__webpack_require__.t(Jb,2);const Zb=BigInt(0),Qb=BigInt(1),ew=BigInt(2),tw=BigInt(3),rw=BigInt(8),nw=Object.freeze({a:Zb,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:Qb,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),sw=(e,t)=>(e+t/ew)/t,iw={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=nw,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Qb*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=r,o=BigInt("0x100000000000000000000000000000000"),a=sw(i*e,t),c=sw(-n*e,t);let l=Lw(e-a*r-c*s,t),u=Lw(-a*n-c*i,t);const h=l>o,d=u>o;if(h&&(l=t-l),d&&(u=t-u),l>o||u>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}};function ow(e){const{a:t,b:r}=nw,n=Lw(e*e),s=Lw(n*e);return Lw(s+t*e+r)}const aw=nw.a===Zb;class cw extends Error{constructor(e){super(e)}}function lw(e){if(!(e instanceof uw))throw new TypeError("JacobianPoint expected")}class uw{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof pw))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(pw.ZERO)?uw.ZERO:new uw(e.x,e.y,Qb)}static toAffineBatch(e){const t=function(e,t=nw.P){const r=new Array(e.length),n=Nw(e.reduce((e,n,s)=>n===Zb?e:(r[s]=e,Lw(e*n,t)),Qb),t);return e.reduceRight((e,n,s)=>n===Zb?e:(r[s]=Lw(e*r[s],t),Lw(e*n,t)),n),r}(e.map(e=>e.z));return e.map((e,r)=>e.toAffine(t[r]))}static normalizeZ(e){return uw.toAffineBatch(e).map(uw.fromAffine)}equals(e){lw(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e,a=Lw(n*n),c=Lw(o*o),l=Lw(t*c),u=Lw(s*a),h=Lw(Lw(r*o)*c),d=Lw(Lw(i*n)*a);return l===u&&h===d}negate(){return new uw(this.x,Lw(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=Lw(e*e),s=Lw(t*t),i=Lw(s*s),o=e+s,a=Lw(ew*(Lw(o*o)-n-i)),c=Lw(tw*n),l=Lw(c*c),u=Lw(l-ew*a),h=Lw(c*(a-u)-rw*i),d=Lw(ew*t*r);return new uw(u,h,d)}add(e){lw(e);const{x:t,y:r,z:n}=this,{x:s,y:i,z:o}=e;if(s===Zb||i===Zb)return this;if(t===Zb||r===Zb)return e;const a=Lw(n*n),c=Lw(o*o),l=Lw(t*c),u=Lw(s*a),h=Lw(Lw(r*o)*c),d=Lw(Lw(i*n)*a),p=Lw(u-l),f=Lw(d-h);if(p===Zb)return f===Zb?this.double():uw.ZERO;const g=Lw(p*p),m=Lw(p*g),y=Lw(l*g),b=Lw(f*f-m-ew*y),w=Lw(f*(y-b)-h*m),v=Lw(n*o*p);return new uw(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=uw.ZERO;if("bigint"==typeof e&&e===Zb)return t;let r=Ow(e);if(r===Qb)return this;if(!aw){let e=t,n=this;for(;r>Zb;)r&Qb&&(e=e.add(n)),n=n.double(),r>>=Qb;return e}let{k1neg:n,k1:s,k2neg:i,k2:o}=iw.splitScalar(r),a=t,c=t,l=this;for(;s>Zb||o>Zb;)s&Qb&&(a=a.add(l)),o&Qb&&(c=c.add(l)),l=l.double(),s>>=Qb,o>>=Qb;return n&&(a=a.negate()),i&&(c=c.negate()),c=new uw(Lw(c.x*iw.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=aw?128/e+1:256/e+1,r=[];let n=this,s=n;for(let i=0;i<t;i++){s=n,r.push(s);for(let t=1;t<2**(e-1);t++)s=s.add(n),r.push(s);n=s.double()}return r}wNAF(e,t){!t&&this.equals(uw.BASE)&&(t=pw.BASE);const r=t&&t._WINDOW_SIZE||1;if(256%r)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let n=t&&dw.get(t);n||(n=this.precomputeWindow(r),t&&1!==r&&(n=uw.normalizeZ(n),dw.set(t,n)));let s=uw.ZERO,i=uw.BASE;const o=1+(aw?128/r:256/r),a=2**(r-1),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let t=0;t<o;t++){const r=t*a;let o=Number(e&c);e>>=u,o>a&&(o-=l,e+=Qb);const h=r,d=r+Math.abs(o)-1,p=t%2!=0,f=o<0;0===o?i=i.add(hw(p,n[h])):s=s.add(hw(f,n[d]))}return{p:s,f:i}}multiply(e,t){let r,n,s=Ow(e);if(aw){const{k1neg:e,k1:i,k2neg:o,k2:a}=iw.splitScalar(s);let{p:c,f:l}=this.wNAF(i,t),{p:u,f:h}=this.wNAF(a,t);c=hw(e,c),u=hw(o,u),u=new uw(Lw(u.x*iw.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:i}=this.wNAF(s,t);r=e,n=i}return uw.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,s=this.equals(uw.ZERO);null==e&&(e=s?rw:Nw(n));const i=e,o=Lw(i*i),a=Lw(o*i),c=Lw(t*o),l=Lw(r*a),u=Lw(n*i);if(s)return pw.ZERO;if(u!==Qb)throw new Error("invZ was invalid");return new pw(c,l)}}function hw(e,t){const r=t.negate();return e?r:t}uw.BASE=new uw(nw.Gx,nw.Gy,Qb),uw.ZERO=new uw(Zb,Qb,Zb);const dw=new WeakMap;class pw{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,dw.delete(this)}hasEvenY(){return this.y%ew===Zb}static fromCompressedHex(e){const t=32===e.length,r=Pw(t?e:e.subarray(1));if(!qw(r))throw new Error("Point is not on curve");let n=function(e){const{P:t}=nw,r=BigInt(6),n=BigInt(11),s=BigInt(22),i=BigInt(23),o=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=Dw(l,tw)*l%t,h=Dw(u,tw)*l%t,d=Dw(h,ew)*c%t,p=Dw(d,n)*d%t,f=Dw(p,s)*p%t,g=Dw(f,o)*f%t,m=Dw(g,a)*g%t,y=Dw(m,o)*f%t,b=Dw(y,tw)*l%t,w=Dw(b,i)*p%t,v=Dw(w,r)*c%t,E=Dw(v,ew);if(E*E%t!==e)throw new Error("Cannot find square root");return E}(ow(r));const s=(n&Qb)===Qb;t?s&&(n=Lw(-n)):!(1&~e[0])!==s&&(n=Lw(-n));const i=new pw(r,n);return i.assertValidity(),i}static fromUncompressedHex(e){const t=Pw(e.subarray(1,33)),r=Pw(e.subarray(33,65)),n=new pw(t,r);return n.assertValidity(),n}static fromHex(e){const t=Rw(e),r=t.length,n=t[0];if(32===r)return this.fromCompressedHex(t);if(33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return pw.BASE.multiply(zw(e))}static fromSignature(e,t,r){const{r:n,s}=Kw(t);if(![0,1,2,3].includes(r))throw new Error("Cannot recover: invalid recovery bit");const i=Mw(Rw(e)),{n:o}=nw,a=2===r||3===r?n+o:n,c=Nw(a,o),l=Lw(-i*c,o),u=Lw(s*c,o),h=1&r?"03":"02",d=pw.fromHex(h+xw(a)),p=pw.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return Iw(this.toHex(e))}toHex(e=!1){const t=xw(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${xw(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!qw(t)||!qw(r))throw new Error(e);const n=Lw(r*r);if(Lw(n-ow(t))!==Zb)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new pw(this.x,Lw(-this.y))}double(){return uw.fromAffine(this).double().toAffine()}add(e){return uw.fromAffine(this).add(uw.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return uw.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=uw.fromAffine(this),s=t===Zb||t===Qb||this!==pw.BASE?n.multiplyUnsafe(t):n.multiply(t),i=uw.fromAffine(e).multiplyUnsafe(r),o=s.add(i);return o.equals(uw.ZERO)?void 0:o.toAffine()}}function fw(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function gw(e){if(e.length<2||2!==e[0])throw new Error(`Invalid signature integer tag: ${Ew(e)}`);const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw new Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:Pw(r),left:e.subarray(t+2)}}pw.BASE=new pw(nw.Gx,nw.Gy),pw.ZERO=new pw(Zb,Zb);class mw{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=yw(e),r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(`${r}: Expected string or Uint8Array`);const n=t?Ew(e):e;if(128!==n.length)throw new Error(`${r}: Expected 64-byte hex`);return new mw(Tw(n.slice(0,64)),Tw(n.slice(64,128)))}static fromDER(e){const t=yw(e);if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r,s:n}=function(e){if(e.length<2||48!=e[0])throw new Error(`Invalid signature tag: ${Ew(e)}`);if(e[1]!==e.length-2)throw new Error("Invalid signature: incorrect length");const{data:t,left:r}=gw(e.subarray(2)),{data:n,left:s}=gw(r);if(s.length)throw new Error(`Invalid signature: left bytes after parsing: ${Ew(s)}`);return{r:t,s:n}}(t?e:Iw(e));return new mw(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!$w(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!$w(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=nw.n>>Qb;return this.s>e}normalizeS(){return this.hasHighS()?new mw(this.r,Lw(-this.s,nw.n)):this}toDERRawBytes(){return Iw(this.toDERHex())}toDERHex(){const e=fw(_w(this.s)),t=fw(_w(this.r)),r=e.length/2,n=t.length/2,s=_w(r),i=_w(n);return`30${_w(n+r+4)}02${i}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Iw(this.toCompactHex())}toCompactHex(){return xw(this.r)+xw(this.s)}}function yw(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function bw(e){if(!yw(e))throw new Error("Uint8Array expected")}function ww(...e){if(e.every(bw),1===e.length)return e[0];const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const s=e[t];r.set(s,n),n+=s.length}return r}const vw=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ew(e){bw(e);let t="";for(let r=0;r<e.length;r++)t+=vw[e[r]];return t}const Sw={_0:48,_9:57,A:65,F:70,a:97,f:102};function Aw(e){return e>=Sw._0&&e<=Sw._9?e-Sw._0:e>=Sw.A&&e<=Sw.F?e-(Sw.A-10):e>=Sw.a&&e<=Sw.f?e-(Sw.a-10):void 0}function Iw(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t<r;t++,s+=2){const r=Aw(e.charCodeAt(s)),i=Aw(e.charCodeAt(s+1));if(void 0===r||void 0===i){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}n[t]=16*r+i}return n}const kw=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function xw(e){if("bigint"!=typeof e)throw new Error("Expected bigint");if(!(Zb<=e&&e<kw))throw new Error("Expected number 0 <= n < 2^256");return e.toString(16).padStart(64,"0")}function Cw(e){const t=Iw(xw(e));if(32!==t.length)throw new Error("Error: expected 32 bytes");return t}function _w(e){const t=e.toString(16);return 1&t.length?`0${t}`:t}function Tw(e){if("string"!=typeof e)throw new TypeError("hexToNumber: expected string, got "+typeof e);return BigInt(`0x${e}`)}function Pw(e){return Tw(Ew(e))}function Rw(e){return yw(e)?Uint8Array.from(e):Iw(e)}function Ow(e){if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)return BigInt(e);if("bigint"==typeof e&&$w(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function Lw(e,t=nw.P){const r=e%t;return r>=Zb?r:t+r}function Dw(e,t){const{P:r}=nw;let n=e;for(;t-- >Zb;)n*=n,n%=r;return n}function Nw(e,t=nw.P){if(e===Zb||t<=Zb)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=Lw(e,t),n=t,s=Zb,i=Qb,o=Qb,a=Zb;for(;r!==Zb;){const e=n/r,t=n%r,c=s-o*e,l=i-a*e;n=r,r=t,s=o,i=a,o=c,a=l}if(n!==Qb)throw new Error("invert: does not exist");return Lw(s,t)}function Mw(e,t=!1){const r=function(e){const t=8*e.length-256,r=Pw(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n}=nw;return r>=n?r-n:r}let Fw,Bw;class Uw{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return Yw.hmacSha256(this.k,...e)}hmacSync(...e){return Bw(this.k,...e)}checkSync(){if("function"!=typeof Bw)throw new cw("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return ww(...t)}generateSync(){this.checkSync(),this.incr();let e=0;const t=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);const r=this.v.slice();t.push(r),e+=this.v.length}return ww(...t)}}function $w(e){return Zb<e&&e<nw.n}function qw(e){return Zb<e&&e<nw.P}function jw(e,t,r,n=!0){const{n:s}=nw,i=Mw(e,!0);if(!$w(i))return;const o=Nw(i,s),a=pw.BASE.multiply(i),c=Lw(a.x,s);if(c===Zb)return;const l=Lw(o*Lw(t+r*c,s),s);if(l===Zb)return;let u=new mw(c,l),h=(a.x===u.r?0:2)|Number(a.y&Qb);return n&&u.hasHighS()&&(u=u.normalizeS(),h^=1),{sig:u,recovery:h}}function zw(e){let t;if("bigint"==typeof e)t=e;else if("number"==typeof e&&Number.isSafeInteger(e)&&e>0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw new Error("Expected 32 bytes of private key");t=Tw(e)}else{if(!yw(e))throw new TypeError("Expected valid private key");if(32!==e.length)throw new Error("Expected 32 bytes of private key");t=Pw(e)}if(!$w(t))throw new Error("Expected private key: 0 < key < n");return t}function Kw(e){if(e instanceof mw)return e.assertValidity(),e;try{return mw.fromDER(e)}catch(t){return mw.fromCompact(e)}}function Vw(e){return Pw(e.length>32?e.slice(0,32):e)}function Hw(e){const t=Vw(e),r=Lw(t,nw.n);return Gw(r<Zb?t:r)}function Gw(e){return Cw(e)}const Ww={strict:!0};pw.BASE._setWindowSize(8);const Xw={node:Yb,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0},Jw={},Yw={bytesToHex:Ew,hexToBytes:Iw,concatBytes:ww,mod:Lw,invert:Nw,isValidPrivateKey(e){try{return zw(e),!0}catch(e){return!1}},_bigintTo32Bytes:Cw,_normalizePrivateKey:zw,hashToPrivateKey:e=>{if((e=Rw(e)).length<40||e.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");return Cw(Lw(Pw(e),nw.n-Qb)+Qb)},randomBytes:(e=32)=>{if(Xw.web)return Xw.web.getRandomValues(new Uint8Array(e));if(Xw.node){const{randomBytes:t}=Xw.node;return Uint8Array.from(t(e))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Yw.hashToPrivateKey(Yw.randomBytes(40)),precompute(e=8,t=pw.BASE){const r=t===pw.BASE?t:new pw(t.x,t.y);return r._setWindowSize(e),r.multiply(tw),r},sha256:async(...e)=>{if(Xw.web){const t=await Xw.web.subtle.digest("SHA-256",ww(...e));return new Uint8Array(t)}if(Xw.node){const{createHash:t}=Xw.node,r=t("sha256");return e.forEach(e=>r.update(e)),Uint8Array.from(r.digest())}throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(e,...t)=>{if(Xw.web){const r=await Xw.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=ww(...t),s=await Xw.web.subtle.sign("HMAC",r,n);return new Uint8Array(s)}if(Xw.node){const{createHmac:r}=Xw.node,n=r("sha256",e);return t.forEach(e=>n.update(e)),Uint8Array.from(n.digest())}throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(e,...t)=>{let r=Jw[e];if(void 0===r){const t=await Yw.sha256(Uint8Array.from(e,e=>e.charCodeAt(0)));r=ww(t,t),Jw[e]=r}return Yw.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof Fw)throw new cw("sha256Sync is undefined, you need to set it");let r=Jw[e];if(void 0===r){const t=Fw(Uint8Array.from(e,e=>e.charCodeAt(0)));r=ww(t,t),Jw[e]=r}return Fw(r,...t)},_JacobianPoint:uw};Object.defineProperties(Yw,{sha256Sync:{configurable:!1,get:()=>Fw,set(e){Fw||(Fw=e)}},hmacSha256Sync:{configurable:!1,get:()=>Bw,set(e){Bw||(Bw=e)}}});var Zw=__webpack_require__(1176);function Qw(e){return new Uint8Array(Zw.keccak256.arrayBuffer(e))}function ev(e,t,r){try{return function(e,t,r,n=Ww){let s;try{s=Kw(e),t=Rw(t)}catch(e){return!1}const{r:i,s:o}=s;if(n.strict&&s.hasHighS())return!1;const a=Mw(t);let c;try{c=function(e){return e instanceof pw?(e.assertValidity(),e):pw.fromHex(e)}(r)}catch(e){return!1}const{n:l}=nw,u=Nw(o,l),h=Lw(a*u,l),d=Lw(i*u,l),p=pw.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&Lw(p.x,l)===i}(mw.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}const tv="Invalid record id";function rv(e,t){switch(t){case"udp":return rv(e,"udp4")||rv(e,"udp6");case"tcp":return rv(e,"tcp4")||rv(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const s=t.slice(0,3);let i;switch(s){case"udp":i=r?e.get("udp6"):e.get("udp");break;case"tcp":i=r?e.get("tcp6"):e.get("tcp");break;default:return}return i?function(e,t,r,n){let s=$l("/"+e+"/"+Ml(e,r));return s=s.encapsulate($l("/"+t+"/"+Ml(t,n))),s}(r?"ip6":"ip4",s,n,i):void 0}const nv=parseInt("11111",2),sv=parseInt("10000000",2),iv=parseInt("01111111",2),ov={0:lv,1:lv,2:function(e,t){const r=cv(e,t),n=t.offset,s=t.offset+r,i=[];for(let t=n;t<s;t++)t===n&&0===e[t]||i.push(e[t]);return t.offset+=r,Uint8Array.from(i)},3:function(e,t){const r=cv(e,t),n=e[t.offset];t.offset++;const s=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw new Error("Unused bits in bit string is unimplemented");return s},4:function(e,t){const r=cv(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:function(e,t){return t.offset++,null},6:function(e,t){const r=cv(e,t),n=t.offset+r,s=e[t.offset];t.offset++;let i=0,o=0;s<40?(i=0,o=s):s<80?(i=1,o=s-40):(i=2,o=s-80);let a=`${i}.${o}`,c=[];for(;t.offset<n;){const r=e[t.offset];if(t.offset++,c.push(127&r),r<128){c.reverse();let e=0;for(let t=0;t<c.length;t++)e+=c[t]<<7*t;a+=`.${e}`,c=[]}}return a},16:lv,22:lv,48:lv};function av(e,t={offset:0}){const r=e[t.offset]&nv;if(t.offset++,null!=ov[r])return ov[r](e,t);throw new Error("No decoder for tag "+r)}function cv(e,t){let r=0;if((e[t.offset]&sv)===sv){const n=e[t.offset]&iv;let s="0x";t.offset++;for(let r=0;r<n;r++,t.offset++)s+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(s,16)}else r=e[t.offset],t.offset++;return r}function lv(e,t){cv(e,t);const r=[];for(;!(t.offset>=e.byteLength);){const n=av(e,t);if(null===n)break;r.push(n)}return r}function uv(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);const t=function(e){let t=e.toString(16);t.length%2==1&&(t="0"+t);const r=new os;for(let e=0;e<t.length;e+=2)r.append(Uint8Array.from([parseInt(`${t[e]}${t[e+1]}`,16)]));return r}(e.byteLength);return new os(Uint8Array.from([t.byteLength|sv]),t)}function hv(e){const t=new os;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new os(Uint8Array.from([2]),uv(t),t)}function dv(e){const t=Uint8Array.from([0]),r=new os(t,e);return new os(Uint8Array.from([3]),uv(r),r)}function pv(e,t=48){const r=new os;for(const t of e)r.append(t);return new os(Uint8Array.from([t]),uv(r),r)}class fv{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){var e;return null==this._raw&&(this._raw=(e=this.jwk,pv([hv(Uint8Array.from([1])),pv([Ev(e.crv)],160),pv([dv(new os(Uint8Array.from([4]),xt(e.x??"","base64url"),xt(e.y??"","base64url")))],161)]).subarray())),this._raw}toMultihash(){return at.digest(Uv(this))}toCID(){return mt.createV1(114,this.toMultihash())}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}async verify(e,t,r){return async function(e,t,r,n){const s=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();const i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}const gv=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),mv=Uint8Array.from([6,5,43,129,4,0,34]),yv=Uint8Array.from([6,5,43,129,4,0,35]),bv={ext:!0,kty:"EC",crv:"P-256"},wv={ext:!0,kty:"EC",crv:"P-384"},vv={ext:!0,kty:"EC",crv:"P-521"};function Ev(e){if("P-256"===e)return gv;if("P-384"===e)return mv;if("P-521"===e)return yv;throw new Ai(`Invalid curve ${e}`)}Error;class Sv extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}}class Av extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}const Iv={get(e=globalThis){const t=e.crypto;if(null==t?.subtle)throw new Av("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};let kv;const xv=(async()=>{try{return await Iv.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function Cv(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class _v{type="Ed25519";raw;constructor(e){this.raw=Tv(e,32)}toMultihash(){return at.digest(Uv(this))}toCID(){return mt.createV1(114,this.toMultihash())}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}verify(e,t,r){r?.signal?.throwIfAborted();const n=async function(e,t,r){return null==kv&&(kv=await xv),kv?async function(e,t,r){if(e.buffer instanceof ArrayBuffer){const n=await Iv.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Iv.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}(e,t,r):function(e,t,r){return $a.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(e,t,r)}(this.raw,t,e);return Cv(n)?n.then(e=>(r?.signal?.throwIfAborted(),e)):n}}function Tv(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ai(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var Pv,Rv,Ov,Lv;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(Pv||(Pv={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(Rv||(Rv={})),function(e){e.codec=()=>Sr(Rv)}(Pv||(Pv={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Pv.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.Type=Pv.codec().decode(e);break;case 2:n.Data=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Ov||(Ov={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Pv.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()},(e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos<s;){const t=e.uint32();switch(t>>>3){case 1:n.Type=Pv.codec().decode(e);break;case 2:n.Data=e.bytes();break;default:e.skipType(7&t)}}return n})),t),e.encode=t=>$t(t,e.codec()),e.decode=(t,r)=>V(t,e.codec(),r)}(Lv||(Lv={}));class Dv{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e)throw new Ai("JWK was missing components");return pv([Nv,dv(pv([hv(xt(e.n,"base64url")),hv(xt(e.e,"base64url"))]))]).subarray()}(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return mt.createV1(114,this._multihash)}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}verify(e,t,r){return async function(e,t,r,n){const s=await Iv.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();const i=await Iv.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},s,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),i}(this.jwk,t,e,r)}}const Nv=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Mv(e,t,r){const n=function(e){const t=av(e[1],{offset:0});return{kty:"RSA",n:Ln(t[0],"base64url"),e:Ln(t[1],"base64url")}}(e);return null==r&&(r=nt(18,xn(Ov.encode({Type:Pv.RSA,Data:t})))),new Dv(n,r)}class Fv{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return Fc.ProjectivePoint.fromHex(e),e}catch(e){throw new Ii(String(e))}}(e),this.raw=function(e){return Fc.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return at.digest(Uv(this))}toCID(){return mt.createV1(114,this.toMultihash())}toString(){return Ee.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rs(this.raw,e.raw)}verify(e,t,r){return function(e,t,r,n){const s=ht.digest(r instanceof Uint8Array?r:r.subarray());if(Cv(s))return s.then(({digest:r})=>(n?.signal?.throwIfAborted(),Fc.verify(t,r,e))).catch(e=>{if("AbortError"===e.name)throw e;throw new Sv(String(e))});try{return n?.signal?.throwIfAborted(),Fc.verify(t,s.digest,e)}catch(e){throw new Sv(String(e))}}(this._key,t,e,r)}}function Bv(e){if(32===e.byteLength)return t=Tv(t=e,32),new _v(t);if(33===e.byteLength)return function(e){return new Fv(e)}(e);var t;const r=av(e),n=r[1]?.[0];if("1.2.840.10045.3.1.7"===n||"1.3.132.0.34"===n||"1.3.132.0.35"===n)return function(e){const t=e[1][1][0];let r,n;if(65===t.byteLength)return r=Ln(t.subarray(1,33),"base64url"),n=Ln(t.subarray(33),"base64url"),new fv({...bv,key_ops:["verify"],x:r,y:n});if(97===t.byteLength)return r=Ln(t.subarray(1,49),"base64url"),n=Ln(t.subarray(49),"base64url"),new fv({...wv,key_ops:["verify"],x:r,y:n});if(133===t.byteLength)return r=Ln(t.subarray(1,67),"base64url"),n=Ln(t.subarray(67),"base64url"),new fv({...vv,key_ops:["verify"],x:r,y:n});throw new Ai(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}(r);if("1.2.840.113549.1.1.1"===r[0]?.[0])return Mv(r,e);throw new Ai("Could not extract public key from raw bytes")}function Uv(e){return Ov.encode({Type:Pv[e.type],Data:e.raw})}const $v=Symbol.for("nodejs.util.inspect.custom");class qv{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[bi]=!0;toString(){return null==this.string&&(this.string=Ee.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return mt.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return rs(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return rs(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[$v](){return`PeerId(${this.toString()})`}}class jv extends qv{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class zv extends qv{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class Kv extends qv{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}function Vv(e){const t=e.reduce((e,t)=>e+2+t.bytes.length,0),r=new Uint8Array(t),n=new DataView(r.buffer);let s=0;return e.forEach(e=>{if(e.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");n.setUint16(s,e.bytes.length),s+=2,r.set(e.bytes,s),s+=e.bytes.length}),r}function Hv(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class Gv extends Map{seq;signature;constructor(e={},t=BigInt(1),r){super(Object.entries(e)),this.seq=t,this.signature=r}set(e,t){return this.signature=void 0,this.seq++,super.set(e,t)}get id(){const e=this.get("id");if(!e)throw new Error("id not found.");return Mn(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw new Error(tv)}get rs(){const e=this.get("rs");if(e)return jn(e)}get rsv(){const e=this.get("rsv");if(e)return jn(e)}get ip(){return Wv(this,"ip","ip4")}set ip(e){Jv(this,"ip","ip4",e)}get tcp(){return Xv(this,"tcp","tcp")}set tcp(e){Yv(this,"tcp","tcp",e)}get udp(){return Xv(this,"udp","udp")}set udp(e){Yv(this,"udp","udp",e)}get ip6(){return Wv(this,"ip6","ip6")}set ip6(e){Jv(this,"ip6","ip6",e)}get tcp6(){return Xv(this,"tcp6","tcp")}set tcp6(e){Yv(this,"tcp6","tcp",e)}get udp6(){return Xv(this,"udp6","udp")}set udp6(e){Yv(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r<e.length;){const n=new DataView(e.buffer,r,2).getUint16(0);r+=2;const s=e.slice(r,r+n);r+=n,t.push($l(s))}return t}(e)}set multiaddrs(e){Zv(this,"multiaddrs",e,Vv)}get waku2(){const e=this.get("waku2");if(e)return function(e){const t={relay:!1,store:!1,filter:!1,lightPush:!1};return e%2&&(t.relay=!0),(e>>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){Zv(this,"waku2",e,e=>new Uint8Array([Hv(e)]))}}function Wv(e,t,r){const n=e.get(t);if(n)return Ml(r,n)}function Xv(e,t,r){const n=e.get(t);if(n)return Number(Ml(r,n))}function Jv(e,t,r,n){Zv(e,t,n,Fl.bind({},r))}function Yv(e,t,r,n){Jv(e,t,r,n?.toString(10))}function Zv(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function Qv(e,t){return async function(e,t,r={}){const{seed:n,m:s,d:i}=function(e,t,r){if(null==e)throw new Error(`sign: expected valid message hash, not "${e}"`);const n=Rw(e),s=zw(t),i=[Gw(s),Hw(n)];if(null!=r){!0===r&&(r=Yw.randomBytes(32));const e=Rw(r);if(32!==e.length)throw new Error("sign: Expected 32 bytes of extra data");i.push(e)}return{seed:ww(...i),m:Vw(n),d:s}}(e,t,r.extraEntropy),o=new Uw(32,32);let a;for(await o.reseed(n);!(a=jw(await o.generate(),s,i,r.canonical));)await o.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:s,recovered:i}=Object.assign({canonical:!0,der:!0},t),o=s?r.toDERRawBytes():r.toCompactRawBytes();return i?[o,n]:o}(a,r)}(Qw(t),e,{der:!1})}const eE=new Hn("enr");var tE,rE;!function(e){e.TCP="tcp",e.UDP="udp"}(tE||(tE={})),function(e){e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"}(rE||(rE={}));class nE extends Gv{static RECORD_PREFIX="enr:";peerId;static create(e={},t=BigInt(1),r){const n=new nE(e,t,r);try{const e=n.publicKey;e&&(n.peerId=function(e){const t=Bv(e);if("secp256k1"!==t.type)throw new Error("Keypair type not implemented");return function(e){if("Ed25519"===e.type)return new zv({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Kv({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new jv({multihash:e.toCID().multihash,publicKey:e});throw new Hi}(t)}(e))}catch(e){eE.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=pw.fromHex(e).toRawBytes(!1);return Nn(Qw(t.slice(1)))}(this.publicKey):void 0;throw new Error(tv)}getLocationMultiaddr=rv.bind({},this);get shardInfo(){return this.rs&&this.rsv&&eE.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw new Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw new Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){const e=[];for(const t of Object.values(rE)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}const t=this.multiaddrs??[];return e.concat(t).map(e=>this.peerId?e.encapsulate(`/p2p/${this.peerId.toString()}`):e)}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const e=this.peerId;return this.multiaddrs.map(t=>t.encapsulate(`/p2p/${e.toString()}`))}return[]}verify(e,t){if(!this.get("id")||"v4"!==this.id)throw new Error(tv);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return ev(t,Qw(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw new Error(tv);return this.signature=await Qv(t,e),this.signature}}let sE=!1,iE=!1;const oE={debug:1,default:2,info:2,warning:3,error:4,off:5};let aE=oE.default,cE=null;const lE=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach(t=>{try{if("test"!=="test".normalize(t))throw new Error("bad normalize")}catch(r){e.push(t)}}),e.length)throw new Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(e){return e.message}return null}();var uE,hE;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(uE||(uE={})),function(e){e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"}(hE||(hE={}));const dE="0123456789abcdef";class pE{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==oE[r]&&this.throwArgumentError("invalid log level name","logLevel",e),aE>oE[r]||console.log.apply(console,t)}debug(...e){this._log(pE.levels.DEBUG,e)}info(...e){this._log(pE.levels.INFO,e)}warn(...e){this._log(pE.levels.WARNING,e)}makeError(e,t,r){if(iE)return this.makeError("censored error",t,{});t||(t=pE.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach(e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e<t.length;e++)r+=dE[t[e]>>4],r+=dE[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}}),n.push(`code=${t}`),n.push(`version=${this.version}`);const s=e;let i="";switch(t){case hE.NUMERIC_FAULT:{i="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":i+="-"+t;break;case"negative-power":case"negative-width":i+="-unsupported";break;case"unbound-bitwise-result":i+="-unbound-result"}break}case hE.CALL_EXCEPTION:case hE.INSUFFICIENT_FUNDS:case hE.MISSING_NEW:case hE.NONCE_EXPIRED:case hE.REPLACEMENT_UNDERPRICED:case hE.TRANSACTION_REPLACED:case hE.UNPREDICTABLE_GAS_LIMIT:i=t}i&&(e+=" [ See: https://links.ethers.org/v5-errors-"+i+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const o=new Error(e);return o.reason=s,o.code=t,Object.keys(r).forEach(function(e){o[e]=r[e]}),o}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,pE.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){null==e&&(e="platform missing String.prototype.normalize"),lE&&this.throwError("platform missing String.prototype.normalize",pE.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:lE})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,pE.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,pE.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",e<t&&this.throwError("missing argument"+r,pE.errors.MISSING_ARGUMENT,{count:e,expectedCount:t}),e>t&&this.throwError("too many arguments"+r,pE.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",pE.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",pE.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",pE.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return cE||(cE=new pE("logger/5.8.0")),cE}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",pE.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),sE){if(!e)return;this.globalLogger().throwError("error censorship permanent",pE.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}iE=!!e,sE=!!t}static setLogLevel(e){const t=oE[e.toLowerCase()];null!=t?aE=t:pE.globalLogger().warn("invalid log level - "+e)}static from(e){return new pE(e)}}pE.errors=hE,pE.levels=uE;const fE=new pE("bytes/5.8.0");function gE(e){return!!e.toHexString}function mE(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return mE(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function yE(e){return"number"==typeof e&&e==e&&e%1==0}function bE(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!yE(e.length)||e.length<0)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!yE(r)||r<0||r>=256)return!1}return!0}function wE(e,t){if(t||(t={}),"number"==typeof e){fE.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),mE(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),gE(e)&&(e=e.toHexString()),vE(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":fE.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e<r.length;e+=2)n.push(parseInt(r.substring(e,e+2),16));return mE(new Uint8Array(n))}return bE(e)?mE(new Uint8Array(e)):fE.throwArgumentError("invalid arrayify value","value",e)}function vE(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/)||t&&e.length!==2+2*t)}const EE="0123456789abcdef";function SE(e,t){if(t||(t={}),"number"==typeof e){fE.checkSafeUint53(e,"invalid hexlify value");let t="";for(;e;)t=EE[15&e]+t,e=Math.floor(e/16);return t.length?(t.length%2&&(t="0"+t),"0x"+t):"0x00"}if("bigint"==typeof e)return(e=e.toString(16)).length%2?"0x0"+e:"0x"+e;if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),gE(e))return e.toHexString();if(vE(e))return e.length%2&&("left"===t.hexPad?e="0x0"+e.substring(2):"right"===t.hexPad?e+="0":fE.throwArgumentError("hex data is odd-length","value",e)),e.toLowerCase();if(bE(e)){let t="0x";for(let r=0;r<e.length;r++){let n=e[r];t+=EE[(240&n)>>4]+EE[15&n]}return t}return fE.throwArgumentError("invalid hexlify value","value",e)}const AE=new pE("rlp/5.8.0");function IE(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function kE(e,t,r){let n=0;for(let s=0;s<r;s++)n=256*n+e[t+s];return n}function xE(e){if(Array.isArray(e)){let t=[];if(e.forEach(function(e){t=t.concat(xE(e))}),t.length<=55)return t.unshift(192+t.length),t;const r=IE(t.length);return r.unshift(247+r.length),r.concat(t)}var t;vE(t=e)&&!(t.length%2)||bE(t)||AE.throwArgumentError("RLP object must be BytesLike","object",e);const r=Array.prototype.slice.call(wE(e));if(1===r.length&&r[0]<=127)return r;if(r.length<=55)return r.unshift(128+r.length),r;const n=IE(r.length);return n.unshift(183+n.length),n.concat(r)}function CE(e,t,r,n){const s=[];for(;r<t+1+n;){const i=_E(e,r);s.push(i.result),(r+=i.consumed)>t+1+n&&AE.throwError("child data too short",pE.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:s}}function _E(e,t){if(0===e.length&&AE.throwError("data too short",pE.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&AE.throwError("data short segment too short",pE.errors.BUFFER_OVERRUN,{});const n=kE(e,t+1,r);return t+1+r+n>e.length&&AE.throwError("data long segment too short",pE.errors.BUFFER_OVERRUN,{}),CE(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&AE.throwError("data array too short",pE.errors.BUFFER_OVERRUN,{}),CE(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&AE.throwError("data array too short",pE.errors.BUFFER_OVERRUN,{});const n=kE(e,t+1,r);return t+1+r+n>e.length&&AE.throwError("data array too short",pE.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:SE(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&AE.throwError("data too short",pE.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:SE(e.slice(t+1,t+1+r))}}return{consumed:1,result:SE(e[t])}}const TE=new Hn("enr:decoder");class PE{static fromString(e){if(!e.startsWith(nE.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${nE.RECORD_PREFIX}'`);return PE.fromRLP(xt(e.slice(4),"base64url"))}static fromRLP(e){return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw new Error("Decoded ENR must be an array");if(e.length%2!=0)throw new Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw new Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw new Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),s={};for(let e=0;e<n.length;e+=2)try{s[Mn(n[e])]=n[e+1]}catch(t){TE.error("Failed to decode ENR key to UTF-8, skipping it",n[e],t)}const i=function(e){return e.length?BigInt("0x"+Nn(e)):BigInt(0)}(r),o=nE.create(s,i,t);return function(e,t,r,n){const s=Dn(SE(xE([e,...t])));if(!r.verify(s,n))throw new Error("Unable to verify ENR signature")}(r,n,o,t),o}(function(e){const t=wE(e),r=_E(t,0);return r.consumed!==t.length&&AE.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(Dn))}}class RE extends Map{#N=0;#M=new Map;#F=new Map;#B;#U;#$;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if("number"==typeof e.maxAge&&0===e.maxAge)throw new TypeError("`maxAge` must be a number greater than 0");this.#B=e.maxSize,this.#U=e.maxAge||Number.POSITIVE_INFINITY,this.#$=e.onEviction}get __oldCache(){return this.#F}#q(e){if("function"==typeof this.#$)for(const[t,r]of e)this.#$(t,r.value)}#j(e,t){return"number"==typeof t.expiry&&t.expiry<=Date.now()&&("function"==typeof this.#$&&this.#$(e,t.value),this.delete(e))}#z(e,t){if(!1===this.#j(e,t))return t.value}#K(e,t){return t.expiry?this.#z(e,t):t.value}#V(e,t){const r=t.get(e);return this.#K(e,r)}#H(e,t){this.#M.set(e,t),this.#N++,this.#N>=this.#B&&(this.#N=0,this.#q(this.#F),this.#F=this.#M,this.#M=new Map)}#G(e,t){this.#F.delete(e),this.#H(e,t)}*#W(){for(const e of this.#F){const[t,r]=e;this.#M.has(t)||!1===this.#j(t,r)&&(yield e)}for(const e of this.#M){const[t,r]=e;!1===this.#j(t,r)&&(yield e)}}get(e){if(this.#M.has(e)){const t=this.#M.get(e);return this.#K(e,t)}if(this.#F.has(e)){const t=this.#F.get(e);if(!1===this.#j(e,t))return this.#G(e,t),t.value}}set(e,t,{maxAge:r=this.#U}={}){const n="number"==typeof r&&r!==Number.POSITIVE_INFINITY?Date.now()+r:void 0;return this.#M.has(e)?this.#M.set(e,{value:t,expiry:n}):this.#H(e,{value:t,expiry:n}),this}has(e){return this.#M.has(e)?!this.#j(e,this.#M.get(e)):!!this.#F.has(e)&&!this.#j(e,this.#F.get(e))}peek(e){return this.#M.has(e)?this.#V(e,this.#M):this.#F.has(e)?this.#V(e,this.#F):void 0}delete(e){const t=this.#M.delete(e);return t&&this.#N--,this.#F.delete(e)||t}clear(){this.#M.clear(),this.#F.clear(),this.#N=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");const t=[...this.#W()],r=t.length-e;r<0?(this.#M=new Map(t),this.#F=new Map,this.#N=t.length):(r>0&&this.#q(t.slice(0,r)),this.#F=new Map(t.slice(r)),this.#M=new Map,this.#N=0),this.#B=e}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[Symbol.iterator](){for(const e of this.#M){const[t,r]=e;!1===this.#j(t,r)&&(yield[t,r.value])}for(const e of this.#F){const[t,r]=e;this.#M.has(t)||!1===this.#j(t,r)&&(yield[t,r.value])}}*entriesDescending(){let e=[...this.#M];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,s]=r;!1===this.#j(n,s)&&(yield[n,s.value])}e=[...this.#F];for(let t=e.length-1;t>=0;--t){const r=e[t],[n,s]=r;this.#M.has(n)||!1===this.#j(n,s)&&(yield[n,s.value])}}*entriesAscending(){for(const[e,t]of this.#W())yield[e,t.value]}get size(){if(!this.#N)return this.#F.size;let e=0;for(const t of this.#F.keys())this.#M.has(t)||e++;return Math.min(this.#N+e,this.#B)}get maxSize(){return this.#B}entries(){return this.entriesAscending()}forEach(e,t=this){for(const[r,n]of this.entriesAscending())e.call(t,n,r,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function OE(e,t,r){return`${e}?name=${t}&type=${r}`}async function LE(e,t){const r=await fetch(e,{headers:new Headers({accept:"application/dns-json"}),signal:t});return await r.json()}function DE(e,t){return`${t}_${e}`}const NE=Object.assign(Dg("dns-over-http-resolver"),{error:Dg("dns-over-http-resolver:error")}),ME=class{_cache;_TXTcache;_servers;_request;_abortControllers;constructor(e={}){this._cache=new RE({maxSize:e?.maxCache??100}),this._TXTcache=new RE({maxSize:e?.maxCache??100}),this._servers=["https://cloudflare-dns.com/dns-query","https://dns.google/resolve"],this._request=e.request??LE,this._abortControllers=[]}cancel(){this._abortControllers.forEach(e=>{e.abort()})}getServers(){return this._servers}_getShuffledServers(){const e=[...this._servers];for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*t),n=e[t];e[t]=e[r],e[r]=n}return e}setServers(e){this._servers=e}async resolve(e,t="A"){switch(t){case"A":return this.resolve4(e);case"AAAA":return this.resolve6(e);case"TXT":return this.resolveTxt(e);default:throw new Error(`${t} is not supported`)}}async resolve4(e){const t="A",r=this._cache.get(DE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(OE(r,e,t),s.signal),i=n.Answer.map(e=>e.data),o=Math.min(...n.Answer.map(e=>e.TTL));return this._cache.set(DE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),NE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(e=>e!==s)}}if(n)throw Object.assign(new Error("queryA ECANCELLED"),{code:"ECANCELLED"});throw new Error(`Could not resolve ${e} record ${t}`)}async resolve6(e){const t="AAAA",r=this._cache.get(DE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(OE(r,e,t),s.signal),i=n.Answer.map(e=>e.data),o=Math.min(...n.Answer.map(e=>e.TTL));return this._cache.set(DE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),NE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(e=>e!==s)}}if(n)throw Object.assign(new Error("queryAaaa ECANCELLED"),{code:"ECANCELLED"});throw new Error(`Could not resolve ${e} record ${t}`)}async resolveTxt(e){const t="TXT",r=this._TXTcache.get(DE(e,t));if(null!=r)return r;let n=!1;for(const r of this._getShuffledServers()){const s=new AbortController;this._abortControllers.push(s);try{const n=await this._request(OE(r,e,t),s.signal),i=n.Answer.map(e=>[e.data.replace(/['"]+/g,"")]),o=Math.min(...n.Answer.map(e=>e.TTL));return this._TXTcache.set(DE(e,t),i,{maxAge:o}),i}catch(i){s.signal.aborted&&(n=!0),NE.error(`${r} could not resolve ${e} record ${t}`)}finally{this._abortControllers=this._abortControllers.filter(e=>e!==s)}}if(n)throw Object.assign(new Error("queryTxt ECANCELLED"),{code:"ECANCELLED"});throw new Error(`Could not resolve ${e} record ${t}`)}clearCache(){this._cache.clear(),this._TXTcache.clear()}},FE=new Hn("dns-over-https");class BE{resolver;static async create(){return new BE}constructor(e=new ME){this.resolver=e}async resolveTXT(e){let t;try{t=await this.resolver.resolveTxt(e)}catch(e){throw FE.error("query failed: ",e),new Error("DNS query failed")}if(!t)throw new Error(`Could not resolve ${e}`);const r=[];return t.forEach(e=>{"string"==typeof e?r.push(e):Array.isArray(e)?e.forEach(e=>{"string"==typeof e?r.push(e):r.push(Mn(e))}):r.push(Mn(e))}),r}}var UE=__webpack_require__(5818);class $E{static RECORD_PREFIX=nE.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(e,t){if(!e.startsWith(this.ROOT_PREFIX))throw new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=$E.parseRootValues(e),n=UE.decode.asBytes(t),s=e.split(" sig")[0],i=Fn(s);if(!ev(xt(r.signature,"base64url").slice(0,64),Qw(i),new Uint8Array(n)))throw new Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree root entry");t.shift();const[r,n,s,i]=t;if(!r)throw new Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw new Error("Could not parse 'l' value from ENRTree root entry");if(!s)throw new Error("Could not parse 'seq' value from ENRTree root entry");if(!i)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(s),signature:i}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw new Error("Could not parse public key from ENRTree tree entry");if(!n)throw new Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const qE=new Hn("discovery:fetch_nodes");function jE(e,t){return t.relay>=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function zE(e,t){if(!e.nodeId)return!1;for(const r of t)if(e.nodeId===r.nodeId)return!1;return!0}function KE(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function VE(e,t,r){if(jE(t,r))throw"Internal Error: Waku2 wanted capabilities are already fulfilled";const n=function(e,t){return{relay:t.relay<e.relay,store:t.store<e.store,filter:t.filter<e.filter,lightPush:t.lightPush<e.lightPush}}(t,r);return n.relay&&e.relay||n.store&&e.store||n.filter&&e.filter||n.lightPush&&e.lightPush}const HE=new Hn("discovery:dns");class GE{dns;_DNSTreeCache;_errorTolerance=10;static async dnsOverHttp(e){return e||(e=await BE.create()),new GE(e)}async getPeers(e,t){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:s}=$E.parseTree(e[r]),i={domain:s,publicKey:n,visits:{}},o=await async function(e,t,r){const n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},s=n.relay+n.store+n.filter+n.lightPush,i={relay:0,store:0,filter:0,lightPush:0};let o=0;const a=[];for(;!jE(n,i)&&o<s+t;){const e=await r();e&&zE(e,a)&&(e.waku2&&VE(e.waku2,n,i)&&(KE(e.waku2,i),a.push(e)),qE.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),o++}return a}(t,this._errorTolerance,()=>this._search(s,i));return HE.info("retrieved peers: ",o.map(e=>({id:e.peerId?.toString(),multiaddrs:e.multiaddrs?.map(e=>e.toString())}))),o}constructor(e){this._DNSTreeCache={},this.dns=e}async*getNextPeer(e,t){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:s}=$E.parseTree(e[r]),i={domain:s,publicKey:n,visits:{}};for await(const e of async function*(e,t,r){const n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},s=n.relay+n.store+n.filter+n.lightPush,i={relay:0,store:0,filter:0,lightPush:0};let o=0;const a=new Set;for(;!jE(n,i)&&o<s+t;){const e=await r();e&&e.nodeId&&!a.has(e.nodeId)&&(a.add(e.nodeId),e.waku2&&VE(e.waku2,n,i)&&(KE(e.waku2,i),yield e),qE.info(`got new peer candidate from DNS address=${e.nodeId}@${e.ip}`)),o++}}(t,this._errorTolerance,()=>this._search(s,i)))yield e}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,s;t.visits[e]=!0;const i=function(e){return e.startsWith($E.ROOT_PREFIX)?$E.ROOT_PREFIX:e.startsWith($E.BRANCH_PREFIX)?$E.BRANCH_PREFIX:e.startsWith($E.RECORD_PREFIX)?$E.RECORD_PREFIX:""}(r);try{switch(i){case $E.ROOT_PREFIX:return n=$E.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case $E.BRANCH_PREFIX:return s=$E.parseBranch(r),n=function(e,t){const r={};for(const[n,s]of e.entries())t.visits[s]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw new Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(s,t),await this._search(n,t);case $E.RECORD_PREFIX:return PE.fromString(r);default:return null}}catch(t){return HE.error(`Failed to search DNS tree ${i} at subdomain ${e}: ${t}`),null}}catch(t){return HE.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw new Error("Received empty result array while fetching TXT record");if(!n[0].length)throw new Error("Received empty TXT record");const s=n.join("");return this._DNSTreeCache[e]=s,s}}const WE=new Hn("peer-discovery-dns");class XE extends Zl{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;WE.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){WE.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const{wantedNodeCapabilityCount:t}=this._options,r=await GE.dnsOverHttp();this.nextPeer=r.getNextPeer.bind(r,e,t)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:t,shardInfo:r}=e;if(!t)continue;const n={[Wb]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let s=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(Wb)||(s=!0,await this._components.peerStore.merge(t.id,{tags:n})):(s=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:zn(r)}}})),s&&this.dispatchEvent(new CustomEvent("peer",{detail:t}))}}stop(){this._started=!1}get[Zh](){return!0}get[Symbol.toStringTag](){return"@waku/bootstrap"}}class JE{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new JE({query:{numPeers:t},response:void 0})}encode(){return mr.encode(this.proto)}static decode(e){const t=mr.decode(e);return new JE(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const YE="/vac/waku/peer-exchange/2.0.0-alpha1",ZE=new Hn("peer-exchange");class QE{components;streamManager;constructor(e){this.components=e,this.streamManager=new Ms(YE,e)}async query(e){const{numPeers:t,peerId:r}=e,n=JE.createRequest({numPeers:BigInt(t)});if(!await this.components.peerStore.get(r))return{peerInfos:null,error:_n.NO_PEER_AVAILABLE};let s;try{s=await this.streamManager.getStream(r)}catch(e){return ZE.error("Failed to get stream",e),{peerInfos:null,error:_n.NO_STREAM_AVAILABLE}}const i=await _s([n.encode()],Nu,s,Bu,async e=>await es(e));try{const e=new os;i.forEach(t=>{e.append(t)});const{response:t}=JE.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map(e=>e.enr).filter(xr).map(async e=>({ENR:await PE.fromRLP(e)}))),error:null}:(ZE.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:_n.EMPTY_PAYLOAD})}catch(e){return ZE.error("Failed to decode push reply",e),{peerInfos:null,error:_n.DECODE_FAILED}}}}const eS=new Hn("peer-exchange-discovery"),tS=1e4,rS=3,nS=Tn.PEER_EXCHANGE;class sS extends Zl{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{const{protocols:t,peerId:r}=e.detail;t.includes(YE)&&!this.queryingPeers.has(r.toString())&&(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch(e=>eS.error(`Error querying peer ${e}`)))};constructor(e,t={}){super(),this.components=e,this.peerExchange=new QE(e),this.options=t,this.isStarted=!1}start(){this.isStarted||(this.dispatchEvent(new CustomEvent("waku:peer-exchange:started",{detail:!0})),eS.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(eS.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[Zh](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{const t=e.toString(),{queryInterval:r=tS,maxRetries:n=rS}=this.options;eS.info(`Querying peer: ${t} (attempt ${this.queryAttempts.get(t)??1})`),await this.query(e);const s=this.queryAttempts.get(t)??1;s>n?this.abortQueriesForPeer(t):setTimeout(()=>{this.queryAttempts.set(t,s+1),this.startRecurringQueries(e).catch(e=>{eS.error(`Error in startRecurringQueries: ${e}`)})},r*s)};async query(e){const{error:t,peerInfos:r}=await this.peerExchange.query({numPeers:10,peerId:e});if(t)return eS.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(const e of r){const{ENR:t}=e;if(!t){eS.warn("No ENR in peerInfo object, skipping");continue}const{peerId:r,peerInfo:n,shardInfo:s}=t;if(r&&n){if(await this.components.peerStore.has(r)){const{hasMultiaddrDiff:e,hasShardDiff:t}=await this.checkPeerInfoDiff(n,s);if(e||t){eS.info(`Peer ${r.toString()} has updated multiaddrs or shardInfo, updating`),e&&(eS.info(`Peer ${r.toString()} has updated multiaddrs, updating`),await this.components.peerStore.patch(r,{multiaddrs:n.multiaddrs})),t&&s&&(eS.info(`Peer ${r.toString()} has updated shardInfo, updating`),await this.components.peerStore.merge(r,{metadata:{shardInfo:zn(s)}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:n.multiaddrs}})));continue}}await this.components.peerStore.save(r,{tags:{[nS]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...s&&{metadata:{shardInfo:zn(s)}},...n.multiaddrs&&{multiaddrs:n.multiaddrs}}),eS.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:n.multiaddrs}}))}}return{error:null,peerInfos:r}}abortQueriesForPeer(e){eS.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}async checkPeerInfoDiff(e,t){const{id:r}=e,n=await this.components.peerStore.get(r),s=n.addresses.map(e=>e.multiaddr.toString()),i=e.multiaddrs.map(e=>e.toString()),o=s.some(e=>!i.includes(e));let a=!1;const c=n.metadata.get("shardInfo");if(c){const e=jn(c);(e||t)&&(a=e.clusterId!==t?.clusterId||e.shards.some(e=>!t?.shards.includes(e)))}return{hasMultiaddrDiff:o,hasShardDiff:a}}}const iS=new Hn("local-cache-discovery"),oS=Tn.LOCAL;class aS extends Zl{components;options;isStarted;peers=[];constructor(e,t){super(),this.components=e,this.options=t,this.isStarted=!1,this.peers=this.getPeersFromLocalStorage()}get[Symbol.toStringTag](){return"@waku/local-peer-cache-discovery"}async start(){if(!this.isStarted){iS.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers);for(const{id:e,address:t}of this.peers){const r=Yc(e);await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[$l(t)],tags:{[this.options?.tagName??oS]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:[$l(t)]}})))}iS.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&(iS.info("Stopping Local Storage Discovery"),this.components.events.removeEventListener("peer:identify",this.handleNewPeers),this.isStarted=!1,this.savePeersToLocalStorage())}handleNewPeers=e=>{const{peerId:t,listenAddrs:r}=e.detail,n=function(e){const t=e.find(e=>e.toString().includes("ws")||e.toString().includes("wss"));if(!t)throw new Error("No ws multiaddr found in the given addresses");return t}(r),s=this.getPeersFromLocalStorage(),i=s.findIndex(e=>e.id===t.toString());i>=0?s[i].address=n.toString():s.push({id:t.toString(),address:n.toString()}),this.peers=s,this.savePeersToLocalStorage()};getPeersFromLocalStorage(){try{const e=localStorage.getItem("waku:peers");return e?JSON.parse(e).filter(cS):[]}catch(e){return iS.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){iS.error("Error saving peers to local storage:",e)}}}function cS(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}function lS(e){const t=["enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im","enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"],r=[];return e?.dns&&r.push(function(e,t=Xb){return r=>new XE(r,{enrUrls:e,wantedNodeCapabilityCount:t})}(t)),e?.localPeerCache&&r.push((e,t)=>new aS(e,t)),e?.peerExchange&&r.push(e=>new sS(e)),r}const uS=new Hn("sdk:create");const hS={dns:!0,peerExchange:!0,localPeerCache:!0};async function dS(e){const t=(e.networkConfig??Rn).clusterId??1;uS.info("Creating Waku node with cluster id: ",t);const r=e?.libp2p??{},n=r.peerDiscovery??[];e?.defaultBootstrap?n.push(...lS({...hS,...e.discovery})):n.push(...lS(e.discovery));const s=[...e.bootstrapPeers||[],...e.store?.peers||[]];var i;return s.length&&n.push((i={list:s},e=>new Rd(e,i))),r.peerDiscovery=n,async function(e,t,r){return t?.hideWebSocketInfo||Gb()||(console.info("%cIgnore WebSocket connection failures","background: gray; color: white; font-size: x-large"),console.info("%cWaku tries to discover peers and some of them are expected to fail","background: gray; color: white; font-size: x-large")),async function(e={}){e.privateKey??=await qc("Ed25519");const t=new Hb({...await Eg(e),peerId:(r=e.privateKey,Zc(r.publicKey))});var r;return!1!==e.start&&await t.start(),t}({transports:[jf({filter:!1===t?.filterMultiaddrs||Gb()?Uf:$f})],streamMuxers:[bf()],connectionEncrypters:[Yh()],...t,services:{identify:Kp({agentVersion:r??"js-waku"}),ping:Ef({maxInboundStreams:t?.pingMaxInboundStreams??10}),metadata:Wl(e),...t?.services}})}(t,r,e?.userAgent)}async function pS(e={}){const t=await dS(e),r=new Iu(e,t,{store:!0,lightpush:!0,filter:!0});return!1!==e?.autoStart&&await r.start(),r}function fS(e){return t=this,r=void 0,s=function(){var t,r,n;return function(e,t){var r,n,s,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!((s=(s=i.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){i.label=a[1];break}if(6===a[0]&&i.label<s[1]){i.label=s[1],s=a;break}if(s&&i.label<s[2]){i.label=s[2],i.ops.push(a);break}s[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],n=0}finally{r=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}(this,function(s){switch(s.label){case 0:return t=new TextEncoder,r=t.encode(e),[4,crypto.subtle.digest("SHA-256",r)];case 1:return n=s.sent(),[2,Array.from(new Uint8Array(n)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")]}})},new((n=void 0)||(n=Promise))(function(e,i){function o(e){try{c(s.next(e))}catch(e){i(e)}}function a(e){try{c(s.throw(e))}catch(e){i(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n(function(e){e(r)})).then(o,a)}c((s=s.apply(t,r||[])).next())});var t,r,n,s}var gS="/js-waku-examples/1/message-ratio/utf8",mS=null;function yS(){return e=this,t=void 0,n=function(){var e,t;return function(e,t){var r,n,s,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!((s=(s=i.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){i.label=a[1];break}if(6===a[0]&&i.label<s[1]){i.label=s[1],s=a;break}if(s&&i.label<s[2]){i.label=s[2],i.ops.push(a);break}s[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],n=0}finally{r=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}(this,function(r){switch(r.label){case 0:return mS?[2,mS]:(e=localStorage.getItem("seed"))?[3,2]:[4,fS(Math.random().toString())];case 1:e=r.sent().slice(0,32),localStorage.setItem("seed",e),r.label=2;case 2:return[4,jc("Ed25519",xt(e))];case 3:return[4,pS({defaultBootstrap:!0,discovery:{dns:!0,peerExchange:!0,localPeerCache:!1},numPeersToUse:2,libp2p:{privateKey:r.sent()}})];case 4:return t=r.sent(),window.waku=t,[4,t.start()];case 5:return r.sent(),[4,t.waitForPeers()];case 6:return r.sent(),mS=t,[2,t]}})},new((r=void 0)||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())});var e,t,r,n}function bS(){return null==mS?void 0:mS.libp2p.peerId.toString()}function wS(){return Yn({contentTopic:gS})}var vS=__webpack_require__(2549),ES=new vS.Type("ChatMessage").add(new vS.Field("id",1,"string")).add(new vS.Field("timestamp",2,"uint64")).add(new vS.Field("senderPeerId",3,"string")).add(new vS.Field("content",4,"string"));function SS(e){var t="".concat(Date.now(),"-").concat(Math.random().toString(36).substring(2,9)),r=ES.create({id:t,timestamp:Date.now(),senderPeerId:bS()||"unknown",content:e});return ES.encode(r).finish()}var AS,IS=document.getElementById("sentByMeCount"),kS=document.getElementById("receivedMineCount"),xS=document.getElementById("receivedOthersCount"),CS=document.getElementById("peerIdDisplay"),_S=document.getElementById("messageList"),TS=document.getElementById("searchInput"),PS=document.getElementById("failedToSendCount"),RS=0,OS=0,LS=0,DS=0,NS=[];function MS(e){AS=e,CS&&(CS.textContent=e)}function FS(){RS++,IS&&(IS.textContent=RS.toString())}function BS(){DS++,PS&&(PS.textContent=DS.toString())}function US(e,t){NS.push(e),$S()}function $S(e){if(_S){_S.innerHTML="";var t=e?NS.filter(function(t){var r=e.toLowerCase();return t.content.toLowerCase().includes(r)||t.id.toLowerCase().includes(r)||t.senderPeerId.toLowerCase().includes(r)}):NS;t.sort(function(e,t){return e.timestamp-t.timestamp}),t.forEach(function(e){var t=document.createElement("div");t.classList.add("message-item");var r="",n="";e.failureInfo?(r="failed",n="Me (Failed)",t.style.backgroundColor="#ffebee",t.style.borderLeft="4px solid #f44336"):e.senderPeerId===AS?(r="sent",n="Me"):(r="received-other",n="Other (".concat(e.senderPeerId.substring(0,6),"...)")),t.classList.add(r);var s=document.createElement("p");s.classList.add("message-id"),s.textContent="ID: ".concat(e.id);var i=document.createElement("p");i.classList.add("content"),i.textContent=e.content;var o=document.createElement("p");o.classList.add("sender-info"),o.textContent="From: ".concat(n);var a=document.createElement("p");if(a.classList.add("timestamp"),a.textContent=new Date(e.timestamp).toLocaleTimeString(),t.appendChild(s),t.appendChild(o),t.appendChild(i),t.appendChild(a),e.failureInfo){var c=document.createElement("p");c.classList.add("failure-info"),c.style.color="#d32f2f",c.style.fontWeight="bold",c.textContent="Failed: ".concat(e.failureInfo.error).concat(e.failureInfo.peer?" (Peer: ".concat(e.failureInfo.peer.substring(0,12),"...)"):""),t.appendChild(c)}_S.appendChild(t)})}}function qS(){return TS?TS.value:""}var jS=function(){return jS=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var s in t=arguments[r])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},jS.apply(this,arguments)},zS=function(e,t,r,n){return new(r||(r=Promise))(function(s,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}c((n=n.apply(e,t||[])).next())})},KS=function(e,t){var r,n,s,i={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!((s=(s=i.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){i.label=a[1];break}if(6===a[0]&&i.label<s[1]){i.label=s[1],s=a;break}if(s&&i.label<s[2]){i.label=s[2],i.ops.push(a);break}s[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],n=0}finally{r=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}},VS=0,HS=null,GS=!1;document.addEventListener("DOMContentLoaded",function(){console.log("DOM fully loaded and parsed. Starting app initialization."),function(){zS(this,void 0,void 0,function(){var e,t,r,n,s,i,o,a,c,l,u,h,d=this;return KS(this,function(p){switch(p.label){case 0:return p.trys.push([0,3,,4]),console.log("Initializing Waku node..."),[4,yS()];case 1:return e=p.sent(),t=bS(),console.log("Waku node initialized. Peer ID:",t),t&&MS(t),r=function(){return zS(d,void 0,void 0,function(){var r,n,s,i,o,a,c,l,u,h,d,p,f;return KS(this,function(g){switch(g.label){case 0:r=wS(),VS++,console.log("Sending batch C".concat(VS," of ").concat(5," messages...")),n=0,g.label=1;case 1:if(!(n<5))return[3,8];s="Batch ".concat(VS," - Msg ").concat(n+1," @ ").concat((new Date).toLocaleTimeString()),i=SS(s),o=ES.decode(i),a=o.id||"temp-id-".concat(Date.now()),c={id:a,timestamp:Date.now(),senderPeerId:t||"unknown",content:s},g.label=2;case 2:return g.trys.push([2,4,,5]),[4,e.lightPush.send(r,{payload:i,timestamp:new Date(c.timestamp)},{autoRetry:!0})];case 3:return(l=g.sent()).successes.length>0?(console.log("Message ".concat(n+1," (ID: ").concat(c.id,") sent successfully.")),FS(),US(c)):(console.warn("Failed to send message ".concat(n+1," (ID: ").concat(c.id,"):"),l.failures),u=l.failures.length>0?String(l.failures[0].error)||"Unknown error":"No peers available",h=l.failures.length>0?null===(f=l.failures[0].peerId)||void 0===f?void 0:f.toString():void 0,p=jS(jS({},c),{failureInfo:{error:u,peer:h}}),BS(),US(p)),[3,5];case 4:return d=g.sent(),console.error("Error sending message ".concat(n+1," (ID: ").concat(c.id,"):"),d),p=jS(jS({},c),{failureInfo:{error:String(d)||"Unknown error"}}),BS(),US(p),[3,5];case 5:return[4,new Promise(function(e){return setTimeout(e,100)})];case 6:g.sent(),g.label=7;case 7:return n++,[3,1];case 8:return console.log("Message batch sending complete."),[2]}})})},n=function(){return zS(d,void 0,void 0,function(){var t,r=this;return KS(this,function(n){return GS||(GS=!0,(t=document.getElementById("toggleContinuousSendButton"))&&(t.textContent="Stop Continuous Sending"),t&&t.classList.replace("btn-success","btn-danger"),console.log("Starting continuous message sending..."),HS=window.setInterval(function(){return zS(r,void 0,void 0,function(){var t,r,n,s,i,o,a,c;return KS(this,function(l){switch(l.label){case 0:t=wS(),r="Continuous Send @ ".concat((new Date).toLocaleTimeString()),n=SS(r),s=ES.decode(n),i=s.id||"temp-id-".concat(Date.now()),o={id:i,timestamp:Date.now(),senderPeerId:bS()||"unknown",content:r},l.label=1;case 1:return l.trys.push([1,3,,4]),[4,e.lightPush.send(t,{payload:n,timestamp:new Date(o.timestamp)},{autoRetry:!0})];case 2:return(a=l.sent()).successes.length>0?(console.log("Continuous message (ID: ".concat(o.id,") sent successfully.")),FS(),US(o)):console.warn("Failed to send continuous message (ID: ".concat(o.id,"):"),a.failures),[3,4];case 3:return c=l.sent(),console.error("Error sending continuous message (ID: ".concat(o.id,"):"),c),[3,4];case 4:return[2]}})})},2e3)),[2]})})},s=function(){if(GS&&null!==HS){GS=!1;var e=document.getElementById("toggleContinuousSendButton");e&&(e.textContent="Start Continuous Sending"),e&&e.classList.replace("btn-danger","btn-success"),console.log("Stopping continuous message sending..."),clearInterval(HS),HS=null}},i=function(){return zS(d,void 0,void 0,function(){var r;return KS(this,function(n){switch(n.label){case 0:return r=Qn(gS),window.storeQuery=function(){e.store.queryWithOrderedCallback([r],function(e){console.log("DEBUG",e)})},console.log("Subscribing to messages..."),[4,e.filter.subscribe(r,function(e){console.log("Raw Waku message received, payload length:",e.payload.length);var r=function(e){try{var t=ES.decode(e);return{id:t.id,timestamp:Number(t.timestamp),senderPeerId:t.senderPeerId,content:t.content}}catch(e){return console.error("Failed to decode message:",e),null}}(e.payload);r?(console.log("Decoded chat message:",r),r.senderPeerId===t?(OS++,kS&&(kS.textContent=OS.toString()),console.log("Received own message (loopback):",r.id)):(LS++,xS&&(xS.textContent=LS.toString()),US(r),console.log("Received message from other peer:",r.id))):console.warn("Could not decode received Waku message. Payload might be malformed or not a ChatMessage.")})];case 1:return n.sent(),console.log("Subscription active."),[2]}})})},(o=document.getElementById("sendMessageButton"))&&o.addEventListener("click",function(){console.log("Send Message Button clicked"),r()}),(a=document.getElementById("toggleContinuousSendButton"))&&a.addEventListener("click",function(){GS?s():n()}),(c=document.getElementById("searchButton"))&&c.addEventListener("click",function(){console.log("Search button clicked"),$S(qS())}),(l=document.getElementById("searchInput"))&&l.addEventListener("input",function(){console.log("Search input changed"),$S(qS())}),[4,i()];case 2:return p.sent(),console.log("Application setup complete. Click 'Send New Message Batch' to send messages."),[3,4];case 3:return u=p.sent(),console.error("Critical error during app initialization:",u),(h=document.getElementById("peerIdDisplay"))&&(h.textContent="Error connecting to Waku Network."),[3,4];case 4:return[2]}})})}()})})()})();
|
|
//# sourceMappingURL=index.js.map
|